Ejemplo n.º 1
0
                UBInt32("cap"),
                UBInt16("DL_earfcn"),
                UBInt8("DL_prbs"),
                UBInt16("UL_earfcn"),
                UBInt8("UL_prbs"))

CAPS_RESPONSE = Struct("caps_response",
                       BitStruct("flags", Padding(30),
                                 Bit("ue_measure"),
                                 Bit("ue_report")),
                       UBInt32("nof_cells"),
                       Array(lambda ctx: ctx.nof_cells, CAPS_C))

UE_R = Struct("ues",
              UBInt16("pci"),
              Bytes("plmn_id", 4),
              UBInt16("rnti"),
              UBInt64("imsi"))

UE_REPORT_RESPONSE = Struct("ue_report_response",
                            UBInt32("nof_ues"),
                            Array(lambda ctx: ctx.nof_ues, UE_R))

CAPS_REQUEST = Struct("caps_request",
                      UBInt8("type"),
                      UBInt8("version"),
                      UBInt32("enbid"),
                      UBInt16("cellid"),
                      UBInt32("modid"),
                      UBInt16("length"),
                      UBInt32("seq"),
Ejemplo n.º 2
0
    ),
    "authentication_size" / Switch(
        this.authentication_method,
        {
            ProvisioningAuthenticationMethod.NONE: Const(0, Int8ub),
            ProvisioningAuthenticationMethod.STATIC: Const(0, Int8ub),
            ProvisioningAuthenticationMethod.OUTPUT: Int8ub,
            ProvisioningAuthenticationMethod.INPUT: Int8ub,
        },
    ),
)

ProvisioningPublicKey = Struct(
    "key" /
    ProvisioningPublicKeyAdapter(Struct(
        "x" / Bytes(32),
        "y" / Bytes(32),
    ), ), )

ProvisioningInputComplete = Struct()

ProvisioningConfirmation = Struct("confirmation" / Bytes(16), )

ProvisioningRandom = Struct("random" / Bytes(16), )

ProvisioningData = Struct(
    "encrypted_provisioning_data" / Bytes(25),
    "provisioning_data_mic" / Bytes(8),
)

ProvisioningPayload = Struct(
Ejemplo n.º 3
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.')
class Microsoft_Windows_CoreSystem_InitMachineConfig_1_0(Etw):
    pattern = Struct(
        "evtErrorId" / Int64ul, "evtHiveNameLength" / Int16ul,
        "evtHiveName" / Bytes(lambda this: this.evtHiveNameLength),
        "evtStatus" / Int32ul, "evtAdditionalInfo" / Int64ul)
Ejemplo n.º 5
0
class Microsoft_Windows_Serial_ClassExtension_V2_22_1(Etw):
    pattern = Struct("Device" / Int64ul, "Offset" / Int64ul,
                     "Length" / Int32ul, "TransferModeEvent" / Int32ul,
                     "Payload" / Bytes(lambda this: this.Length))
                    quality=obj["lfQuality"], pitch_and_family=obj["lfPitchAndFamily"], face_name=obj["lfFaceName"])

    def _encode(self, obj, context, path):
        return {"lfHeight": obj.height, "lfWidth": obj.width, "lfEscapement": obj.escapement,
                "lfOrientation": obj.orientation, "lfWeight": obj.weight, "lfItalic": obj.italic,
                "lfUnderline": obj.underline, "lfStrikeOut": obj.strikeout, "lfCharSet": obj.char_set,
                "lfOutPrecision": obj.out_precision, "lfClipPrecision": obj.clip_precision, "lfQuality": obj.quality,
                "lfPitchAndFamily": obj.pitch_and_family, "lfFaceName": obj.face_name}


FontStruct = FontStructAdapter(LOGFONTW)

RawRuleStruct = """
Struct that contains a single rule which can be applied on the process monitor events.
""" * Struct(
    "reserved1" / Default(Bytes(3), 0) * "!!Unknown field!!",
    "column" / ColumnType,
    "relation" / RuleRelationType,
    "action" / RuleActionType,
    "value_offset" / Tell,  # NOT IN THE REAL FORMAT - USED FOR BUILDING ONLY
    "value_length" / Default(Int32ul, 0),
    "before_value_offset" / Tell,  # NOT IN THE REAL FORMAT - USED FOR BUILDING ONLY
    "value" / FixedUTF16CString(lambda this: this.value_length, "value"),
    "after_value_offset" / Tell,  # NOT IN THE REAL FORMAT - USED FOR BUILDING ONLY
    "reserved2" / Default(Bytes(5), 0) * "!!Unknown field!!",

    # To calculate value string in build time
    "value_length" / Pointer(lambda this: this.value_offset,
                             Default(Int32ul, lambda this: this.after_value_offset - this.before_value_offset))
)
Ejemplo n.º 7
0
# -------------------- Payload Verification --------------------

# encrypted payload is split into multiple data blocks with hashes
PayloadBlock = Struct(
    "block_index" / Checksum(Int32ul, lambda this: this._index, this),
    "block_hash_offset" / Tell,
    Padding(32),
    "block_data" / Prefixed(Int32ul, GreedyBytes),
    # block_hash has to be at the end with a pointer because it needs to
    # come after other fields
    "block_hash" / Pointer(
        this.block_hash_offset,
        IfThenElse(
            len_(this.block_data) == 0,
            Checksum(Bytes(32), lambda _: b'\x00' * 32, this),
            Checksum(
                Bytes(32),
                lambda block_data: hashlib.sha256(block_data).digest(),
                this.block_data,
                # exception=PayloadChecksumError
            ))),
)

PayloadBlocks = RepeatUntil(
    lambda item, a, b: len(item.block_data) ==
    0,  # and item.block_hash == b'\x00' * 32,
    PayloadBlock)

# -------------------- Payload Decryption/Decompression --------------------
class Microsoft_Windows_DHCPv6_Client_1012_0(Etw):
    pattern = Struct("NetworkHintString" / WString, "NetworkHint" / WString,
                     "HWLength" / Int32ul,
                     "HWAddress" / Bytes(lambda this: this.HWLength))
Ejemplo n.º 9
0
            "droprelic": actions.droprelic,
            "gatherpoint": actions.gatherpoint,
            "townbell": actions.townbell,
            "resign": actions.resign,
            "tribute": actions.tribute,
            "queue": actions.queue,
            "multiqueue": actions.multiqueue,
            "research": actions.research,
            "sell": actions.sell,
            "buy": actions.buy,
            "backtowork": actions.backtowork,
            "de": actions.de,
            "postgame": actions.postgame
        },
        default=Struct("unk_action" / Computed(lambda ctx: ctx._.type),
                       "bytes" / Bytes(lambda ctx: ctx._._.length - 1)))),
    Padding(4))

# Action - length followed by data.
action = "action" / Struct("length" / Int32ul, action_data)

# Synchronization.
sync = "sync" / Struct(
    "time_increment" / Int32ul, Peek("next" / Int32ul), "checksum" / If(
        lambda ctx: not ctx.next,
        Struct(Padding(8), "sync" / Int32ul, "unknown" / Bytes(4),
               "sequence" / Int32ul,
               If(lambda ctx: ctx.sequence > 0, Bytes(332)), Bytes(8))))

# View lock.
viewlock = "viewlock" / Struct("view" / Struct("x" / Float32l, "y" / Float32l),
class Microsoft_Windows_DHCPv6_Client_51060_0(Etw):
    pattern = Struct("InterfaceGUID" / WString, "HWLength" / Int32ul,
                     "HWAddress" / Bytes(lambda this: this.HWLength))
class Microsoft_Windows_DHCPv6_Client_51062_0(Etw):
    pattern = Struct("HWLength" / Int32ul,
                     "HWAddress" / Bytes(lambda this: this.HWLength),
                     "StatusCode" / Int32ul)
Ejemplo n.º 12
0
    Computed(lambda ctx: ctx.population_limit_encoded *
             (25 if ctx._.version in
              [Version.USERPATCH14, Version.USERPATCH15] else 1)),
    Embedded(
        If(
            lambda ctx: ctx._.version != Version.AOK,
            Struct(Peek("game_type_id" / Byte), GameTypeEnum(
                "game_type" / Byte), "lock_teams" / Flag))),
    If(
        lambda ctx: ctx._.version == Version.DE,
        Struct("treaty_length" / Byte, "cheat_codes_used" / Int32ul,
               If(lambda ctx: ctx._._.save_version >= 13.13, Padding(4)))),
    Embedded(
        If(
            lambda ctx: ctx._.version != Version.AOK,
            Struct(
                "num_chat" / Int32ul,
                Array(
                    lambda ctx: ctx.num_chat,  # pre-game chat messages
                    "messages" / Struct(
                        "message_length" / Int32ul, "message" /
                        Bytes(lambda ctx: ctx.message_length -
                              (1 if ctx.message_length > 0 else 0)),
                        If(lambda ctx: ctx.message_length > 0,
                           Padding(1))))))),
    "de" / If(
        lambda ctx: ctx._.version == Version.DE,
        Struct(
            "map_seed" / If(lambda ctx: ctx._._.save_version >= 13.08,
                            Int32sl), Bytes(10))))
Ejemplo n.º 13
0
    PascalString(lengthfield="scenario_filename_length" / Int16ul),
    If(
        lambda ctx: ctx._._.version == Version.DE,
        Struct(Padding(64),
               If(lambda ctx: find_save_version(ctx) >= 13.34, Padding(64)))))

# Scenarios have intro text, a bitmap, and cinematics.
messages = "messages" / Struct(
    "instruction_id" / Int32ul,
    "hints_id" / Int32ul,
    "victory_id" / Int32ul,
    "defeat_id" / Int32ul,
    "history_id" / Int32ul,
    "scouts_id" / If(lambda ctx: ctx._._.version != Version.AOK, Int32ul),
    "instructions_length" / Int16ul,
    "instructions" / Bytes(lambda ctx: ctx.instructions_length),
    "hints" / PascalString(lengthfield="hints_length" / Int16ul),
    "victory" / PascalString(lengthfield="victory_length" / Int16ul),
    "defeat" / PascalString(lengthfield="defeat_length" / Int16ul),
    "history" / PascalString(lengthfield="history_length" / Int16ul),
    "scouts" / If(lambda ctx: ctx._._.version != Version.AOK,
                  PascalString(lengthfield="scouts_length" / Int16ul)),
    "pg_cin" / PascalString(lengthfield="pg_cin_length" / Int16ul),
    "vict_cin" / PascalString(lengthfield="vict_cin_length" / Int16ul),
    "loss_cin" / PascalString(lengthfield="loss_cin_length" / Int16ul),
    "background" / PascalString(lengthfield="background_length" / Int16ul),
    "bitmap_included" / Int32ul,
    "bitmap_x" / Int32ul,
    "bitmap_y" / Int32ul,
    Padding(2),
    # bitmap here if it is included
class Microsoft_Windows_WinINet_Capture_2004_0(Etw):
    pattern = Struct("SessionId" / Int32ul, "SequenceNumber" / Int32ul,
                     "Flags" / Int32ul, "PayloadByteLength" / Int32ul,
                     "Payload" / Bytes(lambda this: this.PayloadByteLength))
Ejemplo n.º 15
0
from .adapters import PGMFlags, StatusAdapter, DateAdapter, ZoneFlags, PartitionStatus, EventAdapter
from ..common import CommunicationSourceIDEnum, ProductIdEnum, calculate_checksum

LoginConfirmationResponse = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / BitStruct(
                "command" / Const(0x1, Nibble), "status" /
                Struct("reserved" / Flag, "alarm_reporting_pending" / Flag,
                       "Winload_connected" / Flag, "NeWare_connected" / Flag)),
            "length" / Rebuild(
                Int8ub, lambda this: this._root._subcons.fields.sizeof() + this
                ._root._subcons.checksum.sizeof()), "result" /
            BitStruct("_not_used0" / BitsInteger(4), "partition_2" / Flag,
                      "_not_used1" / BitsInteger(3)), "callback" / Int16ub)),
    "checksum" / Checksum(Bytes(1), lambda data: calculate_checksum(data),
                          this.fields.data))

InitializeCommunication = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / Struct("command" / Const(0x00, Int8ub)),
            "module_address" / Default(Int8ub, 0x00),
            "_not_used0" / Padding(2),
            "product_id" / ProductIdEnum,
            "firmware" /
            Struct("version" / Int8ub, "revision" / Int8ub, "build" / Int8ub),
            "panel_id" / Int16ub,
            "pc_password" / Default(Bytes(2), b'0000'),
            "modem_speed" / Bytes(1),
            "source_method" / Default(
Ejemplo n.º 16
0
            decrypted = Utils.decrypt(obj, context['_']['token'])
            decrypted = decrypted.rstrip(b"\x00")
        except Exception:
            _LOGGER.debug("Unable to decrypt, returning raw bytes.")
            return obj

        try:
            jsoned = json.loads(decrypted.decode('utf-8'))
        except:
            _LOGGER.error("unable to parse json, was: %s", decrypted)
            raise

        return jsoned


Message = Struct(
    # for building we need data before anything else.
    "data" / Pointer(32, RawCopy(EncryptionAdapter(GreedyBytes))),
    "header" / RawCopy(
        Struct(
            Const(Int16ub,
                  0x2131), "length" / Rebuild(Int16ub, Utils.get_length),
            "unknown" / Default(Int32ub, 0x00000000), "devtype" /
            Enum(Default(Int16ub, 0x02f2), default=Pass, **xiaomi_devices),
            "serial" / Default(Int16ub, 0xa40d),
            "ts" / TimeAdapter(Default(Int32ub, datetime.datetime.utcnow())))),
    "checksum" /
    IfThenElse(Utils.is_hello, Bytes(16),
               Checksum(Bytes(16), Utils.md5, Utils.checksum_field_bytes)),
)
Ejemplo n.º 17
0
class FNVPlugin(BasePlugin):
    """The plugin for Fallout: New Vegas.

    This plugin structure *should* handle plugins for the games:
        - Fallout 3
        - Fallout: New Vegas

    Note:
        This structure *currently* reads all data on initialization.
        This may appear as *slower* initialization times for larger plugins.
        Should be fixed by
        `lazy constructs <https://construct.readthedocs.io/en/latest/lazy.html>`_
        when they become more stable.

    **Credit:**
        - `FopDoc <https://tes5edit.github.io/fopdoc/FalloutNV/Records.html>`_
    """

    subrecord_struct = Struct(
        "type" / PaddedString(4, "utf8"),
        "data_size" / Int16ul,
        "data" / Bytes(lambda this: this.data_size),
        "parsed"
        / Computed(
            lambda this: FNVPlugin.parse_subrecord(
                this._.id, this._.type, this.type, this.data
            )
        ),
    )
    """The structure for FO3/FNV subrecords.

    Returns:
        :class:`~construct.core.Struct`: The structure of FO3/FNV subrecords
    """

    record_struct = Struct(
        "type" / PaddedString(4, "utf8"),
        "data_size" / Int32ul,
        "flags"
        / FlagsEnum(
            Int32ul,
            master=0x00000001,
            _unknown_0=0x00000002,
            _unknown_1=0x00000004,
            _unknown_2=0x00000008,
            form_initialized=0x00000010,
            deleted=0x00000020,
            constant=0x00000040,
            fire_disabled=0x00000080,
            inaccessible=0x00000100,
            casts_shadows=0x00000200,
            persistent=0x00000400,
            initially_disabled=0x00000800,
            ignored=0x00001000,
            no_voice_filter=0x00002000,
            cannot_save=0x00004000,
            visible_when_distant=0x00008000,
            random_anim_start=0x00010000,
            dangerous=0x00020000,
            compressed=0x00040000,
            cant_wait=0x00080000,
            _unknown_3=0x00100000,
            _unknown_4=0x00200000,
            _unknown_5=0x00400000,
            _unknown_6=0x00800000,
            destructible=0x01000000,
            obstacle=0x02000000,
            navmesh_filter=0x04000000,
            navmesh_box=0x08000000,
            non_pipboy=0x10000000,
            child_can_use=0x20000000,
            navmesh_ground=0x40000000,
            _unknown_7=0x80000000,
        ),
        "id" / Int32ul,
        "revision" / Int32ul,
        "version" / Int16ul,
        "_unknown_0" / Int16ul,
        # NOTE: ignores compressed data size as it is handled by GreedyBytes
        If(lambda this: this.flags.compressed, Padding(4)),
        "data"
        / IfThenElse(
            lambda this: this.flags.compressed,
            Compressed(Bytes(lambda this: this.data_size), "zlib"),
            Bytes(lambda this: this.data_size),
        ),
        "subrecords"
        / Computed(
            lambda this: GreedyRange(FNVPlugin.subrecord_struct).parse(
                this.data, id=this.id, type=this.type
            )
        ),
    )
    """The structure for FO3/FNV records.

    Returns:
        :class:`~construct.core.Struct`: The structure of FO3/FNV records
    """

    # TODO: instead of using ``GreedyRange`` to handle parsing unknown length lists,
    # should probably use other repeaters to avoid messy construct debugging
    # (will always raise exception when expects record type to exist, but gets 0 bytes)
    group_struct = Struct(
        "type" / Const(b"GRUP"),
        "group_size" / Int32ul,
        # TODO: find a better way of lazily building ``label`` in place
        # instead of computing it later
        # NOTE: deferred until group_type is determined
        "_label" / Bytes(4),
        "group_type"
        / Enum(
            Int32sl,
            top_level=0,
            world_children=1,
            interior_cell_block=2,
            interior_cell_subblock=3,
            exterior_cell_block=4,
            exterior_cell_subblock=5,
            cell_children=6,
            topic_children=7,
            cell_persistent_children=8,
            cell_temporary_children=9,
            cell_visible_distant_children=10,
        ),
        "label"
        / Computed(
            lambda this: Switch(
                this.group_type,
                {
                    "top_level": PaddedString(4, "utf8"),
                    "world_children": FNVFormID(["WRLD"]),
                    "interior_cell_block": Int32sl,
                    "interior_cell_subblock": Int32sl,
                    "exterior_cell_block": Struct("y" / Int8sl, "x" / Int8sl),
                    "exterior_cell_subblock": Struct("y" / Int8sl, "x" / Int8sl),
                    "cell_children": FNVFormID(["CELL"]),
                    "topic_children": FNVFormID(["DIAL"]),
                    "cell_persistent_children": FNVFormID(["CELL"]),
                    "cell_temporary_children": FNVFormID(["CELL"]),
                    "cell_visible_distant_children": FNVFormID(["CELL"]),
                },
                default=GreedyBytes,
            ).parse(this._label)
        ),
        "stamp" / Int16ul,
        "_unknown_0" / Bytes(6),
        "data" / Bytes(lambda this: this.group_size - 24),
        "subgroups"
        / If(
            lambda this: (len(this.data) > 4 and this.data[:4] == b"GRUP"),
            Computed(
                lambda this: GreedyRange(
                    LazyBound(lambda: FNVPlugin.group_struct)
                ).parse(this.data)
            ),
        ),
        "records"
        / If(
            lambda this: this.subgroups is None,
            Computed(
                lambda this: GreedyRange(FNVPlugin.record_struct).parse(this.data)
            ),
        ),
    )
    """The structure for FO3/FNV groups.

    Returns:
        :class:`~construct.core.Struct`: The structure of FO3/FNV groups
    """

    plugin_struct = Struct(
        "header" / record_struct * "Plugin header record",
        "groups" / GreedyRange(group_struct) * "Plugin groups",
    )
    """The structure for FO3/FNV plugins.

    Returns:
        :class:`~construct.core.Struct`: The structure of FO3/FNV plugins
    """

    # NOTE: working record is mangaled in order to protect state during
    # subrecord parsing for record state
    __working_record = {}

    @classmethod
    def can_handle(cls, filepath: str) -> bool:
        """Determines if a given file can be handled by the plugin.

        Args:
            filepath (str): The filepath to evaluate

        Raises:
            FileNotFoundError: When the given `filepath` cannot be found

        Returns:
            bool: True if file can be handled, otherwise False
        """

        if not os.path.isfile(filepath):
            raise FileNotFoundError(f"file {filepath!r} does not exist")

        header = cls.record_struct.parse_file(filepath)

        # NOTE: must clear class working record after every "full" file parse
        # otherwise, subsequent parses will have fragmented data when trying to discover
        # and parse subrecords
        cls.__working_record = {}
        return header.type == "TES4" and header.version == 15

    @classmethod
    def parse_subrecord(
        cls,
        record_id: int,
        record_type: str,
        subrecord_type: str,
        subrecord_data: bytes,
        strict: bool = True,
    ) -> Container:
        """Parses a subrecord's data.

        Args:
            record_type (str): The parent record type
            subrecord_type (str): The subrecord type
            subrecord_data (bytes): The subrecord data to parse
            strict (bool): Defaults to True, If True, enforce strict subrecord discovery

        Returns:
            Container: The resulting parsed container
        """

        (record_type, subrecord_type) = (record_type.upper(), subrecord_type.upper())

        # handle reset of working record state
        if record_id not in cls.__working_record:
            cls.__working_record[record_id] = []

        record_subrecords = RecordMapping.get(record_type)
        if record_subrecords:
            (parsed, working_record) = record_subrecords.handle_working(
                subrecord_type,
                subrecord_data,
                cls.__working_record[record_id],
                strict=strict,
            )
            cls.__working_record[record_id].extend(working_record)
            return parsed
Ejemplo n.º 18
0
        raise NotImplementedError("override control_outputs in a subclass")

    def process_event(self, event):
        raise NotImplementedError("override process_event in a subclass")

    def generate_event_notifications(self, event):
        raise NotImplementedError(
            "override generate_event_notifications in a subclass")


InitiateCommunication = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / BitStruct("command" / Const(7, Nibble), "reserved0" /
                             Const(2, Nibble)), "reserved1" / Padding(35))),
    "checksum" / Checksum(Bytes(1), lambda data: calculate_checksum(data),
                          this.fields.data))

InitiateCommunicationResponse = Struct(
    "fields" / RawCopy(
        Struct(
            "po" / BitStruct("command" / Const(7, Nibble), "message_center" /
                             Nibble), "new_protocol" / Const(0xFF, Int8ub),
            "protocol_id" / Int8ub, "protocol" /
            Struct("version" / Int8ub, "revision" / Int8ub, "build" / Int8ub),
            "family_id" / Int8ub, "product_id" / ProductIdEnum,
            "talker" / Enum(Int8ub,
                            BOOT_LOADER=0,
                            CONTROLLER_APPLICATION=1,
                            MODULE_APPLICATION=2), "application" /
            Struct("version" / Int8ub, "revision" / Int8ub, "build" / Int8ub),
Ejemplo n.º 19
0
class Microsoft_Windows_CAPI2_8200_0(Etw):
    pattern = Struct("Subsystem" / WString, "Algorithm" / WString,
                     "Length" / Int16ul,
                     "Value" / Bytes(lambda this: this.Length))
Ejemplo n.º 20
0
    MemberPrimitiveTyped=8,
    MemberReference=9,
    ObjectNull=10,
    MessageEnd=11,
    BinaryLibrary=12,
    ObjectNullMultiple256=13,
    ObjectNullMultiple=14,
    ArraySinglePrimitive=15,
    ArraySingleObject=16,
    ArraySingleString=17,
    MethodCall=21,
    MethodReturn=22)

LengthPrefixedString = Struct(
        "len" / VarInt,
        "data" / Bytes(this.len))

ClassInfo = Struct(
    "ObjectId" / Int32ul,
    "Name" / LengthPrefixedString,
    "MemberCount" / Int32ul,
    "MemberNames" / Array(this.MemberCount, LengthPrefixedString))

BinaryTypeEnumeration = Enum(Byte,
    Primitive=0,
    String=1,
    Object=2,
    SystemClass=3,
    Class=4,
    ObjectArray=5,
    StringArray=6,
class Microsoft_Windows_RRAS_20004_0(Etw):
    pattern = Struct("DebugString" / WString, "BufferSize" / Int32ul,
                     "Buffer" / Bytes(lambda this: this.BufferSize))
Ejemplo n.º 22
0
from construct import (
    Struct, Int32ul, Float32l, Array, Padding, Flag, If,
    Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
    Int64ul
)

from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version

# pylint: disable=invalid-name, bad-continuation

de_string = Struct(
    Const(b"\x60\x0A"),
    "length"/Int16ul,
    "value"/Bytes(lambda ctx: ctx.length)
)

separator = Const(b"\xa3_\x02\x00")

de = "de"/Struct(
    "version"/Float32l,
    "interval_version"/Int32ul,
    "game_options_version"/Int32ul,
    "dlc_count"/Int32ul,
    "dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
    "dataset_ref"/Int32ul,
    "difficulty"/DifficultyEnum(Int32ul),
    "selected_map_id"/Int32ul,
    "resolved_map_id"/Int32ul,
    "reveal_map"/Int32ul,
class Microsoft_Windows_CoreSystem_InitMachineConfig_2_0(Etw):
    pattern = Struct(
        "evtHiveNameLength" / Int16ul,
        "evtHiveName" / Bytes(lambda this: this.evtHiveNameLength))
Ejemplo n.º 24
0
    this,
    Const,
    Terminated,
)


class EnumStr(Enum):
    def _decode(self, obj, context, path):
        try:
            return self.decmapping[obj]
        except KeyError:
            return EnumIntegerString.new(obj, "")


fe_chip_version = EnumStr(
    Bytes(1),
    RD53A=b"0",
    ITkpix_v1=b"1",
    ITkpix_v1p1=b"2",
    ITkpix_v2=b"3",
)

fe_chip_wafer = Struct(
    "batch_number" / EnumStr(
        Bytes(1),
        RD53A=b"0",
        ITkpix_v1=b"1",
        CROC=b"2",
    ),
    "number" / Bytes(6),
)
Ejemplo n.º 25
0
class Microsoft_Windows_Serial_ClassExtension_V2_15_1(Etw):
    pattern = Struct(
        "Device" / Int64ul, "IOCTL" / Int32ul,
        "IOCTLInputBufferLength" / Int32ul,
        "IOCTLInputBuffer" / Bytes(lambda this: this.IOCTLInputBufferLength))
Ejemplo n.º 26
0
from construct import (Array, Bytes, Embed, GreedyRange, If, Struct, UBInt8,
                       UBInt16)
from msa.core.data.constants import LEN_COD_CATEGORIA
from msa.core.documentos.constants import LEN_LEN_OPC, LEN_LEN_UBIC, LEN_SERIAL

struct_voto = Struct("voto", Bytes("len_ubic", LEN_LEN_UBIC),
                     Bytes("ubicacion", lambda ctx: int(ctx.len_ubic)),
                     Bytes("len_opciones", LEN_LEN_OPC),
                     Bytes("opciones", lambda ctx: int(ctx.len_opciones)),
                     Bytes("serial", LEN_SERIAL))

struct_recuento = Struct("Recuento", UBInt8("grupo"),
                         GreedyRange(Bytes("datos", 1)))

struct_recuento_dni = Struct(
    "Recuento con dni",
    UBInt8("len_docs"),
    Bytes("documentos", lambda ctx: ctx.len_docs),
    Embed(struct_recuento),
)

struct_apertura = Struct(
    "Apertura",
    UBInt16("numero_mesa"),
    UBInt8("hora"),
    UBInt8("minutos"),
    UBInt8("cantidad_autoridades"),
    UBInt8("len_nombres"),
    Array(lambda ctx: ctx.len_nombres, Bytes("nombres", 1)),
    Array(lambda ctx: ctx.cantidad_autoridades, Bytes("tipos", 1)),
    UBInt8("len_docs"),
Ejemplo n.º 27
0
        STATE_READY=1,
        # bereithalten
        STATE_SET=2,
        # spielen
        STATE_PLAYING=3,
        # spiel zu ende
        STATE_FINISHED=4),
    "first_half" / Flag,
    "kick_of_team" / Byte,
    "secondary_state" / Enum(Byte,
                             STATE_NORMAL=0,
                             STATE_PENALTYSHOOT=1,
                             STATE_OVERTIME=2,
                             STATE_TIMEOUT=3,
                             STATE_DIRECT_FREEKICK=4,
                             STATE_INDIRECT_FREEKICK=5,
                             STATE_PENALTYKICK=6,
                             DROPBALL=128,
                             UNKNOWN=255),
    "secondary_state_info" / Bytes(4),
    "drop_in_team" / Flag,
    "drop_in_time" / Short,
    "seconds_remaining" / Int16sl,
    "secondary_seconds_remaining" / Short,
    "teams" / Array(2, "team" / TeamInfo))

GAME_CONTROLLER_RESPONSE_VERSION = 2

ReturnData = Struct("header" / Const(b"RGrt"), "version" / Const(2, Byte),
                    "team" / Byte, "player" / Byte, "message" / Byte)
Ejemplo n.º 28
0
# max brightness:
# 4345 02 01 d6 71 00 00 64 0000 15000000000000
# white, warm:
# 4345 01 02 00 00 00 00 64 078f 15000000000000

StateResult = Struct(
    "onoff" / Embedded(OnOff),
    "mode" / ModeAdapter(Byte),
    "color" / Embedded(Color),
    "temperature" / Int16ub,  #, as Temeprature contains brightness.
    "temp_fraction" / Default(Byte, 0),
)

# Using hardcoded devid, this may or may not work if you try to use different
# bluetooth adapters (or devices) to control the same light.
Pair = "Pair" / Struct("devid" / Default(Bytes(16), 0x1234))

# Note, requests with (mostly) even, responses with odd

RequestType = "reqtype" / Enum(
    Byte,
    SetOnOff=0x40,
    SetColor=0x41,
    SetBrightness=0x42,
    SetTemperature=0x43,
    GetState=0x44,
    SetAlarm=0x46,
    GetAlarm=0x47,
    DeleteAlarm=0x48,
    SetFlow=0x4a,
    SetFlowTimerBrightness=0x4b,
Ejemplo n.º 29
0
    TERMINATOR,
)
from .ami_bitstructs import EntryChunk, DateShort
import struct

DIVIDEND_PAY_DATE = "Dividend Pay Date"

DELISTING_DATE = "Delisting Date"
SwappedField = FormatField("<", "f")

# Const(b"\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x3F")
from construct import CString

ascii_str = CString("ascii")
Master = Struct(
    "Header" / Bytes(8),
    "NumSymbols" / Int32ul,
    "Symbols" / GreedyRange(
        Struct(
            "Symbol" / Padded(492, CString("ascii")),
            "CONST" / Const(
                b"\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x3F"
            ),
            "Rest" / Bytes(1172 - 5 - 16 - 490 + 3),
        )),
)

# Symbol 7-151
# FullName Byte 152- 499
# 22C- 22F Schares Float
SymbolHeader = Struct(
Ejemplo n.º 30
0
PT_SET_SLICE = 0x19
PT_DEL_SLICE = 0x1A
PT_SLICE_STATUS_RESPONSE = 0x1B
PT_SLICE_STATUS_REQUEST = 0x1C

PT_IGMP_REPORT = 0xE0
PT_INCOMING_MCAST_ADDR = 0xE1

HEADER = Struct(
    "version" / Int8ub,
    "type" / Int8ub,
    "length" / Int32ub,
    "seq" / Int32ub,
    "xid" / Int32ub,
    "device" / Bytes(6),
)
HEADER.name = "header"

HELLO_REQUEST = Struct(
    "version" / Int8ub,
    "type" / Int8ub,
    "length" / Int32ub,
    "seq" / Int32ub,
    "xid" / Int32ub,
    "device" / Bytes(6),
)
HELLO_REQUEST.name = "hello_request"

HELLO_RESPONSE = Struct(
    "version" / Int8ub,