Bogon Filtering using Regex

, posted: 24-Jan-2018 13:16

I had to filter the Bogon (RFC1918 + CGNAT (RFC6598) + Loopback (RFC990) + Link Local (RFC3927)) from within a proxy server I was setting up. RFC5735 covers a lot of the non-routeable addresses all in a single RFC with the exception of CGNAT. I used this page as a start and tweaked it to my own requirements.

My regex testing site of preference is: https://regex101.com/ as it has an excellent UI to test with and breaks out what the regex is doing.

This is the regex I ended up with:

((?:10|127)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})|((?:192\.168|169\.254|172\.(?:1[6-9]|2[0-9]|3[0-1])|100\.(?:6[4-9]|[7-9][0-9]|1[0-1][0-9]|12[0-7]))(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){2})

Reading it the regex blocks the following ranges:

10.0.0.0/8 & 127.0.0.0/8

Regex: ((?:10|127)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})

Explanation - A non capture group ?: match 10 or 127 then capture ". + 1-255" {3} times as a non capture group.

 

192.168.0.0/16 & 169.254.0.0/16

Regex: ((?:192\.168|169\.254)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){2})

Explanation: A non capture group ?: match 192.168 or 169.254 then capture ". + 1-255" {2} times as a non capture group.

 

172.16.0.0/12

Regex: ((172\.(?:1[6-9]|2[0-9]|3[0-1])(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){2})

Explanation: "172." then non capture group 16-19 or 20-29 or 30-31 then capture ". + 1-255" {2} times as a non capture group.

 

100.64.0.0/10

Regex: ((100\.(?:6[4-9]|[7-9][0-9]|1[0-1][0-9]|12[0-7])(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){2})

Explanation: "100." then non capture group 64-69 or 70-99 or 100-119 or 120 to 127 then capture ". + 1-255" {2} times as a non capture group.

 

Hope someone finds this useful.





BarTender's profile

Bar Tender
Wellington
New Zealand