|
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