-
Notifications
You must be signed in to change notification settings - Fork 73
/
netnode.py
388 lines (299 loc) · 9.96 KB
/
netnode.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
import logging
import struct
from collections import namedtuple
import six
logger = logging.getLogger(__name__)
def uint32(i):
"""
Convert the given signed number into its 32-bit little endian unsigned number value.
Example::
assert uint32(-1) == 0xFFFFFFFF
Example::
assert uint32(1) == 1
"""
return struct.unpack(">I", struct.pack(">i", i))[0]
def uint64(i):
"""
Convert the given signed number into its 64-bit little endian unsigned number value.
Example::
assert uint64(-1) == 0xFFFFFFFFFFFFFFFF
Example::
assert uint64(1) == 1
"""
return struct.unpack(">Q", struct.pack(">q", i))[0]
class TAGS:
"""
via: https://www.hex-rays.com/products/ida/support/sdkdoc/group__nn__res.html#gaedcc558fe55e19ebc6e304ba7ad8c4d6
"""
ALTVAL = "A"
SUPVAL = "S"
CHARVAL = "C" # this is just a guess...
HASHVAL = "H"
VALUE = "V"
NAME = "N"
LINK = "L"
def make_key(nodeid, tag=None, index=None, wordsize=4):
"""
Example::
k = make_key('Root Node')
Example::
k = make_key(0x401000, 'X')
Example::
k = make_key(0x401000, 'X', 0x4010A24)
"""
if wordsize == 4:
wordformat = "I"
elif wordsize == 8:
wordformat = "Q"
else:
raise ValueError("unexpected wordsize")
if isinstance(nodeid, six.string_types):
return b"N" + nodeid.encode("utf-8")
elif isinstance(nodeid, six.integer_types):
if tag is None:
raise ValueError("tag required")
if not isinstance(tag, str):
raise ValueError("tag must be a string")
if len(tag) != 1:
raise ValueError("tag must be a single character string")
tag = tag.encode("ascii")
if index is None:
return b"." + struct.pack(">" + wordformat + "c", nodeid, tag)
elif index < 0:
return b"." + struct.pack(
">" + wordformat + "c" + wordformat.lower(), nodeid, tag, index
)
else:
return b"." + struct.pack(
">" + wordformat + "c" + wordformat, nodeid, tag, index
)
else:
raise ValueError("unexpected type of nodeid: " + str(type(nodeid)))
ComplexKey = namedtuple("ComplexKey", ["nodeid", "tag", "index"])
TAG_LENGTH = 1
KEY_HEADER_LENGTH = 1
def parse_key(buf, wordsize=4):
if six.indexbytes(buf, 0x0) != 0x2E:
raise ValueError("buf is not a complex key")
if wordsize == 4:
wordformat = "I"
elif wordsize == 8:
wordformat = "Q"
else:
raise ValueError("unexpected wordsize")
nodeid, tag = struct.unpack_from(">" + wordformat + "c", buf, 1)
tag = tag.decode("ascii")
if len(buf) >= TAG_LENGTH + 2 * wordsize + KEY_HEADER_LENGTH:
offset = TAG_LENGTH + KEY_HEADER_LENGTH + wordsize
index = struct.unpack_from(">" + wordformat, buf, offset)[0]
else:
index = None
return ComplexKey(nodeid, tag, index)
def as_uint(buf, wordsize=None):
if len(buf) == 1:
return struct.unpack("<B", buf)[0]
elif len(buf) == 2:
return struct.unpack("<H", buf)[0]
elif len(buf) == 4:
return struct.unpack("<L", buf)[0]
elif len(buf) == 8:
return struct.unpack("<Q", buf)[0]
else:
return RuntimeError("unexpected buf size")
def as_int(buf, wordsize=None):
if len(buf) == 1:
return struct.unpack("<b", buf)[0]
elif len(buf) == 2:
return struct.unpack("<h", buf)[0]
elif len(buf) == 4:
return struct.unpack("<l", buf)[0]
elif len(buf) == 8:
return struct.unpack("<q", buf)[0]
else:
return RuntimeError("unexpected buf size")
def as_string(buf, wordsize=None):
return bytes(buf).rstrip(b"\x00").decode("utf-8").rstrip("\x00")
# try to implement the methods here:
#
# https://www.hex-rays.com/products/ida/support/sdkdoc/classnetnode.html
Entry = namedtuple("Entry", ["key", "parsed_key", "value"])
class Netnode(object):
def __init__(self, db, nodeid):
"""
Args:
db (idb.IDB): the IDA Pro database.
nodeid (Union[str, int]): the node id used to identify the netnode.
Example::
nn = Netnode("Root Node")
print(nn.supval(1303)) # --> "6.95"
Example::
nn = Netnode(0x401000)
for xref in nn.alts(tag='X'):
print(xref)
TODO: how to address the following keys:
- $ MAX LINK
- $ MAX NODE
- $ MAX DESC
these are unaddressable via IDA Pro netnodes, too.
"""
self.idb = db
self.wordsize = self.idb.wordsize
if self.wordsize == 4:
self.nodebase = 0xFF000000
elif self.wordsize == 8:
self.nodebase = 0xFF00000000000000
else:
raise RuntimeError("unexpected wordsize")
if isinstance(nodeid, six.string_types):
key = make_key(nodeid, wordsize=self.wordsize)
cursor = self.idb.id0.find(key)
self.nodeid = as_uint(cursor.value)
logger.info("resolved string netnode %s to %x", nodeid, self.nodeid)
elif isinstance(nodeid, six.integer_types):
self.nodeid = nodeid
else:
raise ValueError("unexpected type for nodeid")
@staticmethod
def get_nodebase(db):
if db.wordsize == 4:
return 0xFF000000
elif db.wordsize == 8:
return 0xFF00000000000000
def name(self):
"""
fetch the name associated with the netnode.
basically supval(tag='N')
Returns:
str: the name stored in the netnode.
Raises:
KeyError: if the name for the netnode does not exist.
"""
key = make_key(self.nodeid, TAGS.NAME, wordsize=self.wordsize)
cursor = self.idb.id0.find(key)
return as_string(cursor.value)
def get_tag_entries(self, tag=TAGS.SUPVAL):
"""
generate the entries for the given tag in this netnode.
this replaces:
- *1st
- *nxt
- *last
- *prev
Yields:
Entry: an entry (with key and value) under the given tag in this netnode.
"""
key = make_key(self.nodeid, tag, wordsize=self.wordsize)
try:
cursor = self.idb.id0.find_prefix(key)
except KeyError:
return
while bytes(cursor.key).startswith(key):
parsed_key = parse_key(cursor.key, wordsize=self.idb.wordsize)
yield Entry(cursor.key, parsed_key, bytes(cursor.value))
try:
cursor.next()
except IndexError:
break
def get_val(self, index, tag=TAGS.SUPVAL):
"""
fetch a sup/alt/hash/etc value from the netnode.
the nodeid for this netnode must be an integer/effective address.
Args:
index (int): the index of the data to fetch.
tag (str): single character tag.
Returns:
bytes: the raw data.
"""
key = make_key(self.nodeid, tag, index, wordsize=self.wordsize)
cursor = self.idb.id0.find(key)
return bytes(cursor.value)
def supval(self, index, tag=TAGS.SUPVAL):
return self.get_val(index, tag)
def supstr(self, index, tag=TAGS.SUPVAL):
return as_string(self.supval(index, tag))
def sups(self, tag=TAGS.SUPVAL):
"""
this replaces:
- sup1st
- supnxt
- suplast
- supprev
"""
for entry in self.get_tag_entries(tag=tag):
yield entry.parsed_key.index
def supentries(self, tag=TAGS.SUPVAL):
for entry in self.get_tag_entries(tag=tag):
yield entry
def altval(self, index, tag=TAGS.ALTVAL):
return as_int(self.get_val(index, tag))
def alts(self, tag=TAGS.ALTVAL):
"""
this replaces:
- alt1st
- altnxt
- altlast
- altprev
"""
for entry in self.get_tag_entries(tag=tag):
yield entry.parsed_key.index
def altentries(self, tag=TAGS.ALTVAL):
for entry in self.get_tag_entries(tag=tag):
# TODO: cast the value?
yield entry
def charval(self, index, tag=TAGS.CHARVAL):
return as_int(self.get_val(index, tag))
def chars(self, tag=TAGS.ALTVAL):
"""
this replaces:
- char1st
- charnxt
- charlast
- charprev
"""
for entry in self.get_tag_entries(tag=tag):
yield entry.parsed_key.index
def charentries(self, tag=TAGS.CHARVAL):
for entry in self.get_tag_entries(tag=tag):
yield Entry(entry.key, entry.parsed_key, as_int(entry.value))
def hashval(self, index, tag=TAGS.HASHVAL):
"""
TODO: how is this different from a supval?
"""
return self.get_val(index, tag)
def hashes(self, tag=TAGS.HASHVAL):
"""
this replaces:
- hash1st
- hashnxt
- hashlast
- hashprev
"""
for entry in self.get_tag_entries(tag=tag):
yield entry.parsed_key.index
def hashentries(self, tag=TAGS.HASHVAL):
for entry in self.get_tag_entries(tag=tag):
yield entry
def valobj(self):
"""
fetch the default netnode value.
this is basically supval(tag='V').
"""
key = make_key(self.nodeid, TAGS.VALUE, wordsize=self.wordsize)
cursor = self.idb.id0.find(key)
return bytes(cursor.value)
def valstr(self):
return as_string(self.valobj())
def value_exists(self):
try:
return self.valobj() is not None
except KeyError:
return False
def long_value(self):
return as_uint(self.valobj())
def blobsize(self):
"""
TODO: how is this arbitrary data stored?
"""
raise NotImplementedError()
def getblob(self):
raise NotImplementedError()