|
Package Libs ::
Module immutils
|
|
1
2
3 """
4 (c) Immunity, Inc. 2004-2007
5
6
7 U{Immunity Inc.<http://www.immunityinc.com>}
8
9
10 MOSDEF utils for non-CANVAS users
11
12 """
13
14
15 __VERSION__ = '1.0'
16
17
18
19
20
21
22
23
24
25
26 import sys, os
27 sys.path.append('.')
28
29
30
31
36 devlog = __ignore
37 isdebug = __ignore
38 warnings_safely_ignore = __ignore
39 warning_restore = __ignore
40 deprecate = __ignore
41 uniqlist = __retsamearg
42
43
44
45
46
47
48
49
50
51 _MOSDEFimport_hook = True
52 _MOSDEFimport_cachefailedimport = True
53
54
55
56
57
58 from traceback import format_exc
63 modname = args[0]
64 if __debug__:
65 if len(args) < 4 or args[3] == None:
66 devlog('MOSDEFimport', "IMPORT %s" % modname)
67 else:
68 if len(args[3]) == 1:
69 val = args[3][0]
70 else:
71 val = str(args[3])[1:-1]
72 devlog('MOSDEFimport', "FROM %s IMPORT %s" % (modname, val), nofile = True)
73 if _MOSDEFimport_cachefailedimport:
74 modhash = mod_hash(modname)
75 if modhash in _failed_imported_module_table:
76 devlog('MOSDEFimport', "already failed to import <%s>" % modname, nofile = True)
77 raise ImportError
78 cwd = os.getcwd()
79 filepath = os.path.dirname(globals()['__file__'])
80 mosdefpath = filepath.replace(cwd, ".")
81
82
83
84 sys.path = uniqlist(sys.path)
85 if cwd != mosdefpath and mosdefpath not in sys.path:
86 sys.path.insert(0, mosdefpath)
87 import_time = time.time()
88 try:
89 return sys.modules['__builtin__'].__import__orig(*args)
90 except:
91 if _MOSDEFimport_cachefailedimport:
92 _failed_imported_module_table += [modhash]
93 devlog('all', "failed to import <%s> (lost %ss)" % (modname, time.time() - import_time), nofile = True)
94 devlog('ImportError', format_exc(0).split('\n')[1], nodesc = True)
95 if isdebug('ImportErrorTrace'):
96 backtrace()
97 raise
98 import __builtin__
99 if _MOSDEFimport_hook and not hasattr(__builtin__, '__import__orig'):
100 import time
101 __builtin__.__import__orig = __builtin__.__import__
102 __builtin__.__import__ = __MOSDEFimport__
103 _MOSDEFimport_hook = False
104 _failed_imported_module_table = []
105 devlog('all', "__import__ hooked with __MOSDEFimport__")
106 del __builtin__
107
108
109
110
111
112
113
114
115
116
117
118 import types
119
121
123 if type(arg) == types.DictType:
124 d = {}
125 for item in arg.items():
126 d.__setitem__(item[0], item[1])
127 arg = d
128 return types.DictType.__init__(self, arg)
129
131 if type(itemvalue) == types.FloatType:
132 itemvalue = int(itemvalue)
133 return types.DictType.__setitem__(self, itemname, itemvalue)
134
136 item = types.DictType.__getitem__(self, itemname)
137 if type(item) == types.FloatType:
138 item = int(item)
139 return item
140
143
145 try:
146 wordstr=intel_order(word)
147 except:
148 wordstr=str(word)
149 for ch in badchars:
150 if wordstr.count(ch):
151 return 1
152 return 0
153
154
155
156
157
158
159
160
161
162
163
165 assert not bits % 8, "bits should be sizeof(char) aligned, got %d" % bits
166
168 if assertmsg != "":
169 assertmsg += "\n"
170 assert len(s) >= l, "%sexpecting a at_least_%d_chars string, got %d_chars instead.\nstring is: %s" % \
171 (assertmsg, l, len(s), prettyprint(s))
172
181
182
185
197
200
201
202
203
204
208
211
214
217
220
221
222
223
224
226 check_bits_consistancy(bits)
227 assert type(s) == type(""), "str2int_bits() expects a string argument, got %s" % type(s)
228 nchars = bits / 8
229 check_string_len(s, nchars, "str2int_bits(%d, s): string=<%s> len=%d" % (bits, s, len(s)))
230 r = 0
231 warnings_safely_ignore(FutureWarning)
232 for i in range(0, nchars):
233
234 r += ord(s[nchars-i-1]) << 8*i
235 warning_restore()
236 return r
237
241
244
247
250
253
256
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
275 """
276 oppposite of istr2int
277 """
278 return str2int32(astring)
279
280
281
284
286 check_bits_consistancy(bits)
287 r = 0
288 warnings_safely_ignore(FutureWarning)
289 for b in range(0, bits, 8):
290 r += (((i >> b) & 0xff) << (bits - (b + 8)))
291 warning_restore()
292 return r
293
296
299
302
303 """
304 istr2halfword(halfword2bstr(dInt(x))) == byteswap_16(x)
305 """
306
307
308
309
310
311
312
313
314
315
317 if not type(s) == type(""):
318 return "can not hexdump %s" % type(s)
319 tmp=""
320 for c in s:
321 tmp+="[0x%2.2x]"%ord(c)
322 return tmp
323
324 goodchars=".()~!#$%^&*()-=_/\\:<>"
325
327 import string
328 if not type(instring) == type(""):
329 devlog("prettyprint got %s and not string" % type(instring))
330 instring = str(instring)
331
332 tmp=""
333 for ch in instring:
334
335 if ch in string.printable and ch not in ["\x0c"]:
336 tmp+=ch
337 else:
338 value="%2.2x" % ord(ch)
339 tmp+="["+value+"]"
340
341 return tmp
342
344 if not type(data) == type(""):
345 devlog("c_array() got %s and not string" % type(data))
346 return "c_array() can not dump %s" % type(data)
347 if not len(data):
348 return "c_array() got void buffer"
349
350 ucharbuf = "unsigned char buf[] = \""
351 for uchar in data:
352 ucharbuf += "\\x%02x" % ord(uchar)
353 ucharbuf += "\"; // %d byte" % len(data)
354 if len(data) > 1:
355 ucharbuf += "s"
356 if desc:
357 ucharbuf += ", %s" % desc
358
359 return ucharbuf
360
361 -def shellcode_dump(sc, align=0, alignpad=" ", alignmax=16, mode=None):
362 import types
363 assert type(align) == type(0), "error in arguments, expecting an int for 'align'"
364 if not type(sc) in [types.StringType, types.BufferType]:
365 devlog("shellcode_dump() got %s and not string" % type(sc))
366 return type(sc)
367 if not len(sc):
368 return "void buffer"
369 if mode and mode.upper() == "RISC":
370 align=4
371 alignmax=4
372 if align:
373 alignmax *= align
374 buf = ""
375 i = 0
376 for c in sc:
377 buf += "%02x " % ord(c)
378 if align and (i % align) == (align - 1):
379 buf += alignpad
380 if alignmax and (i % alignmax) == (alignmax - 1):
381 buf += "\n"
382 i += 1
383 if buf[-1] == "\n":
384 buf = buf[:-1]
385 return buf
386
388 """
389 we just want to write some data on any fd, opened or closed.
390 """
391 import os
392 try:
393 os.write(fd, data)
394 except OSError, errargs:
395 import errno
396 if errargs.errno != errno.EBADF:
397 raise
398
400 sys.stderr.write("WARNING: %s\n" % msg)
401
402
403
404
405
406
407
408
409
411 binstr = ""
412 for bit in range(0, bits):
413 if i & (long(1) << bit):
414 binstr = "1" + binstr
415 else:
416 binstr = "0" + binstr
417 return binstr
418
421
424
427
430
433
436
439
440
441
442
443
444
445
446
447
449 """
450 Turns sint into an int, hopefully
451 python's int() doesn't handle negatives with base 0 well
452 """
453 if sint==None or type(sint) in [type( (1,1) ), type( [1]), type( {} ) ]:
454 devlog("Type ERROR: dInt(%s)!"%str(sint))
455
456 raise TypeError, "type %s for dInt(%s)" % (type(sint), str(sint))
457
458 s=str(sint)
459 if s[0:2]=="0x":
460 return long(s,0)
461 else:
462
463
464 return long(float(s))
465
467 """ returns [1,0,0,0,0,0,0,0] from "\x80"
468 """
469 if not bits:
470
471 bits=len(astr)*8
472 ret=[]
473
474 for c in astr:
475
476 mask=0x80
477 for i in range(0,8):
478
479 if mask & ord(c):
480 bit=1
481 else:
482 bit=0
483 ret+=[bit]
484 if len(ret)==bits:
485 break
486 mask=mask >> 1
487 return ret
488
490 mydict={"1":1,"0":0}
491 tmp=0
492 for c in mystr:
493 value=mydict[c]
494 tmp=(tmp<<1)+value
495 return tmp
496
497
499 tbl=[]
500 tmp=""
501 hex=""
502 i=0
503 for a in buf:
504 hex+="%02X "% ord(a)
505 i+=1
506 if ord(a) >=0x20 and ord(a) <0x7f:
507 tmp+=a
508 else:
509 tmp+="."
510 if i%16 == 0:
511 tbl.append((hex, tmp))
512 hex=""
513 tmp=""
514 tbl.append((hex, tmp))
515 return tbl
516
518 """
519 A nicely displayed hexdump as a string
520 """
521
522 if not type(s) == type(""):
523 return "can not hexdump %s" % type(s)
524 tmp=[]
525 i=1
526 for c in s:
527 tmp+=["%2.2x "%ord(c)]
528 if i%length==0:
529 tmp+=["\n"]
530 i+=1
531 return "".join(tmp)
532
533
534
537
539
540 c=dInt(c)
541
542
543
544 return c & ((long(1) << bits) - 1)
545
552
554 n = 1 << 3
555 while True:
556 if bits <= n:
557 break
558 n <<= 1
559 n /= 4
560 return "0x%%0%dx" % n
561
562
568
578
579 -def bits(myint, maxbits=32):
580 """counts the number of bits in an integer the slow way"""
581 b = 0
582 myint = uint_bits(maxbits, myint)
583 while myint >> b:
584 b += 1
585 return b
586
587
588
591
594
597
600
603
606
609
612
615
618
621
624
627
630
632 """
633 Checks for integer, hex or no
634 """
635 try:
636 num = int(str,0)
637 return 1
638 except ValueError:
639 return 0
640
641
642
643
644
645
646
647
648
649
650
652 deprecate("use sint16() instead")
653 return sint16(i)
654
656 deprecate("use sint32() instead")
657 return sint32(big)
658
660 assert sys.version_info[0] >= 2 and (sys.version_info[0] == 2 and sys.version_info[1] >= 4), \
661 "\nyou tried to call int2uns() but your python %d.%d is too old to handle it correctly\n" \
662 "Python versions before 2.4 are fucked up with integers, rely on 2.4 only!" % \
663 (sys.version_info[0], sys.version_info[1])
664 deprecate("use uint32() instead")
665 return uint32(small)
666
670
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
691 deprecate("use str2littleendian instead")
692 return str2littleendian(astring)
693
694
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 >>> print hexprint(halfword2bstr(0x1234))
726 [0x12][0x34]
727 >>> print hexprint(short2bigstr(0x1234))
728 [0x12][0x34]
729 >>> print hexprint("".join(int2list(uint16(0x1234))[2:4]))
730 [0x12][0x34]
731
732 >>> print hexprint(halfword2istr(0x1234))
733 [0x34][0x12]
734 >>> print hexprint("".join(int2list(byteswap_16(uint16(0x1234)))[2:4]))
735 [0x34][0x12]
736
737 >>> print uint16fmt(istr2halfword(halfword2bstr(dInt(0x1234))))
738 0x3412
739 >>> print uint16fmt(byteswap_16(0x1234))
740 0x3412
741
742 >>> print hexprint(halfword2bstr(0x1234))
743 [0x12][0x34]
744 >>> print hexprint(int2str_bits(16, 0x1234))
745 [0x12][0x34]
746 >>> print hexprint(halfword2bstr(0x12345678))
747 [0x56][0x78]
748 >>> print hexprint(int2str_bits(16, 0x12345678))
749 [0x56][0x78]
750 >>> print hexprint(int2str16(0x1234))
751 [0x12][0x34]
752 >>> print hexprint(int2str16(0x1234, swap=1))
753 [0x34][0x12]
754 >>> print hexprint(int2str16_swapped(0x1234))
755 [0x34][0x12]
756 """
757
761
765
768
771
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
809 """
810 Opposite of str2bigendian
811 """
812
813 return int2str32(int32)
814
816 """
817 bijection of str2littleendian()
818 """
819
820 return int2str32_swapped(int32)
821
822
823
824
825
826
827
828
829
830
831
832
833
837
839 if num == 0:
840 return '0'*32
841 if num < 0 :
842 return ''
843 ret=''
844
845 for a in range(0,32):
846 ret = str(num&0x1) + ret
847 num = num >> 1
848
849 return ret
850
851
852
853
854
855
856
857
858
859
860
861 if __name__=="__main__":
862
863 warnings_safely_ignore(FutureWarning)
864
865 - def test(funcname):
866 print "testing %s() ..." % funcname
867
868 print "running tests..."
869
870 test("split_int32")
871 assert split_int32(0x12345678) == [0x12, 0x34, 0x56, 0x78]
872
873 test("str2int16")
874 assert str2int16('\x12\x34\x56') == 0x1234
875 assert nstr2halfword('\x12\x34\x56\x78') == 0x1234
876
877 test("str2int16_swapped")
878 assert str2int16_swapped('\x12\x34') == 0x3412
879 assert istr2halfword('\x12\x34') == 0x3412
880 assert str2int16_swapped('\x12\x34\x56\x78') == 0x3412
881
882 test("str2littleendian")
883 assert str2littleendian('\x12\x34\x56\x78') == 0x78563412
884 assert intel_str2int('\x12\x34\x56\x78') == 0x78563412
885 assert istr2int('\x12\x34\x56\x78') == 0x78563412
886
887 test("str2bigendian/str2int32")
888 assert str2int32('\x12\x34\x56\x78') == 0x12345678
889 assert str2bigendian('\x12\x34\x56\x78') == 0x12345678
890
891 test("int2str16")
892 assert int2str16(0x1234) == '\x12\x34'
893 assert halfword2bstr(0x1234) == '\x12\x34'
894 assert short2bigstr(0x1234) == '\x12\x34'
895 assert big_short(0x1234) == '\x12\x34'
896
897 test("int2str16_swapped")
898 assert int2str16_swapped(0x1234) == '\x34\x12'
899 assert halfword2istr(0x1234) == '\x34\x12'
900 assert intel_short(0x1234) == '\x34\x12'
901 assert intel_short(0x12345678) == '\x78\x56'
902
903 test("int2str32")
904 assert int2str32(0x12345678) == '\x12\x34\x56\x78'
905 assert big_order(0x12345678) == '\x12\x34\x56\x78'
906
907 test("int2str32_swapped")
908 assert int2str32_swapped(0x12345678) == '\x78\x56\x34\x12'
909 assert intel_order(0x12345678) == '\x78\x56\x34\x12'
910
911 test("binary_string_int")
912 assert print_binary(0x12345678) == '00010010001101000101011001111000'
913
914 test("binary_string_int")
915 assert binary_string_short(0x12345678) == '0101011001111000'
916
917 try:
918 assert int2uns(-1) == 0xffffffffL
919 except AssertionError:
920 print "[!] failed: int2uns(-1) == 0xffffffff"
921 assert sys.version_info[0] >= 2, "word, what an old Python you have :/"
922 if sys.version_info[0] == 2 and sys.version_info[1] < 4:
923 print "Python 2.3 integers are fucked up, rely on 2.4 only!"
924 print "your version can not handle int2uns() correctly"
925 pass
926 else:
927 raise
928
929 test("uint16")
930 assert uint16(0xffff) == 0xffff
931 assert uint16(0x12345678) == 0x5678
932
933 test("sint16")
934 assert sint16(0xffff) == -1
935 assert sint16(0xffff) == sint16(-1)
936 assert signedshort(0xffff) == -1
937
938 test("sint32")
939 assert sint32(-1) == -1
940 assert big2int(0x123456789) == 0x23456789
941
942 test("uintfmt_bits")
943 assert uintfmt_bits(32, 0x12345678) == '0x12345678'
944 assert uintfmt_bits(32, 0x1234) == '0x00001234'
945 assert uintfmt_bits(24, 0x1234) == '0x00001234'
946 assert uintfmt_bits(16, 0x1234) == '0x1234'
947
948 test("uint16fmt")
949 assert uint16fmt(0x123456) == '0x3456'
950 assert uint16fmt(-0x123456) == '0xcbaa'
951
952 test("uint32fmt")
953 assert uint32fmt(0x1234) == '0x00001234'
954
955 test("uint64fmt")
956 assert uint64fmt(0x12345678) == '0x0000000012345678'
957 assert uint64fmt(-1) == '0xffffffffffffffff'
958
959 test("sint16fmt")
960 assert sint16fmt(0x1234) == '0x1234'
961 assert sint16fmt(-0x1234) == '-0x1234'
962 assert sint16fmt(-0x12345678) == '-0x5678'
963
964
965
966 test("sint32fmt")
967 assert sint32fmt(0x1234) == '0x00001234'
968 assert sint32fmt(-0x1234) == '-0x00001234'
969
970 test("sint64fmt")
971 assert sint64fmt(-1) == '-0x0000000000000001'
972
973 test("byteswap_32")
974 assert byteswap_32(0x12345678) == 0x78563412
975
976 test("byteswap_64")
977 assert byteswap_64(0x1234567890123456) == 0x5634129078563412
978
979
980 assert uint8fmt(0x0f) == '0x0f'
981
982 print "done."
983