Пример #1
0
def Fat16Header(name):
    return Struct(name, Bytes("jumpInstruction", 3),
                  Bytes("creatingSystemId", 8), ULInt16("sectorSize"),
                  Byte("sectorsPerCluster"), ULInt16("reservedSectorCount"),
                  Byte("fatCount"), ULInt16("rootdirEntryCount"),
                  ULInt16("sectorCount_small"), Byte("mediaId"),
                  ULInt16("sectorsPerFat"), ULInt16("sectorsPerTrack"),
                  ULInt16("sideCount"), ULInt32("hiddenSectorCount"),
                  ULInt32("sectorCount_large"), Byte("physicalDriveNumber"),
                  Byte("currentHead"), Byte("extendedBootSignature"),
                  Bytes("volumeId", 4), Bytes("volumeLabel", 11),
                  Const(Bytes("fsType", 8), "FAT16   "),
                  Bytes("bootCode", 448),
                  Const(Bytes("bootSectorSignature", 2), "\x55\xaa"))
Пример #2
0
    def __init__(self, tps, ref, parent_ref, check=False):
        self.tps = tps
        self.__ref = ref
        self.parent_ref = parent_ref
        self.check = check
        self.__page_child_ref = []

        self.tps.seek(ref * 0x100 + self.tps.header.size)
        page = PAGE_HEADER_STRUCT.parse(
            self.tps.read(PAGE_HEADER_STRUCT.sizeof()))

        if page.hierarchy_level != 0:
            page.data = Array(lambda ctx: page.record_count,
                              ULInt32('page_child_ref')).parse(
                                  self.tps.read(page.size -
                                                PAGE_HEADER_STRUCT.sizeof()))

        self.offset = page.offset
        self.size = page.size
        self.uncompressed_size = page.uncompressed_size
        self.uncompressed_unabridged_size = page.uncompressed_unabridged_size
        self.record_count = page.record_count
        self.hierarchy_level = page.hierarchy_level
        if self.hierarchy_level != 0:
            self.__page_child_ref = page.data

        if self.check:
            check_value('page_offset', self.offset,
                        ref * 0x100 + self.tps.header.size)
Пример #3
0
class TpsDecryptor:

    CHUNK_DATA_STRUCT = Array(16, ULInt32('data'))
    DATA_STRUCT = GreedyRange(CHUNK_DATA_STRUCT)

    def __init__(self, file, password, encoding='utf-8'):
        self.file = file
        self.encoding = encoding
        if password is None:
            self.password = password
        else:
            self.password = bytes(password, encoding=self.encoding) + b'\x00'
            self.keys = []

            byte_keys = [0] * 64

            for i in range(64):
                byte_keys[(i * 0x11) & 0x3F] = (i + self.password[(i + 1) % len(self.password)]) & 0xFF

            self.keys = self.CHUNK_DATA_STRUCT.parse(bytes(byte_keys))

            for i in range(2):
                for pos_a in range(16):
                    data_a = self.keys[pos_a]
                    pos_b = data_a & 0x0F
                    data_b = self.keys[pos_b]
                    self.keys[pos_b] = (data_a + (data_a & data_b)) & 0xFFFFFFFF
                    self.keys[pos_a] = ((data_a | data_b) + data_a) & 0xFFFFFFFF

    def decrypt(self, size, pos=None):
        if pos is None:
            pos = self.file.tell()
        align_start_pos = pos & 0xFFFFFFC0
        self.file.seek(align_start_pos)
        align_end_pos = ((size + pos - 1) | 0x3F) + 1
        result = self.DATA_STRUCT.parse(self.file.read(align_end_pos - align_start_pos))
        for chunk_number in range(len(result)):
            for i in range(16):
                pos_a = 15 - i
                key = self.keys[pos_a]
                pos_b = key & 0x0F

                data_a = result[chunk_number][pos_a]
                data_a = data_a - key

                data_b = result[chunk_number][pos_b]
                data_b = data_b - key

                result[chunk_number][pos_a] = ((data_a & key) | (data_b & ~key)) & 0xFFFFFFFF
                result[chunk_number][pos_b] = ((data_b & key) | (data_a & ~key)) & 0xFFFFFFFF

        self.file.seek(pos + size)
        return self.DATA_STRUCT.build(result)[pos - align_start_pos:pos - align_start_pos + size]

    def encrypt(self, size, pos=None):
        # TODO
        pass

    def is_encrypted(self):
        return self.password is not None
Пример #4
0
def DirEntry(name):
    return Struct(
        name,
        Bytes("name", 8),
        Bytes("extension", 3),
        BitStruct("attributes", Flag("unused"), Flag("device"),
                  Flag("archive"), Flag("subDirectory"), Flag("volumeLabel"),
                  Flag("system"), Flag("hidden"), Flag("readonly")),
        # reserved
        Padding(10),
        ULInt16("timeRecorded"),
        ULInt16("dateRecorded"),
        ULInt16("firstCluster"),
        ULInt32("fileSize"))
Пример #5
0

class XorObfuscation(Adapter):
    def _encode(self, obj, ctx):
        return _xor(obj)

    def _decode(self, obj, ctx):
        return _xor(obj)


# not sure what this is, contains build date
burnhdr2 = Struct(
    "burnhdr2",
    Magic(b"SUNP BURN HDR 2"),
    Padding(1),
    ULInt32("count"),
    Padding(12),
    MetaArray(lambda ctx: ctx.count, XorObfuscation(Bytes("mystery", 128))),
)

# burnhdr3 contains filenames that should be backed up
burnhdr3 = Struct(
    "burnhdr3",
    Magic(b"SUNP BURN HDR 3"),
    Padding(1),
    ULInt32("num_filenames"),
    Padding(12),
    MetaArray(
        lambda ctx: ctx.num_filenames, String("filename",
                                              0x70,
                                              padchar=b"\x00")
Пример #6
0
from construct import ULInt32, Embed
from construct import Struct, Container
# from construct.debug import Probe

from pox.ethanol.ssl_message.msg_core import msg_default
from pox.ethanol.ssl_message.msg_core import field_intf_name, field_station, field_ssid
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

msg_frequency = Struct(
    'msg_frequency',
    Embed(msg_default),  # default fields
    Embed(field_ssid),
    Embed(field_intf_name),
    Embed(field_station),
    ULInt32('frequency'),
    # Probe()
)


def get_frequency(server, id=0, intf_name=None, sta_ip=None, sta_port=0):
    """ the interface is configured to use the frequency returned by this function
        can ask the AP to relay this request to the station if (sta_ip, sta_port) is provided

      @param server: tuple (ip, port_num)
      @param id: message id
      @param intf_name: name of the wireless interface
      @type intf_name: str
      @param sta_ip: ip address of the station that this message should be relayed to, if sta_ip is different from None
      @type sta_ip: str
      @param sta_port: socket port number of the station
from pox.ethanol.ssl_message.msg_core import msg_default
from pox.ethanol.ssl_message.msg_core import field_station, field_mac_addr, field_ssid, field_intf_name
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

# ###############################################################
#
# MSG_TYPE.MSG_WLAN_INFO
#
# ###############################################################
wlan_entry = Struct(
    'wlan_entry',
    SLInt32('ifindex'),
    Embed(field_intf_name),
    ULInt32('wlan_indx'),
    ULInt32('phy_indx'),
    ULInt64('dev'),
    Embed(field_mac_addr),
    Embed(field_ssid),
    ULInt32('channel_type'),
    ULInt32('chan_width'),
    ULInt32('freq'),
    ULInt32('freq1'),
    ULInt32('freq2'),
    SLInt32('iftype'),
)
""" information about a wifi interface"""

msg_wlan_info = Struct(
    'msg_wlan_info',
Пример #8
0
""" Snapcast messages. """

from construct import (ULInt8, ULInt16, ULInt32, ULInt64,
                       Embed, Struct, Enum, Array,
                       PascalString, Switch, Container)

ENCODING = 'utf-8'
BASE_SIZE = 26

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

timestamp = Embed(Struct('time',
    ULInt32('secs'),
    ULInt32('usecs')
))


snaptype = Enum(ULInt16('type'),
    Base=0,
    Header=1,
    WireChunk=2,
    SampleFormat=3,
    ServerSettings=4,
    Time=5,
    Request=6,
    Ack=7,
    Command=8,
    Hello=9,
    Map=10,
    String=11
)
Пример #9
0
def read_ftr(filename, delete_keys=None):
    offset_size = 1859

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

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

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

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

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

    dat['record'] = df_ftr

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

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

    return (dat)
Пример #10
0
from keystore.keybag import Keybag
from structs import HFSPlusVolumeHeader, kHFSPlusFileRecord, getString
from construct import Struct, ULInt16, ULInt32, String
from Crypto.Cipher import AES
from construct.macros import ULInt64, Padding
from structs import kHFSRootParentID
import hashlib
"""
iOS >= 4 raw images
http://opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/hfs/hfs_cprotect.c
http://opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/sys/cprotect.h
"""

cp_root_xattr = Struct("cp_root_xattr", ULInt16("major_version"),
                       ULInt16("minor_version"), ULInt64("flags"),
                       ULInt32("reserved1"), ULInt32("reserved2"),
                       ULInt32("reserved3"), ULInt32("reserved4"))

cprotect_xattr = Struct("cprotect_xattr", ULInt16("xattr_major_version"),
                        ULInt16("xattr_minor_version"), ULInt32("flags"),
                        ULInt32("persistent_class"), ULInt32("key_size"),
                        String("persistent_key", length=0x28))

cprotect4_xattr = Struct(
    "cprotect_xattr", ULInt16("xattr_major_version"),
    ULInt16("xattr_minor_version"), ULInt32("flags"),
    ULInt32("persistent_class"), ULInt32("key_size"), Padding(20),
    String("persistent_key", length=lambda ctx: ctx["key_size"]))

#HAX: flags set in finderInfo[3] to tell if the image was already decrypted
FLAG_DECRYPTING = 0x454d4664  #EMFd big endian
Пример #11
0
    >>> build_output = SONG.build(sng)
    >>> build_output == raw_input
    True
"""

from construct import Struct, If, Array, PrefixedArray, Padding, \
    SLInt8, ULInt16, SLInt16, ULInt32, SLInt32, LFloat32, LFloat64, String


def array(struct):
    """Standard prefixed arrays."""
    return PrefixedArray(struct, ULInt32('count'))


BEAT = Struct('ebeats', LFloat32('time'), ULInt16('measure'), ULInt16('beat'),
              ULInt32('phraseIteration'), ULInt32('mask'))

PHRASE = Struct('phrases', SLInt8('solo'), SLInt8('disparity'),
                SLInt8('ignore'), Padding(1), ULInt32('maxDifficulty'),
                ULInt32('phraseIterationLinks'),
                String('name', 32, padchar='\x00'))

CHORD_TEMPLATE = Struct('chordTemplates', ULInt32('mask'), SLInt8('fret0'),
                        SLInt8('fret1'), SLInt8('fret2'), SLInt8('fret3'),
                        SLInt8('fret4'), SLInt8('fret5'), SLInt8('finger0'),
                        SLInt8('finger1'), SLInt8('finger2'),
                        SLInt8('finger3'), SLInt8('finger4'),
                        SLInt8('finger5'), Array(6, SLInt32('notes')),
                        String('chordName', 32, padchar='\x00'))

BEND_VALUE = Struct(
Пример #12
0
# Symbol Servers:
# Microsoft: http://msdl.microsoft.com/download/symbols/
# Mozilla Firefox: http://symbols.mozilla.org/
# Google Chrome: https://chromium-browser-symsrv.commondatastorage.googleapis.com

def GUID(name):
    return Struct(name,
        ULInt32("Data1"),
        ULInt16("Data2"),
        ULInt16("Data3"),
        String("Data4", 8))

CV_RSDS_HEADER = Struct("CV_RSDS",
    Const(Bytes("Signature", 4), "RSDS"),
    GUID("GUID"),
    ULInt32("Age"),
    CString("Filename"))

CV_NB10_HEADER = Struct("CV_NB10",
    Const(Bytes("Signature", 4), "NB10"),
    ULInt32("Offset"),
    ULInt32("Timestamp"),
    ULInt32("Age"),
    CString("Filename"))

logger = getLogger("symfetch")
RSDS_TYPE_STRING = "<I16BI"

def parse_arguments():
    usage = 'usage: %prog [options] pe_file'
    parser = OptionParser(usage=usage)
Пример #13
0
"""
TPS File Page
"""

from warnings import warn

from construct import Array, Byte, Struct, ULInt16, ULInt32

from .utils import check_value

# Page header
PAGE_HEADER_STRUCT = Struct(
    'page',
    ULInt32('offset'),
    # size - total size with header
    ULInt16('size'),
    ULInt16('uncompressed_size'),
    # ??? self.uncompressed_unabridged_size strange value
    ULInt16('uncompressed_unabridged_size'),
    ULInt16('record_count'),
    Byte('hierarchy_level'),
)


class TpsPage:
    def __init__(self, tps, ref, parent_ref, check=False):
        self.tps = tps
        self.__ref = ref
        self.parent_ref = parent_ref
        self.check = check
        self.__page_child_ref = []
Пример #14
0
    def _encode(self, obj, context):
        try:
            forms = self.pokemon_forms[ context['national_id'] ]
        except KeyError:
            return None

        return forms.index(obj) << 3



# And here we go.
# Docs: http://projectpokemon.org/wiki/Pokemon_NDS_Structure
pokemon_struct = Struct('pokemon_struct',
    # Header
    ULInt32('personality'),  # XXX aughgh http://bulbapedia.bulbagarden.net/wiki/Personality
    Padding(2),
    ULInt16('checksum'),  # XXX should be checked or calculated

    # Block A
    ULInt16('national_id'),
    ULInt16('held_item_id'),
    ULInt16('original_trainer_id'),
    ULInt16('original_trainer_secret_id'),
    ULInt32('exp'),
    ULInt8('happiness'),
    ULInt8('ability_id'),  # XXX needs to match personality + species
    BitStruct('markings',
        Padding(2),
        Flag('diamond'),
        Flag('star'),
Пример #15
0
from construct import ULInt32
from construct import Embed
from construct import Struct
from construct import Container
# from construct.debug import Probe

from pox.ethanol.ssl_message.msg_core import msg_default
from pox.ethanol.ssl_message.msg_core import field_intf_name
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

msg_ap_rtsthreshold = Struct(
    'msg_ap_rtsthreshold',
    Embed(msg_default),  # default fields
    Embed(field_intf_name),
    ULInt32('rts_threshold'),
    # Probe(),
)


def get_ap_rtsthreshold(server, id=0, intf_name=None):
    """ verify is the interface is broadcasting the SSID
      @param server: tuple (ip, port_num)
      @param id: message id
      @param intf_name: name of the wireless interface
      @type intf_name: str
      @return: msg, value
    """
    if intf_name is None:
        return None, None
Пример #16
0
    SLInt64('frequency'),
    SLInt32('channel'),
    LFloat32('signal'),  # float in C is coded as little endian 32 bit number
    SLInt32('powerconstraint'),
    SLInt32('tx_power'),
    SLInt32('link_margin'),
    SLInt32('age'),
    SLInt8('is_dBm'),  # this is a boolean coded as a 8 bit integer
)

msg_ap_in_range = Struct(
    'msg_ap_in_range',
    Embed(msg_default),  # default fields
    Embed(field_intf_name),
    Embed(field_station),
    ULInt32('num_aps'),
    Array(lambda ctx: ctx.num_aps, ap_in_range),
    # Probe(),
)


def get_ap_in_range(server, id=0, intf_name=None, sta_ip=None, sta_port=0):
    """ request the ap or the client to try to detect the aps in range, using 802.11 scanning capability

      @param server: tuple (ip, port_num)
      @param id: message id
      @param intf_name: name of the wireless interface
      @type intf_name: str
      @param sta_ip: ip address of the station that this message should be relayed to, if sta_ip is different from None
      @type sta_ip: str
      @param sta_port: socket port number of the station
Пример #17
0
def ssexy_linux(fname, *eips):
    import elf32
    from construct import Struct, ULInt32, ULInt16, ULInt8, Array, CString
    from construct import OptionalGreedyRange

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

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

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

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

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

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

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

    imports = {}

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

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

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

    instructions = pyasm2.block()

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

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

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

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

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

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

        #print str(instr)

        #print str(instr)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    OEP = elf.entry

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

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

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

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

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

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

    print '\n'.join(program)
Пример #18
0
def GUID(name):
    return Struct(name,
        ULInt32("Data1"),
        ULInt16("Data2"),
        ULInt16("Data3"),
        String("Data4", 8))
Пример #19
0
from construct import ULInt32
from construct import Embed
from construct import Struct, Array
from construct import Container
# from construct.debug import Probe

from pox.ethanol.ssl_message.msg_core import msg_default
from pox.ethanol.ssl_message.msg_core import field_station, field_ssid, field_intf_name
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

ssid_info = Struct('ssid_info',
                   Embed(field_intf_name),
                   Embed(field_ssid),
                   ULInt32('channel'),
                   ULInt32('frequency'),
                   )

msg_ssid = Struct('msg_ssid',
                  Embed(msg_default),  # default fields
                  Embed(field_station),
                  ULInt32('num_ssids'),
                  Array(lambda ctx: ctx.num_ssids, ssid_info),
                  # Probe()
                  )


def get_ssid(server, id=0, intf_name=[], sta_ip=None, sta_port=0):
    """
      returns the value
Пример #20
0
def array(struct):
    """Standard prefixed arrays."""
    return PrefixedArray(struct, ULInt32('count'))
Пример #21
0
    def __iter__(self):
        table_definition = self.tables.get_definition(
            self.current_table_number)
        for page_ref in self.pages.list():
            if self.pages[page_ref].hierarchy_level == 0:
                for record in TpsRecordsList(self,
                                             self.pages[page_ref],
                                             encoding=self.encoding,
                                             check=self.check):
                    if record.type == 'DATA' and record.data.table_number == self.current_table_number:
                        check_value('table_record_size', len(record.data.data),
                                    table_definition.record_size)
                        # TODO convert name to string
                        fields = {"b':RecNo'": record.data.record_number}
                        for field in table_definition.record_table_definition_field:
                            field_data = record.data.data[field.
                                                          offset:field.offset +
                                                          field.size]
                            value = ''
                            if field.type == 'BYTE':
                                value = ULInt8('byte').parse(field_data)
                            elif field.type == 'SHORT':
                                value = SLInt16('short').parse(field_data)
                            elif field.type == 'USHORT':
                                value = ULInt16('ushort').parse(field_data)
                            elif field.type == 'DATE':
                                value = self.to_date(field_data)
                            elif field.type == 'TIME':
                                value = self.to_time(field_data)
                            elif field.type == 'LONG':
                                #TODO
                                if field.name.decode(encoding='cp437').split(
                                        ':')[1].lower() in self.date_fieldname:
                                    if SLInt32('long').parse(field_data) == 0:
                                        value = None
                                    else:
                                        value = date.fromordinal(
                                            657433 +
                                            SLInt32('long').parse(field_data))
                                elif field.name.decode(encoding='cp437').split(
                                        ':')[1].lower() in self.time_fieldname:
                                    s, ms = divmod(
                                        SLInt32('long').parse(field_data), 100)
                                    value = str('{}.{:03d}'.format(
                                        time.strftime('%Y-%m-%d %H:%M:%S',
                                                      time.gmtime(s)), ms))
                                else:
                                    value = SLInt32('long').parse(field_data)
                            elif field.type == 'ULONG':
                                value = ULInt32('ulong').parse(field_data)
                            elif field.type == 'FLOAT':
                                value = LFloat32('float').parse(field_data)
                            elif field.type == 'DOUBLE':
                                value = LFloat64('double').parse(field_data)
                            elif field.type == 'DECIMAL':
                                # TODO BCD
                                if field_data[0] & 0xF0 == 0xF0:
                                    sign = -1
                                    field_data = bytearray(field_data)
                                    field_data[0] &= 0x0F
                                else:
                                    sign = 1
                                value = sign * int(hexlify(
                                    field_data)) / 10**field.decimal_count
                            elif field.type == 'STRING':
                                value = text_type(
                                    field_data,
                                    encoding=self.encoding).strip()
                            elif field.type == 'CSTRING':
                                value = text_type(
                                    field_data,
                                    encoding=self.encoding).strip()
                            elif field.type == 'PSTRING':
                                value = text_type(
                                    field_data[1:field_data[0] + 1],
                                    encoding=self.encoding).strip()
                            else:
                                # GROUP=0x16
                                # raise ValueError
                                #TODO
                                pass

                            fields[text_type(field.name)] = value
                        # print(fields)
                        yield fields
Пример #22
0
@requires: construct 2.5.2
"""

from construct import SLInt32, ULInt32
from construct import Embed, Struct, Container, Array

from pox.ethanol.ssl_message.msg_core import msg_default, field_ssid, field_station, field_intf_name
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

ssid_info = Struct(
    'ssid_info',
    Embed(field_intf_name),
    Embed(field_ssid),
    ULInt32('channel'),
    ULInt32('frequency'),
)
""" information about the configured SSID: wiphy, ESSID, channel, frequency, mode
"""

msg_ap_ssid = Struct(
    'msg_ap_ssid',
    Embed(msg_default),  # default fields
    Embed(field_station),
    SLInt32('num_ssids'),
    Array(lambda ctx: ctx.num_ssids, ssid_info),
)
""" message structure """

Пример #23
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.')
Пример #24
0
"""

from construct import SLInt8, ULInt32, SLInt64
from construct import Embed
from construct import Struct, Container, Array
# from construct.debug import Probe

from pox.ethanol.ssl_message.msg_core import msg_default
from pox.ethanol.ssl_message.msg_core import field_station, field_intf_name, field_mac_addr
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, tri_boolean, len_of_string

intfs = Struct('intfs',
               SLInt64('ifindex'),
               Embed(field_intf_name),
               ULInt32('intf_type'),
               Embed(field_mac_addr),
               SLInt8('is_wifi'),
               )

msg_intf = Struct('msg_intf',
                  Embed(msg_default),  # default fields
                  Embed(field_station),
                  ULInt32('num_intf'),
                  Array(lambda ctx: ctx.num_intf, intfs),
                  # Probe()
                  )


def __get_intf(server, m_id=0, intf_name=[], sta_ip=None, sta_port=0, m_type=None):
    """
Пример #25
0
from pox.ethanol.ssl_message.msg_core import field_intf_name
from pox.ethanol.ssl_message.msg_core import field_station
from pox.ethanol.ssl_message.msg_core import field_mac_addr
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

iw_bitrates = Struct(
    'iw_bitrates',
    LFloat32("bitrate"),
    ULInt8('is_short'),  # this is a boolean coded as a byte
)

iw_bands = Struct(
    'iw_bands',
    Embed(field_intf_name),
    ULInt32('band'),
    ULInt32('num_bitrates'),
    # Probe(),
    Array(lambda ctx: ctx.num_bitrates, iw_bitrates),
)

msg_tx_bitrates = Struct(
    'msg_tx_bitrates',
    Embed(msg_default),  # default fields
    Embed(field_intf_name),
    Embed(field_station),
    ULInt32('num_bands'),
    # Probe(),
    Array(lambda ctx: ctx.num_bands, iw_bands),
)
Пример #26
0
from pox.ethanol.ssl_message.msg_core import msg_default
from pox.ethanol.ssl_message.msg_core import field_station, field_intf_name, field_mac_addr
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

# ###############################################################
#
# MSG_TYPE.MSG_GET_RADIO_WLANS
#
# ###############################################################
""" info about one wlan"""
list_of_radio_wlans = Struct(
    'list_of_radio_wlans',
    Embed(field_intf_name),
    Embed(field_mac_addr),
    ULInt32('wiphy'),
)
""" message structure """
msg_radio_wlans = Struct(
    'msg_radio_wlans',
    Embed(msg_default),  # default fields
    Embed(field_station),
    ULInt32('num_wlans'),
    Array(lambda ctx: ctx.num_wlans, list_of_radio_wlans),
    # Probe()
)


def get_radio_wlans(server, id=0, intf_name=None, sta_ip=None, sta_port=0):
    """ requests the radio wlans, if intf_name is not None, only this interface is considered, otherwise returns all wireless interfaces
Пример #27
0
from construct import ULInt32
from construct import Embed
from construct import Struct, Container
# from construct.debug import Probe

from pox.ethanol.ssl_message.msg_core import msg_default
from pox.ethanol.ssl_message.msg_core import field_intf_name, field_station
from pox.ethanol.ssl_message.msg_common import MSG_TYPE, VERSION
from pox.ethanol.ssl_message.msg_common import send_and_receive_msg, len_of_string

msg_powersave = Struct('msg_powersave',
                       Embed(msg_default),  # default fields
                       Embed(field_intf_name),
                       Embed(field_station),
                       ULInt32('value'),
                       # Probe()
                       )


def get_powersave_mode(server, id=0, intf_name=None, sta_ip=None, sta_port=0):
    """ get if the powersave is set or not
      @param server: tuple (ip, port_num)
      @param id: message id
      @param intf_name: name of the wireless interface
      @type intf_name: str
      @param sta_ip: ip address of the station that this message should be relayed to, if sta_ip is different from None
      @type sta_ip: str
      @param sta_port: socket port number of the station
      @type sta_port: int
Пример #28
0
RECORD_TYPE = Enum(
    Byte('type'),
    NULL=None,
    DATA=0xF3,
    METADATA=0xF6,
    TABLE_DEFINITION=0xFA,
    TABLE_NAME=0xFE,
    _default_='INDEX',
)

DATA_RECORD_DATA = Struct('field_data', UBInt32('record_number'),
                          Bytes('data', lambda ctx: ctx['data_size'] - 9))

METADATA_RECORD_DATA = Struct('field_metadata', Byte('metadata_type'),
                              ULInt32('metadata_record_count'),
                              ULInt32('metadata_record_last_access'))

TABLE_DEFINITION_RECORD_DATA = Struct(
    'table_definition',
    Bytes('table_definition_bytes', lambda ctx: ctx['data_size'] - 5))

INDEX_RECORD_DATA = Struct('field_index',
                           Bytes('data', lambda ctx: ctx['data_size'] - 10),
                           ULInt32('record_number'))

RECORD_STRUCT = Struct(
    'record', ULInt16('data_size'), Peek(Byte('first_byte')),
    Embed(
        IfThenElse(
            'record_type', lambda ctx: ctx['first_byte'] == 0xFE,
Пример #29
0
from Crypto.Cipher import AES
from construct.macros import ULInt64, Padding
from structs import kHFSRootParentID
import hashlib

"""
iOS >= 4 raw images
http://opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/hfs/hfs_cprotect.c
http://opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/sys/cprotect.h
"""

cp_root_xattr = Struct("cp_root_xattr",
    ULInt16("major_version"),
    ULInt16("minor_version"),
    ULInt64("flags"),
    ULInt32("reserved1"),
    ULInt32("reserved2"),
    ULInt32("reserved3"),
    ULInt32("reserved4")
)

cprotect_xattr = Struct("cprotect_xattr",
    ULInt16("xattr_major_version"),
    ULInt16("xattr_minor_version"),
    ULInt32("flags"),
    ULInt32("persistent_class"),
    ULInt32("key_size"),
    String("persistent_key", length=0x28)
)

cprotect4_xattr = Struct("cprotect_xattr",