Skip to content

Commit 3314d87

Browse files
committed
contrib: makeseeds: Factor out ASN lookup
1 parent 301c2b1 commit 3314d87

File tree

1 file changed

+31
-24
lines changed

1 file changed

+31
-24
lines changed

contrib/seeds/makeseeds.py

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,31 @@ def filtermultiport(ips):
121121
hist[ip['sortkey']].append(ip)
122122
return [value[0] for (key,value) in list(hist.items()) if len(value)==1]
123123

124+
def lookup_asn(net, ip):
125+
'''
126+
Look up the asn for an IP (4 or 6) address by querying cymry.com, or None
127+
if it could not be found.
128+
'''
129+
try:
130+
if net == 'ipv4':
131+
ipaddr = ip
132+
prefix = '.origin'
133+
else: # http://www.team-cymru.com/IP-ASN-mapping.html
134+
res = str() # 2001:4860:b002:23::68
135+
for nb in ip.split(':')[:4]: # pick the first 4 nibbles
136+
for c in nb.zfill(4): # right padded with '0'
137+
res += c + '.' # 2001 4860 b002 0023
138+
ipaddr = res.rstrip('.') # 2.0.0.1.4.8.6.0.b.0.0.2.0.0.2.3
139+
prefix = '.origin6'
140+
141+
asn = int([x.to_text() for x in dns.resolver.query('.'.join(
142+
reversed(ipaddr.split('.'))) + prefix + '.asn.cymru.com',
143+
'TXT').response.answer][0].split('\"')[1].split(' ')[0])
144+
return asn
145+
except Exception:
146+
sys.stderr.write('ERR: Could not resolve ASN for "' + ip + '"\n')
147+
return None
148+
124149
# Based on Greg Maxwell's seed_filter.py
125150
def filterbyasn(ips, max_per_asn, max_total):
126151
# Sift out ips by type
@@ -129,33 +154,15 @@ def filterbyasn(ips, max_per_asn, max_total):
129154

130155
# Filter IPv46 by ASN
131156
result = []
132-
asn_count = {}
157+
asn_count = collections.defaultdict(int)
133158
for ip in ips_ipv46:
134159
if len(result) == max_total:
135160
break
136-
try:
137-
if ip['net'] == 'ipv4':
138-
ipaddr = ip['ip']
139-
prefix = '.origin'
140-
else: # http://www.team-cymru.com/IP-ASN-mapping.html
141-
res = str() # 2001:4860:b002:23::68
142-
for nb in ip['ip'].split(':')[:4]: # pick the first 4 nibbles
143-
for c in nb.zfill(4): # right padded with '0'
144-
res += c + '.' # 2001 4860 b002 0023
145-
ipaddr = res.rstrip('.') # 2.0.0.1.4.8.6.0.b.0.0.2.0.0.2.3
146-
prefix = '.origin6'
147-
148-
asn = int([x.to_text() for x in dns.resolver.query('.'.join(
149-
reversed(ipaddr.split('.'))) + prefix + '.asn.cymru.com',
150-
'TXT').response.answer][0].split('\"')[1].split(' ')[0])
151-
if asn not in asn_count:
152-
asn_count[asn] = 0
153-
if asn_count[asn] == max_per_asn:
154-
continue
155-
asn_count[asn] += 1
156-
result.append(ip)
157-
except:
158-
sys.stderr.write('ERR: Could not resolve ASN for "' + ip['ip'] + '"\n')
161+
asn = lookup_asn(ip['net'], ip['ip'])
162+
if asn is None or asn_count[asn] == max_per_asn:
163+
continue
164+
asn_count[asn] += 1
165+
result.append(ip)
159166

160167
# Add back Onions
161168
result.extend(ips_onion)

0 commit comments

Comments
 (0)