Example #1
0
def read_ftr(filename, delete_keys=None):
    offset_size = 1859

    ftr_record_struct = Struct("record",
        LFloat32("Datetime"),
        LFloat32("PosX"),
        LFloat32("PosY"),
        LFloat32("Altitude"),
        LFloat32("Qx"),
        LFloat32("Qy"),
        LFloat32("Qz"),
        LFloat32("Qw"),
        LFloat32("DistUnused"),
    )

    ftr_struct = Struct("ftr_header",
        String("filetype", 4),
        #Bytes("unknown00", 136),
        #String("FirstName", 17),
        Bytes("unknown00", 135),
        String("FirstName", 17),
        String("FamilyName", 17),
        String("Country", 17),
        String("RN", 8),
        String("CN", 4),
        Bytes("unknown02", 5),
        String("Landscape", 17),
        Bytes("unknown03", offset_size - 4 - 135 - 17 - 17 - 17 - 17 - 17),
        ULInt32("length"), # uint32 (4 bytes) @ 1859
        Array(lambda ctx: ctx.length, ftr_record_struct),
    )

    with open(filename, "rb") as fd:
        dat = ftr_struct.parse_stream(fd)

    df_ftr = pd.DataFrame(dat['record'])

    df_ftr['Time'] = df_ftr['Datetime'] * 3600.0
    df_ftr['Time'] = df_ftr['Time'] - df_ftr['Time'].irow(0)
    df_ftr['Datetime'] = pd.to_datetime(df_ftr['Time'], unit='s')
    df_ftr['Deltatime'] = df_ftr['Datetime'] - df_ftr['Datetime'].shift(1)
    df_ftr['Deltatime'] = df_ftr['Deltatime'] / np.timedelta64(1, 's') # Deltatime as seconds
    #df_ftr['Vz'] = ((df_ftr['Altitude'] - df_ftr['Altitude'].shift(1)).fillna(0) / df_ftr['Deltatime']).fillna(0)
    #df_ftr = df_ftr.set_index('Datetime', verify_integrity=True)
    df_ftr = df_ftr.set_index('Time', verify_integrity=True) # Time (s)

    dat['record'] = df_ftr

    if delete_keys is not None:
        for key in delete_keys:
            if key in dat.keys():
                del dat[key]

    for key in ['FirstName', 'FamilyName', 'Country', 'Landscape', 'RN', 'CN']:
        length = ord(dat[key][0])
        s = dat[key][1:length+1]
        dat[key] = s.replace('\x00', '')
        assert len(dat[key])==length, "Length error with %s len=%d should be %d" % (s, len(s), length)

    return(dat)
Example #2
0
    def __init__(self, filename, encoding=None, password=None, cached=True, check=False,
                 current_tablename=None, date_fieldname=None,
                 time_fieldname=None, decryptor_class=TpsDecryptor):
        self.filename = filename
        self.encoding = encoding
        self.password = password
        self.cached = cached
        self.check = check
        self.current_table_number = None
        # Name part before .tps
        self.name = os.path.basename(filename)
        self.name = text_type(os.path.splitext(self.name)[0]).lower()
        if date_fieldname is not None:
            self.date_fieldname = date_fieldname
        else:
            self.date_fieldname = []
        if time_fieldname is not None:
            self.time_fieldname = time_fieldname
        else:
            self.time_fieldname = []
        self.cache_pages = {}

        if not os.path.isfile(self.filename):
            raise FileNotFoundError(self.filename)

        self.file_size = os.path.getsize(self.filename)

        # Check file size
        if check:
            if self.file_size & 0x3F != 0:
                # TODO check translate
                warn('File size is not a multiple of 64 bytes.', RuntimeWarning)

        with open(self.filename, mode='r+b') as tpsfile:
            self.tps_file = mmap.mmap(tpsfile.fileno(), 0)

            self.decryptor = decryptor_class(self.tps_file, self.password)

            try:
                # TPS file header
                header = Struct('header',
                                ULInt32('offset'),
                                ULInt16('size'),
                                ULInt32('file_size'),
                                ULInt32('allocated_file_size'),
                                Const(Bytes('top_speed_mark', 6), b'tOpS\x00\x00'),
                                UBInt32('last_issued_row'),
                                ULInt32('change_count'),
                                ULInt32('page_root_ref'),
                                Array(lambda ctx: (ctx['size'] - 0x20) / 2 / 4, ULInt32('block_start_ref')),
                                Array(lambda ctx: (ctx['size'] - 0x20) / 2 / 4, ULInt32('block_end_ref')), )

                self.header = header.parse(self.read(0x200))
                self.pages = TpsPagesList(self, self.header.page_root_ref, check=self.check)
                self.tables = TpsTablesList(self, encoding=self.encoding, check=self.check)
                self.set_current_table(current_tablename)
            except adapters.ConstError:
                print('Bad cryptographic keys.')
Example #3
0
 def test(self):
     pstring = Struct("pstring", 
         UBInt8("length"),
         Struct("inner",
             UBInt8("inner_length"),
             Bytes("data", foo),
         )
     )
     obj = pstring.parse(six.b("\x03\x02helloXXX"))
     print(repr(obj))
     self.assertEqual(obj, Container(length = 3, inner = Container(inner_length = 2, data = six.b("hello"))))
     size = pstring._sizeof(Container(inner_length = 2, _ = Container(length = 3)))
     self.assertEqual(size, 7)
Example #4
0
def parse_header(data):
    """
    split up header information (using construct)
    """
    mavlink_header = Struct('header',
        Const(Byte('magic'), MAVLINK_MAGIC),
        Byte('plength'),
        Byte('sequence'),
        Byte('sysid'),
        Byte('compid'),
        Byte('msgid'),
    )
    return mavlink_header.parse(data[0:6])
Example #5
0
 def _parse(self, stream, context):
     data = Struct._parse(self, stream, context)
     size = data._end - data._start
     aligned_length = aligned4(size)
     if aligned_length > size:
         # ignore the input
         stream.read(aligned_length - size)
     return data
Example #6
0
    def setUp(self):

        self.cons = Struct('foo',
            Enum(Byte("a_enum"),
                ALFA=1,
                BETA=2
                ),
                Switch('switch', lambda ctx: ctx.a_enum, {
                    'ALFA': Embed(Struct('struct_alfa', Byte('byte_alfa'))),
                    'BETA': Embed(Struct('struct_beta', Byte('byte_beta'))),
                })
            )
Example #7
0
    def test_overwrite(self):
        s = Struct("s",
            Byte("a"),
            Byte("a"),
            allow_overwrite = True
        )
        self.assertEqual(s.parse(six.b("\x01\x02")).a, 2)

        s = Struct("s",
            Byte("a"),
            Embedded(Struct("b",
                Byte("a"),
                allow_overwrite = True
            )),
        )
        self.assertEqual(s.parse(six.b("\x01\x02")).a, 2)

        s = Struct("s",
            Embedded(Struct("b",
                Byte("a"),
            )),
            Byte("a"),
            allow_overwrite = True
        )
        self.assertEqual(s.parse(six.b("\x01\x02")).a, 2)
Example #8
0
def get_data(binary_data):
    """Get data from binary string."""

    raw_header, raw_body = binary_data[:HEADER_LENTH], binary_data[HEADER_LENTH+1:]

    # TODO !!! Uncomment when will take valid data !!!
    #header = HEADER_FORMAT.parse(raw_header)
    # if binascii.crc_hqx(raw_body, 0xffff) != header.checksum:
    #     logger.exception('Checksums is not match')
    #     raise InputError(binascii.crc_hqx(raw_body, 0xffff), 'Checksums is not match')

    result = {}

    while True:
        current_type = raw_body[:1]
        if not current_type:
            return result
        type_of_struct = "0x{}".format(binascii.hexlify(current_type))

        data = STRUCT_TYPES.get(type_of_struct, None)
        if not data:
            logger.exception('Data type is not exist')
            raise AttributeError

        data_size = data[1] if not isinstance(data[1], int) else Byte[data[1]]
        body_format = Struct(
            "type" / Int8ul,
            "data" / data_size,
        )

        # TODO !!! Remove that exception when will take valid data
        try:
            current = body_format.parse(raw_body[:data_size.sizeof()+1])
        except :
            return result

        result[data[0]] =  current.data

        raw_body = raw_body[body_format.sizeof():]
Example #9
0
def dispatch(stream, protodef):
    opcode = ULInt16("opcode").parse_stream(stream)

    if opcode in protodef:
        func, macro = protodef[opcode]
        data = macro.parse_stream(stream)
        func(data)
    else:
        data = ''
        pktlen = packet_lengths.get(opcode, -1)

        if pktlen > 0:
            data = stream.read(pktlen - 2)
        elif pktlen == -1:
            datadef = Struct("data",
                             ULInt16("length"),
                             MetaField("ignore",
                                       lambda ctx: ctx["length"] - 4))
            data = datadef.parse_stream(stream)

        netlog.warning('UNIMPLEMENTED opcode={:04x} data={}'.format(
            opcode, data))
Example #10
0
class TestMetaFieldStruct(unittest.TestCase):
    def setUp(self):
        self.mf = MetaField("data", lambda context: context["length"])
        self.s = Struct("foo", Byte("length"), self.mf)

    def test_trivial(self):
        pass

    def test_parse(self):
        c = self.s.parse(b"\x03ABC")
        self.assertEqual(c.length, 3)
        self.assertEqual(c.data, b"ABC")

        c = self.s.parse(b"\x04ABCD")
        self.assertEqual(c.length, 4)
        self.assertEqual(c.data, b"ABCD")

    def test_sizeof_default(self):
        self.assertRaises(SizeofError, self.mf.sizeof)

    def test_sizeof(self):
        context = Container(length=4)
        self.assertEqual(self.mf.sizeof(context), 4)
 def __init__(self):
     # 接收数据的数据格式定义
     self.rfidFrame = Struct("frame",
                             OptionalGreedyRange(
                                 Struct("packets",
                                        UBInt16("header"),
                                        Enum(UBInt8("cmdcode"),
                                             F1=0xF1,
                                             F2=0xF2,
                                             F3=0xF3,
                                             F4=0xF4,
                                             ),
                                        Switch("datas", lambda ctx: ctx.cmdcode, {
                                            "F1": Struct("sub",
                                                         UBInt8("readerID"),
                                                         UBInt8("packet_len"),
                                                         UBInt8("status"),
                                                         Array(lambda ctx: (
                                                                               ctx.packet_len - 2 - 1 - 1 - 1 - 1 - 2) / 6,
                                                               Struct("blocks",
                                                                      # UBInt8('elec'),
                                                                      Array(3, UBInt8('cardID')),
                                                                      UBInt8('triggerID'),
                                                                      UBInt16('relativeTime')
                                                                      )
                                                               )
                                                         ),
                                            "F2": Struct("sub", UBInt8("packet_len"), UBInt8("readerID")),
                                            "F3": Struct("sub", UBInt8("packet_len"), UBInt8("result")),
                                            "F4": Struct("sub", UBInt8("packet_len"), UBInt8("rssl")),
                                        }
                                               ),
                                        UBInt16("crc"),
                                        )
                             ),
                             OptionalGreedyRange(
                                 UBInt8("leftovers"),
                             ),
                             )
     self.readerID = None
     self.rssl = 1
     self.triggerID = None
Example #12
0
class TestEmbedingBranch(TestCase):

    def setUp(self):

        self.cons = Struct('foo',
            Enum(Byte("a_enum"),
                ALFA=1,
                BETA=2
                ),
                Switch('switch', lambda ctx: ctx.a_enum, {
                    'ALFA': Embed(Struct('struct_alfa', Byte('byte_alfa'))),
                    'BETA': Embed(Struct('struct_beta', Byte('byte_beta'))),
                })
            )

    def test_construct(self):
        contents = self.cons.parse('\x01\x03\xee\x33')
        self.assertIn('a_enum', contents)
        self.assertEqual(contents['a_enum'], 'ALFA')
        self.assertIn('byte_alfa', contents)
class RfidFrame(object):
    def __init__(self):
        # 接收数据的数据格式定义
        self.rfidFrame = Struct("frame",
                                OptionalGreedyRange(
                                    Struct("packets",
                                           UBInt16("header"),
                                           Enum(UBInt8("cmdcode"),
                                                F1=0xF1,
                                                F2=0xF2,
                                                F3=0xF3,
                                                F4=0xF4,
                                                ),
                                           Switch("datas", lambda ctx: ctx.cmdcode, {
                                               "F1": Struct("sub",
                                                            UBInt8("readerID"),
                                                            UBInt8("packet_len"),
                                                            UBInt8("status"),
                                                            Array(lambda ctx: (
                                                                                  ctx.packet_len - 2 - 1 - 1 - 1 - 1 - 2) / 6,
                                                                  Struct("blocks",
                                                                         # UBInt8('elec'),
                                                                         Array(3, UBInt8('cardID')),
                                                                         UBInt8('triggerID'),
                                                                         UBInt16('relativeTime')
                                                                         )
                                                                  )
                                                            ),
                                               "F2": Struct("sub", UBInt8("packet_len"), UBInt8("readerID")),
                                               "F3": Struct("sub", UBInt8("packet_len"), UBInt8("result")),
                                               "F4": Struct("sub", UBInt8("packet_len"), UBInt8("rssl")),
                                           }
                                                  ),
                                           UBInt16("crc"),
                                           )
                                ),
                                OptionalGreedyRange(
                                    UBInt8("leftovers"),
                                ),
                                )
        self.readerID = None
        self.rssl = 1
        self.triggerID = None

    def rfidFrameParse(self, bytestream):
        return self.rfidFrame.parse(bytestream)

    def handle_data(self, pkgs):
        cmdcode = pkgs[0].cmdcode
        # datas = pkgs.packets.datas[0]
        # 对指令码判断工作模式
        if cmdcode == "F1":
            # 存储温度,湿度,以及其他数据
            print self.data_p(pkgs)
            # #rfidDb.saveID( self.cardID,self.triggerID,) #存储触发器id和卡号到数据库
            #
            # print 'the trigger ID is :', self.triggerID
            # print 'the card ID is :', self.cardID

        elif cmdcode == "F2":
            # 得到阅读器id
            self.readerID = self.getReaderID(pkgs)
            print self.readerID

        elif cmdcode == 'F3':  # 此处还不能写小写的f3,是字符串匹配,要和系统返回的一样.否则无法进入循环
            # 获得设置门限值的结果
            result = self.getResult(pkgs)
            result = hex(result)  # 此处result的值是2进制数要转换成16进制数来进行门限值的设置结果判断

            if result == '0xaa':
                print 'setted success'
            else:
                print 'setted falure'

        elif cmdcode == "F4":
            # 得到门限值
            self.rssl = self.getRSSI(pkgs)
            print self.rssl

    def getReaderID(self, pkgs):
        return pkgs[0].datas.readerID

    def getCardID(self, pkgs):
        return pkgs[0].datas.blocks[0].cardID

    def getTriggerID(self, pkgs):
        return pkgs[0].datas.blocks[0].triggerID

    def getResult(self, pkgs):
        return pkgs[0].datas.result

    def getRSSI(self, pkgs):
        return pkgs[0].datas.rssl

    def data_p(self, pkgs):

        data = ""  # 处理卡号和触发器id
        important_data = ""
        for pkg in pkgs[0].datas.blocks:
            cardID = pkg.cardID
            if cardID[0] == 1:
                print cardID
                print dec_to_hex(cardID[1]) + dec_to_hex(cardID[2]), "电量异常"

            data += dec_to_hex(cardID[1])
            data += dec_to_hex(cardID[2])

            triggerID = pkg.triggerID
            if triggerID != 0:
                important_data += hex_to_dec(data) + ":" + str(triggerID) + ","
            data = ""

        important_data = important_data[0:-1] + "\n"
        return important_data
class Microsoft_Windows_NFC_ClassExtension_104_1(Etw):
    pattern = Struct(
        "FileObject" / Int64ul
    )
Example #15
0
 def setUp(self):
     self.mf = MetaField("data", lambda context: context["length"])
     self.s = Struct("foo", Byte("length"), self.mf)
Example #16
0
 def __init__(self, name, *subcons, **kw):
     subcons = (Anchor("_start"),) + subcons + (Anchor("_end"),)
     Struct.__init__(self, name, *subcons, **kw)
Example #17
0
    def __setup_constructors(self):
        '''Set endianness and create transport-specific constructors.'''
        # Set endianness of constructors before using them.
        self._set_endian('little')

        self.__Length = Int32ul
        self.__Type = Enum(
                Int16ul,
                default=Pass,
                Undefined=0x0000,
                Command=0x0001,
                Data=0x0002,
                Response=0x0003,
                Event=0x0004,
                )
        # This is just a convenience constructor to get the size of a header.
        self.__Code = Int16ul
        self.__Header = Struct(
                'Length' / self.__Length,
                'Type' / self.__Type,
                'Code' / self.__Code,
                'TransactionID' / self._TransactionID,
                )
        # These are the actual constructors for parsing and building.
        self.__CommandHeader = Struct(
                'Length' / self.__Length,
                'Type' / self.__Type,
                'OperationCode' / self._OperationCode,
                'TransactionID' / self._TransactionID,
                )
        self.__ResponseHeader = Struct(
                'Length' / self.__Length,
                'Type' / self.__Type,
                'ResponseCode' / self._ResponseCode,
                'TransactionID' / self._TransactionID,
                )
        self.__EventHeader = Struct(
                'Length' / self.__Length,
                'Type' / self.__Type,
                'EventCode' / self._EventCode,
                'TransactionID' / self._TransactionID,
                )
        # Apparently nobody uses the SessionID field. Even though it is
        # specified in ISO15740:2013(E), no device respects it and the session
        # number is implicit over USB.
        self.__Param = Range(0, 5, self._Parameter)
        self.__CommandTransactionBase = Struct(
                Embedded(self.__CommandHeader),
                'Payload' / Bytes(
                    lambda ctx, h=self.__Header: ctx.Length - h.sizeof()
                )
        )
        self.__CommandTransaction = ExprAdapter(
                self.__CommandTransactionBase,
                encoder=lambda obj, ctx, h=self.__Header: Container(
                    Length=len(obj.Payload) + h.sizeof(),
                    **obj
                    ),
                decoder=lambda obj, ctx: obj,
                )
        self.__ResponseTransactionBase = Struct(
                Embedded(self.__ResponseHeader),
                'Payload' / Bytes(
                    lambda ctx, h=self.__Header: ctx.Length - h.sizeof())
                )
        self.__ResponseTransaction = ExprAdapter(
                self.__ResponseTransactionBase,
                encoder=lambda obj, ctx, h=self.__Header: Container(
                    Length=len(obj.Payload) + h.sizeof(),
                    **obj
                    ),
                decoder=lambda obj, ctx: obj,
                )
Example #18
0
class Microsoft_Windows_Websocket_Protocol_Component_2_0(Etw):
    pattern = Struct("Id" / Int32ul, "OperationType" / Int32ul)
Example #19
0
class Microsoft_Windows_Websocket_Protocol_Component_1_0(Etw):
    pattern = Struct("TraceMessage" / WString, "Error" / Int32ul)
Example #20
0
class Microsoft_Windows_Subsys_Csr_4_1(Etw):
    pattern = Struct("Status" / Int32ul, "ProcessId" / Int32ul)
Example #21
0
class Microsoft_Windows_Subsys_Csr_4_0(Etw):
    pattern = Struct("Status" / Int32ul)
Example #22
0
class Microsoft_Windows_Subsys_Csr_3_0(Etw):
    pattern = Struct("ProcessId" / Int32ul, "Level" / Int32ul,
                     "Flags" / Int32ul)
Example #23
0
LOAD_SEGMENT_CHUNK_HEADER_LENGTH = 3
MIN_PADDING_LENGTH = 1
SCP_MAC_LENGTH = 0xE


LEDGER_HSM_URL = "https://hsmprod.hardwarewallet.com/hsm/process"
LEDGER_HSM_KEY = "perso_11"


ApduListAppsResponse = Struct(
    Const(b"\x01"),  # Version
    apps=GreedyRange(
        Struct(
            # Application
            # Prefixed by the size of the structure, size included.
            _size=Rebuild(Int8ub, 1 + 4 + 32 + 32 + len_(this.name)),
            flags=Hex(Int32ub),
            code_data_hash=Bytes(32),
            full_hash=Bytes(32),
            name=PascalString(Int8ub, "utf-8"),
        )
    ),
)

VersionInfo = Struct(
    target_id=Hex(Int32ub),
    se_version=PascalString(Int8ub, "utf-8"),
    _flags_len=Const(b"\x04"),
    flags=FlagsEnum(
        Int32ul,
        recovery_mode=1,
        signed_mcu=2,
Example #24
0
    @classmethod
    def decode(cls, data: str, encoding: str):
        data_bytes = decode_byte_string(data, encoding)
        parsed = DECODE_VALIDATOR_LIST_LAYOUT.parse(data_bytes)
        print(parsed)
        return ValidatorList(
            max_validators=parsed['max_validators'],
            validators=[
                ValidatorStakeInfo.decode_container(container)
                for container in parsed['validators']
            ],
        )


FEE_LAYOUT = Struct(
    "denominator" / Int64ul,
    "numerator" / Int64ul,
)

STAKE_POOL_LAYOUT = Struct(
    "account_type" / Int8ul,
    "manager" / PUBLIC_KEY_LAYOUT,
    "staker" / PUBLIC_KEY_LAYOUT,
    "stake_deposit_authority" / PUBLIC_KEY_LAYOUT,
    "stake_withdraw_bump_seed" / Int8ul,
    "validator_list" / PUBLIC_KEY_LAYOUT,
    "reserve_stake" / PUBLIC_KEY_LAYOUT,
    "pool_mint" / PUBLIC_KEY_LAYOUT,
    "manager_fee_account" / PUBLIC_KEY_LAYOUT,
    "token_program_id" / PUBLIC_KEY_LAYOUT,
    "total_lamports" / Int64ul,
    "pool_token_supply" / Int64ul,
Example #25
0
    def __setup_constructors(self):
        '''Set endianness and create transport-specific constructors.'''
        # Set endianness of constructors before using them.
        self._set_endian('little')

        self.__Length = Int32ul
        self.__Type = Enum(
            Int32ul,
            Undefined=0x00000000,
            InitCommand=0x00000001,
            InitCommandAck=0x00000002,
            InitEvent=0x00000003,
            InitEventAck=0x00000004,
            InitFail=0x00000005,
            Command=0x00000006,
            Response=0x00000007,
            Event=0x00000008,
            StartData=0x00000009,
            Data=0x0000000A,
            Cancel=0x0000000B,
            EndData=0x0000000C,
            Ping=0x0000000D,
            Pong=0x0000000E,
        )
        self.__Header = Struct(
            'Length' / self.__Length,
            'Type' / self.__Type,
        )
        self.__Param = Range(0, 5, self._Parameter)
        self.__EventParam = Range(0, 3, self._Parameter)
        self.__PacketBase = Struct(
            Embedded(self.__Header),
            'Payload' / Bytes(
                lambda ctx, h=self.__Header: ctx.Length - h.sizeof()),
        )
        self.__Packet = ExprAdapter(
            self.__PacketBase,
            encoder=lambda obj, ctx, h=self.__Header: Container(
                Length=len(obj.Payload) + h.sizeof(),
                **obj
            ),
            decoder=lambda obj, ctx: obj,
        )
        # Yet another arbitrary string type. Max-length CString utf8-encoded
        self.__PTPIPString = ExprAdapter(
            RepeatUntil(
                lambda obj, ctx, lst:
                six.unichr(obj) in '\x00' or len(lst) == 40, Int16ul
            ),
            encoder=lambda obj, ctx:
            [] if len(obj) == 0 else[ord(c) for c in six.text_type(obj)]+[0],
            decoder=lambda obj, ctx:
            u''.join(
                [six.unichr(o) for o in obj]
            ).split('\x00')[0],
        )
        # PTP/IP packets
        # Command
        self.__ProtocolVersion = Struct(
            'Major' / Int16ul,
            'Minor' / Int16ul,
        )
        self.__InitCommand = Embedded(Struct(
            'InitiatorGUID' / Array(16, Int8ul),
            'InitiatorFriendlyName' / self.__PTPIPString,
            'InitiatorProtocolVersion' / self.__ProtocolVersion,
        ))
        self.__InitCommandACK = Embedded(Struct(
            'ConnectionNumber' / Int32ul,
            'ResponderGUID' / Array(16, Int8ul),
            'ResponderFriendlyName' / self.__PTPIPString,
            'ResponderProtocolVersion' / self.__ProtocolVersion,
        ))
        # Event
        self.__InitEvent = Embedded(Struct(
            'ConnectionNumber' / Int32ul,
        ))
        # Common to Events and Command requests
        self.__Reason = Enum(
            # TODO: Verify these codes...
            Int32ul,
            Undefined=0x0000,
            RejectedInitiator=0x0001,
            Busy=0x0002,
            Unspecified=0x0003,
        )
        self.__InitFail = Embedded(Struct(
            'Reason' / self.__Reason,
        ))

        self.__DataphaseInfo = Enum(
            Int32ul,
            Undefined=0x00000000,
            In=0x00000001,
            Out=0x00000002,
        )
        self.__Command = Embedded(Struct(
            'DataphaseInfo' / self.__DataphaseInfo,
            'OperationCode' / self._OperationCode,
            'TransactionID' / self._TransactionID,
            'Parameter' / self.__Param,
        ))
        self.__Response = Embedded(Struct(
            'ResponseCode' / self._ResponseCode,
            'TransactionID' / self._TransactionID,
            'Parameter' / self.__Param,
        ))
        self.__Event = Embedded(Struct(
            'EventCode' / self._EventCode,
            'TransactionID' / self._TransactionID,
            'Parameter' / self.__EventParam,
        ))
        self.__StartData = Embedded(Struct(
            'TransactionID' / self._TransactionID,
            'TotalDataLength' / Int64ul,
        ))
        # TODO: Fix packing and unpacking dataphase data
        self.__Data = Embedded(Struct(
            'TransactionID' / self._TransactionID,
            'Data' / Bytes(
                lambda ctx:
                ctx._.Length -
                self.__Header.sizeof() -
                self._TransactionID.sizeof()
            ),
        ))
        self.__EndData = Embedded(Struct(
            'TransactionID' / self._TransactionID,
            'Data' / Bytes(
                lambda ctx:
                ctx._.Length -
                self.__Header.sizeof() -
                self._TransactionID.sizeof()
            ),
        ))
        self.__Cancel = Embedded(Struct(
            'TransactionID' / self._TransactionID,
        ))
        # Convenience construct for parsing packets

        self.__PacketPayload = Debugger(Struct(
            'Header' / Embedded(self.__Header),
            'Payload' / Embedded(Switch(
                lambda ctx: ctx.Type,
                {
                    'InitCommand': self.__InitCommand,
                    'InitCommandAck': self.__InitCommandACK,
                    'InitEvent': self.__InitEvent,
                    'InitFail': self.__InitFail,
                    'Command': self.__Command,
                    'Response': self.__Response,
                    'Event': self.__Event,
                    'StartData': self.__StartData,
                    'Data': self.__Data,
                    'EndData': self.__EndData,
                },
                default=Pass,
            ))
        ))
Example #26
0
class Microsoft_Windows_Websocket_Protocol_Component_4_0(Etw):
    pattern = Struct("Id" / Int32ul)
Example #27
0
        return play_method(command, *command_args)


class ProntoPulseAdapter(Adapter):
    def _decode(self, obj, context, path):
        return int(obj * context._.modulation_period)

    def _encode(self, obj, context, path):
        raise RuntimeError('Not implemented')


ChuangmiIrSignal = Struct(
    Const(0xa567,
          Int16ul), 'edge_count' / Rebuild(Int16ul,
                                           len_(this.edge_pairs) * 2 - 1),
    'times_index' / Array(16, Int32ul), 'edge_pairs' / Array(
        (this.edge_count + 1) // 2,
        BitStruct(
            'gap' / BitsInteger(4),
            'pulse' / BitsInteger(4),
        )))

ProntoBurstPair = Struct(
    'pulse' / ProntoPulseAdapter(Int16ub),
    'gap' / ProntoPulseAdapter(Int16ub),
)

Pronto = Struct(
    Const(0, Int16ub),
    '_ticks' / Int16ub,
    'modulation_period' / Computed(this._ticks * 0.241246),
    'frequency' / Computed(1000000 / this.modulation_period),
class Microsoft_Windows_AssignedAccess_10004_0(Etw):
    pattern = Struct("AppID" / WString)
Example #29
0
 Who : jesse @ housejunkie . ca
"""

from construct import (
    Byte,
    Enum,
    Struct,
    UBInt16,
    UBInt32,
)
from construct.protocols.layer3.ipv4 import IpAddress

igmp_type = Enum(Byte("igmp_type"), 
    MEMBERSHIP_QUERY = 0x11,
    MEMBERSHIP_REPORT_V1 = 0x12,
    MEMBERSHIP_REPORT_V2 = 0x16,
    LEAVE_GROUP = 0x17,
)

igmpv2_header = Struct("igmpv2_header",
    igmp_type,
    Byte("max_resp_time"),
    UBInt16("checksum"),
    IpAddress("group_address"),
)

if __name__ == '__main__':
    
    capture = "1600FA01EFFFFFFD".decode("hex")
    print igmpv2_header.parse(capture)
class Microsoft_Windows_AssignedAccess_20000_0(Etw):
    pattern = Struct("SID" / WString, "UserName" / WString, "AppID" / WString,
                     "AppName" / WString)
Example #31
0
class Microsoft_AppV_ServiceLog_3_0(Etw):
    pattern = Struct(
        "Message" / WString,
        "Function" / WString,
        "Line" / Int32ul
    )
class Microsoft_Windows_AssignedAccess_30000_0(Etw):
    pattern = Struct("File" / CString, "LineNumber" / Int32ul,
                     "ErrorCode" / Int32ul, "ErrorCodeExpanded" / Int32sl)
Example #33
0
File: test.py Project: kooksee/TIOT
  if(sysstr =="Windows"):
    print ("Call Windows tasks")
  elif(sysstr == "Linux"):
    print ("Call Linux tasks")
  else:
    print ("Other System tasks")

# UsePlatform()


from construct import Struct, OptionalGreedyRange, Embed, Enum, Switch,String
from construct import UBInt8, UBInt16, UBInt32, UBInt64, Byte
from construct.macros import Array
rfid = Struct("frame",
                   UBInt8("flagID"),
                   String("f",1),
                     Array(4, String("nodeID",1)),
                   )
mm = rfid.parse("F1070E0100138E0000F21D65" | hexStr_to_hex)
print mm
print [binascii.b2a_hex(x) for x in mm.nodeID]
# print binascii.b2a_hex(mm.f)
# print mm.flagID
# print '01' | hex_to_dec
# print [binascii.b2a_hex(x) for x in mm.nodeID ]

a = {'or':2}
# print a[::-1]
if not a.get('order'):
    print 12
class Microsoft_Windows_AssignedAccess_31001_0(Etw):
    pattern = Struct("ErrorCode" / Int32sl)
class Microsoft_Windows_AssignedAccess_32000_0(Etw):
    pattern = Struct("Custom" / WString, "ErrorCode" / Int32ul)
class Microsoft_Windows_NFC_ClassExtension_201_1(Etw):
    pattern = Struct(
        "RadioIsOn" / Int8ul
    )
Example #37
0
            SERVER_INVITE_OPTION = 0x12
        ),
        Switch("OptionData", lambda ctx: ctx["OptionID"],
            {
                "CLIENT_NICK_OPTION" : CString('Nickname'),
                "CLIENT_MEMBERSHIP_OPTION" : ClientMemberShipOption,
                "SERVER_OPTION" : Struct("ServerOption", ULInt16('Port')),
                "SERVER_CHANNELS_OPTION" : PrefixedArray(CString('Channels'), ULInt8("NumChannels")),
                "SERVER_INVITE_OPTION" : ServerInviteOption
            }
        )
)


peerPDU = Struct(
          'peerPDU',
          CString('ClientID'),
          OptionalGreedyRepeater(Option)
)


if __name__ == '__main__':
    data = peerPDU.build(Container(ClientID="Bob", Option=[
                                                    Container(OptionID="SERVER_INVITE_OPTION", OptionData=Container(ChannelID="TM2011", ClientID=["Alice", "Billy"])),
                                                    Container(OptionID="CLIENT_NICK_OPTION", OptionData="Susan")]
                                  )
    )

    print repr(data)
    packet = peerPDU.parse(data)
    print packet
class Microsoft_Windows_NFC_ClassExtension_303_1(Etw):
    pattern = Struct(
        "Version" / Int32ul
    )
Example #39
0
from construct import Struct, Int64ul, Int32ul, Int16ul, Int8ul
from ctypes import CFUNCTYPE, c_void_p, c_uint32, c_uint64, c_uint8, c_uint16, c_ssize_t
import ctypes
import chip.native
import threading
import chip.tlv
import chip.exceptions
import typing
from dataclasses import dataclass

# The type should match CommandStatus in interaction_model/Delegate.h
# CommandStatus should not contain padding
IMCommandStatus = Struct(
    "Status" / Int8ul,
    "ClusterStatus" / Int8ul,
    "EndpointId" / Int16ul,
    "ClusterId" / Int32ul,
    "CommandId" / Int32ul,
    "CommandIndex" / Int8ul,
)

# The type should match WriteStatus in interaction_model/Delegate.h
IMWriteStatus = Struct(
    "NodeId" / Int64ul,
    "AppIdentifier" / Int64ul,
    "Status" / Int8ul,
    "EndpointId" / Int16ul,
    "ClusterId" / Int32ul,
    "AttributeId" / Int32ul,
)

# AttributePath should not contain padding
class Microsoft_Windows_NFC_ClassExtension_304_1(Etw):
    pattern = Struct(
        "FirmwareFile" / WString,
        "Force" / Int8ul
    )
Example #41
0
'''
Siemens/Bruker Diffrac-AT Raw Format
 * https://github.com/wojdyr/xylib/blob/master/xylib/brucker_raw.cpp
'''
from __future__ import absolute_import
import numpy as np
from construct import (Padding, Struct, Switch, String, Array, Const, OnDemand,
                       Embedded, Computed, Int32ul, Int16ul, Float64l,
                       Float32l, this, Check)
from .construct_utils import FixedSizeCString

Block_v2 = Struct('header_len' / Int16ul, 'num_steps' / Int16ul, Padding(4),
                  'time_per_step' / Float32l, 'x_step' / Float64l,
                  'x_start' / Float64l, Padding(26), 'temperature' / Int16ul,
                  Padding(this.header_len - 48),
                  'y' / OnDemand(Array(this.num_steps, Float32l)))

RAW_v2 = Struct('num_steps' / Int32ul, Padding(162),
                'date_time_measure' / FixedSizeCString(20),
                'anode_material' / FixedSizeCString(2), 'lambda1' / Float32l,
                'lambda2' / Float32l, 'intensity_ratio' / Float32l, Padding(8),
                'sample_runtime' / Float32l, Padding(42),
                'blocks' / Array(this.num_steps, Block_v2))

Block_v101 = Struct(
    'header_len' / Int32ul, Check(this.header_len == 304),
    'num_steps' / Int32ul, 'start_theta' / Float64l, 'start_2theta' / Float64l,
    Padding(76), 'high_voltage' / Float32l,
    'amplifier_gain' / Float32l, 'discriminator_1_lower_level' / Float32l,
    Padding(64), 'step_size' / Float64l,
    Padding(8), 'time_per_step' / Float32l, Padding(12), 'rpm' / Float32l,
class Microsoft_Windows_NFC_ClassExtension_306_1(Etw):
    pattern = Struct(
        "RfArrivalDepartureEvent" / Int32ul
    )
Example #43
0
class IPTransport(object):
    '''Implement IP transport.'''
    def __init__(self, device=None):
        '''Instantiate the first available PTP device over IP'''
        self.__setup_constructors()
        logger.debug('Init IP')

        self.__dev = device
        if device is None:
            raise NotImplementedError(
                'IP discovery not implemented. Please provide a device.'
            )
        self.__device = device

        # Signal usable implicit session
        self.__implicit_session_open = Event()
        # Signal implicit session is shutting down
        self.__implicit_session_shutdown = Event()

        self.__check_session_lock = Lock()
        self.__transaction_lock = Lock()

        self.__event_queue = Queue()

        atexit.register(self._shutdown)

    def _shutdown(self):
        try:
            self.__close_implicit_session()
        except Exception as e:
            logger.error(e)

    @contextmanager
    def __implicit_session(self):
        '''Manage implicit sessions with responder'''
        # There is now an implicit session
        self.__check_session_lock.acquire()
        if not self.__implicit_session_open.is_set():
            try:
                self.__open_implicit_session()
                self.__check_session_lock.release()
                yield
            except Exception as e:
                logger.error(e)
                raise PTPError('Failed to open PTP/IP implicit session')
            finally:
                if self.__implicit_session_open.is_set():
                    self.__close_implicit_session()
                if self.__check_session_lock.locked():
                    self.__check_session_lock.release()
        else:
            self.__check_session_lock.release()
            yield

    def __open_implicit_session(self):
        '''Establish implicit session with responder'''

        self.__implicit_session_shutdown.clear()

        # Establish Command and Event connections
        if type(self.__device) is tuple:
            host, port = self.__device
            self.__setup_connection(host, port)
        else:
            self.__setup_connection(self.__device)

        self.__implicit_session_open.set()

        # Prepare Event and Probe threads
        self.__event_proc = Thread(
            name='EvtPolling',
            target=self.__poll_events
        )
        self.__event_proc.daemon = False

        self.__ping_pong_proc = Thread(
            name='PingPong',
            target=self.__ping_pong
        )
        self.__ping_pong_proc.daemon = False

        # Launch Event and Probe threads
        self.__event_proc.start()
        self.__ping_pong_proc.start()

    def __close_implicit_session(self):
        '''Terminate implicit session with responder'''
        self.__implicit_session_shutdown.set()

        if not self.__implicit_session_open.is_set():
            return

        # Only join running threads.
        if self.__event_proc.is_alive():
            self.__event_proc.join(2)
        if self.__ping_pong_proc.is_alive():
            self.__ping_pong_proc.join(2)

        logger.debug('Close connections for {}'.format(repr(self.__dev)))
        try:
            self.__evtcon.shutdown(socket.SHUT_RDWR)
        except socket.error as e:
            if e.errno == 107:
                pass
            else:
                raise e
        try:
            self.__cmdcon.shutdown(socket.SHUT_RDWR)
        except socket.error as e:
            if e.errno == 107:
                pass
            else:
                raise e
        self.__evtcon.close()
        self.__cmdcon.close()

        self.__implicit_session_open.clear()

    def __setup_connection(self, host=None, port=15740):
        '''Establish a PTP/IP session for a given host'''
        logger.debug(
            'Establishing PTP/IP connection with {}:{}'
            .format(host, port)
        )
        socket.setdefaulttimeout(5)
        hdrlen = self.__Header.sizeof()
        # Command Connection Establishment
        self.__cmdcon = create_connection((host, port))
        # Send InitCommand
        # TODO: Allow users to identify as an arbitrary initiator.
        init_cmd_req_payload = self.__InitCommand.build(
            Container(
                InitiatorGUID=16*[0xFF],
                InitiatorFriendlyName='PTPy',
                InitiatorProtocolVersion=Container(
                    Major=100,
                    Minor=000,
                ),
            ))
        init_cmd_req = self.__Packet.build(
            Container(
                Type='InitCommand',
                Payload=init_cmd_req_payload,
            )
        )
        actual_socket(self.__cmdcon).sendall(init_cmd_req)
        # Get ACK/NACK
        init_cmd_req_rsp = actual_socket(self.__cmdcon).recv(72)
        init_cmd_rsp_hdr = self.__Header.parse(
            init_cmd_req_rsp[0:hdrlen]
        )

        if init_cmd_rsp_hdr.Type == 'InitCommandAck':
            cmd_ack = self.__InitCommandACK.parse(init_cmd_req_rsp[hdrlen:])
            logger.debug(
                'Command connection ({}) established'
                .format(cmd_ack.ConnectionNumber)
            )
        elif init_cmd_rsp_hdr.Type == 'InitFail':
            cmd_nack = self.__InitFail.parse(init_cmd_req_rsp[hdrlen:])
            msg = 'InitCommand failed, Reason: {}'.format(
                cmd_nack
            )
            logger.error(msg)
            raise PTPError(msg)
        else:
            msg = 'Unexpected response Type to InitCommand : {}'.format(
                init_cmd_rsp_hdr.Type
            )
            logger.error(msg)
            raise PTPError(msg)

        # Event Connection Establishment
        self.__evtcon = create_connection((host, port))
        self.__evtcon.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.__evtcon.setsockopt(socket.IPPROTO_TCP, socket.SO_KEEPALIVE, 1)

        # Send InitEvent
        payload = self.__InitEvent.build(Container(
            ConnectionNumber=cmd_ack.ConnectionNumber,
        ))
        evt_req = self.__Packet.build(
            Container(
                Type='InitEvent',
                Payload=payload,
            )
        )
        actual_socket(self.__evtcon).sendall(evt_req)
        # Get ACK/NACK
        init_evt_req_rsp = actual_socket(self.__evtcon).recv(
            hdrlen + self.__InitFail.sizeof()
        )
        init_evt_rsp_hdr = self.__Header.parse(
            init_evt_req_rsp[0:hdrlen]
        )

        if init_evt_rsp_hdr.Type == 'InitEventAck':
            logger.debug(
                'Event connection ({}) established'
                .format(cmd_ack.ConnectionNumber)
            )
        elif init_evt_rsp_hdr.Type == 'InitFail':
            evt_nack = self.__InitFail.parse(init_evt_req_rsp[hdrlen:])
            msg = 'InitEvent failed, Reason: {}'.format(
                evt_nack
            )
            logger.error(msg)
            raise PTPError(msg)
        else:
            msg = 'Unexpected response Type to InitEvent : {}'.format(
                init_evt_rsp_hdr.Type
            )
            logger.error(msg)
            raise PTPError(msg)

    # Helper methods.
    # ---------------------
    def __setup_constructors(self):
        '''Set endianness and create transport-specific constructors.'''
        # Set endianness of constructors before using them.
        self._set_endian('little')

        self.__Length = Int32ul
        self.__Type = Enum(
            Int32ul,
            Undefined=0x00000000,
            InitCommand=0x00000001,
            InitCommandAck=0x00000002,
            InitEvent=0x00000003,
            InitEventAck=0x00000004,
            InitFail=0x00000005,
            Command=0x00000006,
            Response=0x00000007,
            Event=0x00000008,
            StartData=0x00000009,
            Data=0x0000000A,
            Cancel=0x0000000B,
            EndData=0x0000000C,
            Ping=0x0000000D,
            Pong=0x0000000E,
        )
        self.__Header = Struct(
            'Length' / self.__Length,
            'Type' / self.__Type,
        )
        self.__Param = Range(0, 5, self._Parameter)
        self.__EventParam = Range(0, 3, self._Parameter)
        self.__PacketBase = Struct(
            Embedded(self.__Header),
            'Payload' / Bytes(
                lambda ctx, h=self.__Header: ctx.Length - h.sizeof()),
        )
        self.__Packet = ExprAdapter(
            self.__PacketBase,
            encoder=lambda obj, ctx, h=self.__Header: Container(
                Length=len(obj.Payload) + h.sizeof(),
                **obj
            ),
            decoder=lambda obj, ctx: obj,
        )
        # Yet another arbitrary string type. Max-length CString utf8-encoded
        self.__PTPIPString = ExprAdapter(
            RepeatUntil(
                lambda obj, ctx, lst:
                six.unichr(obj) in '\x00' or len(lst) == 40, Int16ul
            ),
            encoder=lambda obj, ctx:
            [] if len(obj) == 0 else[ord(c) for c in six.text_type(obj)]+[0],
            decoder=lambda obj, ctx:
            u''.join(
                [six.unichr(o) for o in obj]
            ).split('\x00')[0],
        )
        # PTP/IP packets
        # Command
        self.__ProtocolVersion = Struct(
            'Major' / Int16ul,
            'Minor' / Int16ul,
        )
        self.__InitCommand = Embedded(Struct(
            'InitiatorGUID' / Array(16, Int8ul),
            'InitiatorFriendlyName' / self.__PTPIPString,
            'InitiatorProtocolVersion' / self.__ProtocolVersion,
        ))
        self.__InitCommandACK = Embedded(Struct(
            'ConnectionNumber' / Int32ul,
            'ResponderGUID' / Array(16, Int8ul),
            'ResponderFriendlyName' / self.__PTPIPString,
            'ResponderProtocolVersion' / self.__ProtocolVersion,
        ))
        # Event
        self.__InitEvent = Embedded(Struct(
            'ConnectionNumber' / Int32ul,
        ))
        # Common to Events and Command requests
        self.__Reason = Enum(
            # TODO: Verify these codes...
            Int32ul,
            Undefined=0x0000,
            RejectedInitiator=0x0001,
            Busy=0x0002,
            Unspecified=0x0003,
        )
        self.__InitFail = Embedded(Struct(
            'Reason' / self.__Reason,
        ))

        self.__DataphaseInfo = Enum(
            Int32ul,
            Undefined=0x00000000,
            In=0x00000001,
            Out=0x00000002,
        )
        self.__Command = Embedded(Struct(
            'DataphaseInfo' / self.__DataphaseInfo,
            'OperationCode' / self._OperationCode,
            'TransactionID' / self._TransactionID,
            'Parameter' / self.__Param,
        ))
        self.__Response = Embedded(Struct(
            'ResponseCode' / self._ResponseCode,
            'TransactionID' / self._TransactionID,
            'Parameter' / self.__Param,
        ))
        self.__Event = Embedded(Struct(
            'EventCode' / self._EventCode,
            'TransactionID' / self._TransactionID,
            'Parameter' / self.__EventParam,
        ))
        self.__StartData = Embedded(Struct(
            'TransactionID' / self._TransactionID,
            'TotalDataLength' / Int64ul,
        ))
        # TODO: Fix packing and unpacking dataphase data
        self.__Data = Embedded(Struct(
            'TransactionID' / self._TransactionID,
            'Data' / Bytes(
                lambda ctx:
                ctx._.Length -
                self.__Header.sizeof() -
                self._TransactionID.sizeof()
            ),
        ))
        self.__EndData = Embedded(Struct(
            'TransactionID' / self._TransactionID,
            'Data' / Bytes(
                lambda ctx:
                ctx._.Length -
                self.__Header.sizeof() -
                self._TransactionID.sizeof()
            ),
        ))
        self.__Cancel = Embedded(Struct(
            'TransactionID' / self._TransactionID,
        ))
        # Convenience construct for parsing packets

        self.__PacketPayload = Debugger(Struct(
            'Header' / Embedded(self.__Header),
            'Payload' / Embedded(Switch(
                lambda ctx: ctx.Type,
                {
                    'InitCommand': self.__InitCommand,
                    'InitCommandAck': self.__InitCommandACK,
                    'InitEvent': self.__InitEvent,
                    'InitFail': self.__InitFail,
                    'Command': self.__Command,
                    'Response': self.__Response,
                    'Event': self.__Event,
                    'StartData': self.__StartData,
                    'Data': self.__Data,
                    'EndData': self.__EndData,
                },
                default=Pass,
            ))
        ))

    def __parse_response(self, ipdata):
        '''Helper method for parsing data.'''
        # Build up container with all PTP info.
        response = self.__PacketPayload.parse(ipdata)
        # Sneak in an implicit Session ID
        response['SessionID'] = self.session_id
        return response

    def __recv(self, event=False, wait=False, raw=False):
        '''Helper method for receiving packets.'''
        hdrlen = self.__Header.sizeof()
        with self.__implicit_session():
            ip = (
                actual_socket(self.__evtcon)
                if event
                else actual_socket(self.__cmdcon)
            )
            data = bytes()
            while True:
                try:
                    ipdata = ip.recv(hdrlen)
                except socket.timeout:
                    if event:
                        return None
                    else:
                        ipdata = ip.recv(hdrlen)

                if len(ipdata) == 0 and not event:
                    raise PTPError('Command connection dropped')
                elif event:
                    return None

                # Read a single entire header
                while len(ipdata) < hdrlen:
                    ipdata += ip.recv(hdrlen - len(ipdata))
                header = self.__Header.parse(
                    ipdata[0:hdrlen]
                )
                # Read a single entire packet
                while len(ipdata) < header.Length:
                    ipdata += ip.recv(header.Length - len(ipdata))
                # Run sanity checks.
                if header.Type not in [
                        'Cancel',
                        'Data',
                        'Event',
                        'Response',
                        'StartData',
                        'EndData',
                ]:
                    raise PTPError(
                        'Unexpected PTP/IP packet type {}'
                        .format(header.Type)
                    )
                if header.Type not in ['StartData', 'Data', 'EndData']:
                    break
                else:
                    response = self.__parse_response(ipdata)

                if header.Type == 'StartData':
                    expected = response.TotalDataLength
                    current_transaction = response.TransactionID
                elif (
                        header.Type == 'Data' and
                        response.TransactionID == current_transaction
                ):
                    data += response.Data
                elif (
                        header.Type == 'EndData' and
                        response.TransactionID == current_transaction
                ):
                    data += response.Data
                    datalen = len(data)
                    if datalen != expected:
                        logger.warning(
                            '{} data than expected {}/{}'
                            .format(
                                'More' if datalen > expected else 'Less',
                                datalen,
                                expected
                            )
                        )
                    response['Data'] = data
                    response['Type'] = 'Data'
                    return response

        if raw:
            # TODO: Deal with raw Data packets??
            return ipdata
        else:
            return self.__parse_response(ipdata)

    def __send(self, ptp_container, event=False):
        '''Helper method for sending packets.'''
        packet = self.__Packet.build(ptp_container)
        ip = (
            actual_socket(self.__evtcon)
            if event
            else actual_socket(self.__cmdcon)
        )
        while ip.sendall(packet) is not None:
            logger.debug('Failed to send {} packet'.format(ptp_container.Type))

    def __send_request(self, ptp_container):
        '''Send PTP request without checking answer.'''
        # Don't modify original container to keep abstraction barrier.
        ptp = Container(**ptp_container)

        # Send unused parameters always
        ptp['Parameter'] += [0] * (5 - len(ptp.Parameter))

        # Send request
        ptp['Type'] = 'Command'
        ptp['DataphaseInfo'] = 'In'
        ptp['Payload'] = self.__Command.build(ptp)
        self.__send(ptp)

    def __send_data(self, ptp_container, data):
        '''Send data without checking answer.'''
        # Don't modify original container to keep abstraction barrier.
        ptp = Container(**ptp_container)
        # Send data
        ptp['Type'] = 'Data'
        ptp['DataphaseInfo'] = 'Out'
        ptp['Payload'] = data
        self.__send(ptp)

    # Actual implementation
    # ---------------------
    def send(self, ptp_container, data):
        '''Transfer operation with dataphase from initiator to responder'''
        logger.debug('SEND {}{}'.format(
            ptp_container.OperationCode,
            ' ' + str(list(map(hex, ptp_container.Parameter)))
            if ptp_container.Parameter else '',
        ))
        with self.__implicit_session():
            with self.__transaction_lock:
                self.__send_request(ptp_container)
                self.__send_data(ptp_container, data)
                # Get response and sneak in implicit SessionID and missing
                # parameters.
                return self.__recv()

    def recv(self, ptp_container):
        '''Transfer operation with dataphase from responder to initiator.'''
        logger.debug('RECV {}{}'.format(
            ptp_container.OperationCode,
            ' ' + str(list(map(hex, ptp_container.Parameter)))
            if ptp_container.Parameter else '',
        ))
        with self.__implicit_session():
            with self.__transaction_lock:
                self.__send_request(ptp_container)
                dataphase = self.__recv()
                if hasattr(dataphase, 'Data'):
                    response = self.__recv()
                    if (
                            (ptp_container.TransactionID != dataphase.TransactionID) or
                            (ptp_container.SessionID != dataphase.SessionID) or
                            (dataphase.TransactionID != response.TransactionID) or
                            (dataphase.SessionID != response.SessionID)
                    ):
                        raise PTPError(
                            'Dataphase does not match with requested operation'
                        )
                    response['Data'] = dataphase.Data
                    return response
                else:
                    return dataphase

    def mesg(self, ptp_container):
        '''Transfer operation without dataphase.'''
        op = ptp_container['OperationCode']
        if op == 'OpenSession':
            self.__open_implicit_session()

        with self.__implicit_session():
            with self.__transaction_lock:
                self.__send_request(ptp_container)
                # Get response and sneak in implicit SessionID and missing
                # parameters for FullResponse.
                response = self.__recv()

        rc = response['ResponseCode']
        if op == 'OpenSession':
            if rc != 'OK':
                self.__close_implicit_session()
        elif op == 'CloseSession':
            if rc == 'OK':
                self.__close_implicit_session()

        return response

    def event(self, wait=False):
        '''Check event.

        If `wait` this function is blocking. Otherwise it may return None.
        '''
        evt = None
        ipdata = None
        timeout = None if wait else 0.001
        if not self.__event_queue.empty():
            ipdata = self.__event_queue.get(block=not wait, timeout=timeout)
        if ipdata is not None:
            evt = self.__parse_response(ipdata)

        return evt

    def __poll_events(self):
        '''Poll events, adding them to a queue.'''
        logger.debug('Start')
        while (
                not self.__implicit_session_shutdown.is_set() and
                self.__implicit_session_open.is_set() and
                _main_thread_alive()
        ):
            try:
                evt = self.__recv(event=True, wait=False, raw=True)
            except OSError as e:
                if e.errno == 9 and not self.__implicit_session_open.is_set():
                    break
                else:
                    raise e
            if evt is not None:
                logger.debug('Event queued')
                self.__event_queue.put(evt)
            sleep(5e-3)
        logger.debug('Stop')

    def __ping_pong(self):
        '''Poll events, adding them to a queue.'''
        logger.debug('Start')
        last = time()
        while (
                not self.__implicit_session_shutdown.is_set() and
                self.__implicit_session_open.is_set() and
                _main_thread_alive()
        ):
            if time() - last > 10:
                logger.debug('PING')
                # TODO: implement Ping Pong
                last = time()
            sleep(0.10)
        logger.debug('Stop')
Example #44
0
class Microsoft_AppV_ServiceLog_1_0(Etw):
    pattern = Struct(
        "stringValue1" / WString
    )
Example #45
0
class USBTransport(object):
    '''Implement USB transport.'''
    def __init__(self, *args, **kwargs):
        device = kwargs.get('device', None)
        '''Instantiate the first available PTP device over USB'''
        logger.debug('Init USB')
        self.__setup_constructors()
        # If no device is specified, find all devices claiming to be Cameras
        # and get the USB endpoints for the first one that works.
        if device is None:
            logger.debug('No device provided, probing all USB devices.')
        if isinstance(device, six.string_types):
            name = device
            logger.debug(
                'Device name provided, probing all USB devices for {}.'
                .format(name)
            )
            device = None
        else:
            name = None
        devs = (
            [device] if (device is not None)
            else find_usb_cameras(name=name)
        )
        self.__claimed = False
        self.__acquire_camera(devs)

        self.__event_queue = Queue()
        self.__event_shutdown = Event()
        # Locks for different end points.
        self.__inep_lock = RLock()
        self.__intep_lock = RLock()
        self.__outep_lock = RLock()
        # Slightly redundant transaction lock to avoid catching other request's
        # response
        self.__transaction_lock = RLock()

        self.__event_proc = Thread(
            name='EvtPolling',
            target=self.__poll_events
        )
        self.__event_proc.daemon = False
        atexit.register(self._shutdown)
        self.__event_proc.start()

    def __available_cameras(self, devs):
        for dev in devs:
            if self.__setup_device(dev):
                logger.debug('Found USB PTP device {}'.format(dev))
                yield
        else:
            message = 'No USB PTP device found.'
            logger.error(message)
            raise PTPError(message)

    def __acquire_camera(self, devs):
        '''From the cameras given, get the first one that does not fail'''

        for _ in self.__available_cameras(devs):
            # Stop system drivers
            try:
                if self.__dev.is_kernel_driver_active(
                        self.__intf.bInterfaceNumber):
                    try:
                        self.__dev.detach_kernel_driver(
                            self.__intf.bInterfaceNumber)
                    except usb.core.USBError:
                        message = (
                            'Could not detach kernel driver. '
                            'Maybe the camera is mounted?'
                        )
                        logger.error(message)
            except NotImplementedError as e:
                logger.debug('Ignoring unimplemented function: {}'.format(e))
            # Claim camera
            try:
                logger.debug('Claiming {}'.format(repr(self.__dev)))
                usb.util.claim_interface(self.__dev, self.__intf)
                self.__claimed = True
            except Exception as e:
                logger.warn('Failed to claim PTP device: {}'.format(e))
                continue
            self.__dev.reset()
            break
        else:
            message = (
                'Could not acquire any camera.'
            )
            logger.error(message)
            raise PTPError(message)

    def _shutdown(self):
        logger.debug('Shutdown request')
        self.__event_shutdown.set()
        # Free USB resource on shutdown.

        # Only join a running thread.
        if self.__event_proc.is_alive():
            self.__event_proc.join(2)

        try:
            if self.__claimed:
                logger.debug('Release {}'.format(repr(self.__dev)))
                usb.util.release_interface(self.__dev, self.__intf)
        except Exception as e:
            logger.warn(e)

    # Helper methods.
    # ---------------------
    def __setup_device(self, dev):
        '''Get endpoints for a device. True on success.'''
        self.__inep = None
        self.__outep = None
        self.__intep = None
        self.__cfg = None
        self.__dev = None
        self.__intf = None
        # Attempt to find the USB in, out and interrupt endpoints for a PTP
        # interface.
        for cfg in dev:
            for intf in cfg:
                if intf.bInterfaceClass == PTP_USB_CLASS:
                    for ep in intf:
                        ep_type = endpoint_type(ep.bmAttributes)
                        ep_dir = endpoint_direction(ep.bEndpointAddress)
                        if ep_type == ENDPOINT_TYPE_BULK:
                            if ep_dir == ENDPOINT_IN:
                                self.__inep = ep
                            elif ep_dir == ENDPOINT_OUT:
                                self.__outep = ep
                        elif ((ep_type == ENDPOINT_TYPE_INTR) and
                                (ep_dir == ENDPOINT_IN)):
                            self.__intep = ep
                if not (self.__inep and self.__outep and self.__intep):
                    self.__inep = None
                    self.__outep = None
                    self.__intep = None
                else:
                    logger.debug('Found {}'.format(repr(self.__inep)))
                    logger.debug('Found {}'.format(repr(self.__outep)))
                    logger.debug('Found {}'.format(repr(self.__intep)))
                    self.__cfg = cfg
                    self.__dev = dev
                    self.__intf = intf
                    return True
        return False

    def __setup_constructors(self):
        '''Set endianness and create transport-specific constructors.'''
        # Set endianness of constructors before using them.
        self._set_endian('little')

        self.__Length = Int32ul
        self.__Type = Enum(
                Int16ul,
                default=Pass,
                Undefined=0x0000,
                Command=0x0001,
                Data=0x0002,
                Response=0x0003,
                Event=0x0004,
                )
        # This is just a convenience constructor to get the size of a header.
        self.__Code = Int16ul
        self.__Header = Struct(
                'Length' / self.__Length,
                'Type' / self.__Type,
                'Code' / self.__Code,
                'TransactionID' / self._TransactionID,
                )
        # These are the actual constructors for parsing and building.
        self.__CommandHeader = Struct(
                'Length' / self.__Length,
                'Type' / self.__Type,
                'OperationCode' / self._OperationCode,
                'TransactionID' / self._TransactionID,
                )
        self.__ResponseHeader = Struct(
                'Length' / self.__Length,
                'Type' / self.__Type,
                'ResponseCode' / self._ResponseCode,
                'TransactionID' / self._TransactionID,
                )
        self.__EventHeader = Struct(
                'Length' / self.__Length,
                'Type' / self.__Type,
                'EventCode' / self._EventCode,
                'TransactionID' / self._TransactionID,
                )
        # Apparently nobody uses the SessionID field. Even though it is
        # specified in ISO15740:2013(E), no device respects it and the session
        # number is implicit over USB.
        self.__Param = Range(0, 5, self._Parameter)
        self.__CommandTransactionBase = Struct(
                Embedded(self.__CommandHeader),
                'Payload' / Bytes(
                    lambda ctx, h=self.__Header: ctx.Length - h.sizeof()
                )
        )
        self.__CommandTransaction = ExprAdapter(
                self.__CommandTransactionBase,
                encoder=lambda obj, ctx, h=self.__Header: Container(
                    Length=len(obj.Payload) + h.sizeof(),
                    **obj
                    ),
                decoder=lambda obj, ctx: obj,
                )
        self.__ResponseTransactionBase = Struct(
                Embedded(self.__ResponseHeader),
                'Payload' / Bytes(
                    lambda ctx, h=self.__Header: ctx.Length - h.sizeof())
                )
        self.__ResponseTransaction = ExprAdapter(
                self.__ResponseTransactionBase,
                encoder=lambda obj, ctx, h=self.__Header: Container(
                    Length=len(obj.Payload) + h.sizeof(),
                    **obj
                    ),
                decoder=lambda obj, ctx: obj,
                )

    def __parse_response(self, usbdata):
        '''Helper method for parsing USB data.'''
        # Build up container with all PTP info.
        logger.debug('Transaction:')
        usbdata = bytearray(usbdata)
        if logger.isEnabledFor(logging.DEBUG):
            for l in hexdump(
                    six.binary_type(usbdata[:512]),
                    result='generator'
            ):
                logger.debug(l)
        transaction = self.__ResponseTransaction.parse(usbdata)
        response = Container(
            SessionID=self.session_id,
            TransactionID=transaction.TransactionID,
        )
        logger.debug('Interpreting {} transaction'.format(transaction.Type))
        if transaction.Type == 'Response':
            response['ResponseCode'] = transaction.ResponseCode
            response['Parameter'] = self.__Param.parse(transaction.Payload)
        elif transaction.Type == 'Event':
            event = self.__EventHeader.parse(
                usbdata[0:self.__Header.sizeof()]
            )
            response['EventCode'] = event.EventCode
            response['Parameter'] = self.__Param.parse(transaction.Payload)
        else:
            command = self.__CommandHeader.parse(
                usbdata[0:self.__Header.sizeof()]
            )
            response['OperationCode'] = command.OperationCode
            response['Data'] = transaction.Payload
        return response

    def __recv(self, event=False, wait=False, raw=False):
        '''Helper method for receiving data.'''
        # TODO: clear stalls automatically
        ep = self.__intep if event else self.__inep
        lock = self.__intep_lock if event else self.__inep_lock
        usbdata = array.array('B', [])
        with lock:
            tries = 0
            # Attempt to read a header
            while len(usbdata) < self.__Header.sizeof() and tries < 5:
                if tries > 0:
                    logger.debug('Data smaller than a header')
                    logger.debug(
                        'Requesting {} bytes of data'
                        .format(ep.wMaxPacketSize)
                    )
                try:
                    usbdata += ep.read(
                        ep.wMaxPacketSize
                    )
                except usb.core.USBError as e:
                    # Return None on timeout or busy for events
                    if (
                            (e.errno is None and
                             ('timeout' in e.strerror.decode() or
                              'busy' in e.strerror.decode())) or
                            (e.errno == 110 or e.errno == 16 or e.errno == 5)
                    ):
                        if event:
                            return None
                        else:
                            logger.warning('Ignored exception: {}'.format(e))
                    else:
                        logger.error(e)
                        raise e
                tries += 1
            logger.debug('Read {} bytes of data'.format(len(usbdata)))

            if len(usbdata) == 0:
                if event:
                    return None
                else:
                    raise PTPError('Empty USB read')

            if (
                    logger.isEnabledFor(logging.DEBUG) and
                    len(usbdata) < self.__Header.sizeof()
            ):
                logger.debug('Incomplete header')
                for l in hexdump(
                        six.binary_type(bytearray(usbdata)),
                        result='generator'
                ):
                    logger.debug(l)

            header = self.__ResponseHeader.parse(
                bytearray(usbdata[0:self.__Header.sizeof()])
            )
            if header.Type not in ['Response', 'Data', 'Event']:
                raise PTPError(
                    'Unexpected USB transfer type. '
                    'Expected Response, Event or Data but received {}'
                    .format(header.Type)
                )
            while len(usbdata) < header.Length:
                usbdata += ep.read(
                    min(
                        header.Length - len(usbdata),
                        # Up to 64kB
                        64 * 2**10
                    )
                )
        if raw:
            return usbdata
        else:
            return self.__parse_response(usbdata)

    def __send(self, ptp_container, event=False):
        '''Helper method for sending data.'''
        ep = self.__intep if event else self.__outep
        lock = self.__intep_lock if event else self.__outep_lock
        transaction = self.__CommandTransaction.build(ptp_container)
        with lock:
            try:
                sent = 0
                while sent < len(transaction):
                    sent = ep.write(
                        # Up to 64kB
                        transaction[sent:(sent + 64*2**10)]
                    )
            except usb.core.USBError as e:
                # Ignore timeout or busy device once.
                if (
                        (e.errno is None and
                         ('timeout' in e.strerror.decode() or
                          'busy' in e.strerror.decode())) or
                        (e.errno == 110 or e.errno == 16 or e.errno == 5)
                ):
                    logger.warning('Ignored USBError {}'.format(e.errno))
                    ep.write(transaction)

    def __send_request(self, ptp_container):
        '''Send PTP request without checking answer.'''
        # Don't modify original container to keep abstraction barrier.
        ptp = Container(**ptp_container)
        # Don't send unused parameters
        try:
            while not ptp.Parameter[-1]:
                ptp.Parameter.pop()
                if len(ptp.Parameter) == 0:
                    break
        except IndexError:
            # The Parameter list is already empty.
            pass

        # Send request
        ptp['Type'] = 'Command'
        ptp['Payload'] = self.__Param.build(ptp.Parameter)
        self.__send(ptp)

    def __send_data(self, ptp_container, data):
        '''Send data without checking answer.'''
        # Don't modify original container to keep abstraction barrier.
        ptp = Container(**ptp_container)
        # Send data
        ptp['Type'] = 'Data'
        ptp['Payload'] = data
        self.__send(ptp)

    @property
    def _dev(self):
        return None if self.__event_shutdown.is_set() else self.__dev

    @_dev.setter
    def _dev(self, value):
        raise ValueError('Read-only property')

    # Actual implementation
    # ---------------------
    def send(self, ptp_container, data):
        '''Transfer operation with dataphase from initiator to responder'''
        datalen = len(data)
        logger.debug('SEND {} {} bytes{}'.format(
            ptp_container.OperationCode,
            datalen,
            ' ' + str(list(map(hex, ptp_container.Parameter)))
            if ptp_container.Parameter else '',
        ))
        with self.__transaction_lock:
            self.__send_request(ptp_container)
            self.__send_data(ptp_container, data)
            # Get response and sneak in implicit SessionID and missing
            # parameters.
            response = self.__recv()
        logger.debug('SEND {} {} bytes {}{}'.format(
            ptp_container.OperationCode,
            datalen,
            response.ResponseCode,
            ' ' + str(list(map(hex, response.Parameter)))
            if ptp_container.Parameter else '',
        ))
        return response

    def recv(self, ptp_container):
        '''Transfer operation with dataphase from responder to initiator.'''
        logger.debug('RECV {}{}'.format(
            ptp_container.OperationCode,
            ' ' + str(list(map(hex, ptp_container.Parameter)))
            if ptp_container.Parameter else '',
        ))
        with self.__transaction_lock:
            self.__send_request(ptp_container)
            dataphase = self.__recv()
            if hasattr(dataphase, 'Data'):
                response = self.__recv()
                if not (ptp_container.SessionID ==
                        dataphase.SessionID ==
                        response.SessionID):
                    self.__dev.reset()
                    raise PTPError(
                        'Dataphase session ID missmatch: {}, {}, {}.'
                        .format(
                            ptp_container.SessionID,
                            dataphase.SessionID,
                            response.SessionID
                        )
                    )
                if not (ptp_container.TransactionID ==
                        dataphase.TransactionID ==
                        response.TransactionID):
                    self.__dev.reset()
                    raise PTPError(
                        'Dataphase transaction ID missmatch: {}, {}, {}.'
                        .format(
                            ptp_container.TransactionID,
                            dataphase.TransactionID,
                            response.TransactionID
                        )
                    )
                if not (ptp_container.OperationCode ==
                        dataphase.OperationCode):
                    self.__dev.reset()
                    raise PTPError(
                        'Dataphase operation code missmatch: {}, {}.'.
                        format(
                            ptp_container.OperationCode,
                            dataphase.OperationCode
                        )
                    )

                response['Data'] = dataphase.Data
            else:
                response = dataphase

        logger.debug('RECV {} {}{}{}'.format(
            ptp_container.OperationCode,
            response.ResponseCode,
            ' {} bytes'.format(len(response.Data))
            if hasattr(response, 'Data') else '',
            ' ' + str(list(map(hex, response.Parameter)))
            if response.Parameter else '',
        ))
        return response

    def mesg(self, ptp_container):
        '''Transfer operation without dataphase.'''
        logger.debug('MESG {}{}'.format(
            ptp_container.OperationCode,
            ' ' + str(list(map(hex, ptp_container.Parameter)))
            if ptp_container.Parameter else '',
        ))
        with self.__transaction_lock:
            self.__send_request(ptp_container)
            # Get response and sneak in implicit SessionID and missing
            # parameters for FullResponse.
            response = self.__recv()
        logger.debug('MESG {} {}{}'.format(
            ptp_container.OperationCode,
            response.ResponseCode,
            ' ' + str(list(map(hex, response.Parameter)))
            if response.Parameter else '',
        ))
        return response

    def event(self, wait=False):
        '''Check event.

        If `wait` this function is blocking. Otherwise it may return None.
        '''
        evt = None
        usbdata = None
        if wait:
            usbdata = self.__event_queue.get(block=True)
        elif not self.__event_queue.empty():
            usbdata = self.__event_queue.get(block=False)

        if usbdata is not None:
            evt = self.__parse_response(usbdata)

        return evt

    def __poll_events(self):
        '''Poll events, adding them to a queue.'''
        while not self.__event_shutdown.is_set() and _main_thread_alive():
            try:
                evt = self.__recv(event=True, wait=False, raw=True)
                if evt is not None:
                    logger.debug('Event queued')
                    self.__event_queue.put(evt)
            except usb.core.USBError as e:
                logger.error(
                    '{} polling exception: {}'.format(repr(self.__dev), e)
                )
                # check if disconnected
                if e.errno == 19:
                    break
            except Exception as e:
                logger.error(
                    '{} polling exception: {}'.format(repr(self.__dev), e)
                )
Example #46
0
class IpAddressAdapter(Adapter):
	def _encode(self,obj,context):
		return "".join(chr(int(b)) for b in obj.split())
	def _decode(self,obj,context):
		return ".".join(str(ord(b)) for b in obj)

#IpAddressAdapter(Bytes("foo",4)).parse("\x01\x02\x03\x04")



class PrintContext(Construct):
	def _parse(self, stream, context):
		print context
		print "hello"

foo = Struct("foo",
			 Byte("a"),
			 Byte("b"),
			 PrintContext("c"),
			 Struct("bar",
					Byte("a"),
					Byte("b"),
					PrintContext("c"),
					),
			 PrintContext("d"),
			 )

foo.parse("\x01\x02\x03\x04")


Example #47
0
"""
What : Internet Group Management Protocol, Version 2
 How : http://www.ietf.org/rfc/rfc2236.txt
 Who : jesse @ housejunkie . ca
"""

from construct import Byte, Enum,Struct, UBInt16
from construct.protocols.layer3.ipv4 import IpAddress
from binascii import unhexlify
import six


igmp_type = Enum(Byte("igmp_type"), 
    MEMBERSHIP_QUERY = 0x11,
    MEMBERSHIP_REPORT_V1 = 0x12,
    MEMBERSHIP_REPORT_V2 = 0x16,
    LEAVE_GROUP = 0x17,
)

igmpv2_header = Struct("igmpv2_header",
    igmp_type,
    Byte("max_resp_time"),
    UBInt16("checksum"),
    IpAddress("group_address"),
)

if __name__ == '__main__':
    capture = unhexlify(six.b("1600FA01EFFFFFFD"))
    print (igmpv2_header.parse(capture))
class Microsoft_Windows_NFC_ClassExtension_310_1(Etw):
    pattern = Struct(
        "Status" / Int32ul
    )
from pox.ethanol.ssl_message.msg_core import field_intf_name, field_station
from pox.ethanol.ssl_message.msg_core import field_mac_addr
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

from pox.ethanol.events import Events

events_snr_threshold_reached = Events()
"""to handle a receiving snr_threshold_reached message, just add your function to events_snr_threshold_reached
   your function must use 'def my_funct(**kwargs)' signature for compatibility
   @change: we send to parameters: msg, fromaddr, sta_mac, intf_name, mac_ap
"""

field_mac_ap = Struct(
    'mac_ap',
    SLInt32('mac_ap_size'),
    If(lambda ctx: ctx["mac_ap_size"] > 0, CString("mac_ap")),
)
""" handles a mac address field for the new ap (a C char * field)
"""

msg_snr_threshold_reached = Struct(
    'msg_snr_threshold_reached',
    Embed(msg_default),  # default fields
    Embed(field_station),
    Embed(field_mac_addr),  # sta_mac
    Embed(field_intf_name),  # intf_name
    Embed(field_mac_ap),  # mac_ap
    SLInt64('snr'),
    # Probe()
)
class Microsoft_Windows_NFC_ClassExtension_4_1(Etw):
    pattern = Struct(
        "MessageType" / Int8ul,
        "PacketBoundaryFlag" / Int8ul,
        "PacketSize" / Int16ul
    )
Example #51
0
"""
from __future__ import division, print_function

import sys

from construct import Array, Bytes, ULInt32, Struct
import yaml

_BOOTIMGHDR = Struct("boot_img_hdr",
                      Bytes("magic", 8),
                      ULInt32("kernel_size"),
                      ULInt32("kernel_addr"),
                      ULInt32("ramdisk_size"),
                      ULInt32("ramdisk_addr"),
                      ULInt32("second_size"),
                      ULInt32("second_addr"),
                      ULInt32("tags_addr"),
                      ULInt32("page_size"),
                      Array(2, ULInt32("unused")),
                      Bytes("name", 16),
                      Bytes("cmdline", 512),
                      Array(8, ULInt32("id")),
                      Bytes("extra_cmdline", 1024))

_HEADERLEN = _BOOTIMGHDR.sizeof()

_OUT = "{filename}_{start:08x}-{end:08x}.{name}"


def header_to_yaml(filename):
    with open(filename, 'rb') as f:
class Microsoft_Windows_NFC_ClassExtension_103_1(Etw):
    pattern = Struct(
        "FileObject" / Int64ul,
        "PayloadSize" / Int64ul
    )
class Microsoft_Windows_NFC_ClassExtension_308_1(Etw):
    pattern = Struct(
        "Status" / Int32ul,
        "Length" / Int16ul
    )
Example #54
0
class Microsoft_AppV_ServiceLog_2_0(Etw):
    pattern = Struct(
        "WString1" / WString
    )
Example #55
0
def ssexy_linux(fname, *eips):
    import elf32
    from construct import Struct, ULInt32, ULInt16, ULInt8, Array, CString
    from construct import OptionalGreedyRange

    # assume low-endian binary
    elf32_rel = Struct('elf32_rel', ULInt32('r_offset'), ULInt32('r_info'))
    ELF32_R_SYM = lambda x: x.r_info >> 8
    ELF32_R_TYPE = lambda x: x.r_info & 0xff
    R_386_PC32 = 2

    elf32_sym = Struct('elf32_sym', ULInt32('st_name'), ULInt32('st_value'),
        ULInt32('st_size'), ULInt8('st_info'), ULInt8('st_other'),
        ULInt16('st_shndx'))

    elf = elf32.elf32_file.parse_stream(file(fname, 'rb'))

    # retrieve section by name
    elf32_section = lambda elf, name: [x for x in elf.sections
        if x.name == name][0]

    # for now we assume that all code is in the .text section
    code_section = [x for x in elf.sections if x.name == '.text']
    if not len(code_section):
        raise Exception('your binary doesn\'t have a .text section..')

    relocs = [x.data.value for x in elf.sections if x.name == '.rel.dyn']
    if not len(relocs):
        raise Exception('no relocs available, compile with -pie')

    # read all relocations
    relocs = Array(len(relocs[0]) / elf32_rel.sizeof(),
        elf32_rel).parse(relocs[0])
    # now get the offsets of the relocations
    relocs = set([x.r_offset for x in relocs])

    imports = {}

    # a list of addresses that were used.
    addresses = []

    # a list of all m128 values we use
    m128s = []

    # a list of all dword values we use
    m32s = []

    instructions = pyasm2.block()

    # get string at offset
    dynstr = lambda x: CString(None).parse(
        elf32_section(elf, '.dynstr').data.value[x:])

    # read the symbol table
    imports = OptionalGreedyRange(elf32_sym).parse(elf32_section(elf,
        '.dynsym').data.value)

    # resolve relocations
    section = elf32_section(elf, '.rel.dyn')
    relocates = {}
    for x in xrange(0, section.size, elf32_rel.sizeof()):
        x = elf32_rel.parse(section.data.value[x:x+elf32_rel.sizeof()])
        # relocation to fixup addresses to imports
        if ELF32_R_TYPE(x) == R_386_PC32:
            relocates[x.r_offset] = dynstr(imports[ELF32_R_SYM(x)].st_name)

    # walk each section, find those that are executable and disassemble those
    section = elf32_section(elf, '.text')
    g = distorm3.DecomposeGenerator(section.addr, section.data.value,
            distorm3.Decode32Bits)
    for instr in g:
        # useless instruction?
        if str(instr) in ('NOP', 'ADD [EAX], AL', 'LEA ESI, [ESI]',
                    'INT 3') or str(instr)[:2] == 'DB':
            continue

        # a jump to one of the imports?
        #if instr.mnemonic == 'JMP' and instr.operands[0].type == \
        #        distorm3.OPERAND_ABSOLUTE_ADDRESS and \
        #        instr.operands[0].disp in imports:
        #    iat_label[instr.address] = imports[instr.operands[0].disp]
        #    continue

        # quite hackery, but when the jumps with thunk address have been
        # processed, we can be fairly sure that there will be no (legit)
        # code anymore.
        #if len(iat_label):
        #    break

        #print str(instr)

        #print str(instr)

        # convert the instruction from distorm3 format to pyasm2 format.
        instr = distorm3_to_pyasm2(instr)

        # we create the block already here, otherwise our `labelnr' is
        # not defined.
        #block = pyasm2.block(pyasm2.Label('%08x' % instr.address), instr)
        offset_flat = None
        addr = instr.address

        # now we check if this instruction has a relocation inside it
        # not a very efficient way, but oke.
        reloc = instr.length > 4 and relocs.intersection(range(
            instr.address, instr.address + instr.length - 3))
        if reloc:
            # make an immediate with `addr' set to True
            enable_addr = lambda x: Immediate(int(x), addr=True)

            # TODO support for two relocations in one instruction
            # (displacement *and* immediate)
            reloc = reloc.pop()
            if not hasattr(instr, 'op1'):
                instr.op1, instr.op2 = None, None
            # there is only one operand, that's easy
            if not instr.op2:
                #sys.stderr.write('reloc in op1 %s??\n' % instr.op1)
                if isinstance(instr.op1, pyasm2.MemoryAddress):
                    # special occassion, this memory addres is an import
                    if instr.op1.reg1 is None and \
                            instr.op1.reg2 is None and \
                            int(instr.op1.disp) in imports:
                        instr.op1 = imports[int(instr.op1.disp)]
                    else:
                        addresses.append(int(instr.op1.disp))
                        # change the displacement to a label
                        #instr.op1 = str(instr.op1).replace('0x',
                        #    '__lbl_00')
                        instr.op1 = enable_addr(instr.op1)
                elif isinstance(instr.op1, pyasm2.Immediate):
                    addresses.append(int(instr.op1))
                    offset_flat = int(instr.op1)
                    #instr.op1 = str(instr.op1).replace('0x',
                    #    'offset flat:__lbl_00')
            # if the second operand is an immediate and the relocation is
            # in the last four bytes of the instruction, then this
            # immediate is the reloc. Otherwise, if the second operand is
            # a memory address, then it's the displacement.
            elif isinstance(instr.op2, pyasm2.Immediate) and reloc == \
                    instr.address + instr.length - 4:
                # keep this address
                addresses.append(int(instr.op2))
                # make a label from this address
                # TODO: fix this horrible hack
                offset_flat = int(instr.op2)
                #instr.op2 = pyasm2.Label('offset flat:__lbl_%08x' %
                #    int(instr.op2), prepend=False)
            elif isinstance(instr.op2, pyasm2.MemoryAddress) and \
                    reloc == instr.address + instr.length - 4:
                addresses.append(int(instr.op2.disp))
                # change the displacement to a label
                instr.op2 = enable_addr(instr.op2)
                #instr.op2 = str(instr.op2).replace('0x', '__lbl_00')
                #sys.stderr.write('reloc in op2 memaddr %s\n' %
                #    str(instr.op2))
            # the relocation is not inside the second operand, it must be
            # inside the first operand after all.
            elif isinstance(instr.op1, pyasm2.MemoryAddress):
                addresses.append(int(instr.op1.disp))
                instr.op1 = enable_addr(instr.op1)
                #instr.op1 = str(instr.op1).replace('0x', '__lbl_00')
                #sys.stderr.write('reloc in op1 memaddr %s\n' %
                #    str(instr.op1))
            elif isinstance(instr.op1, pyasm2.Immediate):
                addresses.append(int(instr.op1))
                instr.op1 = enable_addr(instr.op1)
                #instr.op1 = '__lbl_%08x' % int(instr.op1)
                #sys.stderr.write('reloc in op1 imm %s\n' % instr.op1)
            else:
                sys.stderr.write('Invalid Relocation!\n')

        #print instr
        m32len = len(m32s)
        instr = translate.Translater(instr, m128s, m32s).translate()
        if offset_flat:
            encode_offset_flat = lambda x: str(x).replace('0x',
                'offset flat:__lbl_') if isinstance(x, (int, long,
                pyasm2.imm)) and int(x) == offset_flat or isinstance(x,
                pyasm2.mem) and x.disp == offset_flat else x

            if isinstance(instr, pyasm2.block):
                for x in instr.instructions:
                    x.op1 = encode_offset_flat(x.op1)
                    x.op2 = encode_offset_flat(x.op2)
            else:
                x.op1 = encode_offset_flat(x.op1)
                x.op2 = encode_offset_flat(x.op2)

            # update stuff
            m32s = m32s[:m32len] + [x.replace('0x%08x' % offset_flat,
                'offset flat:__lbl_%08x' % offset_flat)
                for x in m32s[m32len:]]

        instructions += pyasm2.block(pyasm2.Label('%08x' % addr), instr)

    # remove any addresses that are from within the current section
    newlist = addresses[:]
    for i in xrange(len(addresses)):
        if addresses[i] >= code_section[0].addr and addresses[i] < \
                code_section[0].addr + code_section[0].size:
            newlist[i] = None
    addresses = filter(lambda x: x is not None, newlist)

    # walk over each instruction, if it has references, we update them
    for instr in instructions.instructions:
        # we can skip labels
        if isinstance(instr, pyasm2.Label):
            continue

        # check for references to imports
        if isinstance(instr, pyasm2.RelativeJump):
            # not very good, but for now (instead of checking relocs) we check
            # if the index is in the iat tabel..
            #if int(instr.lbl.index, 16) in iat_label:
                #instr.lbl.index = iat_label[int(instr.lbl.index, 16)]
                #instr.lbl.prepend = False
            continue

    program = ['.file "ssexy.c"', '.intel_syntax noprefix']

    # we walk over each section, if a reference to this section has been found
    # then we will dump the entire section as bytecode.. with matching labels
    for section in elf.sections:
        base = section.addr
        data = section.data.value
        addr = set(range(base, base + section.size)).intersection(addresses)
        if addr:
            # create a header for this section
            program.append('.section %s' % section.name)

            # for now we do it the easy way.. one line and label per byte, lol
            for addr in xrange(section.size):
                program.append('__lbl_%08x: .byte 0x%02x' % (base + addr,
                    ord(data[addr])))

            # empty line..
            program.append('')

    # now we define all xmm's etc we gathered
    program.append('.align 4')
    program += m32s
    program.append('.align 16')
    program += m128s

    # time to define 'main'
    program.append('.text')
    program.append('.globl Main')
    program.append('.type Main, @function')

    OEP = elf.entry

    # f****d up shit
    relocates = dict(('jmp __lbl_%08x' % k, 'jmp ' + v)
        for k, v in relocates.items())

    eips = ['__lbl_%08x' % x for x in eips]

    # append each instruction
    for instr in instructions.instructions:
        # if this is an label, we want a colon as postfix
        if isinstance(instr, pyasm2.Label):
            program.append(str(instr) + ':')

            # if OEP is at this address, we will also add the `_main' label
            if str(instr) == '__lbl_%08x' % OEP:
                program.append('Main:')

                # we have to initialize the stack register, so..
                # for now we assume esp gpr is stored as first gpr in xmm7
                program.append('movd xmm7, esp')

            # if the label is in the list of addresses to which we have to add
            # an "movd xmm7, esp" instruction, then add it (e.g. callback
            # function for pthread_create)
            if str(instr) in eips:
                program.append('movd xmm7, esp')
        else:
            # TODO: fix this terrible hack as well
            program.append(str(instr).replace('byte', 'byte ptr').replace(
                'word', 'word ptr').replace('retn', 'ret').replace(
                '__lbl_00400000', '0x400000').replace('oword ptr', ''))
            if program[-1] in relocates:
                program[-1] = relocates[program[-1]]

    print '\n'.join(program)
class Microsoft_Windows_NFC_ClassExtension_309_1(Etw):
    pattern = Struct(
        "Length" / Int32ul
    )