-
Notifications
You must be signed in to change notification settings - Fork 2
/
WhoTrack.py
executable file
·349 lines (304 loc) · 9.47 KB
/
WhoTrack.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python
"""
WhoTrack.py originally written by Keith Gilbert - @digital4rensics
www.digital4rensics.com - 5/8/13 - Version 0.2
The script will track basic domain WhoIs information based upon domains entered in the database.
This is an ongoing work and is likely not suitable for production use at the moment.
Planned improvements for: Proxy support, History Tracking
No warranty is implied or expressed, use at your own risk.
usage: WhoTrack.py [-h] [-d DATABASE] [-f FORGET] [-i INSERT] [-l]
[-p PROXIES] [-r REPORT] [-s SERVERS] [-t TEST] [-v]
Track Daily Domain Registrant Changes
optional arguments:
-h, --help show this help message and exit
-d DATABASE, --database DATABASE
Specify database name
-f FORGET, --forget FORGET
Stop monitoring a domain (data is retained)
-i INSERT, --insert INSERT
Insert new domain in to the database
-l, --list List all domains currently tracked
-p PROXIES, --proxies PROXIES
Specify a list of proxies to conduct lookups
-r REPORT, --report REPORT
Specify a report filename other than the default
-s SERVERS, --servers SERVERS
Specify different servers file
-t TEST, --test TEST Bypass database to test parsers against a specific
domain
-v, --verbose Enable command line output
"""
import re
import sys
import socks
import socket
import sqlite3
import argparse
from random import choice
from datetime import date
sys.path.append('./')
sys.path.append('./parsers/')
#Import the list of WhoIs servers from file
def genservers(listname):
try:
list = open(listname, 'r')
except:
ish = "Error opening servers file. Please verify it is located in the same directory and that it exists."
if verb:
print ish
#Ignore comments at the beginning of the file
ignore = re.compile("^;")
paired = {}
#For each entry, create a key,value pair in the dictionary
for line in list:
if not ignore.match(line):
temp = line.split()
paired[temp[0]] = temp[1]
list.close()
if verb:
print "Server list successfully generated\n"
return paired
def genproxies(listname):
try:
list = open(listname, 'r')
except:
ish = "Error opening proxies file. Please verify it is located in the same directory and that it exists."
if verb:
print ish
prox = []
#For each entry, create a key,value pair in the dictionary
for line in list:
if line.startswith(";"):
pass
else:
temp = line.rstrip().split(":")
prox.append(temp)
list.close()
if verb:
print "Proxy list successfully generated\n"
return prox
#Set up the Database
def dbsetup(name):
try:
conn = sqlite3.connect(name, isolation_level=None)
cur = conn.cursor()
except:
ish = "Error connectiong to database\n"
if verb:
print ish
try:
cur.execute("CREATE TABLE IF NOT EXISTS Domains(Domain TEXT, Name TEXT, Org TEXT, Addr TEXT, Email TEXT, Phone TEXT, Fax TEXT, Updated TEXT, Forgotten TEXT)")
return cur
except:
ish = "Error creating database table"
if verb:
print ish
def newdomain(dom, db):
try:
test = db.execute("SELECT count(*) FROM Domains WHERE Domain = ?", (dom,)).fetchone()[0]
if test == 0:
db.execute("INSERT INTO Domains VALUES(?, ?, ?, ?, ?, ?, ?, (SELECT date('now')), ?)", (dom,None,None,None,None,None,None,'No'))
else:
ish = "Domain: " + dom + " already in database, not inserted."
if verb:
print ish
except:
ish = "Error inserting new domain in to database"
if verb:
print ish
#Get Domains to Monitor from Database
def getdata(db):
try:
domlist = []
for row in db.execute("SELECT DISTINCT Domain FROM Domains WHERE Forgotten = ?", ('No',)):
domlist.append(row[0])
return domlist
except:
ish = "Error retrieving domains to monitor from database"
if verb:
print ish
#Check and Insert Records in Database
def insertdata(data, db, dom):
test = []
current = []
newest = db.execute("SELECT MAX(Updated) FROM Domains WHERE Domain = ?", (dom,)).fetchone()[0]
for row in db.execute("SELECT Domain, Name, Org, Addr, Email, Phone, Fax FROM Domains WHERE Domain = ? AND Updated = ? ORDER BY Name desc Limit 1", (dom, newest)):
for elem in row:
current.append(elem)
test.extend([dom, data['name'], data['organization'], data['address'], data['email'], data['phone'], data['fax']])
i=0
change = False
for elem in current:
#Is the old record the same as the new record?
try:
if test[i] == elem:
i += 1
else:
change = True
except:
ish = "Error comparing new and old data for: " + data['name']
if verb:
print ish
if change:
ish = "Change detected\n" + "Old Data: " + str(current) + "\n" + "New Data: " + str(test) + "\n"
db.execute("INSERT INTO Domains VALUES(?, ?, ?, ?, ?, ?, ?, (SELECT date('now')), ?)",
(dom, data['name'], data['organization'], data['address'], data['email'], data['phone'], data['fax'], 'No'))
report.write(ish)
if verb:
print ish
else:
if verb:
print "No change detected for " + dom
#Do the Whois Lookup
def dowhois(dom, col, recurse):
#Variable to track if the call is recursive
redo = False
response = ""
#Find the correct whois server
if recurse:
tld, srv = findserver(recurse, col)
redo = True
else:
tld, srv = findserver(dom, col)
try:
#Build connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((srv, 43))
if verb:
print "Connected Successfully to " + srv + " for " + dom
s.send(dom + "\r\n")
while True:
d = s.recv(4096)
response += d
if not d:
break
s.close()
record = extractdata(dom, tld, response, redo)
if record:
return record
except:
ish = "Error in connection to " + srv + " for " + dom
if verb:
print ish
#Get Correct server to use
def findserver(tld, col):
try:
for key in col.keys():
use = key + "$"
if re.search(use, tld):
return key,col[key]
except:
ish = "Error finding correct whois server"
if verb:
print ish
#Extract the appropriate data from the record
def extractdata(dom, tld, data, stop):
#If .com and not 2nd query, extract appropriate nameserver and initiate new query
if tld == "com" or tld == "net" and stop == False:
reg = re.search('(?<=Registrar: )\w+', data)
newsrv = reg.group().lower()
newdata = dowhois(dom, servlist, newsrv)
return newdata
#Parse whois results for appropriate data using appropriate plugin
else:
#Import the correct parsing module based on TLD or Registrar
try:
parse = __import__(tld)
stripped = parse.parse(data)
return stripped
except:
ish = "Error importing parser"
if verb:
print ish
def listdomains(db):
for row in db.execute("SELECT DISTINCT Domain FROM Domains"):
print row
def forget(dom, db):
try:
test = db.execute("SELECT count(*) FROM Domains WHERE Domain = ?", (dom,)).fetchone()[0]
if test == 0:
ish = "Error: Domain not found"
if verb:
print ish
else:
db.execute("UPDATE Domains SET Forgotten = ? WHERE Domain = ?", ('Yes', dom))
except:
ish = "Error forgetting the domain"
if verb:
print ish
def main():
global servlist
global proxylist
global verb
global report
parser = argparse.ArgumentParser(description="Track Daily Domain Registrant Changes")
parser.add_argument("-d", "--database", help="Specify database name")
parser.add_argument("-f", "--forget", help="Stop monitoring a domain (data is retained)")
parser.add_argument("-i", "--insert", help="Insert new domain in to the database")
parser.add_argument("-l", "--list", action="store_true", help="List all domains currently tracked")
parser.add_argument("-p", "--proxies", help="Specify a list of proxies to conduct lookups")
parser.add_argument("-r", "--report", help="Specify a report filename other than the default")
parser.add_argument("-s", "--servers", help="Specify different servers file")
parser.add_argument("-t", "--test", help="Bypass database to test parsers against a specific domain")
parser.add_argument("-v", "--verbose", action="store_true", help="Enable command line output")
args = parser.parse_args()
#If verbosity is enabled
if args.verbose:
verb = True
else:
verb = False
#If a custom server file was specified
if args.servers:
servlist = genservers(args.servers)
else:
servlist = genservers('servers.txt')
#If testing new parsers
if args.test:
testdat = dowhois(args.test, servlist, None)
print testdat
#If a custom database was specified
if args.database:
db = dbsetup(args.database)
else:
db = dbsetup('WhoTrack.db')
#If only inserting new domain
if args.insert:
newdomain(args.insert, db)
db.close()
sys.exit()
#If forgetting a tracked domain
if args.forget:
forget(args.forget, db)
db.close()
sys.exit()
#If listing current domains
if args.list:
listdomains(db)
db.close()
sys.exit()
if args.report:
report = open(args.report, 'w')
else:
rname = date.isoformat(date.today()) + "_Report.txt"
report = open(rname, 'w')
doms = getdata(db)
#If you want to use proxies to make the requests
if args.proxies:
plist = genproxies(args.proxies)
for row in doms:
selection = choice(plist)
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, selection[0], int(selection[1]))
socket.socket = socks.socksocket
ws = dowhois(row.strip(),servlist, None)
insertdata(ws, db, row)
else:
for row in doms:
ws = dowhois(row.strip(),servlist, None)
insertdata(ws, db, row)
db.close()
report.close()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit()