geongeorge / i-hate-regex

The code for iHateregex.io 😈 - The Regex Cheat Sheet
https://iHateRegex.io
4.5k stars 320 forks source link

Regex for matching b64 encoded IP #103

Open simplylu opened 1 year ago

simplylu commented 1 year ago

This will match valid IPs from 0.0.0.0 to 255.255.255.255 which are base64 encoded.

let regex = /[MNO][CDSTijyz][4AEIMQUYcgk][012345uwxyz][LMNO][CDSTijyz][4AEIMQUYcgk][012345uwxyz][LMNO][ACDQSTgijwyz]([4=AEIMQUYcgk]{1}([012345=uwxyz]{1}([LMNO]{1}([ACDQSTgijwyz]{1}([4=AEIMQUYcgk]{1}([012345=uwxyz]{1}([MNO]{1}([ADQTgjwz]{1}([=AEIMQUYcgk]{1}([012345=wxyz]{1})?)?)?)?)?)?)?)?)?)?/gm;

The following IPs will match:

let matching_ips = [
  "MjU1LjI1NS4yNTUuMjU1",   // 255.255.255.255
  "MTIuMTIzLjE0Mi4xMjM=",   // 12.123.142.123
  "MjU1LjI1NS4yNTUuMg==",   // 255.255.255.2
  "MjU1LjIuMjUuMjU1",   // 255.2.25.255
  "MTIzLjEuMi4xMjM=",   // 123.1.2.123
  "NzguNTYuNDUuMg==",   // 78.56.45.2
  "MTIuNDUuMi4x",   // 12.45.2.1
  "OTEuMS4xLjE=",   // 91.1.1.1
  "MS4yLjMuNA==",   // 1.2.3.4
  … // and so on
]

The following won't:

let non_matching_ips = [
  "LTEuMi4zLjQ", // -1.2.3.4
  "MS4y", // 1.2,
  … // and so on
]

Unfortunately, there are some false-positives, as it matches for example 255.255.255.256, 256.256.256.256 and 1.02.3.4, which cannot be eradicated without massive efforts and making the expression even more unreadable. But for extracting encoded IPs from some data to use it, for example as an IOC, this might be enough, and it's feasible to expect from a human being to check if an IP is valid.