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
28
29
30
35 devlog = __ignore
36 isdebug = __ignore
37 warnings_safely_ignore = __ignore
38 warning_restore = __ignore
39 deprecate = __ignore
40 uniqlist = __retsamearg
41
42
43
44
45
46
47
48
49
50 import types
51
53
55 if type(arg) == types.DictType:
56 d = {}
57 for item in arg.items():
58 d.__setitem__(item[0], item[1])
59 arg = d
60 return types.DictType.__init__(self, arg)
61
63 if type(itemvalue) == types.FloatType:
64 itemvalue = int(itemvalue)
65 return types.DictType.__setitem__(self, itemname, itemvalue)
66
68 item = types.DictType.__getitem__(self, itemname)
69 if type(item) == types.FloatType:
70 item = int(item)
71 return item
72
75
77 try:
78 wordstr=intel_order(word)
79 except:
80 wordstr=str(word)
81 for ch in badchars:
82 if wordstr.count(ch):
83 return 1
84 return 0
85
86
87
88
89
90
91
92
93
94
95
97 assert not bits % 8, "bits should be sizeof(char) aligned, got %d" % bits
98
100 if assertmsg != "":
101 assertmsg += "\n"
102 assert len(s) >= l, "%sexpecting a at_least_%d_chars string, got %d_chars instead.\nstring is: %s" % \
103 (assertmsg, l, len(s), prettyprint(s))
104
113
114
117
129
132
133
134
135
136
140
143
146
149
152
153
154
155
156
158 check_bits_consistancy(bits)
159 assert type(s) == type(""), "str2int_bits() expects a string argument, got %s" % type(s)
160 nchars = bits / 8
161 check_string_len(s, nchars, "str2int_bits(%d, s): string=<%s> len=%d" % (bits, s, len(s)))
162 r = 0
163 warnings_safely_ignore(FutureWarning)
164 for i in range(0, nchars):
165
166 r += ord(s[nchars-i-1]) << 8*i
167 warning_restore()
168 return r
169
173
176
179
182
185
188
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
207 """
208 oppposite of istr2int
209 """
210 return str2int32(astring)
211
212
213
216
218 check_bits_consistancy(bits)
219 r = 0
220 warnings_safely_ignore(FutureWarning)
221 for b in range(0, bits, 8):
222 r += (((i >> b) & 0xff) << (bits - (b + 8)))
223 warning_restore()
224 return r
225
228
231
234
235 """
236 istr2halfword(halfword2bstr(dInt(x))) == byteswap_16(x)
237 """
238
239
240
241
242
243
244
245
246
247
249 if not type(s) == type(""):
250 return "can not hexdump %s" % type(s)
251 tmp=""
252 for c in s:
253 tmp+="[0x%2.2x]"%ord(c)
254 return tmp
255
256 goodchars=".()~!#$%^&*()-=_/\\:<>"
257
259 import string
260 if not type(instring) == type(""):
261 devlog("prettyprint got %s and not string" % type(instring))
262 instring = str(instring)
263
264 tmp=""
265 for ch in instring:
266
267 if ch in string.printable and ch not in ["\x0c"]:
268 tmp+=ch
269 else:
270 value="%2.2x" % ord(ch)
271 tmp+="["+value+"]"
272
273 return tmp
274
276 if not type(data) == type(""):
277 devlog("c_array() got %s and not string" % type(data))
278 return "c_array() can not dump %s" % type(data)
279 if not len(data):
280 return "c_array() got void buffer"
281
282 ucharbuf = "unsigned char buf[] = \""
283 for uchar in data:
284 ucharbuf += "\\x%02x" % ord(uchar)
285 ucharbuf += "\"; // %d byte" % len(data)
286 if len(data) > 1:
287 ucharbuf += "s"
288 if desc:
289 ucharbuf += ", %s" % desc
290
291 return ucharbuf
292
293 -def shellcode_dump(sc, align=0, alignpad=" ", alignmax=16, mode=None):
294 import types
295 assert type(align) == type(0), "error in arguments, expecting an int for 'align'"
296 if not type(sc) in [types.StringType, types.BufferType]:
297 devlog("shellcode_dump() got %s and not string" % type(sc))
298 return type(sc)
299 if not len(sc):
300 return "void buffer"
301 if mode and mode.upper() == "RISC":
302 align=4
303 alignmax=4
304 if align:
305 alignmax *= align
306 buf = ""
307 i = 0
308 for c in sc:
309 buf += "%02x " % ord(c)
310 if align and (i % align) == (align - 1):
311 buf += alignpad
312 if alignmax and (i % alignmax) == (alignmax - 1):
313 buf += "\n"
314 i += 1
315 if buf[-1] == "\n":
316 buf = buf[:-1]
317 return buf
318
320 """
321 we just want to write some data on any fd, opened or closed.
322 """
323 import os
324 try:
325 os.write(fd, data)
326 except OSError, errargs:
327 import errno
328 if errargs.errno != errno.EBADF:
329 raise
330
332 sys.stderr.write("WARNING: %s\n" % msg)
333
334
335
336
337
338
339
340
341
343 binstr = ""
344 for bit in range(0, bits):
345 if i & (long(1) << bit):
346 binstr = "1" + binstr
347 else:
348 binstr = "0" + binstr
349 return binstr
350
353
356
359
362
365
368
371
372
373
374
375
376
377
378
379
381 """
382 Turns sint into an int, hopefully
383 python's int() doesn't handle negatives with base 0 well
384 """
385 if sint==None or type(sint) in [type( (1,1) ), type( [1]), type( {} ) ]:
386 devlog("Type ERROR: dInt(%s)!"%str(sint))
387
388 raise TypeError, "type %s for dInt(%s)" % (type(sint), str(sint))
389
390 s=str(sint)
391 if s[0:2]=="0x":
392 return long(s,0)
393 else:
394
395
396 return long(float(s))
397
399 """ returns [1,0,0,0,0,0,0,0] from "\x80"
400 """
401 if not bits:
402
403 bits=len(astr)*8
404 ret=[]
405
406 for c in astr:
407
408 mask=0x80
409 for i in range(0,8):
410
411 if mask & ord(c):
412 bit=1
413 else:
414 bit=0
415 ret+=[bit]
416 if len(ret)==bits:
417 break
418 mask=mask >> 1
419 return ret
420
422 mydict={"1":1,"0":0}
423 tmp=0
424 for c in mystr:
425 value=mydict[c]
426 tmp=(tmp<<1)+value
427 return tmp
428
429
431 tbl=[]
432 tmp=""
433 hex=""
434 i=0
435 for a in buf:
436 hex+="%02X "% ord(a)
437 i+=1
438 if ord(a) >=0x20 and ord(a) <0x7f:
439 tmp+=a
440 else:
441 tmp+="."
442 if i%16 == 0:
443 tbl.append((hex, tmp))
444 hex=""
445 tmp=""
446 tbl.append((hex, tmp))
447 return tbl
448
450 """
451 A nicely displayed hexdump as a string
452 """
453
454 if not type(s) == type(""):
455 return "can not hexdump %s" % type(s)
456 tmp=[]
457 i=1
458 for c in s:
459 tmp+=["%2.2x "%ord(c)]
460 if i%length==0:
461 tmp+=["\n"]
462 i+=1
463 return "".join(tmp)
464
465
466
469
471
472 c=dInt(c)
473
474
475
476 return c & ((long(1) << bits) - 1)
477
484
486 n = 1 << 3
487 while True:
488 if bits <= n:
489 break
490 n <<= 1
491 n /= 4
492 return "0x%%0%dx" % n
493
494
500
510
511 -def bits(myint, maxbits=32):
512 """counts the number of bits in an integer the slow way"""
513 b = 0
514 myint = uint_bits(maxbits, myint)
515 while myint >> b:
516 b += 1
517 return b
518
519
520
523
526
529
532
535
538
541
544
547
550
553
556
559
562
564 """
565 Checks for integer, hex or no
566 """
567 try:
568 num = int(str,0)
569 return 1
570 except ValueError:
571 return 0
572
573
574
575
576
577
578
579
580
581
582
584 deprecate("use sint16() instead")
585 return sint16(i)
586
588 deprecate("use sint32() instead")
589 return sint32(big)
590
592 assert sys.version_info[0] >= 2 and (sys.version_info[0] == 2 and sys.version_info[1] >= 4), \
593 "\nyou tried to call int2uns() but your python %d.%d is too old to handle it correctly\n" \
594 "Python versions before 2.4 are fucked up with integers, rely on 2.4 only!" % \
595 (sys.version_info[0], sys.version_info[1])
596 deprecate("use uint32() instead")
597 return uint32(small)
598
602
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
623 deprecate("use str2littleendian instead")
624 return str2littleendian(astring)
625
626
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 >>> print hexprint(halfword2bstr(0x1234))
658 [0x12][0x34]
659 >>> print hexprint(short2bigstr(0x1234))
660 [0x12][0x34]
661 >>> print hexprint("".join(int2list(uint16(0x1234))[2:4]))
662 [0x12][0x34]
663
664 >>> print hexprint(halfword2istr(0x1234))
665 [0x34][0x12]
666 >>> print hexprint("".join(int2list(byteswap_16(uint16(0x1234)))[2:4]))
667 [0x34][0x12]
668
669 >>> print uint16fmt(istr2halfword(halfword2bstr(dInt(0x1234))))
670 0x3412
671 >>> print uint16fmt(byteswap_16(0x1234))
672 0x3412
673
674 >>> print hexprint(halfword2bstr(0x1234))
675 [0x12][0x34]
676 >>> print hexprint(int2str_bits(16, 0x1234))
677 [0x12][0x34]
678 >>> print hexprint(halfword2bstr(0x12345678))
679 [0x56][0x78]
680 >>> print hexprint(int2str_bits(16, 0x12345678))
681 [0x56][0x78]
682 >>> print hexprint(int2str16(0x1234))
683 [0x12][0x34]
684 >>> print hexprint(int2str16(0x1234, swap=1))
685 [0x34][0x12]
686 >>> print hexprint(int2str16_swapped(0x1234))
687 [0x34][0x12]
688 """
689
693
697
700
703
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
741 """
742 Opposite of str2bigendian
743 """
744
745 return int2str32(int32)
746
748 """
749 bijection of str2littleendian()
750 """
751
752 return int2str32_swapped(int32)
753
754
755
756
757
758
759
760
761
762
763
764
765
769
771 if num == 0:
772 return '0'*32
773 if num < 0 :
774 return ''
775 ret=''
776
777 for a in range(0,32):
778 ret = str(num&0x1) + ret
779 num = num >> 1
780
781 return ret
782
783
784
785
786
787
788
789
790
791
792
793 if __name__=="__main__":
794
795 warnings_safely_ignore(FutureWarning)
796
797 - def test(funcname):
798 print "testing %s() ..." % funcname
799
800 print "running tests..."
801
802 test("split_int32")
803 assert split_int32(0x12345678) == [0x12, 0x34, 0x56, 0x78]
804
805 test("str2int16")
806 assert str2int16('\x12\x34\x56') == 0x1234
807 assert nstr2halfword('\x12\x34\x56\x78') == 0x1234
808
809 test("str2int16_swapped")
810 assert str2int16_swapped('\x12\x34') == 0x3412
811 assert istr2halfword('\x12\x34') == 0x3412
812 assert str2int16_swapped('\x12\x34\x56\x78') == 0x3412
813
814 test("str2littleendian")
815 assert str2littleendian('\x12\x34\x56\x78') == 0x78563412
816 assert intel_str2int('\x12\x34\x56\x78') == 0x78563412
817 assert istr2int('\x12\x34\x56\x78') == 0x78563412
818
819 test("str2bigendian/str2int32")
820 assert str2int32('\x12\x34\x56\x78') == 0x12345678
821 assert str2bigendian('\x12\x34\x56\x78') == 0x12345678
822
823 test("int2str16")
824 assert int2str16(0x1234) == '\x12\x34'
825 assert halfword2bstr(0x1234) == '\x12\x34'
826 assert short2bigstr(0x1234) == '\x12\x34'
827 assert big_short(0x1234) == '\x12\x34'
828
829 test("int2str16_swapped")
830 assert int2str16_swapped(0x1234) == '\x34\x12'
831 assert halfword2istr(0x1234) == '\x34\x12'
832 assert intel_short(0x1234) == '\x34\x12'
833 assert intel_short(0x12345678) == '\x78\x56'
834
835 test("int2str32")
836 assert int2str32(0x12345678) == '\x12\x34\x56\x78'
837 assert big_order(0x12345678) == '\x12\x34\x56\x78'
838
839 test("int2str32_swapped")
840 assert int2str32_swapped(0x12345678) == '\x78\x56\x34\x12'
841 assert intel_order(0x12345678) == '\x78\x56\x34\x12'
842
843 test("binary_string_int")
844 assert print_binary(0x12345678) == '00010010001101000101011001111000'
845
846 test("binary_string_int")
847 assert binary_string_short(0x12345678) == '0101011001111000'
848
849 try:
850 assert int2uns(-1) == 0xffffffffL
851 except AssertionError:
852 print "[!] failed: int2uns(-1) == 0xffffffff"
853 assert sys.version_info[0] >= 2, "word, what an old Python you have :/"
854 if sys.version_info[0] == 2 and sys.version_info[1] < 4:
855 print "Python 2.3 integers are fucked up, rely on 2.4 only!"
856 print "your version can not handle int2uns() correctly"
857 pass
858 else:
859 raise
860
861 test("uint16")
862 assert uint16(0xffff) == 0xffff
863 assert uint16(0x12345678) == 0x5678
864
865 test("sint16")
866 assert sint16(0xffff) == -1
867 assert sint16(0xffff) == sint16(-1)
868 assert signedshort(0xffff) == -1
869
870 test("sint32")
871 assert sint32(-1) == -1
872 assert big2int(0x123456789) == 0x23456789
873
874 test("uintfmt_bits")
875 assert uintfmt_bits(32, 0x12345678) == '0x12345678'
876 assert uintfmt_bits(32, 0x1234) == '0x00001234'
877 assert uintfmt_bits(24, 0x1234) == '0x00001234'
878 assert uintfmt_bits(16, 0x1234) == '0x1234'
879
880 test("uint16fmt")
881 assert uint16fmt(0x123456) == '0x3456'
882 assert uint16fmt(-0x123456) == '0xcbaa'
883
884 test("uint32fmt")
885 assert uint32fmt(0x1234) == '0x00001234'
886
887 test("uint64fmt")
888 assert uint64fmt(0x12345678) == '0x0000000012345678'
889 assert uint64fmt(-1) == '0xffffffffffffffff'
890
891 test("sint16fmt")
892 assert sint16fmt(0x1234) == '0x1234'
893 assert sint16fmt(-0x1234) == '-0x1234'
894 assert sint16fmt(-0x12345678) == '-0x5678'
895
896
897
898 test("sint32fmt")
899 assert sint32fmt(0x1234) == '0x00001234'
900 assert sint32fmt(-0x1234) == '-0x00001234'
901
902 test("sint64fmt")
903 assert sint64fmt(-1) == '-0x0000000000000001'
904
905 test("byteswap_32")
906 assert byteswap_32(0x12345678) == 0x78563412
907
908 test("byteswap_64")
909 assert byteswap_64(0x1234567890123456) == 0x5634129078563412
910
911
912 assert uint8fmt(0x0f) == '0x0f'
913
914 print "done."
915