Ejemplo n.º 1
0
def PrefixedOffset(sizetype, type, offs=0):
    return C.FocusedSeq(
        "content", "_data" / C.Rebuild(
            C.Struct("size" / C.Rebuild(sizetype,
                                        C.len_(this.data) - offs),
                     "data" / C.Bytes(this.size + offs)), lambda obj:
            {"data": type.build(obj.content, **{
                **obj._params,
                **obj
            })}), "content" / C.RestreamData(this._data.data, type))
Ejemplo n.º 2
0
def ClassImpl(id):
    return C.FocusedSeq(
        "classes", "_class" /
        C.Computed(lambda this: this._root.defs[evaluate(id, this)]),
        "classes" / C.FocusedSeq(
            "entries", "_index" / C.Index, "_member" /
            C.Computed(lambda this: this._._class.members[this._index]),
            "entries" /
            C.Sequence(C.Computed(this._._member.name),
                       DataEntry(lambda this: this._._._member.type)))[C.len_(
                           this._class.members)])
Ejemplo n.º 3
0
def DataEntry(type):
    return C.FocusedSeq(
        "values",
        "_count" / C.Rebuild(Int32ul, C.len_(this.values)),
        "values" / C.Switch(
            type,
            {
                0: Pass,
                1: ClassEntry(),
                2: ClassEntry(),
                3: Byte,  #boolean
                4: Int8ul,
                5: Int16ul,
                6: Int32ul,
                7: Int64ul,
                8: Int8sl,
                9: Int16sl,
                10: Int32sl,
                11: Int64sl,
                12: Float32l,
                13: Float64l,
                14: CString("utf8"),
                15: RGBA(),
                16: Int64ul,  #pointer
                #17: Int32ul #size, potentially not a uint but that's probably the best option of it
                20: Vector3(),
                21: Vector4(),
                22: Quat4(),
                32: CString(
                    'utf8'
                ),  #specifically a CString, while 14 is probably something like std::string
                46: Capsule(),
                64: Vector2()
            },
            default=C.StopFieldError)[this._count],
    )
Ejemplo n.º 4
0
    "decimal_count" / If(this.type == "DECIMAL", Byte),
    "decimal_size" / If(this.type == "DECIMAL", Byte),
)
# Original code has this kwarg... allow_overwrite=True,

INDEX_TYPE_STRUCT = "type" / Enum(
    BitsInteger(2), KEY=0, INDEX=1, DYNAMIC_INDEX=2)

INDEX_FIELD_ORDER_TYPE_STRUCT = "field_order_type" / Enum(
    Int16ul, ASCENDING=0, DESCENDING=1, _default_="DESCENDING")

TABLE_DEFINITION_INDEX_STRUCT = "record_table_definition_index" / Struct(
    # May be external_filename
    # if external_filename == 0, no external file index
    "external_filename" / CString("ascii"),
    If(len_(this.external_filename) == 0, "index_mark" / Const(1, Byte)),
    "name" / CString("ascii"),
    #                                       Embedded('flags' / BitStruct(
    #                                                       Padding(1),
    #                                                       INDEX_TYPE_STRUCT,
    #                                                       Padding(2),
    #                                                       'NOCASE' / Flag,
    #                                                       'OPT' / Flag,
    #                                                       'DUP' / Flag)),
    "flags" / BitStruct(
        Padding(1),
        INDEX_TYPE_STRUCT,
        Padding(2),
        "NOCASE" / Flag,
        "OPT" / Flag,
        "DUP" / Flag,
Ejemplo n.º 5
0
from construct import (Struct, Bytes, Const, Int8ub, Int16ub, Rebuild, len_,
                       this)

Message = Struct(
    "header" / Const(bytes.fromhex('7E7E')),
    "length" / Rebuild(Int16ub, len_(this.payload) + 4),
    "code" / Int8ub,
    "payload" / Bytes(this.length-4),
    "cmdid" / Int8ub,
    "end" / Const(bytes.fromhex('0D0A')),
)
Ejemplo n.º 6
0
)

extra_entry = "extra_entry" / Struct(
    "size" / Int32ub,
    "id" / Int32ub,
    "data" / Bytes(this.size - 8),
)

productinfo_entry = "productinto_entry" / Struct(
    # TODO: Can we make this a Rebuild as well as have Padding calculated?
    "size" / Int32ub,
    "id" / Const(value=1, subcon=Int32ub),
    "channel" / CString(encoding='ascii'),
    "productversion" / CString(encoding='ascii'),
    "padding" /
    Padding(this.size - len_(this.channel) - len_(this.productversion) - 8),
)

extras_header = "extras_header" / Struct(
    "count" / Int32ub,
    "sections" / Array(this.count, Select(productinfo_entry, extra_entry)),
    "offset" / Tell,
)

index_entry = "index_entry" / Struct(
    "offset" / Int32ub,
    "size" / Int32ub,
    "flags" / Int32ub,
    "name" / CString(encoding='ascii'),
)
        #RPC_TYPE.LIST_PEERS_RESULT : RpcMessage_LIST_PEERS_RESULT,
        #RPC_TYPE.KILL_SESSIONS : RpcMessage_KILL_SESSIONS,
        #RPC_TYPE.KILL_SESSIONS_RESULT : RpcMessage_KILL_SESSIONS_RESULT,
        #RPC_TYPE.DEL_ENTRIES : RpcMessage_DEL_ENTRIES,
        #RPC_TYPE.DEL_ENTRIES_RESULT : RpcMessage_DEL_ENTRIES_RESULT,
        #RPC_TYPE.SHOW_ENTRIES : RpcMessage_SHOW_ENTRIES,
        #RPC_TYPE.SHOW_ENTRIES_RESULT : RpcMessage_SHOW_ENTRIES_RESULT,
        #RPC_TYPE.DUMP_MD : RpcMessage_DUMP_MD,
        #RPC_TYPE.DUMP_MD_RESULT : RpcMessage_DUMP_MD_RESULT,
        #RPC_TYPE.CLEAN_DB : RpcMessage_CLEAN_DB,
        #RPC_TYPE.DEBUGCTL : RpcMessage_DEBUGCTL,
    },
    default=None)

# RPC packet common header
rpc_packet_t = con.Struct("length" / Rebuild(Hex(Int32ub), len_(this.data)),
                          "code" / RPC_TYPE,
                          "data" / con.HexDump(con.Bytes(this.length)))


def rpc_message_build(code, **kwargs):
    """
    Build and serialize an RPC packet
    """
    data = RpcMessage.build(kwargs, code=code)

    return rpc_packet_t.build(Container(code=code, data=data))


def rpc_message_parse(source):
    """
Ejemplo n.º 8
0
    'id', RepeatUntil(lambda item, a, b: item.id == 'end', DynamicHeaderItem))

# -------------------- 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 --------------------
Ejemplo n.º 9
0
    artwork=0x4002,
    invalid_request=0x4003,  # guessed?
    menu_item=0x4101,
    menu_footer=0x4201,
    preview_waveform=0x4402,
    unknown1=0x4502,
    beatgrid=0x4602,
    cues=0x4702,
    waveform=0x4a02,
    unknown2=0x4e02)

DBMessage = Struct(
    "magic" / Const(0x872349ae, DBFieldFixed("int32")),
    "transaction_id" / Default(DBFieldFixed("int32"), 1),
    "type" / DBRequestType,
    "argument_count" / Rebuild(DBFieldFixed("int8"), len_(this.args)),
    "arg_types" / ArgumentTypesField,
    "args" / Array(this.argument_count, DBField))

ManyDBMessages = GreedyRange(DBMessage)

Beatgrid = Struct(
    Padding(4),
    "beat_count" / Int32ul,
    "payload_size" / Int32ul,  # bytes
    "u1" / Default(Int32ul, 1),
    "u2" / Int16ul,
    "u3" / Int16ul,
    "beats" / Array(
        this.beat_count,
        Struct(
Ejemplo n.º 10
0
    "firstBeatLength" / Float32l,
    "startTime" / Float32l,
    "capo" / Int8sl,
    "lastConversionDateTime" / PaddedString(32, encoding="ascii"),
    "part" / Int16sl,
    "songLength" / Float32l,
    "tuning" / array(Int16sl),
    "firstNoteTime" / Float32l,
    "firstNoteTime2" / Float32l,
    "maxDifficulty" / Int32sl,
)

Song = Struct(
    "beats" / array(Beat),
    "phrases" / array(Phrase),
    "chordTemplates" / array(ChordTemplate),
    "chordNotes" / array(ChordNote),
    "vocals" / array(Vocal),
    "symbols" / If(len_(this.vocals) > 0, Symbols),
    "phraseIterations" / array(PhraseIteration),
    "phraseExtraInfos" / array(PhraseExtraInfo),
    "newLinkedDiffs" / array(LinkedDiff),
    "actions" / array(Action),
    "events" / array(Event),
    "tones" / array(Tone),
    "dna" / array(DNA),
    "sections" / array(Section),
    "levels" / array(Level),
    "metadata" / Metadata,
)
Ejemplo n.º 11
0
"""Transaction hash, encoded as a reversed sequence of bytes."""

TxInput = c.Struct(
    "tx" / TxHash,
    "index" / c.Int32ul,
    "script_sig" / BitcoinBytes,
    "sequence" / c.Int32ul,
)
"""Transaction input."""

TxOutput = c.Struct("value" / c.Int64ul, "script_pubkey" / BitcoinBytes)
"""Transaction output."""

TxInputWitness = c.PrefixedArray(CompactUint, BitcoinBytes)
"""Array of witness records."""

Transaction = c.Struct(
    "version" / c.Int32ul,
    "segwit" / ConstFlag(b"\x00\x01"),
    "inputs" / c.PrefixedArray(CompactUint, TxInput),
    "outputs" / c.PrefixedArray(CompactUint, TxOutput),
    "witness" / c.If(c.this.segwit, TxInputWitness[c.len_(c.this.inputs)]),
    "lock_time" / c.Int32ul,
    c.Terminated,
)
"""Bitcoin transaction.

If the `segwit` flag is present (which would otherwise mean 0 inputs, 1 output),
we expect a `witness` field with entries corresponding to each input.
"""
Ejemplo n.º 12
0
Dot1_UntaggedVlanId = core.Struct('value' / core.Int16ub)

Dot1_PortProtocolVlan = core.Struct(
    'flags' / core.BitStruct(
        core.Padding(5),
        'enabled' / core.Flag,
        'supported' / core.Flag,
        core.Padding(1),
    ),
    'vlanid' / core.Int16ub
)

Dot1_VlanName = core.Struct(
    'vlanid' / core.Int16ub,
    'name_len' / core.Rebuild(core.Int8ub,
                              construct.len_(construct.this.value)),
    'vlan_name' / core.String(construct.this.name_len, "utf8")
)

Dot1_ProtocolIdentity = core.Struct(
    'len' / core.Rebuild(core.Int8ub, construct.len_(construct.this.value)),
    'protocol' / core.Bytes(construct.this.len)
)

Dot1_MgmtVlanId = core.Struct('value' / core.Int16ub)

Dot1_LinkAggregationId = core.Struct(
    'status' / core.BitStruct(
        core.Padding(6),
        'enabled' / core.Flag,
        'supported' / core.Flag
Ejemplo n.º 13
0
def checksum_16(data):
    c = 0
    for i in range(len(data) // 2):
        c = c + (data[i * 2 + 1] << 8) + data[i * 2]

    return c & 0xFFFF


WriteCommand = Struct("address" / Int16ul, "value" / Int16ul)

WriteMessageRequest = Struct(
    "fields" / RawCopy(
        Struct(
            "length" / Rebuild(
                Int16ul,
                len_(this.items) * WriteCommand.sizeof() // Int16ul.sizeof() +
                2,
            ),
            "command" /
            Const(vlxDevConstants.WS_WEB_UI_COMMAND_WRITE_DATA, Int16ul),
            "items" / WriteCommand[len_(this.items)],
        )),
    "checksum" /
    Checksum(Int16ul, lambda data: checksum_16(data), this.fields.data),
)

ReadTableResponse = GreedyRange(Int16ub)

ReadTableRequest = Struct(
    "fields" / RawCopy(
        Struct(
Ejemplo n.º 14
0
    ),
)

MSC_TRANSPORT_SUSPEND_RESPONSE_PACKET = construct.Padded(
    BLOCK_SIZE,
    construct.Struct(HEADER_CON, RANDOM_TOKEN_CON, construct.Const(bytes([0x00]))),
)

MSC_TRANSPORT_COMMAND_PACKET = construct.Padded(
    BLOCK_SIZE,
    construct.Struct(
        HEADER_CON,
        TOKEN_CON,
        "command_data_length"
        / construct.Rebuild(
            construct.Int16ub, construct.len_(construct.this.command_data)
        ),
        construct.Const(bytes([0x00, 0x00])),
        "command_data" / construct.Byte[construct.this.command_data_length],
    ),
)

MSC_TRANSPORT_RESPONSE_PACKET = construct.Padded(
    BLOCK_SIZE,
    construct.Struct(
        HEADER_CON,
        RANDOM_TOKEN_CON,
        "response_data" / construct.Prefixed(construct.Int16ub, construct.GreedyBytes),
    ),
)
Ejemplo n.º 15
0
ConfigurationDescriptor = DescriptorFormat(
    "bLength" / construct.Const(9, construct.Int8ul),
    "bDescriptorType" /
    DescriptorNumber(StandardDescriptorNumbers.CONFIGURATION),
    "wTotalLength" / DescriptorField("Length including subordinates"),
    "bNumInterfaces" / DescriptorField("Interface count"),
    "bConfigurationValue" / DescriptorField("Configuration number", default=1),
    "iConfiguration" / DescriptorField("Description string", default=0),
    "bmAttributes" / DescriptorField("Attributes", default=0x80),
    "bMaxPower" / DescriptorField("Max power consumption", default=250),
)

# Field that automatically reflects a string descriptor's length.
StringDescriptorLength = construct.Rebuild(
    construct.Int8ul,
    construct.len_(this.bString) * 2 + 2)

StringDescriptor = DescriptorFormat(
    "bLength" / StringDescriptorLength,
    "bDescriptorType" / DescriptorNumber(StandardDescriptorNumbers.STRING),
    "bString" / construct.GreedyString("utf_16_le"))


StringLanguageDescriptorLength = \
     construct.Rebuild(construct.Int8ul, construct.len_(this.wLANGID) * 2 + 2)

StringLanguageDescriptor = DescriptorFormat(
    "bLength" / StringLanguageDescriptorLength,
    "bDescriptorType" / DescriptorNumber(StandardDescriptorNumbers.STRING),
    "wLANGID" / construct.GreedyRange(construct.Int16ul))
Ejemplo n.º 16
0
blit_game = Struct('relo' / Optional(struct_blit_relo),
                   'bin' / RawCopy(struct_blit_bin),
                   'meta' / Optional(struct_blit_meta))

blit_game_with_meta = Struct('relo' / Optional(struct_blit_relo),
                             'bin' / RawCopy(struct_blit_bin),
                             'meta' / struct_blit_meta)

blit_game_with_meta_and_relo = Struct('relo' / struct_blit_relo,
                                      'bin' / RawCopy(struct_blit_bin),
                                      'meta' / struct_blit_meta)


def compute_icns_data_length(ctx):
    """Compute the required data length for palette based images.
    We need this computation here so we can use `math.ceil` and
    byte-align the result.
    """
    return math.ceil((ctx.width * ctx.height * ctx.bit_length) / 8)


blit_icns = Struct(
    'header' / Const(b'icns'),
    'size' / Rebuild(Int32ub,
                     len_(this.data) + 16),
    'type' / Const(b'ic07'),  # 128×128 icon in PNG format
    'data_length' / Rebuild(Int32ub,
                            len_(this.data) + 8),
    'data' / Bytes(this.data_length - 8))
Ejemplo n.º 17
0
    AddressType.UNICAST,
    AddressType.UNASSIGNED,
)

UnicastUnassignedGroupAddress = AddressTypeValidator(
    Int16ul,
    AddressType.UNICAST,
    AddressType.UNASSIGNED,
    AddressType.GROUP,
)

Int12ul = ExprValidator(Int16ul, (obj_ & 0xF000) == 0x00)

CompositionDataElement = Struct(
    "location" / GATTNamespaceDescriptorAdapter,
    "sig_number" / Rebuild(Int8ul, len_(this["sig_models"])),
    "vendor_number" / Rebuild(Int8ul, len_(this["vendor_models"])),
    "sig_models" / SIGModelId[this["sig_number"]],
    "vendor_models" / VendorModelId[this["vendor_number"]],
)

CompositionData = Struct(
    "cid" / Int16ul,
    "pid" / Int16ul,
    "vid" / Int16ul,
    "crpl" / Int16ul,
    "features" / Int16ul,  # TODO should be parsed
    "elements" / GreedyRange(CompositionDataElement),
)

Retransmit = BitStruct(
Ejemplo n.º 18
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,
Ejemplo n.º 19
0
CompactUint = CompactUintAdapter(CompactUintStruct)

TxInput = c.Struct(
    "tx" / c.Bytes(32),
    "index" / c.Int32ul,
    # TODO coinbase tx
    "script" / c.Prefixed(CompactUint, c.GreedyBytes),
    "sequence" / c.Int32ul,
)

TxOutput = c.Struct(
    "value" / c.Int64ul,
    "pk_script" / c.Prefixed(CompactUint, c.GreedyBytes),
)

StackItem = c.Prefixed(CompactUint, c.GreedyBytes)
TxInputWitness = c.PrefixedArray(CompactUint, StackItem)

Transaction = c.Struct(
    "version" / c.Int32ul,
    "segwit" / ConstFlag(b"\x00\x01"),
    "inputs" / c.PrefixedArray(CompactUint, TxInput),
    "outputs" / c.PrefixedArray(CompactUint, TxOutput),
    "witness" / c.If(this.segwit, TxInputWitness[len_(this.inputs)]),
    "lock_time" / c.Int32ul,
    c.Terminated,
)

print(Transaction.parse(tx_bin))
Ejemplo n.º 20
0
        if obj == 256:
            obj = 0
        return obj


struct_blit_pixel = Struct(
    'r' / Int8ul,
    'g' / Int8ul,
    'b' / Int8ul,
    'a' / Int8ul
)

struct_blit_image = Struct(
    'header' / Const(b'SPRITE'),
    'type' / PaddedString(2, 'ASCII'),
    'size' / Rebuild(Int32ul, len_(this.data) + (this.palette_entries * 4) + 18),
    'width' / Int16ul,
    'height' / Int16ul,
    'format' / Const(0x02, Int8ul),
    'palette_entries' / PaletteCountAdapter(Int8ul),
    'palette' / Array(this.palette_entries, struct_blit_pixel),
    'bit_length' / Computed(compute_bit_length),
    'data_length' / Computed(compute_data_length),
    'data' / Array(this.data_length, Int8ul)
)

struct_blit_meta = Struct(
    'header' / Const(b'BLITMETA'),
    'data' / Prefixed(Int16ul, Struct(
        'checksum' / Checksum(
            Int32ul,
Ejemplo n.º 21
0
        return play_method(command, *command_args)


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

    def _encode(self, obj, context):
        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,
Ejemplo n.º 22
0
        "require_user_click" / c.Flag,
        "red_background" / c.Flag,
        "delay" / c.BitsInteger(4),
    ), bytes_not, 2, bytes_not, 2)

VendorHeader = c.Struct(
    "_start_offset" / c.Tell,
    "magic" / c.Const(b"TRZV"),
    "_header_len" / c.Padding(4),
    "expiry" / c.Int32ul,
    "version" / c.Struct(
        "major" / c.Int8ul,
        "minor" / c.Int8ul,
    ),
    "vendor_sigs_required" / c.Int8ul,
    "vendor_sigs_n" / c.Rebuild(c.Int8ul, c.len_(c.this.pubkeys)),
    "vendor_trust" / VendorTrust,
    "reserved" / c.Padding(14),
    "pubkeys" / c.Bytes(32)[c.this.vendor_sigs_n],
    "vendor_string" / c.Aligned(4, c.PascalString(c.Int8ul, "utf-8")),
    "vendor_image" / Toif,
    "_data_end_offset" / c.Tell,
    c.Padding(-(c.this._data_end_offset + 65) % 512),
    "sigmask" / c.Byte,
    "signature" / c.Bytes(64),
    "_end_offset" / c.Tell,
    "header_len" /
    c.Pointer(c.this._start_offset + 4,
              c.Rebuild(c.Int32ul, c.this._end_offset - c.this._start_offset)),
)
Ejemplo n.º 23
0
    def get_indicator_led(self):
        """Get the indicator led status."""
        return self.send("get_indicatorLamp")


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,
Ejemplo n.º 24
0
ClassMemberDefinition = Struct(
    "name" / DataPointer(Int64ul, CString("utf8"), "names"),
    "type" / Byte,
    "unkn" / Byte,
    "size" / Byte,
    "_unknData" / C.Default(Byte[69], [0 for _ in range(69)]),
)

ClassDefinition = DataPointer(
    Int64ul,
    Struct("hash" / Int64ul,
           "members" / C.PrefixedArray(Int64ul, ClassMemberDefinition)),
    "definitionData")

ClassDefinitionList = C.FocusedSeq(
    "definitions", "_count" / C.Rebuild(Int32ul, C.len_(this.definitions)),
    "definitions" / C.Prefixed(
        Int32ul,
        C.Aligned(
            8,
            C.FocusedSeq(
                "definitions",
                "definitions" / ClassDefinition[this._._count],
                DataEntries("definitionData"),
                DataEntries("names"),
            ))))

# Hierarchy handling
varcount = 0

Ejemplo n.º 25
0
    @classmethod
    def _get_type_for_name(cls, name):
        """ Returns the type that's appropriate for a given descriptor field name. """

        try:
            return cls.USB_TYPES[cls._get_prefix(name)]
        except KeyError:
            raise ValueError(
                "field names must be formatted per the USB standard!")

    def __init__(self, description="", default=None):
        self.description = description
        self.default = default

    def __rtruediv__(self, field_name):
        field_type = self._get_type_for_name(field_name)

        if self.default is not None:
            field_type = construct.Default(field_type, self.default)

        # Build our subconstruct. Construct makes this look super weird,
        # but this is actually "we have a field with <field_name> of type <field_type>".
        # In long form, we'll call it "description".
        return (field_name / field_type) * self.description


# Convenience type that gets a descriptor's own length.
DescriptorLength = \
     construct.Rebuild(construct.Int8ul, construct.len_(construct.this)) \
     * "Descriptor Length"
Ejemplo n.º 26
0
                               Struct(event_index=VarInt, ),
                               "translator_gate":
                               Struct(gate_index=VarInt, ),
                               "logbook":
                               Struct(
                                   string_asset_id=VarInt,
                                   lore_type=ConstructLoreType,
                                   extra=VarInt,
                               )
                           }))

ConstructArea = Struct(
    name=CString("utf8"),
    in_dark_aether=Flag,
    asset_id=VarInt,
    _node_count=Rebuild(VarInt, construct.len_(construct.this.nodes)),
    default_node_index=OptionalValue(VarInt),
    valid_starting_location=Flag,
    nodes=Array(lambda this: this._node_count, ConstructNode),
    connections=Array(
        lambda this: this._node_count,
        Array(lambda this: this._node_count - 1, ConstructRequirement)))

ConstructWorld = Struct(
    name=CString("utf8"),
    dark_name=CString("utf8"),
    asset_id=VarInt,
    areas=PrefixedArray(VarInt, ConstructArea),
)

game_specific_map = {
Ejemplo n.º 27
0
    "offset_end" / Tell,
)

extra_entry = "extra_entry" / Struct(
    "size" / Int32ub,
    "id" / Int32ub,
    "data" / Bytes(this.size - 8),
)

productinfo_entry = "productinto_entry" / Struct(
    "size" / Int32ub,
    "id" / Const(value=1, subcon=Int32ub),
    "channel" / CString(encoding='ascii'),
    "productversion" / CString(encoding='ascii'),
    "padding" / Bytes(
                this.size - len_(this.channel) - len_(this.productversion) -
                # 8 bytes for size/id fields, and an
                # extra 2 bytes for the null terminator after
                # channel and productversion
                8 - 2,
    ),
)

extras_header = "extras_header" / Struct(
    "offset" / Tell,
    "count" / Int32ub,
    "sections" / Array(this.count, Select(productinfo_entry, extra_entry)),
    "offset_end" / Tell,
)

index_entry = "index_entry" / Struct(
Ejemplo n.º 28
0
    "red_background" / c.Flag,
    "delay" / c.BitsInteger(4),
), _transform_vendor_trust, 2, _transform_vendor_trust, 2)


VendorHeader = c.Struct(
    "_start_offset" / c.Tell,
    "magic" / c.Const(b"TRZV"),
    "_header_len" / c.Padding(4),
    "expiry" / c.Int32ul,
    "version" / c.Struct(
        "major" / c.Int8ul,
        "minor" / c.Int8ul,
    ),
    "vendor_sigs_required" / c.Int8ul,
    "vendor_sigs_n" / c.Rebuild(c.Int8ul, c.len_(c.this.pubkeys)),
    "vendor_trust" / VendorTrust,
    "reserved" / c.Padding(14),
    "pubkeys" / c.Bytes(32)[c.this.vendor_sigs_n],
    "vendor_string" / c.Aligned(4, c.PascalString(c.Int8ul, "utf-8")),
    "vendor_image" / Toif,
    "_data_end_offset" / c.Tell,

    c.Padding(-(c.this._data_end_offset + 65) % 512),
    "sigmask" / c.Byte,
    "signature" / c.Bytes(64),

    "_end_offset" / c.Tell,
    "header_len" / c.Pointer(
        c.this._start_offset + 4,
        c.Rebuild(c.Int32ul, c.this._end_offset - c.this._start_offset)
Ejemplo n.º 29
0
        c.FocusedSeq(
            "keyvalue",
            "terminator" / c.Peek(c.Byte),
            c.StopIf(c.this.terminator == 0),
            "keyvalue" / KeyValue,
        )
    ),
    c.Const(b'\0'),
)

PSBT = c.Struct(
    "magic" / c.Const(b'psbt'),
    "sep" / c.Const(b'\xff'),
    "general" / Sequence,
    "transaction" / c.RestreamData(c.this.general[0].value, Transaction),
    "inputs" / c.Array(c.len_(c.this.transaction.inputs), Sequence),
    "outputs" / c.Array(c.len_(c.this.transaction.outputs), Sequence),
    c.Terminated,
)

# key-less format:

ValueOnly = c.Prefixed(CompactUint, c.Struct(
    "type" / c.Byte,
    "value" / c.GreedyBytes,
))

ValueSequence = c.FocusedSeq("content",
    "content" / c.GreedyRange(
        c.FocusedSeq("valueonly",
            "terminator" / c.Peek(c.Byte),
Ejemplo n.º 30
0
    construct.Const(bytes([0x5C, 0x54])),
    "command" / construct.Int16ub,
    "command_data" / construct.Prefixed(
        construct.Int16ub, construct.GreedyRange(TRANSPORT_DATA_PARAMETER)),
)

TRANSPORT_COMMAND_CONTINUE_FRAGMENTED_READ = bytes([0xC5])
TRANSPORT_COMMAND_ABORT_FRAGMENTED_READ = bytes([0xC4])

TRANSPORT_ERROR_RESPONSE_PACKET = construct.Struct("error_code" /
                                                   construct.Int16ub)

TRANSPORT_EXPORT_DATA_RESPONSE_PACKET = construct.Struct(
    construct.Const(bytes([0x90, 0x00])),
    "response_data_length" / construct.Rebuild(
        construct.Int64ub, construct.len_(construct.this.response_data)),
    "response_data" / construct.GreedyBytes,
)

TRANSPORT_RESPONSE_PACKET = construct.Struct(
    "response_data_length" / construct.Rebuild(
        construct.Int16ub, construct.len_(construct.this.response_data)),
    "response_data" / construct.GreedyBytes,
)

TRANSPORT_RESULT = construct.GreedyRange(TRANSPORT_DATA_PARAMETER)


class Transport:
    def __init__(self, tse_path):
        self._transport = msc_transport.MscTransport(tse_path)
Ejemplo n.º 31
0
        "require_user_click" / c.Flag,
        "red_background" / c.Flag,
        "delay" / c.BitsInteger(4),
    ), _transform_vendor_trust, 2, _transform_vendor_trust, 2)

VendorHeader = c.Struct(
    "_start_offset" / c.Tell,
    "magic" / c.Const(b"TRZV"),
    "_header_len" / c.Padding(4),
    "expiry" / c.Int32ul,
    "version" / c.Struct(
        "major" / c.Int8ul,
        "minor" / c.Int8ul,
    ),
    "vendor_sigs_required" / c.Int8ul,
    "vendor_sigs_n" / c.Rebuild(c.Int8ul, c.len_(c.this.pubkeys)),
    "vendor_trust" / VendorTrust,
    "reserved" / c.Padding(14),
    "pubkeys" / c.Bytes(32)[c.this.vendor_sigs_n],
    "vendor_string" / c.Aligned(4, c.PascalString(c.Int8ul, "utf-8")),
    "vendor_image" / Toif,
    "_data_end_offset" / c.Tell,
    c.Padding(-(c.this._data_end_offset + 65) % 512),
    "sigmask" / c.Byte,
    "signature" / c.Bytes(64),
    "_end_offset" / c.Tell,
    "header_len" /
    c.Pointer(c.this._start_offset + 4,
              c.Rebuild(c.Int32ul, c.this._end_offset - c.this._start_offset)),
)
Ejemplo n.º 32
0
@enum.unique
class SshAgentSignatureFlags(enum.Enum):
    """AGENTC_SIGN_REQUEST flags.

    These are flags that can, in theory, be combined, but in practice they all
    conflict with each other, hence they are listed as an Enum here.
    """
    AGENT_NO_FLAGS = 0
    V1_AGENT_OLD_SIGNATURE = 1
    AGENT_RSA_SHA2_256 = 2
    AGENT_RSA_SHA2_512 = 4


SshAgentIdentities = FocusedSeq(
    'keys',
    'nkeys' / Rebuild(Int32ub, len_(this.keys)),
    'keys' / Struct(
        'key_blob' / SshBytes,
        'comment' / SshString,
    )[this.nkeys],
    Terminated,
)

SshAddRSAKey = Struct(
    'n' / SshMPInt,
    'e' / SshMPInt,
    'd' / SshMPInt,
    'iqmp' / SshMPInt,
    'p' / SshMPInt,
    'q' / SshMPInt,
    'comment' / SshString,