-
Notifications
You must be signed in to change notification settings - Fork 8
/
exploitutils.py
2394 lines (2093 loc) · 70.2 KB
/
exploitutils.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##ImmunityHeader v1
###############################################################################
## File : exploitutils.py
## Description:
## :
## Created_On : Fri Jul 17 10:48:26 2009
## Created_By : Rich
## Modified_On: Fri Jul 17 11:03:21 2009
## Modified_By: Rich
##
## (c) Copyright 2009, Immunity Inc all rights reserved.
###############################################################################
#! /usr/bin/env python
#Proprietary CANVAS source code - use only under the license agreement
#specified in LICENSE.txt in your CANVAS distribution
#Copyright Immunity, Inc, 2002-2006
#http://www.immunityinc.com/CANVAS/ for more information
#from __future__ must be at beginning of file...
#from __future__ import generators
from __future__ import with_statement
# 64 bit compatibility, wrap struct.pack and struct unpack
import os, sys
import commands
from canvaserror import *
import logging
class structWrap:
def __init__(self, f = None):
self.f = f
return
def amdsixquatro(self, a, k):
#print "ALTERING: Args, Kwargs: ", a, k
aList = list(a) # unfreeze the tuple to list
sList = []
for c in a[0]:
if c == 'L': c = 'I'
if c == 'l': c = 'i'
sList.append(c)
aList[0] = "".join(sList)
a = tuple(aList) # freeze the list to tuple
#print "ALTERED?: Args, Kwargs: ", a, k
return a, k
def __call__(self, *args, **kwargs):
args, kwargs = self.amdsixquatro(args, kwargs)
ret = self.f(*args, **kwargs)
return ret
import struct
from struct import calcsize
#we can use this to know if we are a 64 bit Python or not
original_long_size = struct.calcsize("<L")
threadchecknonMain_we_are_commandline = False
# end of 64 bit compatibility code
import sys, string
#thanks Tim O'Malley! (BSDish license)
import timeoutsocket
timeoutsocket.setDefaultSocketTimeout(5)
import socket
from MOSDEF.mosdefutils import *
from internal import * # a lot of files only include exploitutils and use internal functions via this include.
import threading
import random
import locale
from libs.tlslite.api import *
import time
# platform_is_win32
import os
global platform_is_win32
platform_is_win32 = False
if sys.platform in [ "win32" , "cygwin" ] or os.name == "nt":
platform_is_win32 = True
#del os #why would we delete os?
import socket
def utf16toascii(buf):
#replace all non-ascii characters with a ?
if buf == "":
return ""
try:
ret = buf.decode("utf-16-le").encode("ascii","replace")
except UnicodeDecodeError:
ret = prettyprint(buf)
if ret[-1] == "\x00":
ret = ret[:-1]
return ret
def getsocklistener(listenport, listenhost="0.0.0.0", ipv6=False, protocol=None):
if protocol in [None, "TCP"]:
protocol = socket.SOCK_STREAM
elif protocol in ["UDP"]:
protocol = socket.SOCK_DGRAM
if ipv6:
s = socket.socket(socket.AF_INET6, protocol)
else:
s = socket.socket(socket.AF_INET, protocol)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
try:
s.bind((listenhost,listenport))
except socket.error:
s.close()
#import traceback
#traceback.print_exc()
return None
if protocol == socket.SOCK_STREAM:
s.listen(5)
return s
def getudplistener(listenport, listenhost="0.0.0.0", ipv6=False):
return getsocklistener(listenport, listenhost, ipv6, "UDP")
def gettcplistener(listenport, listenhost="0.0.0.0", ipv6=False):
"""
Returns None on failure
"""
return getsocklistener(listenport, listenhost, ipv6, "TCP")
import cStringIO
import gzip
def gzipBuffer(buffer):
"""
Gzip encodes a buffer, returning a string of compressed data. This will add the header and footer information
needed by the HTTP spec. Normal zlib.compress() will not, so you can't use it for Content-Encoded: gzip format.
"""
zbuf = cStringIO.StringIO()
zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 9)
zfile.write(buffer)
zfile.close()
return zbuf.getvalue()
#simpler routines for simpler functions
import StringIO
def gunzipstring(data):
"""
Gunzips a string, or throws an exception
"""
datastream = StringIO.StringIO(data)
g = gzip.GzipFile(fileobj=datastream)
data = g.read()
return data
def gzipstring(data):
"""
Gzips a string to another string using StringIO
"""
datastream = StringIO.StringIO()
g = gzip.GzipFile(mode="wb",fileobj=datastream)
g.write(data)
g.close()
ret = datastream.getvalue()
return ret
# read: 0x61626364 == offset 0x1234 .. low nibble for each byte
def offsets(size, endian='<', mask=0x60606060):
dwords = []
ret = ""
align = size % 4
for i in range(0, size/4): # /sizeof(dword)
nibbles = []
nibbles.append(((i*4 + align) & 0xf000) >> 12)
nibbles.append(((i*4 + align) & 0x0f00) >> 8)
nibbles.append(((i*4 + align) & 0x00f0) >> 4)
nibbles.append(((i*4 + align) & 0x000f))
masked = mask
masked |= nibbles[0] << 24
masked |= nibbles[1] << 16
masked |= nibbles[2] << 8
masked |= nibbles[3]
print "[+] masked: %.8X" % masked
dwords.append(masked)
for dword in dwords:
ret += struct.pack(endian + 'L', dword)
print "[+] returning .. %s" % ret
return align * 'A' + ret
def iso8859toascii(buf):
"""
00 -> 7F: ASCII
A0 -> FF: ISO8859
"""
table = {0x82:'e',
0xa1:'!', 0xa2:'c', 0xa3:'L', 0xa5:'Y', 0xa6:'|', 0xa7:'S', 0xa8:'"', 0xa9:'(c)', 0xab:'<<',
0xad:'-', 0xae:'(R)', 0xb0:'o', 0xb1:'+/-', 0xb2:'^2', 0xb3:'^3', 0xb4:'\'', 0xb5:'u', 0xb6:'P',
0xb8:',', 0xb9:'^1', 0xba:'o', 0xbb:'>>', 0xbc:'1/4', 0xbd:'1/2', 0xbe:'1/3', 0xbf:'?',
0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A', 0xc6:'AE', 0xc7:'C',
0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I',
0xd0:'D', 0xd1:'N', 0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd7:'x',
0xd8:'O', 0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U', 0xdd:'Y', 0xde:'b', 0xdf:'B',
0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a', 0xe6:'ae', 0xe7:'c',
0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i',
0xf0:'d', 0xf1:'ni', 0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf7:'%',
0xf8:'o', 0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u', 0xfd:'y', 0xfe:'b', 0xff:'y'}
ret = ""
for c in buf:
ordc = ord(c)
if table.has_key(ordc):
#devlog('iso8859toascii::replace', "0x%02x -> %s" % (ordc, table[ordc]))
ret += table[ordc]
else:
if ordc > 0x7f and ordc < 0xa0:
#devlog('iso8859toascii::missing', "not keeping non-ASCII char 0x%02x: %s" % (ordc, c))
ret += "?"
else:
#devlog('iso8859toascii::keep', "keeping ISO8859 char 0x%02x -> %s" % (ordc, c))
ret += c
return ret
letras = string.ascii_letters + string.ascii_uppercase + string.digits
def randomstring(length):
import random
return "".join([random.choice(letras) for a in range(0, length)])
def randomletters(size=6):
return ''.join(random.choice(string.ascii_letters) for x in range(size))
def xorstrings(a, b):
"""
Xors two string/list of chars together and returns the string result
b is the key, and if it is not long enough, it will be reused from the beginning
"""
tmp = []
for i in xrange(len(a)):
a1 = str(a[i])
b1 = str(b[i % len(b)])
c1 = ord(a1) ^ ord(b1)
tmp += [chr(c1)]
return "".join(tmp)
def hexify(astr):
"""
from \x41 to "\x41"
"""
ret = ""
for c in astr:
ret += "\\x%2.2x"%ord(c)
return ret
def prettydictprint(adict):
"""
print out a dictionary how I like it printed out ...
"""
keys = adict.keys()
keys.sort()
ret2 = "{"
for key in keys:
ret2 += "\"%s\" : \"%s\", "%(hexify(key),hexify(adict[key]))
ret2 += "}"
return ret2
def prettyhexprint(s,length=8):
"""
A nicely displayed hexdump as a string
"""
# we are expecting a string here
if not type(s) == type(""):
logging.error("Can not hexdump type %s" % type(s))
tmp = []
i = 1
for c in s:
tmp += ["%2.2x "%ord(c)]
if i % length == 0:
tmp += ["\n"]
i += 1
return "".join(tmp)
def cleanhexprint(s):
"""
turns ABCD
into
41424344
"""
tmp = []
for c in s:
tmp += ["%2.2x" % ord(c)]
return "".join(tmp)
# Note: this is a 5m lame function
def hexdump(buf):
tbl = []
tmp = ""
h = ""
i = 0
for a in buf:
h += "%02X " % ord(a)
i += 1
if ord(a) >= 0x20 and ord(a) < 0x7f:
tmp += a
else:
tmp += "."
if i % 16 == 0:
tbl.append((h, tmp))
h = ""
tmp = ""
tbl.append((h, tmp))
return tbl
def onlystrings(instr):
"""
prints out all the strings - ununicodes, etc
"""
instr = instr.replace("\x00","")
tmp = ""
space = 0
for ch in instr:
if (ch.isalnum() or ch in goodchars) and ord(ch) < 127:
tmp += ch
space = 0
else:
if not space:
tmp += " "
space = 1
return tmp
def iisuni(inint):
"""
Transforms an integer into %uXXYY%uZZAA - little endia order for IIS use
"""
ret = ""
ret += "%%u%4.4x%%u%4.4x" % (inint & 0xffff,((inint & 0xffff0000L) >> 16) & 0xffff)
return ret
def iisunibuf(buf):
"""
covert an entire buffer into IIS unicode format (note: makes 12 characters out of 4)
"""
ret = ""
mod = 4 - len(buf) % 4
if mod != 4:
buf += "\x00" * mod
while buf != "":
ret += "%%u%2.2x%2.2x%%u%2.2x%2.2x" % (ord(buf[1]), ord(buf[0]), ord(buf[3]), ord(buf[2]))
buf = buf[4:]
return ret
def htmlencode(buf):
"""
takes in a string and encodes it to change all HTML entities (& " etc) into their HTML escape codes
http://www.w3schools.com/xml/xml_cdata.asp
"""
buf = str(buf)
translation = { "<": "<" , ">": ">", "&": "&" }
for key in translation:
buf = buf.replace(key,translation[key])
return buf
def xmlencode(buf):
"""
takes in a string and encodes it to change all XML entities (& " etc) into their XML escape codes
http://www.w3schools.com/xml/xml_cdata.asp
"""
buf = str(buf)
translation = { "<": "<" , ">": ">", "&": "&", "'": "'", "\"": """ }
for key in translation:
buf = buf.replace(key,translation[key])
return buf
def xmldecode(buf):
"""
opposite of xmlencode()
"""
from xml.sax.saxutils import unescape as xmlunescape
return xmlunescape(buf, {"'": "'", """: '"'})
def urlencode(buf):
tmp = ""
for c in buf:
tmp += "%%%2.2x" % ord(c)
return tmp
def urluencode(buf):
tmp = []
bufsize = len(buf)
for c in range(0, bufsize - bufsize%2, 2):
tmp.append("%%u%02x%02x" % (ord(buf[c+1]), ord(buf[c]) ) )
if bufsize %2:
tmp.append( "%%u%02x41" % ord(buf[bufsize-1]) )
return string.joinfields(tmp, "")
def uuencode(buf):
import binascii
s = ""
l = 0
while l < len(buf):
s += binascii.b2a_uu(buf[l:l+45])
l += 45
return s
def uudecode(buf):
import binascii
# XXX do it for each line\n of buffer ?
return binascii.a2b_uu(buf)
def uuencode_file(buf, filename="file", filemode=0644):
return "begin %o %s\n%s`\nend" % (filemode & 0777, filename, uuencode(buf))
def b64encode(buf):
import binascii
return binascii.b2a_base64(buf)
def b64decode(buf):
import binascii
return binascii.a2b_base64(buf)
def indexable(var):
return hasattr(var, '__getitem__')
def sizeable(var):
return hasattr(var, '__len__')
def allowAddress(addr, badbytelist):
for a in range(0, 32, 8):
tmp = (addr >> a) & 0xff
if tmp in badbytelist:
return 0
return 1
def intel_hex(instring):
"""
reverses a string in hex
"""
instring = binstring(instring)
inlist = list(instring)
inlist.reverse()
instring = "".join(inlist)
return instring
def getbyte(buf):
"""
Gets one byte from the stream and returns it as an integer value
"""
return ord(buf[0]), buf[1:]
def getint(buf):
"""For reading an intel order integer out of a buffer
returns integer_in_intel_order, buf[4:]"""
return istr2int(buf), buf[4:]
def getshort(buf):
"""
Get an intel-orderd 16 bit integer from the buffer
returns <the integer>, <buffer[2:]>
"""
return istr2halfword(buf), buf[2:]
#return 1 if there is a bad character in an integer word (converted to a str).
#of course, if you pass a string in, we just handle it as a string
def hasbadchar(word,badchars):
try:
wordstr = intel_order(word)
except:
wordstr = str(word)
for ch in badchars:
if wordstr.count(ch):
return 1
return 0
#returns a string with every other byte in it
def everyother(buffer):
result = ""
i = 0
while i < len(buffer):
result += buffer[i]
i += 2
return result
def csub(a,b):
"""
Do subtraction like C does, with wrapover
don't automatically convert to a LONG integer,
which screws everything up
"""
#print "A=%8.8x - B=%8.8x"%(a,b)
c = uint32(a-b)
#print "C= %8.8x %s"%(c,str(type(c)))
return c
def istr2double(astring):
firsthalf = str2littleendian(astring)
secondhalf = str2littleendian(astring[4:])
return long(firsthalf) + (long(secondhalf) << 32)
def reversedword(myint): #just here for namespace
return reverseword(myint)
def reverseword(long):
data = intel_order(long)
ret = str2bigendian(data)
return ret
def reverseshort(myshort):
data = halfword2istr(myshort)
newshort = nstr2halfword(data)
return newshort
def s_intelword(myint):
return intel_order(myint)
def UTF16toUTF8(utf16buf):
"""Unicode to UTF-8 encoder, should be Windows compliant."""
utf8buf = ''
if (len(utf16buf) % 2) == 1:
utf16buf += '\x00'
for i in range(0, len(utf16buf), 2):
import struct
H = struct.unpack('<H',utf16buf[i:i + 2])[0]
#print '%d'%(H)
if H < 0x80:
utf8buf += utf16buf[i]
elif H < 0x800:
utf8buf += chr(0xc0 | ((ord(utf16buf[i + 1]) & 0xf) << 2) | (ord(utf16buf[i]) >> 6))
utf8buf += chr(0x80 | (ord(utf16buf[i]) & 0x3f))
else:
utf8buf += chr(0xe0 | (ord(utf16buf[i + 1]) >> 4))
utf8buf += chr(0x80 | ((ord(utf16buf[i + 1]) & 0xf) << 2) | (ord(utf16buf[i]) >> 6))
utf8buf += chr(0x80 | (ord(utf16buf[i]) & 0x3f))
return utf8buf
#returns a binary version of the string
def binstring(instring):
result = []
#erase all whitespace
tmp = instring.replace(" ","")
tmp = tmp.replace("\n","")
tmp = tmp.replace("\t","")
tmp = tmp.replace("\r","")
tmp = tmp.replace(",","")
if len(tmp) % 2 != 0:
logging.error("Tried to binstring something of illegal length: %d: *%s*" % (len(tmp), prettyprint(tmp)))
return ""
while tmp != "":
two = tmp[:2]
#account for 0x and \x stuff
if two != "0x" and two != "\\x":
result += [chr(int(two, 16))]
tmp = tmp[2:]
result = "".join(result)
return result
def pathunique(newpath):
if newpath not in sys.path:
sys.path.append(newpath)
def s_binary(instring):
"""
for spike compatability
"""
return binstring(instring)
#overwrites a string in place...hard to do in python
def stroverwrite(instring, overwritestring, offset):
"""
We use this in our exploits as a way to keep them clean.
str += str
str += str2 is bad form.
This api is more of a memcpy() which allows for easy setting of eip offsets and such.
"""
head = instring[:offset]
#print head
tail = instring[offset + len(overwritestring):]
#print tail
result = head + overwritestring + tail
return result
def getnullstring(instring):
null = instring.find("\x00")
if null == -1:
return instring
return instring[:null]
def sunrpcstr(instring, nonull=0):
ret = big_order(len(instring)) + sunstring(instring, nonull=nonull)
return ret
def pad4(instr):
return sunstring(instr, nonull=1)
def sunstring(instring, nonull=0):
"""
pads out a string with a null and to %4
"""
#print "instring=%s"%instring
ret = instring
if not nonull:
instring += chr(0)
padlen = 4 - len(ret) % 4
if padlen == 4:
padlen = 0
#print "Len=%d mod4=%d"%(len(ret),padlen)
ret += chr(0) * (padlen)
#print "hexofit=%s"%hexprint(ret)
return ret
def mod4string(astr):
return sunstring(astr)
def small_prettyprint(instring):
prtstring = prettyprint(instring)
if len(prtstring) > 100:
prtstring = prtstring[:50] + "..." + prtstring[-50:]
return prtstring
def cprint(instring):
"""
prints out a buffer the way C would like to see it
"""
tmp = ""
tmp = "\"" #add start quote
for ch in instring:
value = "\\x%2.2x" % ord(ch)
tmp += value
tmp += "\"" #add finish quote
return tmp
def getsitebase(url):
"""
Used by spkproxy.SPIDER() to get the site base of a url.
"""
return "".join(url.split("/")[2:3]) + "/"
#returns None on error
#returns a dictionary of a string split like a normal HTTP argument list
def splitargs(argstring, orderlist=[]):
resultDict = {}
templist = argstring.split("&")
for pair in templist:
if pair != "":
templist2 = pair.split("=")
if len(templist2) < 2:
#print "Failed to parse the URL arguments because of
#invalid number of equal signs in one argument in:
#\""+pair+"\" len="+str(len(templist2))
return None
else:
#add this argument to the Dict
orderlist.append(templist2[0])
resultDict[templist2[0]] = "=".join(templist2[1:])
return resultDict
def msunistring(instr):
"""Does a backwards string from a standard ASCII string and then adds two nulls"""
if instr in [0,None]:
# a null pointer ...
return None
ret = ""
ret += backwardsunistring(instr)
ret += "\x00\x00"
return ret
def hashit(obj):
"""
Returns a hashable object no matter what!
"""
stringit=False
try:
if obj in {}:
pass
except TypeError:
stringit = True
if stringit:
#unhashable object
return "%r" % (obj,)
else:
return obj
def str_from_object(obj, blacklist=None):
"""
Converts any object into a string representation
in a recursive fashion
"""
if blacklist == None:
blacklist = {}
ret = ""
if hashit(obj) in blacklist:
return "<blacklisted obj>"
#prevent recursive decent
if type(obj) in [type([]), type({})]:
blacklist[hashit(obj)] = True
if type(obj) == type([]):
#we have a list
ret += "["
for o in obj:
ret += str_from_object(o, blacklist)
ret += ","
ret = ret[:-1]
ret += "]"
elif type(obj) == type({}):
#dictionary
ret += "{"
for o in obj.keys():
ret += "%s: "%o
ret += str_from_object(obj[o], blacklist)
ret += ","
ret = ret[:-1]
ret += "}"
else:
ret += str(obj)
return ret
def int32toIpstr(uint, swap=False):
return socket.inet_ntoa(int2str32(uint, swap=swap))
def getNetworkInterfaces():
"""Returns a list of the network interface names on the current machine"""
ret = []
for i in getInterfaceData():
ret += [i[0]]
return ret
def parserouteprint(data):
"""
Instead of parsing the ipconfig /all which relies on English
text, we can pattern match a "route print" command much better.
With Adam's blessing we will deprecate parseipconfig()
"""
final_list = []
interface_count = 1
split_string = "=" * 75
route_table = data.split(split_string)[3].split("\n")
clean_route_table = route_table[3:len(route_table) - 2]
# Now walk through the table and obtain all of the
# interfaces and IP addresses
found_ips = {}
for route in clean_route_table:
entry = route.split(" ")
temp_list = []
for ip in entry:
if ip:
temp_list.append(ip)
if len(temp_list):
# Build our final list
ip_addr = temp_list[3].replace("\t","").replace("\n","")
if temp_list[1] != "255.255.255.255" and temp_list[1] != "0.0.0.0":
if not found_ips.has_key(ip_addr):
netmask = str2bigendian(socket.inet_aton(temp_list[1]))
final_list.append(["#%d" % interface_count, ip_addr, netmask])
found_ips[ip_addr] = netmask
interface_count += 1
return final_list
def parseIPV6IFS(data):
"""
Parses IPV6IFS.exe output in the form of 'IFID ADDRESS%SCOPE'
"""
import struct
ret = []
for a in data.split("\n"):
if a == "":
continue
b = a.split(" ")
devlog('parseIPV6IFS', b)
ifid = "#" + b[0]
addr = b[1]
logging.info("Win32 IPv6 parsed .. ifid %s -> addr %s" % (ifid, addr))
mask = "0xffffffffffffffff" # bogus mask for now BETA
if addr.find("error") != 0:
ret.append( [ifid, addr, mask] )
#print ret
return ret
def getIPv6FromInterfaceLinux(interface):
" Uses /proc/net/if_inet6 to get ipv6 addresses to interfaces "
#print "[!] checking for Linux IPv6 interfaces ..."
try:
fd = open("/proc/net/if_inet6", "r")
except IOError:
#print "[!] no Linux IPv6 information found"
return []
#print "[!] parsing if_inet6 for: %s"% interface
import struct
import string
addrlist = []
try:
# address, index, plen, scope, flags, interface
# fe80000000000000020c29fffe18aa1c 02 40 20 80 eth0
for line in fd.readlines():
iflist = line.split() # split on spaces
paddress = iflist[0] # the address in raw hex
plen = string.atoi(iflist[2], base=16) # XXX: netmask ?
pif = iflist[5] # the interface it's on
address = struct.unpack("4s4s4s4s4s4s4s4s", paddress) # we want a string
if interface in pif:
address = ':'.join(address) # to : form
import socket
# compress the address (google for the win!)
address = socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, address))
#print "[!] IPv6: %s -> %s/%s"% (interface, address, plen)
addrlist += [ [ address, plen ] ]
except:
import traceback
traceback.print_exc(file=sys.stderr)
#addrlist needs to be returned, but we're done parsing
pass
# return a list of found ipv6 addresses for that interface
return addrlist
def getInterfaceData(log_output = True):
"""
Get the Network adapters that are local to this machine
Linux/OS X: IPv4/IPv6/HWaddr
Win32: IPv4/HWaddr (IPv6 comming soon for boxen > WinXP)
returns a list of lists, each list has:
[iface_id (str), ip(str), netmask(str]
"""
from libs import get_interfaces
get_interfaces = get_interfaces.GetInterfaces()
get_interfaces()
interface_list = []
##From our container of all interfaces get each in turn
for iface in get_interfaces.interfaces:
##Then for each interface get each NetIface object
for ni_obj in get_interfaces.interfaces.get(iface):
try:
##This hack is required at c6 has never differentiated
## between address families and so has always been buggy
##NASTY solution as we have to use these crappy lists
## rather than use a NetIface object is to suffix the
## name
if ni_obj.family_name == "AF_INET6":
if_name = "%s-ipv6"%(ni_obj.name)
else:
if_name = ni_obj.name
interface_list.append([if_name,
ni_obj.addr['address'],
ni_obj.netmask['address']])
except:
continue
if log_output:
logging.info("Discovered interfaces:")
for iface in interface_list:
logging.info(" - %s" % iface)
return interface_list
def xordata(data,key):
ret = []
for ch in data:
ch = chr(ord(ch) ^ key)
ret += [ch]
return "".join(ret)
def get_source_ip(target):
"""
Returns an IP address to send out from given a target ip address or host
name
"""
#We fake a connection here just to find the callback interface
randport = random.randint(1,65534)
find_me = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#devlog("canvasengine","Connecting to %s:%d"%(target,randport))
try:
find_me.connect((target,randport))
except socket.error:
#could not assign requested address - i.e. we tried to connect
#to a 192.168.1.0 and the computer complained
#I dunno why it does this. It's super annoying.
#This will always happen on udpscan, for example
return None
callback_ip = find_me.getsockname()[0]
find_me.close()
return callback_ip
def getAllLocalIPs():
return getInterfaceData()
def getLocalIP():
"""
Gets the local IP via some dumb tricks with popen()
No good multiplatform way to do this though
"""
IP = getAllLocalIPs()[0][1]
return IP
def getIPfromARPTable():
"""
Read hosts out of the arp cache and add them to our list
"""
import os
ipList = []
if sys.platform == "win32" or os.name == "nt":
try:
if 0:
#canvas_win32api only exists for Python24
#so let's not do this
import canvas_win32api
arplist = canvas_win32api.GetARPEntryList()
for entry in arplist:
ipList += [int32toIpstr(entry['Addr'], swap=True)]
except:
pass
else:
try: # Linux at least
arplist = file("/proc/net/arp").readlines()[1:]
for entry in arplist:
if entry.count("00:00:00:00:00:00"):
continue
ipList += [entry.split(" ")[0]]
except IOError:
pass
return ipList
def read_bigendianword_packet(s):
data = s.recv(4)
#print "Data=%s"%prettyprint(data)
size = str2bigendian(data)
#print "Size=*%d*\n"%size
data = s.recv(size)
return data
def send_bigendian_halfword_packet(s, packet, additive=0):
length = len(packet) + additive
size = chr(length / 256 & 0xff)
size += chr(length & 0xff)
packet = size + packet
return s.send(packet)
def rrecv(sock, size):
retdata = ""
newsize = 0
while newsize < size:
data = sock.recv(1)
if data == "":
logging.error("Connection ended?!")
return retdata
retdata += data
newsize += len(data)
return retdata
def recv_bigendian_halfword_packet(sock, additive=0):
data = rrecv(sock,2)
#print "size is "+prettyprint(data)
size = ord(data[0])<<8
size += ord(data[1])
#print "Size of packet: %x"%size
data2 = rrecv(sock, size + additive)
return data2
def intelword_recv(s):
"""
This function recieves an intel_order 32 bit integer,
and then recieves that much data from the socket
It may throw the timeout exception if it did not get all
the data it expects
"""
data = s.recv(4)
#print "Data is "+prettyprint(data)
size = istr2int(data)
data = s.recv(size)
return data
def intelhalfword_recv(s):