structure.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. from __future__ import print_function
  2. # Copyright (c) 2003-2016 CORE Security Technologies
  3. #
  4. # This software is provided under under a slightly modified version
  5. # of the Apache Software License. See the accompanying LICENSE file
  6. # for more information.
  7. #
  8. from struct import pack, unpack, calcsize
  9. class Structure:
  10. """ sublcasses can define commonHdr and/or structure.
  11. each of them is an tuple of either two: (fieldName, format) or three: (fieldName, ':', class) fields.
  12. [it can't be a dictionary, because order is important]
  13. where format specifies how the data in the field will be converted to/from bytes (string)
  14. class is the class to use when unpacking ':' fields.
  15. each field can only contain one value (or an array of values for *)
  16. i.e. struct.pack('Hl',1,2) is valid, but format specifier 'Hl' is not (you must use 2 dfferent fields)
  17. format specifiers:
  18. specifiers from module pack can be used with the same format
  19. see struct.__doc__ (pack/unpack is finally called)
  20. x [padding byte]
  21. c [character]
  22. b [signed byte]
  23. B [unsigned byte]
  24. h [signed short]
  25. H [unsigned short]
  26. l [signed long]
  27. L [unsigned long]
  28. i [signed integer]
  29. I [unsigned integer]
  30. q [signed long long (quad)]
  31. Q [unsigned long long (quad)]
  32. s [string (array of chars), must be preceded with length in format specifier, padded with zeros]
  33. p [pascal string (includes byte count), must be preceded with length in format specifier, padded with zeros]
  34. f [float]
  35. d [double]
  36. = [native byte ordering, size and alignment]
  37. @ [native byte ordering, standard size and alignment]
  38. ! [network byte ordering]
  39. < [little endian]
  40. > [big endian]
  41. usual printf like specifiers can be used (if started with %)
  42. [not recommeneded, there is no why to unpack this]
  43. %08x will output an 8 bytes hex
  44. %s will output a string
  45. %s\\x00 will output a NUL terminated string
  46. %d%d will output 2 decimal digits (against the very same specification of Structure)
  47. ...
  48. some additional format specifiers:
  49. : just copy the bytes from the field into the output string (input may be string, other structure, or anything responding to __str__()) (for unpacking, all what's left is returned)
  50. z same as :, but adds a NUL byte at the end (asciiz) (for unpacking the first NUL byte is used as terminator) [asciiz string]
  51. u same as z, but adds two NUL bytes at the end (after padding to an even size with NULs). (same for unpacking) [unicode string]
  52. w DCE-RPC/NDR string (it's a macro for [ '<L=(len(field)+1)/2','"\\x00\\x00\\x00\\x00','<L=(len(field)+1)/2',':' ]
  53. ?-field length of field named 'field', formated as specified with ? ('?' may be '!H' for example). The input value overrides the real length
  54. ?1*?2 array of elements. Each formated as '?2', the number of elements in the array is stored as specified by '?1' (?1 is optional, or can also be a constant (number), for unpacking)
  55. 'xxxx literal xxxx (field's value doesn't change the output. quotes must not be closed or escaped)
  56. "xxxx literal xxxx (field's value doesn't change the output. quotes must not be closed or escaped)
  57. _ will not pack the field. Accepts a third argument, which is an unpack code. See _Test_UnpackCode for an example
  58. ?=packcode will evaluate packcode in the context of the structure, and pack the result as specified by ?. Unpacking is made plain
  59. ?&fieldname "Address of field fieldname".
  60. For packing it will simply pack the id() of fieldname. Or use 0 if fieldname doesn't exists.
  61. For unpacking, it's used to know weather fieldname has to be unpacked or not, i.e. by adding a & field you turn another field (fieldname) in an optional field.
  62. """
  63. commonHdr = ()
  64. structure = ()
  65. debug = 0
  66. def __init__(self, data = None, alignment = 0):
  67. if not hasattr(self, 'alignment'):
  68. self.alignment = alignment
  69. self.fields = {}
  70. self.rawData = data
  71. if data is not None:
  72. self.fromString(data)
  73. else:
  74. self.data = None
  75. @classmethod
  76. def fromFile(self, file):
  77. answer = self()
  78. answer.fromString(file.read(len(answer)))
  79. return answer
  80. def setAlignment(self, alignment):
  81. self.alignment = alignment
  82. def setData(self, data):
  83. self.data = data
  84. def packField(self, fieldName, format = None):
  85. if self.debug:
  86. print("packField( %s | %s )" % (fieldName, format))
  87. if format is None:
  88. format = self.formatForField(fieldName)
  89. if fieldName in self.fields:
  90. ans = self.pack(format, self.fields[fieldName], field = fieldName)
  91. else:
  92. ans = self.pack(format, None, field = fieldName)
  93. if self.debug:
  94. print("\tanswer %r" % ans)
  95. return ans
  96. def getData(self):
  97. if self.data is not None:
  98. return self.data
  99. data = ''
  100. for field in self.commonHdr+self.structure:
  101. try:
  102. data += self.packField(field[0], field[1])
  103. except Exception as e:
  104. if field[0] in self.fields:
  105. e.args += ("When packing field '%s | %s | %r' in %s" % (field[0], field[1], self[field[0]], self.__class__),)
  106. else:
  107. e.args += ("When packing field '%s | %s' in %s" % (field[0], field[1], self.__class__),)
  108. raise
  109. if self.alignment:
  110. if len(data) % self.alignment:
  111. data += ('\x00'*self.alignment)[:-(len(data) % self.alignment)]
  112. #if len(data) % self.alignment: data += ('\x00'*self.alignment)[:-(len(data) % self.alignment)]
  113. return data
  114. def fromString(self, data):
  115. self.rawData = data
  116. for field in self.commonHdr+self.structure:
  117. if self.debug:
  118. print("fromString( %s | %s | %r )" % (field[0], field[1], data))
  119. size = self.calcUnpackSize(field[1], data, field[0])
  120. if self.debug:
  121. print(" size = %d" % size)
  122. dataClassOrCode = str
  123. if len(field) > 2:
  124. dataClassOrCode = field[2]
  125. try:
  126. self[field[0]] = self.unpack(field[1], data[:size], dataClassOrCode = dataClassOrCode, field = field[0])
  127. except Exception as e:
  128. e.args += ("When unpacking field '%s | %s | %r[:%d]'" % (field[0], field[1], data, size),)
  129. raise
  130. size = self.calcPackSize(field[1], self[field[0]], field[0])
  131. if self.alignment and size % self.alignment:
  132. size += self.alignment - (size % self.alignment)
  133. data = data[size:]
  134. return self
  135. def __setitem__(self, key, value):
  136. self.fields[key] = value
  137. self.data = None # force recompute
  138. def __getitem__(self, key):
  139. return self.fields[key]
  140. def __delitem__(self, key):
  141. del self.fields[key]
  142. def __str__(self):
  143. return self.getData()
  144. def __len__(self):
  145. # XXX: improve
  146. return len(self.getData())
  147. def pack(self, format, data, field = None):
  148. if self.debug:
  149. print(" pack( %s | %r | %s)" % (format, data, field))
  150. if field:
  151. addressField = self.findAddressFieldFor(field)
  152. if (addressField is not None) and (data is None):
  153. return ''
  154. # void specifier
  155. if format[:1] == '_':
  156. return ''
  157. # quote specifier
  158. if format[:1] == "'" or format[:1] == '"':
  159. return format[1:]
  160. # code specifier
  161. two = format.split('=')
  162. if len(two) >= 2:
  163. try:
  164. return self.pack(two[0], data)
  165. except:
  166. fields = {'self':self}
  167. fields.update(self.fields)
  168. return self.pack(two[0], eval(two[1], {}, fields))
  169. # address specifier
  170. two = format.split('&')
  171. if len(two) == 2:
  172. try:
  173. return self.pack(two[0], data)
  174. except:
  175. if (two[1] in self.fields) and (self[two[1]] is not None):
  176. return self.pack(two[0], id(self[two[1]]) & ((1<<(calcsize(two[0])*8))-1) )
  177. else:
  178. return self.pack(two[0], 0)
  179. # length specifier
  180. two = format.split('-')
  181. if len(two) == 2:
  182. try:
  183. return self.pack(two[0],data)
  184. except:
  185. return self.pack(two[0], self.calcPackFieldSize(two[1]))
  186. # array specifier
  187. two = format.split('*')
  188. if len(two) == 2:
  189. answer = ''
  190. for each in data:
  191. answer += self.pack(two[1], each)
  192. if two[0]:
  193. if two[0].isdigit():
  194. if int(two[0]) != len(data):
  195. raise Exception("Array field has a constant size, and it doesn't match the actual value")
  196. else:
  197. return self.pack(two[0], len(data))+answer
  198. return answer
  199. # "printf" string specifier
  200. if format[:1] == '%':
  201. # format string like specifier
  202. return format % data
  203. # asciiz specifier
  204. if format[:1] == 'z':
  205. return str(data)+'\0'
  206. # unicode specifier
  207. if format[:1] == 'u':
  208. return str(data)+'\0\0' + (len(data) & 1 and '\0' or '')
  209. # DCE-RPC/NDR string specifier
  210. if format[:1] == 'w':
  211. if len(data) == 0:
  212. data = '\0\0'
  213. elif len(data) % 2:
  214. data += '\0'
  215. l = pack('<L', len(data)/2)
  216. return '%s\0\0\0\0%s%s' % (l,l,data)
  217. if data is None:
  218. raise Exception("Trying to pack None")
  219. # literal specifier
  220. if format[:1] == ':':
  221. return str(data)
  222. # struct like specifier
  223. return pack(format, data)
  224. def unpack(self, format, data, dataClassOrCode = str, field = None):
  225. if self.debug:
  226. print(" unpack( %s | %r )" % (format, data))
  227. if field:
  228. addressField = self.findAddressFieldFor(field)
  229. if addressField is not None:
  230. if not self[addressField]:
  231. return
  232. # void specifier
  233. if format[:1] == '_':
  234. if dataClassOrCode != str:
  235. fields = {'self':self, 'inputDataLeft':data}
  236. fields.update(self.fields)
  237. return eval(dataClassOrCode, {}, fields)
  238. else:
  239. return None
  240. # quote specifier
  241. if format[:1] == "'" or format[:1] == '"':
  242. answer = format[1:]
  243. if answer != data:
  244. raise Exception("Unpacked data doesn't match constant value '%r' should be '%r'" % (data, answer))
  245. return answer
  246. # address specifier
  247. two = format.split('&')
  248. if len(two) == 2:
  249. return self.unpack(two[0],data)
  250. # code specifier
  251. two = format.split('=')
  252. if len(two) >= 2:
  253. return self.unpack(two[0],data)
  254. # length specifier
  255. two = format.split('-')
  256. if len(two) == 2:
  257. return self.unpack(two[0],data)
  258. # array specifier
  259. two = format.split('*')
  260. if len(two) == 2:
  261. answer = []
  262. sofar = 0
  263. if two[0].isdigit():
  264. number = int(two[0])
  265. elif two[0]:
  266. sofar += self.calcUnpackSize(two[0], data)
  267. number = self.unpack(two[0], data[:sofar])
  268. else:
  269. number = -1
  270. while number and sofar < len(data):
  271. nsofar = sofar + self.calcUnpackSize(two[1],data[sofar:])
  272. answer.append(self.unpack(two[1], data[sofar:nsofar], dataClassOrCode))
  273. number -= 1
  274. sofar = nsofar
  275. return answer
  276. # "printf" string specifier
  277. if format[:1] == '%':
  278. # format string like specifier
  279. return format % data
  280. # asciiz specifier
  281. if format == 'z':
  282. if data[-1] != '\x00':
  283. raise Exception("%s 'z' field is not NUL terminated: %r" % (field, data))
  284. return data[:-1] # remove trailing NUL
  285. # unicode specifier
  286. if format == 'u':
  287. if data[-2:] != '\x00\x00':
  288. raise Exception("%s 'u' field is not NUL-NUL terminated: %r" % (field, data))
  289. return data[:-2] # remove trailing NUL
  290. # DCE-RPC/NDR string specifier
  291. if format == 'w':
  292. l = unpack('<L', data[:4])[0]
  293. return data[12:12+l*2]
  294. # literal specifier
  295. if format == ':':
  296. return dataClassOrCode(data)
  297. # struct like specifier
  298. return unpack(format, data)[0]
  299. def calcPackSize(self, format, data, field = None):
  300. # # print " calcPackSize %s:%r" % (format, data)
  301. if field:
  302. addressField = self.findAddressFieldFor(field)
  303. if addressField is not None:
  304. if not self[addressField]:
  305. return 0
  306. # void specifier
  307. if format[:1] == '_':
  308. return 0
  309. # quote specifier
  310. if format[:1] == "'" or format[:1] == '"':
  311. return len(format)-1
  312. # address specifier
  313. two = format.split('&')
  314. if len(two) == 2:
  315. return self.calcPackSize(two[0], data)
  316. # code specifier
  317. two = format.split('=')
  318. if len(two) >= 2:
  319. return self.calcPackSize(two[0], data)
  320. # length specifier
  321. two = format.split('-')
  322. if len(two) == 2:
  323. return self.calcPackSize(two[0], data)
  324. # array specifier
  325. two = format.split('*')
  326. if len(two) == 2:
  327. answer = 0
  328. if two[0].isdigit():
  329. if int(two[0]) != len(data):
  330. raise Exception("Array field has a constant size, and it doesn't match the actual value")
  331. elif two[0]:
  332. answer += self.calcPackSize(two[0], len(data))
  333. for each in data:
  334. answer += self.calcPackSize(two[1], each)
  335. return answer
  336. # "printf" string specifier
  337. if format[:1] == '%':
  338. # format string like specifier
  339. return len(format % data)
  340. # asciiz specifier
  341. if format[:1] == 'z':
  342. return len(data)+1
  343. # asciiz specifier
  344. if format[:1] == 'u':
  345. l = len(data)
  346. return l + (l & 1 and 3 or 2)
  347. # DCE-RPC/NDR string specifier
  348. if format[:1] == 'w':
  349. l = len(data)
  350. return 12+l+l % 2
  351. # literal specifier
  352. if format[:1] == ':':
  353. return len(data)
  354. # struct like specifier
  355. return calcsize(format)
  356. def calcUnpackSize(self, format, data, field = None):
  357. if self.debug:
  358. print(" calcUnpackSize( %s | %s | %r)" % (field, format, data))
  359. # void specifier
  360. if format[:1] == '_':
  361. return 0
  362. addressField = self.findAddressFieldFor(field)
  363. if addressField is not None:
  364. if not self[addressField]:
  365. return 0
  366. try:
  367. lengthField = self.findLengthFieldFor(field)
  368. return self[lengthField]
  369. except:
  370. pass
  371. # XXX: Try to match to actual values, raise if no match
  372. # quote specifier
  373. if format[:1] == "'" or format[:1] == '"':
  374. return len(format)-1
  375. # address specifier
  376. two = format.split('&')
  377. if len(two) == 2:
  378. return self.calcUnpackSize(two[0], data)
  379. # code specifier
  380. two = format.split('=')
  381. if len(two) >= 2:
  382. return self.calcUnpackSize(two[0], data)
  383. # length specifier
  384. two = format.split('-')
  385. if len(two) == 2:
  386. return self.calcUnpackSize(two[0], data)
  387. # array specifier
  388. two = format.split('*')
  389. if len(two) == 2:
  390. answer = 0
  391. if two[0]:
  392. if two[0].isdigit():
  393. number = int(two[0])
  394. else:
  395. answer += self.calcUnpackSize(two[0], data)
  396. number = self.unpack(two[0], data[:answer])
  397. while number:
  398. number -= 1
  399. answer += self.calcUnpackSize(two[1], data[answer:])
  400. else:
  401. while answer < len(data):
  402. answer += self.calcUnpackSize(two[1], data[answer:])
  403. return answer
  404. # "printf" string specifier
  405. if format[:1] == '%':
  406. raise Exception("Can't guess the size of a printf like specifier for unpacking")
  407. # asciiz specifier
  408. if format[:1] == 'z':
  409. return data.index('\x00')+1
  410. # asciiz specifier
  411. if format[:1] == 'u':
  412. l = data.index('\x00\x00')
  413. return l + (l & 1 and 3 or 2)
  414. # DCE-RPC/NDR string specifier
  415. if format[:1] == 'w':
  416. l = unpack('<L', data[:4])[0]
  417. return 12+l*2
  418. # literal specifier
  419. if format[:1] == ':':
  420. return len(data)
  421. # struct like specifier
  422. return calcsize(format)
  423. def calcPackFieldSize(self, fieldName, format = None):
  424. if format is None:
  425. format = self.formatForField(fieldName)
  426. return self.calcPackSize(format, self[fieldName])
  427. def formatForField(self, fieldName):
  428. for field in self.commonHdr+self.structure:
  429. if field[0] == fieldName:
  430. return field[1]
  431. raise Exception("Field %s not found" % fieldName)
  432. def findAddressFieldFor(self, fieldName):
  433. descriptor = '&%s' % fieldName
  434. l = len(descriptor)
  435. for field in self.commonHdr+self.structure:
  436. if field[1][-l:] == descriptor:
  437. return field[0]
  438. return None
  439. def findLengthFieldFor(self, fieldName):
  440. descriptor = '-%s' % fieldName
  441. l = len(descriptor)
  442. for field in self.commonHdr+self.structure:
  443. if field[1][-l:] == descriptor:
  444. return field[0]
  445. return None
  446. def zeroValue(self, format):
  447. two = format.split('*')
  448. if len(two) == 2:
  449. if two[0].isdigit():
  450. return (self.zeroValue(two[1]),)*int(two[0])
  451. if not format.find('*') == -1: return ()
  452. if 's' in format: return ''
  453. if format in ['z',':','u']: return ''
  454. if format == 'w': return '\x00\x00'
  455. return 0
  456. def clear(self):
  457. for field in self.commonHdr + self.structure:
  458. self[field[0]] = self.zeroValue(field[1])
  459. def dump(self, msg = None, indent = 0):
  460. if msg is None: msg = self.__class__.__name__
  461. ind = ' '*indent
  462. print("\n%s" % msg)
  463. fixedFields = []
  464. for field in self.commonHdr+self.structure:
  465. i = field[0]
  466. if i in self.fields:
  467. fixedFields.append(i)
  468. if isinstance(self[i], Structure):
  469. self[i].dump('%s%s:{' % (ind,i), indent = indent + 4)
  470. print("%s}" % ind)
  471. else:
  472. print("%s%s: {%r}" % (ind,i,self[i]))
  473. # Do we have remaining fields not defined in the structures? let's
  474. # print them
  475. remainingFields = list(set(self.fields) - set(fixedFields))
  476. for i in remainingFields:
  477. if isinstance(self[i], Structure):
  478. self[i].dump('%s%s:{' % (ind,i), indent = indent + 4)
  479. print("%s}" % ind)
  480. else:
  481. print("%s%s: {%r}" % (ind,i,self[i]))
  482. class _StructureTest:
  483. alignment = 0
  484. def create(self,data = None):
  485. if data is not None:
  486. return self.theClass(data, alignment = self.alignment)
  487. else:
  488. return self.theClass(alignment = self.alignment)
  489. def run(self):
  490. print()
  491. print("-"*70)
  492. testName = self.__class__.__name__
  493. print("starting test: %s....." % testName)
  494. a = self.create()
  495. self.populate(a)
  496. a.dump("packing.....")
  497. a_str = str(a)
  498. print("packed: %r" % a_str)
  499. print("unpacking.....")
  500. b = self.create(a_str)
  501. b.dump("unpacked.....")
  502. print("repacking.....")
  503. b_str = str(b)
  504. if b_str != a_str:
  505. print("ERROR: original packed and repacked don't match")
  506. print("packed: %r" % b_str)
  507. class _Test_simple(_StructureTest):
  508. class theClass(Structure):
  509. commonHdr = ()
  510. structure = (
  511. ('int1', '!L'),
  512. ('len1','!L-z1'),
  513. ('arr1','B*<L'),
  514. ('z1', 'z'),
  515. ('u1','u'),
  516. ('', '"COCA'),
  517. ('len2','!H-:1'),
  518. ('', '"COCA'),
  519. (':1', ':'),
  520. ('int3','>L'),
  521. ('code1','>L=len(arr1)*2+0x1000'),
  522. )
  523. def populate(self, a):
  524. a['default'] = 'hola'
  525. a['int1'] = 0x3131
  526. a['int3'] = 0x45444342
  527. a['z1'] = 'hola'
  528. a['u1'] = 'hola'.encode('utf_16_le')
  529. a[':1'] = ':1234:'
  530. a['arr1'] = (0x12341234,0x88990077,0x41414141)
  531. # a['len1'] = 0x42424242
  532. class _Test_fixedLength(_Test_simple):
  533. def populate(self, a):
  534. _Test_simple.populate(self, a)
  535. a['len1'] = 0x42424242
  536. class _Test_simple_aligned4(_Test_simple):
  537. alignment = 4
  538. class _Test_nested(_StructureTest):
  539. class theClass(Structure):
  540. class _Inner(Structure):
  541. structure = (('data', 'z'),)
  542. structure = (
  543. ('nest1', ':', _Inner),
  544. ('nest2', ':', _Inner),
  545. ('int', '<L'),
  546. )
  547. def populate(self, a):
  548. a['nest1'] = _Test_nested.theClass._Inner()
  549. a['nest2'] = _Test_nested.theClass._Inner()
  550. a['nest1']['data'] = 'hola manola'
  551. a['nest2']['data'] = 'chau loco'
  552. a['int'] = 0x12345678
  553. class _Test_Optional(_StructureTest):
  554. class theClass(Structure):
  555. structure = (
  556. ('pName','<L&Name'),
  557. ('pList','<L&List'),
  558. ('Name','w'),
  559. ('List','<H*<L'),
  560. )
  561. def populate(self, a):
  562. a['Name'] = 'Optional test'
  563. a['List'] = (1,2,3,4)
  564. class _Test_Optional_sparse(_Test_Optional):
  565. def populate(self, a):
  566. _Test_Optional.populate(self, a)
  567. del a['Name']
  568. class _Test_AsciiZArray(_StructureTest):
  569. class theClass(Structure):
  570. structure = (
  571. ('head','<L'),
  572. ('array','B*z'),
  573. ('tail','<L'),
  574. )
  575. def populate(self, a):
  576. a['head'] = 0x1234
  577. a['tail'] = 0xabcd
  578. a['array'] = ('hola','manola','te traje')
  579. class _Test_UnpackCode(_StructureTest):
  580. class theClass(Structure):
  581. structure = (
  582. ('leni','<L=len(uno)*2'),
  583. ('cuchi','_-uno','leni/2'),
  584. ('uno',':'),
  585. ('dos',':'),
  586. )
  587. def populate(self, a):
  588. a['uno'] = 'soy un loco!'
  589. a['dos'] = 'que haces fiera'
  590. class _Test_AAA(_StructureTest):
  591. class theClass(Structure):
  592. commonHdr = ()
  593. structure = (
  594. ('iv', '!L=((init_vector & 0xFFFFFF) << 8) | ((pad & 0x3f) << 2) | (keyid & 3)'),
  595. ('init_vector', '_','(iv >> 8)'),
  596. ('pad', '_','((iv >>2) & 0x3F)'),
  597. ('keyid', '_','( iv & 0x03 )'),
  598. ('dataLen', '_-data', 'len(inputDataLeft)-4'),
  599. ('data',':'),
  600. ('icv','>L'),
  601. )
  602. def populate(self, a):
  603. a['init_vector']=0x01020304
  604. #a['pad']=int('01010101',2)
  605. a['pad']=int('010101',2)
  606. a['keyid']=0x07
  607. a['data']="\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9"
  608. a['icv'] = 0x05060708
  609. #a['iv'] = 0x01020304
  610. if __name__ == '__main__':
  611. _Test_simple().run()
  612. try:
  613. _Test_fixedLength().run()
  614. except:
  615. print("cannot repack because length is bogus")
  616. _Test_simple_aligned4().run()
  617. _Test_nested().run()
  618. _Test_Optional().run()
  619. _Test_Optional_sparse().run()
  620. _Test_AsciiZArray().run()
  621. _Test_UnpackCode().run()
  622. _Test_AAA().run()