forked from vecna/trackmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanyutils.py
244 lines (185 loc) · 7.04 KB
/
manyutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# -*- encoding: utf-8 -*-
import os
import json
import datetime
from tldextract import TLDExtract
from termcolor import colored
INFOFILES = [ 'phantom.log', '_traceroutes', 'unique_id', 'used_media.json',
'_verbotracelogs', 'domain.infos', 'country', 'information',
'errors.dns',
'source_url_configured.json',
'reverse.dns',
'reverse.status.json',
'reverse.errors.json',
'resolution.dns',
'resolution.status.json',
'resolution.errors.json',
'first.json', 'second.json', 'third.json',
'phantom.results.json', 'trace.results.json' ]
PERMITTED_SECTIONS = [ 'global', 'national', 'local', 'blog', 'removed', 'special', 'all' ]
def get_unique_urls(source_urldir, urldumpsf):
urls = {}
with file(urldumpsf) as f:
for url_request in f.readlines():
if url_request.startswith('http://'):
urls[ url_request[7:].split('/')[0] ] = True
elif url_request.startswith('https://'):
urls[ url_request[8:].split('/')[0] ] = True
elif url_request.startswith('data:'):
continue
elif url_request.startswith('about:blank'):
continue
else:
print colored("%% Unexpected URL schema '%s' from '%s'" % ( url_request, source_urldir ), 'red')
continue
shortened = []
for unique_url in urls.keys():
if len(unique_url) > 4096:
shortened.append(unique_url[:4096])
else:
shortened.append(unique_url)
return shortened
def sortify(outputdir):
urldict = {}
skipped = 0
for urldir in os.listdir(outputdir):
if urldir in INFOFILES:
continue
try:
urlfile = os.path.join(outputdir, urldir, '__urls')
related_urls = get_unique_urls(urldir, urlfile)
except IOError or OSError as einfo:
print "Unable to read", urldir, einfo, "skipping"
continue
TLDio = TLDExtract(cache_file='mozilla_tld_file.dat')
for dirty_url in related_urls:
# dirty_url because may contain ":"
if dirty_url.split(':') != -1:
url = dirty_url.split(':')[0]
else:
url = dirty_url
if urldict.has_key(url):
skipped +=1
continue
dnsplit= TLDio(url)
urldict.update({url : {
'domain' : dnsplit.domain,
'tld' : dnsplit.suffix,
'subdomain' : dnsplit.subdomain }
})
# note:
# https://raw.github.com/mozilla/gecko-dev/master/netwerk/dns/effective_tld_names.dat
# tldextract is based on this file, and cloudfront.net is readed as TLD. but is fine
# I've only to sum domain + TLD in order to identify the "included entity"
return urldict
def url_cleaner(line):
# cleanurl is used to create the dir, media to phantomjs
if line.startswith('http://'):
cleanurl = line[7:]
elif line.startswith('https://'):
cleanurl = line[8:]
# print "https will be converted in http =>", line
else:
raise Exception("Invalid protocol in: %s" % line)
while cleanurl[-1] == '/':
cleanurl = cleanurl[:-1]
dirtyoptions = cleanurl.find("?")
if dirtyoptions != -1:
cleanurl = cleanurl[:dirtyoptions]
cleanurl = cleanurl.split('/')[0]
return cleanurl
def load_global_file(GLOBAL_MEDIA_FILE):
global_media_list = []
counter = 0
TLDio = TLDExtract(cache_file='mozilla_tld_file.dat')
with file(GLOBAL_MEDIA_FILE, 'r') as f:
for line in f.readlines():
line = line[:-1]
if len(line) > 1 and line[0] == '#':
continue
# everything after a 0x20 need to be cut off
line = line.split(' ')[0]
if len(line) < 3:
continue
entry_records = dict({
'category': None,
'url': None,
'site': None,
})
entry_records['category'] = 'global'
entry_records['url'] = line
cleanurl = url_cleaner(line)
domainsplit = TLDio(cleanurl)
domain_plus_tld = "%s.%s" % (domainsplit.domain, domainsplit.suffix)
entry_records['site'] = domain_plus_tld
counter += 1
global_media_list.append(entry_records)
return global_media_list
GLOBAL_MEDIA_FILE = 'special_media/global'
def media_file_cleanings(linelist, globalfile=GLOBAL_MEDIA_FILE, permit_flexible_category=False):
"""
From the format
[global]
http://site.com/with.html
# comment
[othersec]
http://otherweb
return [
{
'category': 'global',
'url': http://site.come/with.html
'site': site.com
}, {
'category': 'othersec',
'url': http://site.come/with.html
'site': site.com
} ]
"""
retlist = []
current_section = None
counter_section = 0
domain_only = []
TLDio = TLDExtract(cache_file='mozilla_tld_file.dat')
for line in linelist:
entry_records = dict({
'category': None,
'url': None,
'site': None,
})
line = line[:-1]
if len(line) > 1 and line[0] == '#':
continue
# everything after a 0x20 need to be cut off
line = line.split(' ')[0]
if len(line) < 3:
continue
if line.startswith('[') and line.find(']') != -1:
candidate_section = line[1:-1]
if permit_flexible_category:
print colored("Importing URLs in category: %s" % candidate_section, 'green')
current_section = candidate_section
continue
if not candidate_section in PERMITTED_SECTIONS:
print "The section in", line, "is invalid: do not match with", PERMITTED_SECTIONS
quit(-1)
# if we had 'global' section: is special!
if candidate_section == 'global':
global_section = load_global_file(globalfile)
retlist += global_section
continue
current_section = candidate_section
continue
entry_records['category'] = current_section
entry_records['url'] = line
cleanurl = url_cleaner(line)
domainsplit = TLDio(cleanurl)
domain_plus_tld = "%s.%s" % (domainsplit.domain, domainsplit.suffix)
# to spot http://www.nytimes.com vs http://nytimes.com
entry_records['site'] = domain_plus_tld
if domain_plus_tld in domain_only and permit_flexible_category == False:
print colored(u' → %s is part of an already seen domain: %s' % (line, domain_plus_tld), 'blue', 'on_white')
else:
domain_only.append(domain_plus_tld)
retlist.append(entry_records)
counter_section += 1
return retlist