Skip to content

Instantly share code, notes, and snippets.

@adriansr
Created January 18, 2019 16:10
Show Gist options
  • Save adriansr/7cd24f7468e319f6395c3ea7152f4c4d to your computer and use it in GitHub Desktop.
Save adriansr/7cd24f7468e319f6395c3ea7152f4c4d to your computer and use it in GitHub Desktop.
# Anonymize IPTABLES logs for documentation!
import os
import re
import sys
random_macs = set()
macs = {}
def random_mac_make():
return "90:10:" + ':'.join(['{0:02x}'.format(ord(x)) for x in os.urandom(4)])
def random_mac():
rand = random_mac_make()
while rand in random_macs:
rand = random_mac_make()
random_macs.add(rand)
return rand
def replace_mac(mac):
if mac in macs:
return macs[mac]
rand = random_mac()
macs[mac] = rand
return rand
def replace_macs(match):
m1 = replace_mac(match.group(1))
m2 = replace_mac(match.group(2))
return 'MAC=' + m1 + ':' + m2
random_ips = set()
ips = {}
doc_ips = [[192, 0, 2], [198, 51, 100], [203, 0, 113]]
known_prefixes = set([ '.'.join([str(y) for y in x ]) for x in [
[0],
[10],
[127],
[169, 254],
[192, 0, 0],
[192, 88, 99],
[192, 168],
[198, 18],
[198, 19],
] + [ [100, x] for x in range(64, 128) ]
+ [ [172, x] for x in range(16, 32) ]
+ [ [x] for x in range(224,256) ]
+ doc_ips])
def random_ip_make_prefix(prefix):
return '.'.join([str(y) for y in (prefix + [ord(x) for x in os.urandom(4 - len(prefix))])])
def random_ip_make(parts):
for i in range(1,4):
if '.'.join([str(x) for x in parts[:i]]) in known_prefixes:
return random_ip_make_prefix(parts[:i])
return random_ip_make_prefix(doc_ips[ord(os.urandom(1)) % len(doc_ips)])
def random_ip(parts):
rand = random_ip_make(parts)
while rand in random_ips:
rand = random_ip_make(parts)
random_ips.add(rand)
return rand
def replace_ip(match):
ip = match.group(1)
if ip in ips:
return '=' + ips[ip]
parts = [int(x) for x in ip.split('.')]
if any(x < 0 or x > 255 for x in parts):
return match
rand = random_ip(parts)
ips[ip] = rand
return '=' + rand
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'Usage: {0} <iptables.log>'.format(sys.argv[0])
sys.exit(1)
handle = open(sys.argv[1], 'rb')
for line in handle:
line = re.sub(r'MAC=([0-9a-fA-F:]{17}):([0-9a-fA-F:]{17})', replace_macs, line)
line = re.sub(r'=([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)', replace_ip, line)
print line,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment