#!/usr/bin/env python2.7


"""Generate Snort rules from a list of dns domains found in http://www.malware-domains.com/files/dynamic_dns.zip
"""
from datetime import datetime
import re
from StringIO import StringIO
import sys
import urllib2
import zipfile

RULE_TEMPLATE = r'alert udp $HOME_NET any -> $DNS_SERVERS 53 (msg:"DNS Query for a dynamic domain <domain_here>"; content:"|01 00 00 01 00 00 00 00 00 00|"; depth:10; offset:2; content:"<content_here>"; fast_pattern; nocase; distance:0; classtype:bad-unknown; sid:<sid_here>; rev:1;)'
STARTING_SID = 1000000
HTTP_PROXY = 'http://127.0.0.1:3128'
FILE_URL = 'http://www.malware-domains.com/files/dynamic_dns.zip'
FILE = 'dynamic_dns.txt'
RULES_FILE = 'local.rules'

proxy_support = urllib2.ProxyHandler({'http':HTTP_PROXY})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

try:
    url = urllib2.urlopen(FILE_URL)
    zf = zipfile.ZipFile(StringIO(url.read()))
except:
    print "Couldn't connect"
    sys.exit(1)

sid = STARTING_SID
timestamp = datetime.utcnow()

with open(RULES_FILE, 'w') as rules_fh:
    rules_fh.write('#autogenerated on ' + timestamp.isoformat('T') + 'Z' + '\n')
    for line in zf.open(FILE).readlines():
        if len(line.strip()) == 0:
            continue
        if line.startswith('#'):
            continue
        m = re.match('(\S+)', line)
        if m:
            domain = m.group(0)
            rule = ''
            rule = RULE_TEMPLATE.replace('<domain_here>', domain)
            rule = rule.replace('<sid_here>', str(sid))
            domain = domain.split('.')
            content = ''
            for a in domain:
                content += '|' + str(hex(len(a))[2:].zfill(2)) + '|' + a
            content += '|00|'
            rule = rule.replace('<content_here>', content) + '\n'
            rules_fh.write(rule)
            sid += 1

