/usr/lib/python2.7/dist-packages/impacket/dcerpc/v5/ndr.py is in python-impacket 0.9.15-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 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 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 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 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 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 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 | # Copyright (c) 2003-2016 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# [C706] Transfer NDR Syntax implementation
#
# Author: Alberto Solino (@agsolino)
#
# ToDo:
# [X] Unions and rest of the structured types
# [ ] Documentation for this library, especially the support for Arrays
#
import random
import inspect
from struct import pack, unpack, calcsize
from impacket import LOG
from impacket.winregistry import hexdump
from impacket.dcerpc.v5.enum import Enum
from impacket.uuid import uuidtup_to_bin
# Something important to have in mind:
# Diagrams do not depict the specified alignment gaps, which can appear in the octet stream
# before an item (see Section 14.2.2 on page 620.)
# Where necessary, an alignment gap, consisting of octets of unspecified value, *precedes* the
# representation of a primitive. The gap is of the smallest size sufficient to align the primitive
class NDR(object):
"""
This will be the base class for all DCERPC NDR Types and represents a NDR Primitive Type
"""
referent = ()
commonHdr = ()
commonHdr64 = ()
structure = ()
structure64 = ()
align = 4
item = None
_isNDR64 = False
def __init__(self, data = None, isNDR64 = False):
object.__init__(self)
self._isNDR64 = isNDR64
self.fields = {}
if isNDR64 is True:
if self.commonHdr64 != ():
self.commonHdr = self.commonHdr64
if self.structure64 != ():
self.structure = self.structure64
if hasattr(self, 'align64'):
self.align = self.align64
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:
if self.isNDR(fieldTypeOrClass):
self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64)
elif fieldTypeOrClass == ':':
self.fields[fieldName] = ''
elif len(fieldTypeOrClass.split('=')) == 2:
try:
self.fields[fieldName] = eval(fieldTypeOrClass.split('=')[1])
except:
self.fields[fieldName] = None
else:
self.fields[fieldName] = []
if data is not None:
self.fromString(data)
def changeTransferSyntax(self, newSyntax):
NDR64Syntax = uuidtup_to_bin(('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0'))
if newSyntax == NDR64Syntax:
if self._isNDR64 is False:
# Ok, let's change everything
self._isNDR64 = True
for fieldName in self.fields.keys():
if isinstance(self.fields[fieldName], NDR):
self.fields[fieldName].changeTransferSyntax(newSyntax)
# Finally, I change myself
if self.commonHdr64 != ():
self.commonHdr = self.commonHdr64
if self.structure64 != ():
self.structure = self.structure64
if hasattr(self, 'align64'):
self.align = self.align64
# And check whether the changes changed the data types
# if so, I need to instantiate the new ones and copy the
# old values
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:
if isinstance(self.fields[fieldName], NDR):
if fieldTypeOrClass != self.fields[fieldName].__class__ and isinstance(self.fields[fieldName], NDRPOINTERNULL) is False:
backupData = self[fieldName]
self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64)
if self.fields[fieldName].fields.has_key('Data'):
self.fields[fieldName].fields['Data'] = backupData
else:
self[fieldName] = backupData
else:
if self._isNDR64 is True:
# Ok, nothing for now
raise
def __setitem__(self, key, value):
if isinstance(value, NDRPOINTERNULL):
value = NDRPOINTERNULL(isNDR64 = self._isNDR64)
if isinstance(self.fields[key], NDRPOINTER):
self.fields[key] = value
elif self.fields[key].fields.has_key('Data'):
if isinstance(self.fields[key].fields['Data'], NDRPOINTER):
self.fields[key].fields['Data'] = value
elif isinstance(value, NDR):
# It's not a null pointer, ok. Another NDR type, but it
# must be the same same as the iteam already in place
if self.fields[key].__class__.__name__ == value.__class__.__name__:
self.fields[key] = value
elif isinstance(self.fields[key]['Data'], NDR):
if self.fields[key]['Data'].__class__.__name__ == value.__class__.__name__:
self.fields[key]['Data'] = value
else:
LOG.error("Can't setitem with class specified, should be %s" % self.fields[key]['Data'].__class__.__name__)
else:
LOG.error("Can't setitem with class specified, should be %s" % self.fields[key].__class__.__name__)
elif isinstance(self.fields[key], NDR):
self.fields[key]['Data'] = value
else:
self.fields[key] = value
def __getitem__(self, key):
if isinstance(self.fields[key], NDR):
if self.fields[key].fields.has_key('Data'):
return self.fields[key]['Data']
return self.fields[key]
def __str__(self):
return self.getData()
def __len__(self):
# XXX: improve
return len(self.getData())
def getDataLen(self, data):
return len(data)
@staticmethod
def isNDR(field):
if inspect.isclass(field):
myClass = field
if issubclass(myClass, NDR):
return True
return False
def dumpRaw(self, msg = None, indent = 0):
if msg is None: msg = self.__class__.__name__
ind = ' '*indent
print "\n%s" % msg
for field in self.commonHdr+self.structure+self.referent:
i = field[0]
if i in self.fields:
if isinstance(self.fields[i], NDR):
self.fields[i].dumpRaw('%s%s:{' % (ind,i), indent = indent + 4)
print "%s}" % ind
elif isinstance(self.fields[i], list):
print "%s[" % ind
for num,j in enumerate(self.fields[i]):
if isinstance(j, NDR):
j.dumpRaw('%s%s:' % (ind,i), indent = indent + 4)
print "%s," % ind
else:
print "%s%s: {%r}," % (ind, i, j)
print "%s]" % ind
else:
print "%s%s: {%r}" % (ind,i,self[i])
def dump(self, msg = None, indent = 0):
if msg is None: msg = self.__class__.__name__
ind = ' '*indent
if msg != '':
print "%s" % msg,
for fieldName, fieldType in self.commonHdr+self.structure+self.referent:
if fieldName in self.fields:
if isinstance(self.fields[fieldName], NDR):
self.fields[fieldName].dump('\n%s%-31s' % (ind, fieldName+':'), indent = indent + 4),
else:
print " %r" % (self[fieldName]),
def getAlignment(self):
return self.align
@staticmethod
def calculatePad(fieldType, soFar):
try:
alignment = calcsize(fieldType.split('=')[0])
except:
alignment = 0
if alignment > 0:
pad = (alignment - (soFar % alignment)) % alignment
else:
pad = 0
return pad
def getData(self, soFar = 0):
data = ''
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
try:
# Alignment of Primitive Types
# NDR enforces NDR alignment of primitive data; that is, any primitive of size n
# octets is aligned at a octet stream index that is a multiple of n.
# (In this version of NDR, n is one of {1, 2, 4, 8}.) An octet stream index indicates
# the number of an octet in an octet stream when octets are numbered, beginning with 0,
# from the first octet in the stream. Where necessary, an alignment gap, consisting of
# octets of unspecified value, precedes the representation of a primitive. The gap is
# of the smallest size sufficient to align the primitive.
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data += '\xbf'*pad
res = self.pack(fieldName, fieldTypeOrClass, soFar)
data += res
soFar += len(res)
except Exception, e:
LOG.error(str(e))
LOG.error("Error packing field '%s | %s' in %s" % (fieldName, fieldTypeOrClass, self.__class__))
raise
return data
def fromString(self, data, soFar = 0):
soFar0 = soFar
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
try:
# Alignment of Primitive Types
# NDR enforces NDR alignment of primitive data; that is, any primitive of size n
# octets is aligned at a octet stream index that is a multiple of n.
# (In this version of NDR, n is one of {1, 2, 4, 8}.) An octet stream index indicates
# the number of an octet in an octet stream when octets are numbered, beginning with 0,
# from the first octet in the stream. Where necessary, an alignment gap, consisting of
# octets of unspecified value, precedes the representation of a primitive. The gap is
# of the smallest size sufficient to align the primitive.
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data = data[pad:]
size = self.unpack(fieldName, fieldTypeOrClass, data, soFar)
data = data[size:]
soFar += size
except Exception,e:
LOG.error(str(e))
LOG.error("Error unpacking field '%s | %s | %r'" % (fieldName, fieldTypeOrClass, data[:256]))
raise
return soFar - soFar0
def pack(self, fieldName, fieldTypeOrClass, soFar = 0):
if isinstance(self.fields[fieldName], NDR):
return self.fields[fieldName].getData(soFar)
data = self.fields[fieldName]
# void specifier
if fieldTypeOrClass[:1] == '_':
return ''
# code specifier
two = fieldTypeOrClass.split('=')
if len(two) >= 2:
try:
return self.pack(fieldName, two[0], soFar)
except:
self.fields[fieldName] = eval(two[1], {}, self.fields)
return self.pack(fieldName, two[0], soFar)
if data is None:
raise Exception('Trying to pack None')
# literal specifier
if fieldTypeOrClass[:1] == ':':
return str(data)
# struct like specifier
return pack(fieldTypeOrClass, data)
def unpack(self, fieldName, fieldTypeOrClass, data, soFar = 0):
size = self.calcUnPackSize(fieldTypeOrClass, data)
data = data[:size]
if isinstance(self.fields[fieldName], NDR):
return self.fields[fieldName].fromString(data, soFar)
# code specifier
two = fieldTypeOrClass.split('=')
if len(two) >= 2:
return self.unpack(fieldName,two[0], data, soFar)
# literal specifier
if fieldTypeOrClass == ':':
if isinstance(fieldTypeOrClass, NDR):
return self.fields[fieldName].fromString(data, soFar)
else:
dataLen = self.getDataLen(data)
self.fields[fieldName] = data[:dataLen]
return dataLen
# struct like specifier
self.fields[fieldName] = unpack(fieldTypeOrClass, data)[0]
return size
def calcPackSize(self, fieldTypeOrClass, data):
if isinstance(fieldTypeOrClass, str) is False:
return len(data)
# code specifier
two = fieldTypeOrClass.split('=')
if len(two) >= 2:
return self.calcPackSize(two[0], data)
# literal specifier
if fieldTypeOrClass[:1] == ':':
return len(data)
# struct like specifier
return calcsize(fieldTypeOrClass)
def calcUnPackSize(self, fieldTypeOrClass, data):
if isinstance(fieldTypeOrClass, str) is False:
return len(data)
# code specifier
two = fieldTypeOrClass.split('=')
if len(two) >= 2:
return self.calcUnPackSize(two[0], data)
# array specifier
two = fieldTypeOrClass.split('*')
if len(two) == 2:
return len(data)
# literal specifier
if fieldTypeOrClass[:1] == ':':
return len(data)
# struct like specifier
return calcsize(fieldTypeOrClass)
# NDR Primitives
class NDRSMALL(NDR):
align = 1
structure = (
('Data', 'b=0'),
)
class NDRUSMALL(NDR):
align = 1
structure = (
('Data', 'B=0'),
)
class NDRBOOLEAN(NDRSMALL):
def dump(self, msg = None, indent = 0):
if msg is None: msg = self.__class__.__name__
if msg != '':
print msg,
if self['Data'] > 0:
print " TRUE"
else:
print " FALSE"
class NDRCHAR(NDR):
align = 1
structure = (
('Data', 'c'),
)
class NDRSHORT(NDR):
align = 2
structure = (
('Data', '<h=0'),
)
class NDRUSHORT(NDR):
align = 2
structure = (
('Data', '<H=0'),
)
class NDRLONG(NDR):
align = 4
structure = (
('Data', '<l=0'),
)
class NDRULONG(NDR):
align = 4
structure = (
('Data', '<L=0'),
)
class NDRHYPER(NDR):
align = 8
structure = (
('Data', '<q=0'),
)
class NDRUHYPER(NDR):
align = 8
structure = (
('Data', '<Q=0'),
)
class NDRFLOAT(NDR):
align = 4
structure = (
('Data', '<f=0'),
)
class NDRDOUBLEFLOAT(NDR):
align = 8
structure = (
('Data', '<d=0'),
)
class EnumType(type):
def __getattr__(self, attr):
return self.enumItems[attr].value
class NDRENUM(NDR):
__metaclass__ = EnumType
align = 2
align64 = 4
structure = (
('Data', '<H'),
)
# 2.2.5.2 NDR64 Simple Data Types
# NDR64 supports all simple types defined by NDR (as specified in [C706] section 14.2)
# with the same alignment requirements except for enumerated types, which MUST be
# represented as signed long integers (4 octets) in NDR64.
structure64 = (
('Data', '<L'),
)
# enum MUST be an python enum (see enum.py)
class enumItems(Enum):
pass
def __setitem__(self, key, value):
if isinstance(value, Enum):
self['Data'] = value.value
else:
return NDR.__setitem__(self,key,value)
def dump(self, msg = None, indent = 0):
if msg is None: msg = self.__class__.__name__
if msg != '':
print msg,
print " %s" % self.enumItems(self.fields['Data']).name,
# NDR Constructed Types (arrays, strings, structures, unions, variant structures, pipes and pointers)
class NDRCONSTRUCTEDTYPE(NDR):
@staticmethod
def isPointer(field):
if inspect.isclass(field):
myClass = field
if issubclass(myClass, NDRPOINTER):
return True
return False
@staticmethod
def isUnion(field):
if inspect.isclass(field):
myClass = field
if issubclass(myClass, NDRUNION):
return True
return False
def getDataReferents(self, soFar = 0):
data = ''
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):
data += self.fields[fieldName].getDataReferents(len(data)+soFar)
data += self.fields[fieldName].getDataReferent(len(data)+soFar)
return data
def getDataReferent(self, soFar=0):
data = ''
soFar0 = soFar
if hasattr(self,'referent') is False:
return ''
if self.fields.has_key('ReferentID'):
if self['ReferentID'] == 0:
return ''
for fieldName, fieldTypeOrClass in self.referent:
try:
if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName], NDRUniConformantVaryingArray):
# So we have an array, first item in the structure must be the array size, although we
# will need to build it later.
if self._isNDR64:
arrayItemSize = 8
arrayPackStr = '<Q'
else:
arrayItemSize = 4
arrayPackStr = '<L'
# The size information is itself aligned according to the alignment rules for
# primitive data types. (See Section 14.2.2 on page 620.) The data of the constructed
# type is then aligned according to the alignment rules for the constructed type.
# In other words, the size information precedes the structure and is aligned
# independently of the structure alignment.
# We need to check whether we need padding or not
pad0 = (arrayItemSize - (soFar % arrayItemSize)) % arrayItemSize
if pad0 > 0:
soFar += pad0
arrayPadding = '\xef'*pad0
else:
arrayPadding = ''
# And now, let's pretend we put the item in
soFar += arrayItemSize
data = self.fields[fieldName].getData(soFar)
data = arrayPadding + pack(arrayPackStr, self.getArrayMaximumSize(fieldName)) + data
else:
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data += '\xcc'*pad
data += self.pack(fieldName, fieldTypeOrClass, soFar)
# Any referent information to pack?
if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):
data += self.fields[fieldName].getDataReferents(soFar0 + len(data))
data += self.fields[fieldName].getDataReferent(soFar0 + len(data))
soFar = soFar0 + len(data)
except Exception, e:
LOG.error(str(e))
LOG.error("Error packing field '%s | %s' in %s" % (fieldName, fieldTypeOrClass, self.__class__))
raise
return data
def calcPackSize(self, fieldTypeOrClass, data):
if isinstance(fieldTypeOrClass, str) is False:
return len(data)
# array specifier
two = fieldTypeOrClass.split('*')
if len(two) == 2:
answer = 0
for each in data:
if self.isNDR(self.item):
item = ':'
else:
item = self.item
answer += self.calcPackSize(item, each)
return answer
else:
return NDR.calcPackSize(self, fieldTypeOrClass, data)
def getArrayMaximumSize(self, fieldName):
if self.fields[fieldName].fields['MaximumCount'] > 0:
return self.fields[fieldName].fields['MaximumCount']
else:
return self.fields[fieldName].getArraySize()
def getArraySize(self,fieldName, data, soFar):
if self._isNDR64:
arrayItemSize = 8
arrayUnPackStr = '<Q'
else:
arrayItemSize = 4
arrayUnPackStr = '<L'
pad0 = (arrayItemSize - (soFar % arrayItemSize)) % arrayItemSize
if pad0 > 0:
soFar += pad0
data = data[pad0:]
if isinstance(self.fields[fieldName], NDRUniConformantArray):
# Array Size is at the very begining
arraySize = unpack(arrayUnPackStr, data[:arrayItemSize])[0]
elif isinstance(self.fields[fieldName], NDRUniConformantVaryingArray):
# NDRUniConformantVaryingArray Array
# Unpack the Maximum Count
maximumCount = unpack(arrayUnPackStr, data[:arrayItemSize])[0]
# Let's store the Maximum Count for later use
self.fields[fieldName].fields['MaximumCount'] = maximumCount
# Unpack the Actual Count
arraySize = unpack(arrayUnPackStr, data[arrayItemSize*2:][:arrayItemSize])[0]
else:
# NDRUniVaryingArray Array
arraySize = unpack(arrayUnPackStr, data[arrayItemSize:][:arrayItemSize])[0]
return arraySize, arrayItemSize+pad0
def fromStringReferents(self, data, soFar = 0):
soFar0 = soFar
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):
size = self.fields[fieldName].fromStringReferents(data, soFar)
data = data[size:]
soFar += size
size = self.fields[fieldName].fromStringReferent(data, soFar)
soFar += size
data = data[size:]
return soFar - soFar0
def fromStringReferent(self, data, soFar = 0):
if hasattr(self, 'referent') is not True:
return 0
soFar0 = soFar
if self.fields.has_key('ReferentID'):
if self['ReferentID'] == 0:
# NULL Pointer, there's no referent for it
return 0
for fieldName, fieldTypeOrClass in self.referent:
try:
if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName], NDRUniConformantVaryingArray):
# Get the array size
arraySize, advanceStream = self.getArraySize(fieldName, data, soFar)
soFar += advanceStream
data = data[advanceStream:]
# Let's tell the array how many items are available
self.fields[fieldName].setArraySize(arraySize)
size = self.fields[fieldName].fromString(data, soFar)
else:
# ToDo: Align only if not NDR
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data = data[pad:]
size = self.unpack(fieldName, fieldTypeOrClass, data, soFar)
if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):
size += self.fields[fieldName].fromStringReferents(data[size:], soFar + size)
size += self.fields[fieldName].fromStringReferent(data[size:], soFar + size)
data = data[size:]
soFar += size
except Exception,e:
LOG.error(str(e))
LOG.error("Error unpacking field '%s | %s | %r'" % (fieldName, fieldTypeOrClass, data[:256]))
raise
return soFar-soFar0
def calcUnPackSize(self, fieldTypeOrClass, data):
if isinstance(fieldTypeOrClass, str) is False:
return len(data)
two = fieldTypeOrClass.split('*')
if len(two) == 2:
return len(data)
else:
return NDR.calcUnPackSize(self, fieldTypeOrClass, data)
# Uni-dimensional Fixed Arrays
class NDRArray(NDRCONSTRUCTEDTYPE):
def dump(self, msg = None, indent = 0):
if msg is None: msg = self.__class__.__name__
ind = ' '*indent
if msg != '':
print msg,
if isinstance(self['Data'], list):
print "\n%s[" % ind
ind += ' '*4
for num,j in enumerate(self.fields['Data']):
if isinstance(j, NDR):
j.dump('%s' % ind, indent = indent + 4),
print ","
else:
print "%s %r," % (ind,j)
print "%s]" % ind[:-4],
else:
print " %r" % self['Data'],
def setArraySize(self, size):
self.arraySize = size
def getArraySize(self):
return self.arraySize
def changeTransferSyntax(self, newSyntax):
# Here we gotta go over each item in the array and change the TS
# Only if the item type is NDR
if hasattr(self, 'item') and self.item is not None:
if self.isNDR(self.item):
for item in self.fields['Data']:
item.changeTransferSyntax(newSyntax)
return NDRCONSTRUCTEDTYPE.changeTransferSyntax(self, newSyntax)
def getAlignment(self):
# Array alignment is the largest alignment of the array element type and
# the size information type, if any.
align = 0
# And now the item
if hasattr(self, "item") and self.item is not None:
if self.isNDR(self.item):
tmpAlign = self.item().getAlignment()
else:
tmpAlign = self.calcPackSize(self.item, '')
if tmpAlign > align:
align = tmpAlign
return align
def getData(self, soFar = 0):
data = ''
soFar0 = soFar
for fieldName, fieldTypeOrClass in self.structure:
try:
if self.isNDR(fieldTypeOrClass) is False:
# If the item is not NDR (e.g. ('MaximumCount', '<L=len(Data)'))
# we have to align it
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data += '\xca'*pad
res = self.pack(fieldName, fieldTypeOrClass, soFar)
data += res
soFar = soFar0 + len(data)
except Exception, e:
LOG.error(str(e))
LOG.error("Error packing field '%s | %s' in %s" % (fieldName, fieldTypeOrClass, self.__class__))
raise
return data
def pack(self, fieldName, fieldTypeOrClass, soFar = 0):
# array specifier
two = fieldTypeOrClass.split('*')
if len(two) == 2:
answer = ''
if self.isNDR(self.item):
item = ':'
dataClass = self.item
self.fields['_tmpItem'] = dataClass(isNDR64=self._isNDR64)
else:
item = self.item
dataClass = None
self.fields['_tmpItem'] = item
for each in self.fields[fieldName]:
pad = self.calculatePad(self.item, len(answer)+soFar)
if pad > 0:
answer += '\xdd' * pad
if dataClass is None:
answer += pack(item, each)
else:
answer += each.getData(len(answer)+soFar)
if dataClass is not None:
for each in self.fields[fieldName]:
if isinstance(each, NDRCONSTRUCTEDTYPE):
answer += each.getDataReferents(len(answer)+soFar)
answer += each.getDataReferent(len(answer)+soFar)
del(self.fields['_tmpItem'])
if isinstance(self, NDRUniConformantArray) or isinstance(self, NDRUniConformantVaryingArray):
# First field points to a field with the amount of items
self.setArraySize(len(self.fields[fieldName]))
else:
self.fields[two[1]] = len(self.fields[fieldName])
return answer
else:
return NDRCONSTRUCTEDTYPE.pack(self, fieldName, fieldTypeOrClass, soFar)
def fromString(self, data, soFar = 0):
soFar0 = soFar
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
try:
if self.isNDR(fieldTypeOrClass) is False:
# If the item is not NDR (e.g. ('MaximumCount', '<L=len(Data)'))
# we have to align it
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data = data[pad:]
size = self.unpack(fieldName, fieldTypeOrClass, data, soFar)
data = data[size:]
soFar += size
except Exception,e:
LOG.error(str(e))
LOG.error("Error unpacking field '%s | %s | %r'" % (fieldName, fieldTypeOrClass, data[:256]))
raise
return soFar - soFar0
def unpack(self, fieldName, fieldTypeOrClass, data, soFar = 0):
# array specifier
two = fieldTypeOrClass.split('*')
answer = []
soFarItems = 0
soFar0 = soFar
if len(two) == 2:
if isinstance(self, NDRUniConformantArray):
# First field points to a field with the amount of items
numItems = self.getArraySize()
elif isinstance(self, NDRUniConformantVaryingArray):
# In this case we have the MaximumCount but it could be different from the ActualCount.
# Let's make the unpack figure this out.
#self.fields['MaximumCount'] = self.getArraySize()
numItems = self[two[1]]
else:
numItems = self[two[1]]
# The item type is determined by self.item
if self.isNDR(self.item):
item = ':'
dataClassOrCode = self.item
self.fields['_tmpItem'] = dataClassOrCode(isNDR64=self._isNDR64)
else:
item = self.item
dataClassOrCode = None
self.fields['_tmpItem'] = item
nsofar = 0
while numItems and soFarItems < len(data):
pad = self.calculatePad(self.item, soFarItems+soFar)
if pad > 0:
soFarItems +=pad
if dataClassOrCode is None:
nsofar = soFarItems + calcsize(item)
answer.append(unpack(item, data[soFarItems:nsofar])[0])
else:
itemn = dataClassOrCode(isNDR64=self._isNDR64)
size = itemn.fromString(data[soFarItems:], soFar+soFarItems)
answer.append(itemn)
nsofar += size + pad
numItems -= 1
soFarItems = nsofar
if dataClassOrCode is not None and isinstance(dataClassOrCode(), NDRCONSTRUCTEDTYPE):
# We gotta go over again, asking for the referents
data = data[soFarItems:]
answer2 = []
for itemn in answer:
size = itemn.fromStringReferents(data, soFarItems+soFar)
soFarItems += size
data = data[size:]
size = itemn.fromStringReferent(data, soFarItems+soFar)
soFarItems += size
data = data[size:]
answer2.append(itemn)
answer = answer2
del answer2
del(self.fields['_tmpItem'])
self.fields[fieldName] = answer
return soFarItems + soFar - soFar0
else:
return NDRCONSTRUCTEDTYPE.unpack(self, fieldName, fieldTypeOrClass, data, soFar)
class NDRUniFixedArray(NDRArray):
structure = (
('Data',':'),
)
# Uni-dimensional Conformant Arrays
class NDRUniConformantArray(NDRArray):
item = 'c'
structure = (
#('MaximumCount', '<L=len(Data)'),
('Data', '*MaximumCount'),
)
structure64 = (
#('MaximumCount', '<Q=len(Data)'),
('Data', '*MaximumCount'),
)
def __init__(self, data = None, isNDR64 = False):
NDRArray.__init__(self, data, isNDR64)
# Let's store the hidden MaximumCount field
self.fields['MaximumCount'] = 0
def __setitem__(self, key, value):
self.fields['MaximumCount'] = None
return NDRArray.__setitem__(self, key, value)
# Uni-dimensional Varying Arrays
class NDRUniVaryingArray(NDRArray):
item = 'c'
structure = (
('Offset','<L=0'),
('ActualCount','<L=len(Data)'),
('Data','*ActualCount'),
)
structure64 = (
('Offset','<Q=0'),
('ActualCount','<Q=len(Data)'),
('Data','*ActualCount'),
)
def __setitem__(self, key, value):
self.fields['ActualCount'] = None
return NDRArray.__setitem__(self, key, value)
# Uni-dimensional Conformant-varying Arrays
class NDRUniConformantVaryingArray(NDRArray):
item = 'c'
commonHdr = (
#('MaximumCount', '<L=len(Data)'),
('Offset','<L=0'),
('ActualCount','<L=len(Data)'),
)
commonHdr64 = (
#('MaximumCount', '<Q=len(Data)'),
('Offset','<Q=0'),
('ActualCount','<Q=len(Data)'),
)
structure = (
('Data','*ActualCount'),
)
def __init__(self, data = None, isNDR64 = False):
NDRArray.__init__(self, data, isNDR64)
# Let's store the hidden MaximumCount field
self.fields['MaximumCount'] = 0
def __setitem__(self, key, value):
self.fields['MaximumCount'] = None
self.fields['ActualCount'] = None
return NDRArray.__setitem__(self, key, value)
def getData(self, soFar = 0):
data = ''
soFar0 = soFar
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
try:
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data += '\xcb'*pad
res = self.pack(fieldName, fieldTypeOrClass, soFar)
data += res
soFar = soFar0 + len(data)
except Exception, e:
LOG.error(str(e))
LOG.error("Error packing field '%s | %s' in %s" % (fieldName, fieldTypeOrClass, self.__class__))
raise
return data
# Multidimensional arrays not implemented for now
# Varying Strings
class NDRVaryingString(NDRUniVaryingArray):
def getData(self, soFar = 0):
# The last element of a string is a terminator of the same size as the other elements.
# If the string element size is one octet, the terminator is a NULL character.
# The terminator for a string of multi-byte characters is the array element zero (0).
if self["Data"][-1:] != '\x00':
self["Data"] = ''.join(self["Data"]) + '\x00'
return NDRUniVaryingArray.getData(self, soFar)
def fromString(self, data, soFar = 0):
ret = NDRUniVaryingArray.fromString(self,data)
# Let's take out the last item
self["Data"] = self["Data"][:-1]
return ret
# Conformant and Varying Strings
class NDRConformantVaryingString(NDRUniConformantVaryingArray):
pass
# Structures
# Structures Containing a Conformant Array
# Structures Containing a Conformant and Varying Array
class NDRSTRUCT(NDRCONSTRUCTEDTYPE):
def getData(self, soFar = 0):
data = ''
arrayPadding = ''
soFar0 = soFar
# 14.3.7.1 Structures Containing a Conformant Array
# A structure can contain a conformant array only as its last member.
# In the NDR representation of a structure that contains a conformant array,
# the unsigned long integers that give maximum element counts for dimensions of the array
# are moved to the beginning of the structure, and the array elements appear in place at
# the end of the structure.
# 14.3.7.2 Structures Containing a Conformant and Varying Array
# A structure can contain a conformant and varying array only as its last member.
# In the NDR representation of a structure that contains a conformant and varying array,
# the maximum counts for dimensions of the array are moved to the beginning of the structure,
# but the offsets and actual counts remain in place at the end of the structure,
# immediately preceding the array elements
lastItem = (self.commonHdr+self.structure)[-1][0]
if isinstance(self.fields[lastItem], NDRUniConformantArray) or isinstance(self.fields[lastItem], NDRUniConformantVaryingArray):
# So we have an array, first item in the structure must be the array size, although we
# will need to build it later.
if self._isNDR64:
arrayItemSize = 8
arrayPackStr = '<Q'
else:
arrayItemSize = 4
arrayPackStr = '<L'
# The size information is itself aligned according to the alignment rules for
# primitive data types. (See Section 14.2.2 on page 620.) The data of the constructed
# type is then aligned according to the alignment rules for the constructed type.
# In other words, the size information precedes the structure and is aligned
# independently of the structure alignment.
# We need to check whether we need padding or not
pad0 = (arrayItemSize - (soFar % arrayItemSize)) % arrayItemSize
if pad0 > 0:
soFar += pad0
arrayPadding = '\xee'*pad0
else:
arrayPadding = ''
# And now, let's pretend we put the item in
soFar += arrayItemSize
else:
arrayItemSize = 0
# Now we need to align the structure
# The alignment of a structure in the octet stream is the largest of the alignments of the fields it
# contains. These fields may also be constructed types. The same alignment rules apply
# recursively to nested constructed types.
alignment = self.getAlignment()
if alignment > 0:
pad = (alignment - (soFar % alignment)) % alignment
if pad > 0:
soFar += pad
data += '\xAB'*pad
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
try:
if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName], NDRUniConformantVaryingArray):
res = self.fields[fieldName].getData(soFar)
if isinstance(self, NDRPOINTER):
pointerData = data[:arrayItemSize]
data = data[arrayItemSize:]
data = pointerData + arrayPadding + pack(arrayPackStr ,self.getArrayMaximumSize(fieldName)) + data
else:
data = arrayPadding + pack(arrayPackStr, self.getArrayMaximumSize(fieldName)) + data
arrayPadding = ''
arrayItemSize = 0
else:
res = self.pack(fieldName, fieldTypeOrClass, soFar)
data += res
soFar = soFar0 + len(data) + len(arrayPadding) + arrayItemSize
except Exception, e:
LOG.error(str(e))
LOG.error("Error packing field '%s | %s' in %s" % (fieldName, fieldTypeOrClass, self.__class__))
raise
# 2.2.5.3.4.1 Structure with Trailing Gap
# NDR64 represents a structure as an ordered sequence of representations of the
# structure members. The trailing gap from the last nonconformant and nonvarying
# field to the alignment of the structure MUST be represented as a trailing pad.
# The size of the structure MUST be a multiple of its alignment.
# See the following figure.
# 4.8 Example of Structure with Trailing Gap in NDR64
# This example shows a structure with a trailing gap in NDR64.
# typedef struct _StructWithPad
# {
# long l;
# short s;
# } StructWithPad;
# The size of the structure in the octet stream MUST contain a 2-byte trailing
# gap to make its size 8, a multiple of the structure's alignment, 4.
# if self._isNDR64 is True:
# # ToDo add trailing gap here
# if alignment > 0:
# pad = (alignment - (soFar % alignment)) % alignment
# if pad > 0:
# soFar += pad
# data += '\xcd'*pad
# print self.__class__ , alignment, pad, hex(soFar)
return data
def fromString(self, data, soFar = 0 ):
soFar0 = soFar
# 14.3.7.1 Structures Containing a Conformant Array
# A structure can contain a conformant array only as its last member.
# In the NDR representation of a structure that contains a conformant array,
# the unsigned long integers that give maximum element counts for dimensions of the array
# are moved to the beginning of the structure, and the array elements appear in place at
# the end of the structure.
# 14.3.7.2 Structures Containing a Conformant and Varying Array
# A structure can contain a conformant and varying array only as its last member.
# In the NDR representation of a structure that contains a conformant and varying array,
# the maximum counts for dimensions of the array are moved to the beginning of the structure,
# but the offsets and actual counts remain in place at the end of the structure,
# immediately preceding the array elements
lastItem = (self.commonHdr+self.structure)[-1][0]
if isinstance(self.fields[lastItem], NDRUniConformantArray) or isinstance(self.fields[lastItem], NDRUniConformantVaryingArray):
# So we have an array, first item in the structure must be the array size, although we
# will need to build it later.
if self._isNDR64:
arrayItemSize = 8
else:
arrayItemSize = 4
# The size information is itself aligned according to the alignment rules for
# primitive data types. (See Section 14.2.2 on page 620.) The data of the constructed
# type is then aligned according to the alignment rules for the constructed type.
# In other words, the size information precedes the structure and is aligned
# independently of the structure alignment.
# We need to check whether we need padding or not
pad0 = (arrayItemSize - (soFar % arrayItemSize)) % arrayItemSize
if pad0 > 0:
soFar += pad0
data = data[pad0:]
# And now, let's pretend we put the item in
soFar += arrayItemSize
# And let's extract the array size for later use, if it is a pointer, it is after the referent ID
if isinstance(self, NDRPOINTER):
# ToDo: Check if we have to align the arrayItemSize
# I guess is it aligned since the NDRPOINTER is aligned already
pointerData = data[:arrayItemSize]
arraySize, advanceStream = self.getArraySize(lastItem, data[arrayItemSize:], soFar+arrayItemSize)
data = pointerData + data[arrayItemSize*2:]
else:
arraySize, advanceStream = self.getArraySize(lastItem, data, soFar)
data = data[arrayItemSize:]
# Let's tell the array how many items are available
self.fields[lastItem].setArraySize(arraySize)
# Now we need to align the structure
# The alignment of a structure in the octet stream is the largest of the alignments of the fields it
# contains. These fields may also be constructed types. The same alignment rules apply
# recursively to nested constructed types.
alignment = self.getAlignment()
if alignment > 0:
pad = (alignment - (soFar % alignment)) % alignment
if pad > 0:
soFar += pad
data = data[pad:]
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
try:
size = self.unpack(fieldName, fieldTypeOrClass, data, soFar)
data = data[size:]
soFar += size
except Exception,e:
LOG.error(str(e))
LOG.error("Error unpacking field '%s | %s | %r'" % (fieldName, fieldTypeOrClass, data[:256]))
raise
return soFar - soFar0
def getAlignment(self):
# Alignment of Constructed Types
#
# NDR enforces NDR alignment of structured data. As with primitive data types, an alignment, n, is determined
# for the structure. Where necessary, an alignment gap of octets of unspecified value precedes the data in
# the NDR octet stream. This gap is the smallest size sufficient to align the first field of the structure
# on an NDR octet stream index of n.
# The rules for calculating the alignment of constructed types are as follows:
# 1) If a conformant structure-that is, a conformant or conformant varying array, or a structure containing
# a conformant or conformant varying array-is embedded in the constructed type, and is the outermost
# structure-that is, is not contained in another structure-then the size information from the contained
# conformant structure is positioned so that it precedes both the containing constructed type and any
# alignment gap for the constructed type. (See Section 14.3.7 for information about structures containing
# arrays.) The size information is itself aligned according to the alignment rules for primitive data
# types. (See Section 14.2.2 on page 620.) The data of the constructed type is then aligned according to
# the alignment rules for the constructed type. In other words, the size information precedes the structure
# and is aligned independently of the structure alignment.
# 2) The alignment of a structure in the octet stream is the largest of the alignments of the fields it
# contains. These fields may also be constructed types. The same alignment rules apply recursively to nested
# constructed types.
align = 0
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:
if isinstance(self.fields[fieldName], NDR):
tmpAlign = self.fields[fieldName].getAlignment()
else:
tmpAlign = self.calcPackSize(fieldTypeOrClass, '')
if tmpAlign > align:
align = tmpAlign
return align
# Unions
class NDRUNION(NDRCONSTRUCTEDTYPE):
commonHdr = (
('tag', NDRUSHORT),
)
commonHdr64 = (
('tag', NDRULONG),
)
union = {
# For example
#1: ('pStatusChangeParam1', PSERVICE_NOTIFY_STATUS_CHANGE_PARAMS_1),
#2: ('pStatusChangeParams', PSERVICE_NOTIFY_STATUS_CHANGE_PARAMS_2),
}
def __init__(self, data = None, isNDR64=False, topLevel = False):
#ret = NDR.__init__(self,None, isNDR64=isNDR64)
self.topLevel = topLevel
self._isNDR64 = isNDR64
self.fields = {}
if isNDR64 is True:
if self.commonHdr64 != ():
self.commonHdr = self.commonHdr64
if self.structure64 != ():
self.structure = self.structure64
if hasattr(self, 'align64'):
self.align = self.align64
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:
if self.isNDR(fieldTypeOrClass):
if self.isPointer(fieldTypeOrClass):
self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64, topLevel = topLevel)
elif self.isUnion(fieldTypeOrClass):
self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64, topLevel = topLevel)
else:
self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64)
elif fieldTypeOrClass == ':':
self.fields[fieldName] = None
elif len(fieldTypeOrClass.split('=')) == 2:
try:
self.fields[fieldName] = eval(fieldTypeOrClass.split('=')[1])
except:
self.fields[fieldName] = None
else:
self.fields[fieldName] = 0
if data is not None:
self.fromString(data)
def __setitem__(self, key, value):
if key == 'tag':
# We're writing the tag, we now should set the right item for the structure
self.structure = ()
if self.union.has_key(value):
self.structure = (self.union[value]),
# Init again the structure
self.__init__(None, isNDR64=self._isNDR64, topLevel = self.topLevel)
self.fields['tag']['Data'] = value
else:
# Let's see if we have a default value
if self.union.has_key('default'):
if self.union['default'] is None:
self.structure = ()
else:
self.structure = (self.union['default']),
# Init again the structure
self.__init__(None, isNDR64=self._isNDR64, topLevel = self.topLevel)
self.fields['tag']['Data'] = 0xffff
else:
raise Exception("Unknown tag %d for union!" % value)
else:
return NDRCONSTRUCTEDTYPE.__setitem__(self,key,value)
def getData(self, soFar = 0):
data = ''
soFar0 = soFar
# Let's align ourselves
alignment = self.getAlignment()
if alignment > 0:
pad = (alignment - (soFar % alignment)) % alignment
else:
pad = 0
if pad > 0:
soFar += pad
data += '\xbc'*pad
for fieldName, fieldTypeOrClass in self.commonHdr:
try:
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data += '\xbb'*pad
res = self.pack(fieldName, fieldTypeOrClass, soFar)
data += res
soFar = soFar0 + len(data)
except Exception, e:
LOG.error(str(e))
LOG.error("Error packing field '%s | %s' in %s" % (fieldName, fieldTypeOrClass, self.__class__))
raise
# WARNING
# Now we need to align what's coming next.
# This doesn't come from the documentation but from seeing the packets in the wire
# for some reason, even if the next field is a SHORT, it should be aligned to
# a DWORD, or HYPER if NDR64.
if self._isNDR64:
align = 8
else:
if hasattr(self, 'notAlign'):
align = 1
else:
align = 4
pad = (align - (soFar % align)) % align
if pad > 0:
data += '\xbd'*pad
soFar += pad
if self.structure is ():
return data
for fieldName, fieldTypeOrClass in self.structure:
try:
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data += '\xbe'*pad
res = self.pack(fieldName, fieldTypeOrClass, soFar)
data += res
soFar = soFar0 + len(data)
except Exception, e:
LOG.error(str(e))
LOG.error("Error packing field '%s | %s' in %s" % (fieldName, fieldTypeOrClass, self.__class__))
raise
return data
def fromString(self, data, soFar = 0 ):
soFar0 = soFar
# Let's align ourselves
alignment = self.getAlignment()
if alignment > 0:
pad = (alignment - (soFar % alignment)) % alignment
else:
pad = 0
if pad > 0:
soFar += pad
data = data[pad:]
if len(data) > 4:
# First off, let's see what the tag is:
# We need to know the tag type and unpack it
tagtype = self.commonHdr[0][1].structure[0][1].split('=')[0]
tag = unpack(tagtype, data[:calcsize(tagtype)])[0]
if self.union.has_key(tag):
self.structure = (self.union[tag]),
self.__init__(None, isNDR64=self._isNDR64, topLevel = self.topLevel)
else:
# Let's see if we have a default value
if self.union.has_key('default'):
if self.union['default'] is None:
self.structure = ()
else:
self.structure = (self.union['default']),
# Init again the structure
self.__init__(None, isNDR64=self._isNDR64, topLevel = self.topLevel)
self.fields['tag']['Data'] = 0xffff
else:
raise Exception("Unknown tag %d for union!" % tag)
for fieldName, fieldTypeOrClass in self.commonHdr:
try:
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data = data[pad:]
size = self.unpack(fieldName, fieldTypeOrClass, data, soFar)
data = data[size:]
soFar += size
except Exception,e:
LOG.error(str(e))
LOG.error("Error unpacking field '%s | %s | %r'" % (fieldName, fieldTypeOrClass, data[:256]))
raise
# WARNING
# Now we need to align what's coming next.
# This doesn't come from the documentation but from seeing the packets in the wire
# for some reason, even if the next field is a SHORT, it should be aligned to
# a DWORD, or HYPER if NDR64.
if self._isNDR64:
align = 8
else:
if hasattr(self, 'notAlign'):
align = 1
else:
align = 4
pad = (align - (soFar % align)) % align
if pad > 0:
data = data[pad:]
soFar += pad
if self.structure is ():
return self
for fieldName, fieldTypeOrClass in self.structure:
try:
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data = data[pad:]
size = self.unpack(fieldName, fieldTypeOrClass, data, soFar)
data = data[size:]
soFar += size
except Exception,e:
LOG.error(str(e))
LOG.error("Error unpacking field '%s | %s | %r'" % (fieldName, fieldTypeOrClass, data[:256]))
raise
return soFar - soFar0
def getAlignment(self):
# Union alignment is the largest alignment of the union discriminator
# and all of the union arms.
# WRONG, I'm calculating it just with the tag, if I do it with the
# arms I get bad stub data. Something wrong I'm doing or the standard
# is wrong (most probably it's me :s )
align = 0
if self._isNDR64:
fields = self.commonHdr+self.structure
else:
fields = self.commonHdr
for fieldName, fieldTypeOrClass in fields:
if isinstance(self.fields[fieldName], NDR):
tmpAlign = self.fields[fieldName].getAlignment()
else:
tmpAlign = self.calcPackSize(fieldTypeOrClass, '')
if tmpAlign > align:
align = tmpAlign
if self._isNDR64:
for fieldName, fieldTypeOrClass in self.union.itervalues():
tmpAlign = fieldTypeOrClass(isNDR64 = self._isNDR64).getAlignment()
if tmpAlign > align:
align = tmpAlign
return align
# Pipes not implemented for now
# Pointers
class NDRPOINTERNULL(NDR):
align = 4
align64 = 8
structure = (
('Data', '<L=0'),
)
structure64 = (
('Data', '<Q=0'),
)
def dump(self, msg = None, indent = 0):
if msg is None: msg = self.__class__.__name__
if msg != '':
print "%s" % msg,
# Here we just print NULL
print " NULL",
NULL = NDRPOINTERNULL()
class NDRPOINTER(NDRSTRUCT):
align = 4
align64 = 8
commonHdr = (
('ReferentID','<L=0xff'),
)
commonHdr64 = (
('ReferentID','<Q=0xff'),
)
referent = (
# This is the representation of the Referent
('Data',':'),
)
def __init__(self, data = None, isNDR64=False, topLevel = False):
NDRSTRUCT.__init__(self,None, isNDR64=isNDR64)
# If we are being called from a NDRCALL, it's a TopLevelPointer,
# if not, it's a embeeded pointer.
# It is *very* important, for every subclass of NDRPointer
# you have to declare the referent in the referent variable
# Not in the structure one!
if topLevel is True:
self.structure = self.referent
self.referent = ()
if data is None:
self.fields['ReferentID'] = random.randint(1,65535)
else:
self.fromString(data)
def __setitem__(self, key, value):
if self.fields.has_key(key) is False:
# Key not found.. let's send it to the referent to handle, maybe it's there
return self.fields['Data'].__setitem__(key,value)
else:
return NDRSTRUCT.__setitem__(self,key,value)
def __getitem__(self, key):
if self.fields.has_key(key):
if isinstance(self.fields[key], NDR):
if self.fields[key].fields.has_key('Data'):
return self.fields[key]['Data']
return self.fields[key]
else:
# Key not found, let's send it to the referent, maybe it's there
return self.fields['Data'].__getitem__(key)
def getData(self, soFar = 0):
# First of all we need to align ourselves
data = ''
pad = self.calculatePad(self.commonHdr[0][1], soFar)
if pad > 0:
soFar += pad
data = '\xaa'*pad
# If we have a ReferentID == 0, means there's no data
if self.fields['ReferentID'] == 0:
if len(self.referent) > 0:
self['Data'] = ''
else:
if self._isNDR64 is True:
return data+'\x00'*8
else:
return data+'\x00'*4
return data + NDRSTRUCT.getData(self, soFar)
def fromString(self,data,soFar = 0):
# First of all we need to align ourselves
pad = self.calculatePad(self.commonHdr[0][1], soFar)
if pad > 0:
soFar += pad
data = data[pad:]
# Do we have a Referent ID == 0?
if self._isNDR64 is True:
unpackStr = '<Q'
else:
unpackStr = '<L'
if unpack(unpackStr, data[:calcsize(unpackStr)])[0] == 0:
# Let's save the value
self['ReferentID'] = 0
self.fields['Data'] = ''
if self._isNDR64 is True:
return pad + 8
else:
return pad + 4
else:
retVal = NDRSTRUCT.fromString(self,data, soFar)
return retVal + pad
def dump(self, msg = None, indent = 0):
if msg is None: msg = self.__class__.__name__
if msg != '':
print "%s" % msg,
# Here we just print the referent
if isinstance(self.fields['Data'], NDR):
self.fields['Data'].dump('', indent = indent)
else:
if self['ReferentID'] == 0:
print " NULL",
else:
print " %r" % (self['Data']),
def getAlignment(self):
if self._isNDR64 is True:
return 8
else:
return 4
# Embedded Reference Pointers not implemented for now
################################################################################
# Common RPC Data Types
class PNDRUniConformantVaryingArray(NDRPOINTER):
referent = (
('Data', NDRUniConformantVaryingArray),
)
class PNDRUniConformantArray(NDRPOINTER):
referent = (
('Data', NDRUniConformantArray),
)
def __init__(self, data = None, isNDR64 = False, topLevel = False):
NDRPOINTER.__init__(self,data,isNDR64,topLevel)
class NDRCALL(NDRCONSTRUCTEDTYPE):
# This represents a group of NDR instances that conforms an NDR Call.
# The only different between a regular NDR instance is a NDR call must
# represent the referents when building the final octet stream
referent = ()
commonHdr = ()
commonHdr64 = ()
structure = ()
structure64 = ()
align = 4
def __init__(self, data = None, isNDR64 = False):
self._isNDR64 = isNDR64
self.fields = {}
if isNDR64 is True:
if self.commonHdr64 != ():
self.commonHdr = self.commonHdr64
if self.structure64 != ():
self.structure = self.structure64
if hasattr(self, 'align64'):
self.align = self.align64
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure+self.referent:
if self.isNDR(fieldTypeOrClass):
if self.isPointer(fieldTypeOrClass):
self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64, topLevel = True)
elif self.isUnion(fieldTypeOrClass):
self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64, topLevel = True)
else:
self.fields[fieldName] = fieldTypeOrClass(isNDR64 = self._isNDR64)
elif fieldTypeOrClass == ':':
self.fields[fieldName] = None
elif len(fieldTypeOrClass.split('=')) == 2:
try:
self.fields[fieldName] = eval(fieldTypeOrClass.split('=')[1])
except:
self.fields[fieldName] = None
else:
self.fields[fieldName] = 0
if data is not None:
self.fromString(data)
def dump(self, msg = None, indent = 0):
NDRCONSTRUCTEDTYPE.dump(self, msg, indent)
print '\n\n'
def getData(self, soFar = 0):
data = ''
soFar0 = soFar
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
try:
pad = self.calculatePad(fieldTypeOrClass, soFar)
if pad > 0:
soFar += pad
data += '\xab'*pad
# Are we dealing with an array?
if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName],
NDRUniConformantVaryingArray):
# Align size item
if self._isNDR64:
pad = (8 - (soFar % 8)) % 8
else:
pad = (4 - (soFar % 4)) % 4
# Pack the item
res = self.pack(fieldName, fieldTypeOrClass, soFar+pad)
# Yes, get the array size
arraySize = self.getArrayMaximumSize(fieldName)
if self._isNDR64:
pad = (8 - (soFar % 8)) % 8
data += '\xce'*pad + pack('<Q', arraySize) + res
else:
pad = (4 - (soFar % 4)) % 4
data += '\xce'*pad + pack('<L', arraySize) + res
else:
data += self.pack(fieldName, fieldTypeOrClass, soFar)
soFar = soFar0 + len(data)
# Any referent information to pack?
# I'm still not sure whether this should go after processing
# all the fields at the call level.
# Guess we'll figure it out testing.
if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):
data += self.fields[fieldName].getDataReferents(soFar)
soFar = soFar0 + len(data)
data += self.fields[fieldName].getDataReferent(soFar)
soFar = soFar0 + len(data)
except Exception, e:
LOG.error(str(e))
LOG.error("Error packing field '%s | %s' in %s" % (fieldName, fieldTypeOrClass, self.__class__))
raise
return data
def fromString(self, data, soFar = 0):
soFar0 = soFar
for fieldName, fieldTypeOrClass in self.commonHdr+self.structure:
try:
# Are we dealing with an array?
if isinstance(self.fields[fieldName], NDRUniConformantArray) or isinstance(self.fields[fieldName],
NDRUniConformantVaryingArray):
# Yes, get the array size
arraySize, advanceStream = self.getArraySize(fieldName, data, soFar)
self.fields[fieldName].setArraySize(arraySize)
soFar += advanceStream
data = data[advanceStream:]
size = self.unpack(fieldName, fieldTypeOrClass, data, soFar)
# Any referent information to unpack?
if isinstance(self.fields[fieldName], NDRCONSTRUCTEDTYPE):
size += self.fields[fieldName].fromStringReferents(data[size:], soFar + size)
size += self.fields[fieldName].fromStringReferent(data[size:], soFar + size)
data = data[size:]
soFar += size
except Exception,e:
LOG.error(str(e))
LOG.error("Error unpacking field '%s | %s | %r'" % (fieldName, fieldTypeOrClass, data[:256]))
raise
return soFar - soFar0
# Top Level Struct == NDRCALL
NDRTLSTRUCT = NDRCALL
class UNKNOWNDATA(NDR):
align = 1
structure = (
('Data', ':'),
)
################################################################################
# Tests
class NDRTest:
def create(self,data = None, isNDR64 = False):
if data is not None:
return self.theClass(data, isNDR64 = isNDR64)
else:
return self.theClass(isNDR64 = isNDR64)
def test(self, isNDR64 = False):
print
print "-"*70
testName = self.__class__.__name__
print "starting test: %s (NDR64 = %s)....." % (testName, isNDR64)
a = self.create(isNDR64 = isNDR64)
self.populate(a)
a.dump("packing.....")
a_str = str(a)
print "packed:"
hexdump(a_str)
print "unpacking....."
b = self.create(a_str, isNDR64 = isNDR64)
b.dump("unpacked.....")
print "\nrepacking....."
b_str = str(b)
if b_str != a_str:
print "ERROR: original packed and repacked don't match"
print "packed: "
hexdump(b_str)
raise
def run(self):
self.test(False)
# Now the same tests but with NDR64
self.test(True)
class TestUniFixedArray(NDRTest):
class theClass(NDRSTRUCT):
structure = (
('Array', NDRUniFixedArray),
)
def populate(self, a):
a['Array'] = '12345678'
class TestStructWithPad(NDRTest):
class theClass(NDRSTRUCT):
structure = (
('long', NDRLONG),
('short', NDRSHORT),
)
def populate(self, a):
a['long'] = 0xaa
a['short'] = 0xbb
#class TestUniConformantArray(NDRTest):
# class theClass(NDRCall):
# structure = (
# ('Array', PNDRUniConformantArray),
# ('Array2', PNDRUniConformantArray),
# )
# def __init__(self, data = None,isNDR64 = False):
# NDRCall.__init__(self, None, isNDR64)
# self.fields['Array'].fields['Data'].item = RPC_UNICODE_STRING
# self.fields['Array2'].fields['Data'].item = RPC_UNICODE_STRING
# if data is not None:
# self.fromString(data)
#
# def populate(self, a):
# array = []
# strstr = RPC_UNICODE_STRING()
# strstr['Data'] = 'ThisIsMe'
# array.append(strstr)
# strstr = RPC_UNICODE_STRING()
# strstr['Data'] = 'ThisIsYou'
# array.append(strstr)
# a['Array'] = array
# a['Array2'] = array
class TestUniVaryingArray(NDRTest):
class theClass(NDRSTRUCT):
structure = (
('Array', NDRUniVaryingArray),
)
def populate(self, a):
a['Array'] = '12345678'
class TestUniConformantVaryingArray(NDRTest):
class theClass(NDRSTRUCT):
structure = (
('Array', NDRUniConformantVaryingArray),
)
def populate(self, a):
a['Array'] = '12345678'
class TestVaryingString(NDRTest):
class theClass(NDRSTRUCT):
structure = (
('Array', NDRVaryingString),
)
def populate(self, a):
a['Array'] = '12345678'
class TestConformantVaryingString(NDRTest):
class theClass(NDRSTRUCT):
structure = (
('Array', NDRConformantVaryingString),
)
def populate(self, a):
a['Array'] = '12345678'
class TestPointerNULL(NDRTest):
class theClass(NDRSTRUCT):
structure = (
('Array', NDRPOINTERNULL),
)
def populate(self, a):
pass
if __name__ == '__main__':
TestUniFixedArray().run()
#TestUniConformantArray().run()
TestUniVaryingArray().run()
TestUniConformantVaryingArray().run()
TestVaryingString().run()
TestConformantVaryingString().run()
TestPointerNULL().run()
TestStructWithPad().run()
|