Exemplo n.º 1
0
def parse(buffer, byteorder = "<"):
    """
    Parameters
    ----------
    buffer: bytes-like

    byteorder: char
        "<": Little-endian
        ">": Big-endian

    Returns
    -------
    dict
        key: Vendor name
        values: list of attributes
    """
    Integer = Int32ul if byteorder == "<" else Int32ub
    Section = Struct(
        "len" / Integer,
        "vendor" / CString(encoding = "ascii"),
        "_pos" / Tell,
        "data" / Bytes(this.len - this._pos),
    )
    SubSectionHeader = Struct(
        "tag" / Byte,
        "len" / Integer,
        "_pos" / Tell,
        "data" / Bytes(this.len - this._pos),
    )

    RawAttribute = Struct(
        "tag" / ULEB,
        "parameterType" / Computed(lambda ctx: ATTRIBUTES[ctx.tag].parameterType),
        "name" / Computed(lambda ctx: ATTRIBUTES[ctx.tag].tag),
        "_conv" / Computed(lambda ctx: ATTRIBUTES[ctx.tag].conv),
        "value" / Switch(this.parameterType, { Reader.INT32: Integer, Reader.ULEB: ULEB, Reader.CSTRING: CString(encoding = "ascii") }),
        "pos" / Tell,
    )
    format_version = buffer[0]
    i = 1
    length = len(buffer)
    result = {}
    while True:
        section = Section.parse(buffer[i : ])
        if not section.vendor in result:
            result[section.vendor] = []
        i += section.len
        res = SubSectionHeader.parse(section.data)
        j = 0
        while j < len(res.data):
            attr = RawAttribute.parse(res.data[j : ])
            r = Attribute(attr.tag, attr.name, attr.value)
            if attr._conv != Ident:
                r.description = attr._conv[attr.value]
            result[section.vendor].append(r)
            j += attr.pos
        if i >= length:
            break
    return result
Exemplo n.º 2
0
class DataRow(BackendMessage):
    key = 'D'
    struct = Struct(
        "_type" / Computed("data_row"), "columncount" / Int16ub,
        "columns" / Array(
            this.columncount,
            Struct("_type" / Computed("C"), "length" / Int16sb,
                   "value" / Bytes(this.length))))
Exemplo n.º 3
0
    def _parse_symbol_section(self, section):
        sh_link = section.sh_link
        if self.b64:
            pass
        else:
            pass
        Symbol = Struct(
            "st_name" / self.Word,
            "st_value" / self.Addr,
            "st_size" / self.Word,
            "st_info" / BitStruct(
                "st_bind" / BitsInteger(4),
                "st_type" / BitsInteger(4),
            ),
            "st_other" / Int8ul,
            "symbol_name" / Computed(lambda ctx: self.get_string(sh_link, ctx.st_name)),
            "st_shndx" / self.Half,
            "section_name" / Computed(lambda ctx: defs.section_name(ctx.st_shndx)),
             "hidden" / Computed(lambda ctx: ctx.st_other in
                 (defs.SymbolVisibility.STV_HIDDEN, defs.SymbolVisibility.STV_INTERNAL)),
        )
        """
        typedef struct {
            Elf32_Word  st_name;
            Elf32_Addr  st_value;
            Elf32_Word  st_size;
            unsigned char   st_info;
            unsigned char   st_other;
            Elf32_Half  st_shndx;
        } Elf32_Sym;

        typedef struct {
            Elf64_Word  st_name;
            unsigned char   st_info;
            unsigned char   st_other;
            Elf64_Half  st_shndx;
            Elf64_Addr  st_value;
            Elf64_Xword st_size;
        } Elf64_Sym;
        """
        num_symbols = len(section.image) // Symbol.sizeof()
        for offset in range(0, len(section.image), Symbol.sizeof()):
            sym = Symbol.parse(section.image[offset : offset + Symbol.sizeof()])
            db_sym = Elf_Symbol(st_name = sym.st_name, st_value = sym.st_value, st_size = sym.st_size,
                st_bind = sym.st_info.st_bind, st_type = sym.st_info.st_type, st_other = sym.st_other,
                st_shndx = sym.st_shndx, symbol_name = sym.symbol_name, section_name = sym.section_name,
                hidden = sym.hidden)
            self.session.add(db_sym)
        #print(db_sym)
        self.session.commit()
        query = self.session.query(Elf_Symbol)
        aaa = query.filter(Elf_Symbol.section_name == "SHN_ABS").all()
        print("SECTIONS",  [a.symbol_name for a in aaa])
Exemplo n.º 4
0
    def __init__(cls, name, bases, namespace):
        '''
        __init__ is called every time a subclass of MessageMeta is declared
        '''
        if not hasattr(cls, "_msgtypes"):
            raise Exception(
                "classes which use MessageMeta must have a '_msgtypes' field")

        if not hasattr(cls, "_classes"):
            raise Exception(
                "classes which use MessageMeta must have a '_classes' field")

        if not hasattr(cls, "struct"):
            # This is one of the direct subclasses
            return

        if cls.__name__ in cls._classes:
            raise Exception("You've already made a class called {}".format(
                cls.__name__))
        cls._classes[cls.__name__] = cls

        # add a _type field to the struct so we can identify it while printing structs
        cls.struct = cls.struct + ("_type" / Computed(name))

        if not hasattr(cls, "key"):
            return

        # register the type, so we can tell the parser about it
        key = cls.key
        if key in cls._msgtypes:
            raise Exception('key {} is already assigned to {}'.format(
                key, cls._msgtypes[key].__name__))
        cls._msgtypes[key] = cls
Exemplo n.º 5
0
 def __constructor(self, device_property):
     '''Get the correct constructor using the latest GetDevicePropDesc.'''
     builder = Struct(
         'DataTypeCode' / Computed(
             lambda ctx: self.__prop_desc[device_property].DataTypeCode),
         'Value' / self._DataType)
     return builder
Exemplo n.º 6
0
class TestThisExpressions(unittest.TestCase):

    this_example = Struct(
        "this_example",
        # straight-forward usage: instead of passing (lambda ctx: ctx["length"]) use this.length
        UBInt8("length"),
        Field("value", this.length),

        # an example of nesting: '_' refers to the parent's scope
        Struct("nested", UBInt8("b1"), UBInt8("b2"),
               Computed("b3", this.b1 * this.b2 + this._.length)),

        # and conditions work as expected
        IfThenElse(
            "condition",
            this.nested.b1 > 50,
            UBInt32("foo"),
            UBInt8("bar"),
        ))

    def test_parse(self):
        res = self.this_example.parse(b"\x05helloABXXXX")
        expected = Container(length=5)(value=b'hello')(nested=Container(b1=65)(
            b2=66)(b3=4295))(condition=1482184792)
        self.assertEquals(res, expected)

    def test_build(self):
        obj = dict(length=5,
                   value=b'hello',
                   nested=dict(b1=65, b2=66, b3=None),
                   condition=1482184792)
        data = self.this_example.build(obj)
        self.assertEquals(data, b"\x05helloABXXXX")
Exemplo n.º 7
0
def DelimitedField(stop):

    return _StripDelimiter(
        Sequence(
            RepeatUntil(
                lambda x, lst, ctx: lst[-len(stop):] == [int(c) for c in stop],
                Byte), Computed(this[0][:-len(stop)]),
            Seek(-len(stop), whence=1)))
Exemplo n.º 8
0
    def do_abbrevs(self):
        section = self.sections['.debug_abbrev']
        image = section.image
        length = len(section.image)
        Abbrevation = Struct(
            "start" / Tell,
            "code" / ULEB,
            "details" / If(lambda ctx: ctx.code != 0,
                           Struct(
                               "tag" / ULEB,
                               "children" / self.u8,
                           )),
            "stop" / Tell,
        )
        Attribute = Struct(
            "start" / Tell,
            "attrValue" / ULEB,
            "formValue" / ULEB,
            "stop" / Tell,
            "next" / Computed((this.attrValue != 0) and (this.formValue != 0)),
        )
        offset = 0
        result = OrderedDict()
        kOffs = offset
        while True:
            print("Offset: {}".format(offset))
            abbrev = Abbrevation.parse(image[offset:])
            if abbrev.code != 0:
                print("{} {} {}".format(abbrev.code,
                                        constants.Tag(abbrev.details.tag),
                                        abbrev.details.children == 1))
            key = (
                kOffs,
                abbrev.code,
            )
            offset += abbrev.stop - abbrev.start
            if offset >= length:
                break
            if abbrev.code == 0:
                kOffs = offset
                result[key] = Abbreviation(0, False, [])
                continue
            result[key] = Abbreviation(constants.Tag(abbrev.details.tag),
                                       (abbrev.details.children == 1), [])
            while True:
                attr = Attribute.parse(image[offset:])

                if attr.attrValue != 0 and attr.formValue != 0:
                    result[key].attrs.append(
                        (constants.AttributeEncoding(attr.attrValue),
                         constants.AttributeForm(attr.formValue)))
                    print("   {} {}".format(
                        constants.AttributeEncoding(attr.attrValue),
                        constants.AttributeForm(attr.formValue)))
                offset += (attr.stop - attr.start)
                if not attr.next:
                    break
        self.abbreviations = result
Exemplo n.º 9
0
 def _SonyPropDesc(self):
     return Struct(
         'PropertyCode' / self._PropertyCode,
         'DataTypeCode' / self._DataTypeCode, 'SonyGetSet' / self._UInt8,
         'GetSet' /
         Computed(lambda x: 'GetSet' if x.SonyGetSet & 0x01 else 'Get'),
         'Visibility' / self._Visibility,
         'FactoryDefaultValue' / self._DataType,
         'CurrentValue' / self._DataType, 'FormFlag' / self._FormFlag,
         'Form' / self._Form(self._DataType))
Exemplo n.º 10
0
def StatusFlags(count, start_index_from=1):
    return DictArray(
        count,
        start_index_from,
        Struct(
            "_index" / Computed(this._index + start_index_from),
            "flag" / Default(Flag, False),
        ),
        pick_key="flag",
    )
Exemplo n.º 11
0
def test_inline():
    s = InliningStruct(
        'raw' @ AttributeRawCopy(InlineStruct('a' / Byte)),
        # make sure `this.raw` is accessible from inside the `InliningStruct` while it's still parsing/building
        'b' / Computed(this.raw))

    value = s.parse(b'\x01')
    assert value == {'a': 1, 'b': b'\x01'}
    assert value.raw == b'\x01'

    assert s.build({'a': 1}) == b'\x01'
Exemplo n.º 12
0
def ZoneFlags(count, start_index_from=1):
    return DictArray(count, start_index_from, BitStruct(
        "_index" / Computed(this._index + start_index_from),
        "generated_alarm" / Default(Flag, False),
        "presently_in_alarm" / Default(Flag, False),
        "activated_entry_delay" / Default(Flag, False),
        "activated_intellizone_delay" / Default(Flag, False),
        "bypassed" / Default(Flag, False),
        "shutted_down" / Default(Flag, False),
        "tx_delay" / Default(Flag, False),
        "supervision_trouble" / Default(Flag, False),
    ))
Exemplo n.º 13
0
    def __init__(self, filepath):
        self.filepath = Path(filepath)
        if not self.filepath.exists():
            raise FileNotFoundError(self.filepath)

        self.oct_header = Struct(
            "magicNumber" / Hex(Int32un), "version" / Hex(Int16un),
            "frameheader" / headerField, "framecount" / intField,
            "linecount" / intField, "linelength" / intField,
            "sampleformat" / intField, "description" / strField,
            "xmin" / floatField, "xmax" / floatField, "xcaption" / strField,
            "ymin" / floatField, "ymax" / floatField, "ycaption" / strField,
            "scantype" / intField, "scandepth" / floatField,
            "scanlength" / floatField, "azscanlength" / floatField,
            "elscanlength" / floatField, "objectdistance" / floatField,
            "scanangle" / floatField, "scans" / intField, "frames" / intField,
            "dopplerflag" / intField, "config" / lazyIntField,
            BytesInteger(4, signed=False, swapped=True))
        self.frame_header = Struct(
            "framedata" / headerField, "framedatetime" / dateField,
            "frametimestamp" / floatField, "framelines" / intField,
            "keylength" / Int32un,
            "key" / PaddedString(this.keylength, "utf8"),
            "dataLength" / Int32un)

        self.frame_image = Struct(
            'rows' / Computed(this._._.header.linelength.value),
            'columns' / Computed(this._.header.framelines.value),
            'totalpixels' / Computed(this.rows * this.columns),
            'offset' / Tell,
            'end' / Computed(this.offset + this.totalpixels * 2),
            'pixels' / Lazy(Array(this.totalpixels, Int16un)), Seek(this.end))

        self.frame = Struct("header" / self.frame_header,
                            "image" / self.frame_image,
                            BytesInteger(4, signed=False, swapped=True))

        self.frame_stack = Array(this.header.framecount.value, self.frame)
        self.file_structure = Struct("header" / self.oct_header,
                                     "data" / self.frame_stack)
Exemplo n.º 14
0
class RowDescription(BackendMessage):
    key = 'T'
    struct = Struct(
        "fieldcount" / Int16ub, "fields" / Array(
            this.fieldcount,
            Struct(
                "_type" / Computed("F"),
                "name" / CString("ascii"),
                "tableoid" / Int32ub,
                "colattrnum" / Int16ub,
                "typoid" / Int32ub,
                "typlen" / Int16sb,
                "typmod" / Int32sb,
                "format_code" / Int16ub,
            )))
Exemplo n.º 15
0
def ModuleTroubles(count, start_index_from=1):
    return DictArray(
        count=count,
        first_index=start_index_from,
        subcon=BitStruct(
            "_index" / Computed(this._index + start_index_from),
            "aux_trouble" / Flag,
            "battery_fail" / Flag,
            "ac_trouble" / Flag,
            "printer_trouble" / Flag,
            "fail_to_comm" / Flag,
            "tlm_trouble" / Flag,
            "rom_error" / Flag,
            "tamper" / Flag,
        ),
    )
Exemplo n.º 16
0
def test_unexpected_placeholder():
    def _change_placeholder(context):
        stream = context._io
        placeholder = context.a.placeholder_data[0]
        stream.seek(-1, os.SEEK_CUR)
        stream.write(bytes([(placeholder + 1) & 0xff]))

    s = Struct(
        'a' / DeferredValue(Byte),
        Computed(
            _change_placeholder
        ),  # overwrites placeholder with different value, should fail sanity check later
        WriteDeferredValue(0x42, this.a))

    with pytest.raises(DeferredError):
        s.build({})
Exemplo n.º 17
0
def _gen_fmh3_struct(int_type, pointer_type, codepoint_type, addr_mode='rel'):
    return Struct(
        "pointer_offset" / (Computed(0) if addr_mode == 'abs' else Tell),
        "signature" / Const(b'FMH3'),
        Padding(4),
        "fonts_count" / Padded(pointer_type.sizeof(), int_type),
        "fonts_pointers_offset" / pointer_type,
        "fonts" / Pointer(
            lambda this: this.fonts_pointers_offset + this.pointer_offset,
            RepeatUntil(
                lambda obj, lst, ctx: ctx._index >= ctx.fonts_count - 1,
                Struct(
                    "pointer" / pointer_type,
                    "data" / Pointer(
                        lambda this: this.pointer + this._.pointer_offset,
                        Struct(
                            "id" / int_type,
                            "advance_width" / Byte,
                            "line_height" / Byte,
                            "box_width" / Byte,
                            "box_height" / Byte,
                            "layout_param_1" / Byte,
                            "layout_param_2_numerator" / Byte,
                            "layout_param_2_denominator" / Byte,
                            Padding(1),
                            "other_params?" / int_type,
                            "tex_size_chars" / int_type,
                            "chars_count" / int_type,
                            "chars_pointer" / pointer_type,
                            "chars" / Pointer(
                                lambda this: this.chars_pointer + this._._.
                                pointer_offset,
                                RepeatUntil(
                                    lambda obj, lst, ctx: ctx._index >= ctx.
                                    chars_count - 1,
                                    Struct(
                                        "codepoint" / codepoint_type,
                                        "halfwidth" / Flag,
                                        Padding(1),
                                        "tex_col" / Byte,
                                        "tex_row" / Byte,
                                        "glyph_x" / Byte,
                                        "glyph_width" / Byte,
                                    ))),
                        )),
                ))),
    )
def EmbeddedBitStruct(name, *args, reversed=False):
    """
    Emulates BitStruct embedding:
        - for parsing, adds Computed accessor fields to the parent construct,
        - for building, Rebuild the bit struct using keys passed to the parent

    NOTE: This is a hack. Do not use unless you absolutely have to.
    """
    bit_struct = BitStruct(*args)

    if reversed:
        bit_struct = Reversed(bit_struct)

    bit_struct.__construct_doc__ = Embedded(Struct(*args))

    return (name / Rebuild(bit_struct, dict), ) + \
        tuple(i.name / Computed(this[name][i.name]) for i in args if i.name is not None)
Exemplo n.º 19
0
    def process_attributes(self, image, readers, size, abbrevOffset):
        Attribute = Struct(
            "start" / Tell,
            "attr" / ULEB,
            "stop" / Tell,
            "size" / Computed(this.stop - this.start),
        )
        level = 0
        offset = 0
        lastAttr = False
        while True:
            start = image.tell()
            attr = Attribute.parse_stream(image)
            offset += attr.size
            abbr = self.abbreviations.get((abbrevOffset, attr.attr))
            if attr.attr == 0 or not abbr.tag:
                print("<{}><{:02x}>: {}".format(level, start,
                                                "Abbrev Number: 0"))
                level -= 1
                if lastAttr:
                    break
            else:
                print("<{}><{:02x}>: Abbrev Number: {} ({})".format(
                    level, start, attr.attr, abbr.tag.name))
                for enc, form in abbr.attrs:
                    reader = readers.get(form)
                    start = image.tell()
                    if form != constants.DW_FORM_flag_present:
                        value = reader.parse_stream(image)
                    else:
                        value = 1
                    startValue = "<{:x}>".format(start)
                    print("   {:7} {:20}: {}".format(startValue, enc.name,
                                                     value))
                    stop = image.tell()
                    offset += (stop - start)
                    if offset >= size - 1:
                        lastAttr = True
                        # 872b


#                offset += (attr.stop - attr.start)
                pos = image.tell()
            if hasattr(abbr, "children") and abbr.children:
                level += 1
Exemplo n.º 20
0
 def _parse_symbol_section(self, section):
     sh_link = section.sh_link
     symbols = []
     Symbol = Struct(
         "st_name" / self.Word,
         "st_value" / self.Addr,
         "st_size" / self.Word,
         "st_info" / BitStruct(
             "st_bind" / BitsInteger(4),
             "st_type" / BitsInteger(4),
         ),
         "st_other" / Int8ul,
         "symbol_name" /
         Computed(lambda ctx: self.get_string(sh_link, ctx.st_name)),
         "st_shndx" / self.Half,
     )
     symbol_cache = {}
     num_symbols = len(section.image) // Symbol.sizeof()
     for offset in range(0, len(section.image), Symbol.sizeof()):
         sym = Symbol.parse(section.image[offset:offset + Symbol.sizeof()])
         section_header = None
         if sym.st_shndx in defs.SpecialSections:
             section_name = defs.special_section_name(sym.st_shndx)
         else:
             if not sym.st_shndx in symbol_cache:
                 section_header = self.session.query(model.Elf_Section).\
                     filter(model.Elf_Section.index == sym.st_shndx).first()
                 if section_header:
                     section_name = section_header.section_name
                 else:
                     section_name = str(sym.st_shndx)
         db_sym = model.Elf_Symbol(
             st_name=sym.st_name,
             st_value=sym.st_value,
             st_size=sym.st_size,
             st_bind=sym.st_info.st_bind,
             st_type=sym.st_info.st_type,
             st_other=sym.st_other,
             st_shndx=sym.st_shndx,
             symbol_name=sym.symbol_name,
             section_name=section_name,
             access=section_header.sh_flags if section_header else 0)
         symbols.append(db_sym)
     self.session.bulk_save_objects(symbols)
     self.session.commit()
Exemplo n.º 21
0
def test_basetypeconstruct():
    # create types/structs
    class BaseTypeTestConstruct(BaseTypeLoadableConstruct):
        def _read(self, reader, config):
            self.test_construct = self._parse_construct(reader.read(), config)

    struct = Struct(
        'a' / Byte,
        'b' / Byte,
        'param' / Computed(lambda ctx: ctx._params.testparam)
    )

    config = TypeLoadConfig(construct_kwargs={'testparam': 42})

    # load
    testtype = BaseTypeTestConstruct(struct)
    testtype.load_bytes(b'\x01\x02', config)

    assert testtype.test_construct == {'a': 1, 'b': 2, 'param': 42}
Exemplo n.º 22
0
    def test_desc_get_property_identical(self, camera, device_property):
        '''
        Check property description and property get share the same value.

        GetDevicePropValue == GetDevicePropDesc.CurrentValue
        '''
        with camera.session():
            value = camera.get_device_prop_value(device_property)
            desc = camera.get_device_prop_desc(device_property)
            # TODO: refactor this into PTPy core to automatically parse and
            # build properties for which a GetDevicePropDesc has been issued.
            builder = 'Builder' / Struct(
                'DataTypeCode' / Computed(lambda ctx: desc.DataTypeCode),
                'CurrentValue' / camera._DataType
                )
            data = builder.build(desc)
            assert value.Data == data,\
                'GetDevicePropDesc.CurrentValue and '\
                'GetDevicePropValue should match.'
Exemplo n.º 23
0
 def process_compile_unit(self, image):
     CompileUnit = Struct(
         "start" / Tell,
         "unit_length" / self.u32,
         "version" / self.u16,
         "debug_abbrev_offset" / self.u32,
         "address_size" / self.u8,
         "stop" / Tell,
         "size" / Computed(this.stop - this.start),
     )
     startPos = image.tell()
     cu = CompileUnit.parse_stream(image)
     print("   Compilation Unit @ offset 0x{:x}:".format(cu.start))
     print("   Length:        0x{:x} (32-bit)".format(cu.unit_length))
     print("   Version:       2".format(cu.version))
     print("   Abbrev Offset: 0x{:x}".format(cu.debug_abbrev_offset))
     print("   Pointer Size:  {}".format(cu.address_size))
     stopPos = image.tell()
     return cu
Exemplo n.º 24
0
def test_enumconvert():
    class TestEnum(Enum):
        A = 0x42

        @property
        def prop(self):
            return 1337

    s = Struct('e' / EnumConvert(Byte, TestEnum),
               'v' / Computed(lambda this: this.e.prop))

    # valid
    assert s.parse(b'\x42') == {'e': TestEnum.A, 'v': 1337}
    assert s.build({'e': TestEnum.A}) == b'\x42'

    # invalid
    with pytest.raises(MappingError):
        s.parse(b'\x00')
    with pytest.raises(MappingError):
        s.build({'e': 0})
Exemplo n.º 25
0
def PGMFlags(count, start_index_from=1):
    return DictArray(
        count,
        start_index_from,
        Bitwise(
            Struct(
                "_index" / Computed(this._index + start_index_from),
                "fire_2_wires" / Default(Flag, False),
                "normally_closed" / Default(Flag, False),
                "_unknown1" / BitsInteger(1),
                "disabled" / ExprSymmetricAdapter(
                    Default(Flag, False), lambda obj, ctx: not obj
                ),  #  False when a relay is assigned
                "_unknown2" / BitsInteger(2),
                "timer_active" / Default(Flag, False),  # when timer is active
                "on" / Default(Flag, False),  # when is activated
                "time_left" /
                Bytewise(ByteSwapped(Default(Int24ub, 0))),  # byte in seconds
            ), ),
    )
Exemplo n.º 26
0
 def _parse_section_headers(self):
     SectionHeaders = Struct(
         "sections" / Array(lambda ctx: self.e_shnum,
             "section" / Struct(
                 "sh_name" / self.Word,
                 "sh_type" / self.Word,
                 "sh_flags" / self.Xword,
                 "sh_addr" / self.Addr,
                 "sh_offset" / self.Off,
                 "sh_size" / self.Xword,
                 "sh_link" / self.Word,
                 "sh_info" / self.Word,
                 "sh_addralign" / self.Xword,
                 "sh_entsize" /self.Xword,
                 "allocate" / Computed(lambda ctx: (ctx.sh_type not in (0, 8) and ctx.sh_size > 0)),
             )
         )
     )
     if hasattr(self, 'e_shnum'):
         if self.e_shnum:
             print("SH_size: {}".format(SectionHeaders.sizeof() / self.e_shnum))
         self._section_headers = SectionHeaders.parse(self.fp[self.e_shoff : ])
         for idx, section in enumerate(self._section_headers.sections):
             if section.allocate:
                 image = self.fp[section.sh_offset : section.sh_offset + section.sh_size]
             else:
                 image = None
             self._images[idx] = image
             section.image = image
         for section in self._section_headers.sections:
             name = self.get_string(self.e_shstrndx, section.sh_name)
             section.name = name
             self._sections_by_name[name] = section
             if section.sh_type == defs.SectionType.SHT_NOTE:
                 print("NOTE!!! {:08X} {:04X}".format(section.sh_offset, section.sh_size))
                 self._parse_note(self.fp[section.sh_offset : section.sh_offset + section.sh_size])
             elif section.sh_type in (defs.SectionType.SHT_SYMTAB, defs.SectionType.SHT_DYNSYM):
                 self._parse_symbol_section(section)
Exemplo n.º 27
0
from etl.parsers.etw.core import Etw, build_etw, Guid as EtwGuid
from etl.utils import Guid

WinTraceHeader = Struct(
    "size" / Int16ul,
    "marker" / Const(0x9000, Int16ul),
    "event_id" / Int16ul,
    "flags" / Int16ul,
    "provider_id" / Guid,
    "thread_id" / Int32ul,
    "process_id" / Int32ul
)

WinTraceRecord = AlignedStruct(8,
    "mark1" / Computed(lambda this: this._io.tell()),
    "event_header" / WinTraceHeader,
    "mark2" / Computed(lambda this: this._io.tell()),
    "user_data" / Bytes(lambda this: this.event_header.size - (this.mark2 - this.mark1))
                               )


class WinTrace:
    """
    This is a python wrapper around construct struct to access interesting fields
    """

    def __init__(self, source: Container):
        """
        :param source Container: The EventTraceRecord Container once it's parsed
        """
Exemplo n.º 28
0
             "module_rom_error_trouble" / Flag,
             "module_tlm_trouble" / Flag,
             "module_fail_to_com_trouble" / Flag,
             "module_printer_trouble" / Flag,
             "module_ac_trouble" / Flag,
             "module_battery_fail" / Flag,
             "module_aux_trouble" / Flag,
             "missing_keypad_trouble" / Flag,
             "missing_module_trouble" / Flag,
             "_future_use_4" / Flag,
             "_future_use_5" / Flag,
             "safety_mismatch_trouble" / Flag,
             "bus_global_fail" / Flag,
             "bus_overload_trouble" / Flag,
             "mdl_com_error" / Flag),
         "date" / Struct("weekday" / Computed(lambda ctx: ctx._._._weekday),
                         "time" / DateAdapter(Bytes(7))),
         "power" / Struct(
             "vdc" / ExprAdapter(
                 Byte,
                 lambda obj, ctx: round(obj *
                                        (20.3 - 1.4) / 255.0 + 1.4, 1), 0),
             "battery" / ExprAdapter(
                 Byte, lambda obj, ctx: round(obj * 22.8 / 255.0, 1), 0),
             "dc" / ExprAdapter(
                 Byte, lambda obj, ctx: round(obj * 22.8 / 255.0, 1), 0),
         )),
     "zone_open" / BitsSwapped(Bitwise(StatusFlags(96))),
     "zone_tamper" / BitsSwapped(Bitwise(StatusFlags(96))),
     "zone_low_battery" / BitsSwapped(Bitwise(StatusFlags(96))),
 ),
Exemplo n.º 29
0
    'type',
    RepeatUntil(lambda item, a, b: item.type == 'end', InnerHeaderItem),
    # FIXME - this is a hack because inner header is not truly a dict,
    #  it has multiple binary elements.
    lump=['binary'])

UnpackedPayload = Reparsed(
    Struct(
        "inner_header" / InnerHeader, "xml" / Unprotect(
            this.inner_header.protected_stream_id.data,
            this.inner_header.protected_stream_key.data, XML(GreedyBytes))))

# -------------------- Main KDBX Structure --------------------

Body = Struct(
    "transformed_key" / Computed(compute_transformed),
    "master_key" / Computed(compute_master),
    "sha256" / Checksum(
        Bytes(32),
        lambda data: hashlib.sha256(data).digest(),
        this._.header.data,
        # exception=HeaderChecksumError,
    ),
    "hmac" / Checksum(
        Bytes(32),
        compute_header_hmac_hash,
        this,
        # exception=CredentialsError,
    ),
    "payload" / UnpackedPayload(
        IfThenElse(
Exemplo n.º 30
0
from construct import Struct, Const, Padding, PaddedString, Int8ul, Int16ul, \
        Int24ul, Int32ul, Flag, Computed, this, Array, BitStruct, Bitwise, \
        BitsInteger, Embedded, Nibble, Sequence, Enum

hgIdent = Struct(
    "signature" / Const(b"EUMEL-"),
    "version" / PaddedString(6, "ascii"),
    Padding(1),
    "isShutup" / Int8ul * "true if value is 0",  # XXX
    "bootCount" / Int16ul,
    Padding(0x24) * "undocumented",
    "_hgblocks2" / Int16ul,
    Padding(0x50) * "unknown/undocumented",
    "_hgblocks" / Int16ul,
    "_plusident" / Int16ul,
    "isPlus" / Computed(this._hgblocks == 1 and this._plusident == 0),
    "blocks" / Computed(this._hgblocks if this.isPlus else this._hgblocks2
                        ),  # XXX: this is not correct
) * "First block of Hintergrund"

blockref = Struct(
    "value" / Int24ul,
    "control" / Int8ul,
)

anchor = Struct(
    Const(b"\xff" * 4),
    "akttab" / blockref,
    "clorX" / blockref,
    Const(b"\xff" * 4 * 3),
    "taskRoot" / blockref,