-
Notifications
You must be signed in to change notification settings - Fork 21
/
thief.py
executable file
·295 lines (275 loc) · 10.6 KB
/
thief.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
#!/usr/bin/env python
# copyrighted by sandrogauci <[email protected]> 2010-2011
#
import random
import os
from time import sleep, time
from optparse import OptionParser
import logging
import logging.handlers
import socket
import select
import sys
import datetime
from lib.tftplib import tftp, tftpstruct
from lib.bruteforcehelper import anotherxrange, getRange
from lib.common import __LICENSE__, __version__, calcloglevel
import lib.contrib.construct
from lib.contrib.progressbar import progressbar
DESC = """
Thief.py downloads files from a tftp server quickly and efficiently
"""
def gen_range(template,myranges):
for myrange in myranges:
for i in myrange:
outstr = template % i
yield(outstr)
def gen_tftpfilelist(fn):
f = open(fn,'r')
while 1:
line = f.readline().strip()
if len(line) == 0:
f.close()
break
yield(line)
def assemblefiles(dumpfiles,sportmap):
files = dict()
for addresses in dumpfiles:
transferdone = False
tmpfile = str()
for part in dumpfiles[addresses]:
data = dumpfiles[addresses][part]
tmpfile += data
if len(data) < 512:
transferdone = True
sport = addresses[1][1]
fn = sportmap[sport]
files[(fn,transferdone)]=tmpfile
return files
def splitpartialfull(dumpfiles):
partial = dict()
full = dict()
for addresses in dumpfiles:
transferdone = False
for part in dumpfiles[addresses]:
data = dumpfiles[addresses][part]
if len(data) < 512:
transferdone = True
break
if transferdone:
full[addresses] = dumpfiles[addresses]
else:
partial[addresses] = dumpfiles[addresses]
return full,partial
def dumpnassemble(dumpfiles,sportmap,dstdir,partialdump=True):
partialfiles = None
if not partialdump:
dumpfiles,partialfiles = splitpartialfull(dumpfiles)
files = assemblefiles(dumpfiles,sportmap)
donefiles = list()
for (fn,done) in files:
if not os.path.exists(dstdir):
os.mkdir(dstdir)
data=files[(fn,done)]
f=open(os.path.join(dstdir,fn),'wb')
f.write(data)
f.close()
donefiles.append(fn)
return partialfiles,donefiles
class mylist:
def __init__(self,limit=20):
self.limit = limit
self.list = []
def append(self,data):
if len(self.list) > self.limit-1:
last = self.list.pop(-1)
if type(last) == socket.socket:
last.close()
self.list.append(data)
def getargs():
global parser
usage = "usage: %prog [options] target\r\n"
usage += "examples:\r\n"
usage += "%prog 10.0.0.1\r\n"
usage += "%prog -p6969 10.0.0.1\r\n"
parser = OptionParser(usage, version="%prog v"+str(__version__)+DESC+__LICENSE__)
parser.add_option('-p',"--port", dest="port", default=69, type="int",
help="Destination port")
parser.add_option('--range','-r', dest="range",
help="Range of hex (default) or numeric filenames")
parser.add_option('--rangetype','-T', dest="rangetype", default="hex",
type="choice", choices=["hex","num"],
help="Range of hex (default, useful for mac addresses) or num for numeric filenames")
parser.add_option('--fntemplate',dest="fntemplate", default="SEP%012X.cnf.xml",
help="""When the --range option is used, by default it produces
filenames for SCCP configuration files using the template
SEP%012X.cnf.xml. You can modify this to reflect any template or
specify a template set in fntemplates.txt""")
parser.add_option('--file','-f', dest="filenamesfile",
default=os.path.join('data','tftplist.txt'),
help="File containing a list of files to download")
parser.add_option('-o','--output',dest="dstdir", default="download",
help="Output directory where the files will be downloaded")
parser.add_option('--listtemplates','-l', dest="listtemplates",
default=False, action="store_true",
help="List known templates")
parser.add_option('--verbose','-v', dest="verbose",
action="count",
help="Increase verbosity")
parser.add_option('--quiet','-q', dest="quiet",
default=False, action="store_true",
help="Sssh! quiet mode")
parser.add_option('--debug',default=False, action="store_true",
help="Enable debug mode and log to debug.log")
(options, args) = parser.parse_args()
return (options, args)
def getfntemplate(fntemplate):
import csv
res = fntemplate
f=open(os.path.join('data','fntemplates.txt'),'r')
reader=csv.reader(f,delimiter=":")
for row in reader:
if row[0] == fntemplate:
res = row[1]
break
f.close()
return res
def listtemplates():
import csv
f=open(os.path.join('data','fntemplates.txt'),'r')
reader=csv.reader(f,delimiter=":")
res = list()
for row in reader:
if len(row) == 2:
res.append(row[0])
f.close()
return res
def main():
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
options,args = getargs()
log.setLevel(calcloglevel(options))
if options.listtemplates:
print "Templates available:"
print "\r\n".join(listtemplates())
sys.exit()
if len(args) != 1:
parser.error("Please pass just one destination tftp server name")
if options.debug:
log.setLevel(logging.DEBUG)
debughandler = logging.handlers.WatchedFileHandler('debug.log')
log.addHandler(debughandler)
dst = (args[0],int(options.port))
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(5)
mydirtysocks = mylist(limit=100)
mydirtysocks.append(s)
t = tftp()
if options.range:
ranges = getRange(options.range,rangetype=options.rangetype)
fntemplate = getfntemplate(options.fntemplate)
try:
fntemplate % 100
except TypeError:
log.critical('The template specified is not a valid one or not found')
return
filelist = gen_range(fntemplate, ranges)
filelist2 = gen_range(fntemplate, ranges)
else:
filelist = gen_tftpfilelist(options.filenamesfile)
filelist2 = gen_tftpfilelist(options.filenamesfile)
dumpfiles = dict()
ackbucket = list()
sportmap = dict()
start_time = datetime.datetime.now()
cleansocks = list()
finito = False
lastrecv = time()
maxlastrecv = 5
if not os.path.exists(options.dstdir):
os.mkdir(options.dstdir)
if not options.quiet:
widgets = ['Test: ', progressbar.Percentage(), ' ', progressbar.Bar(marker=progressbar.RotatingMarker()),
' ', progressbar.ETA(), ' ']
filelistlen = 0
for _tmp in filelist2:
filelistlen += 1
fnno = 0
pbar = progressbar.ProgressBar(widgets=widgets, maxval=filelistlen).start()
while 1:
socklists = list()
socklists.extend(mydirtysocks.list)
socklists.extend(cleansocks)
r,w,e = select.select(socklists,[],[],0.1)
if len(r) > 0:
for s in r:
recv = s.recvfrom(1024)
log.debug('Recv: %s' % `recv`)
lastrecv = time()
buff = recv[0]
ipaddr = recv[1]
try:
response = tftpstruct.parse(buff)
except lib.contrib.construct.core.RangeError:
response = None
if response is None:
log.warn('Error parsing response')
continue
if response.operation == 'ERROR':
if (response.data.errorcode == 'FileNotFound' or
response.data.ErrMsg == 'No such file or directory'):
pass
else:
log.debug(str(response))
log.warn( "Time for a siesta.. I think the tftp can't keep up")
sleep(2)
elif response.operation == 'DATA':
addresses = (ipaddr,s.getsockname())
if addresses not in dumpfiles:
dumpfiles[addresses] = dict()
dumpfiles[addresses][response.data.block] = response.data.data
if s in mydirtysocks.list:
mydirtysocks.list.remove(s)
cleansocks.append(s)
ackbucket.append([response.data.block,ipaddr,s])
else:
if time() - lastrecv > maxlastrecv:
finito = True
if len(ackbucket) > 0:
block,datadst,s = ackbucket.pop(-1)
data = t.makeack(block)
s.sendto(data,datadst)
elif finito:
break
if not finito:
try:
fn = filelist.next()
if not options.quiet:
fnno += 1
pbar.update(fnno)
except StopIteration:
finito = True
continue
data = t.makerrq(fn)
log.debug('asking for %s' % fn)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(5)
log.debug('sending %s' % `data`)
s.sendto(data,dst)
mydirtysocks.append(s)
saddr,sport = s.getsockname()
sportmap[sport] = fn
if random.randrange(84) == 42:
dumpfiles,files = dumpnassemble(dumpfiles,sportmap,options.dstdir,partialdump=False)
for fn in files:
log.info("Dumped %s" % fn)
if (time() - lastrecv > maxlastrecv) or len(dumpfiles.keys()) == 0:
log.error('Did not receive a response after %s seconds, quitting' \
% (time()-lastrecv))
dumpfiles,files = dumpnassemble(dumpfiles,sportmap,options.dstdir,partialdump=True)
for fn in files:
log.info( "pos 2 Dumped %s" % fn)
log.info( "Total time: %s" % (datetime.datetime.now() - start_time) )
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
main()