Esempio n. 1
0
class STDOBJREF(Packet):
    name = 'stdObjRef'
    fields_desc = [
        LEIntEnumField('flags', 1, {0: 'PINGING', 8: 'SORF_NOPING'}),
        LEIntField('cPublicRefs', 0),
        LELongField('OXID', 0),
        LELongField('OID', 0),
        PacketField('IPID', None, UUIDField),
    ]
Esempio n. 2
0
class SMB2_Header(Packet):
    name = "SMB2 Header"
    fields_desc = [
        StrFixedLenField("Start", b"\xfeSMB", 4),
        LEShortField("HeaderLength", 0),
        LEShortField("CreditCharge", 0),
        LEShortField("ChannelSequence", 0),
        LEShortField("Unused", 0),
        ShortEnumField("Command", 0, {0x0000: "SMB2_COM_NEGOCIATE"}),
        LEShortField("CreditsRequested", 0),
        # XLEIntField("Flags", 0),
        FlagsField("Flags", 0, 32, {
            24: "SMB2_FLAGS_SERVER_TO_REDIR",
        }),
        XLEIntField("ChainOffset", 0),
        LELongField("MessageID", 0),
        XLEIntField("ProcessID", 0),
        XLEIntField("TreeID", 0),
        XLELongField("SessionID", 0),
        XNBytesField("Signature", 0, 16),
    ]

    def guess_payload_class(self, payload):
        if self.Command == 0x0000:
            if self.Flags.SMB2_FLAGS_SERVER_TO_REDIR:
                return SMB2_Negociate_Protocol_Response_Header
            return SMB2_Negociate_Protocol_Request_Header
        return super(SMB2_Header, self).guess_payload_class(payload)
Esempio n. 3
0
class NEGOEX_CHECKSUM(Packet):
    fields_desc = [
        LELongField("cbHeaderLength", 20),
        LELongEnumField("ChecksumScheme", 1, {1: "CHECKSUM_SCHEME_RFC3961"}),
        LELongEnumField("ChecksumType", None, _checksum_types),
        XStrLenField("ChecksumValue", b"", length_from=_checksum_size)
    ]
Esempio n. 4
0
class Dot11Beacon(Packet):
    name = "802.11 Beacon"
    fields_desc = [LELongField("timestamp", 0),
                   LEShortField("beacon_interval", 0x0064),
                   FlagsField("cap", 0, 16, capability_list)]

    def network_stats(self):
        """Return a dictionary containing a summary of the Dot11
        elements fields
        """
        summary = {}
        crypto = set()
        p = self.payload
        while isinstance(p, Dot11Elt):
            if p.ID == 0:
                summary["ssid"] = plain_str(p.info)
            elif p.ID == 3:
                summary["channel"] = ord(p.info)
            elif isinstance(p, Dot11EltRates):
                summary["rates"] = p.rates
            elif isinstance(p, Dot11EltRSN):
                crypto.add("WPA2")
            elif p.ID == 221:
                if isinstance(p, Dot11EltMicrosoftWPA) or \
                        p.info.startswith('\x00P\xf2\x01\x01\x00'):
                    crypto.add("WPA")
            p = p.payload
        if not crypto:
            if self.cap.privacy:
                crypto.add("WEP")
            else:
                crypto.add("OPN")
        summary["crypto"] = crypto
        return summary
Esempio n. 5
0
class Dot11Beacon(_Dot11EltUtils):
    name = "802.11 Beacon"
    fields_desc = [
        LELongField("timestamp", 0),
        LEShortField("beacon_interval", 0x0064),
        FlagsField("cap", 0, 16, capability_list)
    ]
Esempio n. 6
0
class Dot15d4AuxSecurityHeader(Packet):
    name = "802.15.4 Auxiliary Security Header"
    fields_desc = [
        BitField("sec_sc_reserved", 0, 3),
        # Key Identifier Mode
        # 0: Key is determined implicitly from the originator and recipient(s) of the frame  # noqa: E501
        # 1: Key is determined explicitly from the the 1-octet Key Index subfield of the Key Identifier field  # noqa: E501
        # 2: Key is determined explicitly from the 4-octet Key Source and the 1-octet Key Index  # noqa: E501
        # 3: Key is determined explicitly from the 8-octet Key Source and the 1-octet Key Index  # noqa: E501
        BitEnumField("sec_sc_keyidmode", 0, 2, {
            0: "Implicit", 1: "1oKeyIndex", 2: "4o-KeySource-1oKeyIndex", 3: "8o-KeySource-1oKeyIndex"}  # noqa: E501
        ),
        BitEnumField("sec_sc_seclevel", 0, 3, {0: "None", 1: "MIC-32", 2: "MIC-64", 3: "MIC-128", 4: "ENC", 5: "ENC-MIC-32", 6: "ENC-MIC-64", 7: "ENC-MIC-128"}),  # noqa: E501
        XLEIntField("sec_framecounter", 0x00000000),  # 4 octets
        # Key Identifier (variable length): identifies the key that is used for cryptographic protection  # noqa: E501
        # Key Source : length of sec_keyid_keysource varies btwn 0, 4, and 8 bytes depending on sec_sc_keyidmode  # noqa: E501
        # 4 octets when sec_sc_keyidmode == 2
        ConditionalField(XLEIntField("sec_keyid_keysource", 0x00000000),
                         lambda pkt: pkt.getfieldval("sec_sc_keyidmode") == 2),
        # 8 octets when sec_sc_keyidmode == 3
        ConditionalField(LELongField("sec_keyid_keysource", 0x0000000000000000),  # noqa: E501
                         lambda pkt: pkt.getfieldval("sec_sc_keyidmode") == 3),
        # Key Index (1 octet): allows unique identification of different keys with the same originator  # noqa: E501
        ConditionalField(XByteField("sec_keyid_keyindex", 0xFF),
                         lambda pkt: pkt.getfieldval("sec_sc_keyidmode") != 0),
    ]
Esempio n. 7
0
class Dot11ProbeResp(Packet):
    name = "802.11 Probe Response"
    fields_desc = [
        LELongField("timestamp", 0),
        LEShortField("beacon_interval", 0x0064),
        FlagsField("cap", 0, 16, capability_list)
    ]
Esempio n. 8
0
class _Dot11NetStats(Packet):
    fields_desc = [LELongField("timestamp", 0),
                   LEShortField("beacon_interval", 0x0064),
                   FlagsField("cap", 0, 16, capability_list)]

    def network_stats(self):
        """Return a dictionary containing a summary of the Dot11
        elements fields
        """
        summary = {}
        crypto = set()
        akmsuite_types = {
            0x00: "Reserved",
            0x01: "802.1X",
            0x02: "PSK"
        }
        p = self.payload
        while isinstance(p, Dot11Elt):
            if p.ID == 0:
                summary["ssid"] = plain_str(p.info)
            elif p.ID == 3:
                summary["channel"] = ord(p.info)
            elif isinstance(p, Dot11EltCountry):
                summary["country"] = plain_str(p.country_string[:2])
                country_descriptor_types = {
                    b"I": "Indoor",
                    b"O": "Outdoor",
                    b"X": "Non-country",
                    b"\xff": "Ignored"
                }
                summary["country_desc_type"] = country_descriptor_types.get(
                    p.country_string[-1:]
                )
            elif isinstance(p, Dot11EltRates):
                summary["rates"] = p.rates
            elif isinstance(p, Dot11EltRSN):
                if p.akm_suites:
                    auth = akmsuite_types.get(p.akm_suites[0].suite)
                    crypto.add("WPA2/%s" % auth)
                else:
                    crypto.add("WPA2")
            elif p.ID == 221:
                if isinstance(p, Dot11EltMicrosoftWPA) or \
                        p.info.startswith(b'\x00P\xf2\x01\x01\x00'):
                    if p.akm_suites:
                        auth = akmsuite_types.get(p.akm_suites[0].suite)
                        crypto.add("WPA/%s" % auth)
                    else:
                        crypto.add("WPA")
            p = p.payload
        if not crypto:
            if self.cap.privacy:
                crypto.add("WEP")
            else:
                crypto.add("OPN")
        summary["crypto"] = crypto
        return summary
Esempio n. 9
0
class USBPcap(Packet):
    ''' Packet used in pcap files '''

    name = 'USBPcap'
    fields_desc = [
        LELongField('urb_id', 0),
        CharEnumField('urb_type', SUBMIT, pcap_urb_type),
        ByteEnumField('urb_transfert', PCAP_CTRL, pcap_urb_transfert),
        BitEnumField('endpoint_direction', USBDefs.EP.Direction.IN, 1,
                     USBDefs.EP.Direction.desc),
        BitField('endpoint_number', 0, 7),
        ByteField('device', 1),
        LEShortField('bus_id', 1),
        ByteEnumField('device_setup_request', 0, pcap_setup_request),
        ByteEnumField('data_present', 0, pcap_data_present),
        LELongField('urb_sec', 0),
        LEIntField('urb_usec', 0),
        LESignedIntEnumField('urb_status', 0, pcap_urb_status),
        LEIntField('urb_length', 0),
        LEIntField('data_length', 0),
        ConditionalField(
            PacketField('urb_setup', GetDescriptor(), URB),
            lambda p: p.urb_transfert == 2 and p.urb_type == 'S',
        ),
        BytesFixedLenField(
            'garbage',
            pcap_garbage,
            length_from=lambda p: 24
            if p.urb_setup is None else 24 - len(p.urb_setup),
        ),
        ConditionalField(
            PacketField('descriptor', DeviceDescriptor(), Descriptor),
            lambda p: p.urb_transfert == 2 and p.urb_type == 'C' and p.
            data_length > 0,
        ),
        StrField('data', ''),
    ]

    def is_ctrl_request(self):
        return self.urb_type == SUBMIT and self.urb_transfert == PCAP_CTRL

    def is_ctrl_response(self):
        return self.urb_type == COMPLETE and self.urb_transfert == PCAP_CTRL
Esempio n. 10
0
class SMBSession_Setup_AndX_Request(Packet):
    name = "Session Setup AndX Request"
    fields_desc = [
        StrFixedLenField("Start", b"\xffSMB", 4),
        ByteEnumField("Command", 0x73,
                      {0x73: "SMB_COM_SESSION_SETUP_ANDX"}),  # noqa: E501
        ByteField("Error_Class", 0),
        ByteField("Reserved", 0),
        LEShortField("Error_Code", 0),
        ByteField("Flags", 0x18),
        LEShortField("Flags2", 0x0001),
        LEShortField("PIDHigh", 0x0000),
        LELongField("Signature", 0x0),
        LEShortField("Unused", 0x0),
        LEShortField("TID", 0),
        LEShortField("PID", 1),
        LEShortField("UID", 0),
        LEShortField("MID", 2),
        ByteField("WordCount", 13),
        ByteEnumField("AndXCommand", 0x75,
                      {0x75: "SMB_COM_TREE_CONNECT_ANDX"}),  # noqa: E501
        ByteField("Reserved2", 0),
        LEShortField("AndXOffset", 96),
        LEShortField("MaxBufferS", 2920),
        LEShortField("MaxMPXCount", 50),
        LEShortField("VCNumber", 0),
        LEIntField("SessionKey", 0),
        LEFieldLenField("ANSIPasswordLength", None, "ANSIPassword"),
        LEShortField("UnicodePasswordLength", 0),
        LEIntField("Reserved3", 0),
        LEShortField("ServerCapabilities", 0x05),
        BitField("UnixExtensions", 0, 1),
        BitField("Reserved4", 0, 7),
        BitField("ExtendedSecurity", 0, 1),
        BitField("CompBulk", 0, 2),
        BitField("Reserved5", 0, 5),
        LEShortField("ByteCount", 35),
        StrLenField("ANSIPassword",
                    "Pass",
                    length_from=lambda x: x.ANSIPasswordLength),  # noqa: E501
        StrNullField("Account", "GUEST"),
        StrNullField("PrimaryDomain", ""),
        StrNullField("NativeOS", "Windows 4.0"),
        StrNullField("NativeLanManager", "Windows 4.0"),
        ByteField("WordCount2", 4),
        ByteEnumField("AndXCommand2", 0xFF, {0xFF: "SMB_COM_NONE"}),
        ByteField("Reserved6", 0),
        LEShortField("AndXOffset2", 0),
        LEShortField("Flags3", 0x2),
        LEShortField("PasswordLength", 0x1),
        LEShortField("ByteCount2", 18),
        ByteField("Password", 0),
        StrNullField("Path", "\\\\WIN2K\\IPC$"),
        StrNullField("Service", "IPC")
    ]
Esempio n. 11
0
class PAS5211GetSnInfoResponse(PAS5211Msg):
    opcode = 7
    name = "PAS5211GetSnInfoResponse"
    fields_desc = [
        StrFixedLenField("serial_number", None, 8),
        LEShortField("found", None),
        LEShortField("type", None),
        LEShortField("onu_state", None),
        LELongField("equalization_delay", None),
        LEShortField("reserved", None)
    ]
Esempio n. 12
0
File: smb.py Progetto: phretor/scapy
class SMB_Header(Packet):
    name = "SMB 1 Protocol Request Header"
    fields_desc = [
        StrFixedLenField("Start", b"\xffSMB", 4),
        ByteEnumField("Command", 0x72, SMB_COM),
        LEIntField("Status", 0),
        FlagsField("Flags", 0x18, 8, [
            "LOCK_AND_READ_OK", "BUF_AVAIL", "res", "CASE_INSENSITIVE",
            "CANONICALIZED_PATHS", "OPLOCK", "OPBATCH", "REPLY"
        ]),
        FlagsField("Flags2", 0x0000, -16, [
            "LONG_NAMES", "EAS", "SMB_SECURITY_SIGNATURE", "COMPRESSED",
            "SMB_SECURITY_SIGNATURE_REQUIRED", "res", "IS_LONG_NAME", "res",
            "res", "res", "REPARSE_PATH", "EXTENDED_SECURITY", "DFS",
            "PAGING_IO", "NT_STATUS", "UNICODE"
        ]),
        LEShortField("PIDHigh", 0x0000),
        LELongField("SecurityFeatures", 0x0),
        LEShortField("Reserved", 0x0),
        LEShortField("TID", 0),
        LEShortField("PID", 1),
        LEShortField("UID", 0),
        LEShortField("MID", 2)
    ]

    def guess_payload_class(self, payload):
        # type: (bytes) -> Packet
        if self.Command == 0x72:
            if self.Flags.REPLY:
                if self.Flags2.EXTENDED_SECURITY:
                    return SMBNegotiate_Response_Extended_Security
                else:
                    return SMBNegotiate_Response_Security
            else:
                return SMBNegotiate_Request
        elif self.Command == 0x73:
            if self.Flags.REPLY:
                if self.Flags2.EXTENDED_SECURITY:
                    return SMBSession_Setup_AndX_Response_Extended_Security
                else:
                    return SMBSession_Setup_AndX_Response
            else:
                if self.Flags2.EXTENDED_SECURITY:
                    return SMBSession_Setup_AndX_Request_Extended_Security
                else:
                    return SMBSession_Setup_AndX_Request
        elif self.Command == 0x25:
            return SMBNetlogon_Protocol_Response_Header
        return super(SMB_Header, self).guess_payload_class(payload)
Esempio n. 13
0
class SMB2_Header(Packet):
    name = "SMB2 Header"
    fields_desc = [
        StrFixedLenField("Start", b"\xfeSMB", 4),
        LEShortField("StructureSize", 64),
        LEShortField("CreditCharge", 0),
        LEShortField("ChannelSequence", 0),
        LEShortField("Unused", 0),
        LEShortEnumField("Command", 0, SMB2_COM),
        LEShortField("CreditsRequested", 0),
        FlagsField(
            "Flags", 0, -32, {
                0x00000001: "SMB2_FLAGS_SERVER_TO_REDIR",
                0x00000002: "SMB2_FLAGS_ASYNC_COMMAND",
                0x00000004: "SMB2_FLAGS_RELATED_OPERATIONS",
                0x00000008: "SMB2_FLAGS_SIGNED",
                0x10000000: "SMB2_FLAGS_DFS_OPERATIONS",
                0x20000000: "SMB2_FLAGS_REPLAY_OPERATION",
            }),
        XLEIntField("NextCommand", 0),
        LELongField("MessageId", 0),
        LELongField("AsyncID", 0),
        LELongField("SessionId", 0),
        XNBytesField("Signature", 0, 16),
    ]

    def guess_payload_class(self, payload):
        if self.Command == 0x0000:  # Negotiate
            if self.Flags.SMB2_FLAGS_SERVER_TO_REDIR:
                return SMB2_Negotiate_Protocol_Response
            return SMB2_Negotiate_Protocol_Request
        elif self.Command == 0x0001:  # Setup
            if self.Flags.SMB2_FLAGS_SERVER_TO_REDIR:
                return SMB2_Session_Setup_Response
            return SMB2_Session_Setup_Request
        return super(SMB2_Header, self).guess_payload_class(payload)
Esempio n. 14
0
class Dot15d4AuxSecurityHeader(Packet):
    KEY_IDENTIFIER_MODE = {
        # Key is determined implicitly from the originator and recipient(s) of
        # the frame
        0: "Implicit",
        # Key is determined explicitly from the the 1-octet Key Index subfield
        # of the Key Identifier field
        1: "1oKeyIndex",
        # Key is determined explicitly from the 4-octet Key Source and the
        # 1-octet Key Index
        2: "4o-KeySource-1oKeyIndex",
        # Key is determined explicitly from the 8-octet Key Source and the
        # 1-octet Key Index
        3: "8o-KeySource-1oKeyIndex"
    }

    SEC_LEVEL = {
        0: "None",
        1: "MIC-32",
        2: "MIC-64",
        3: "MIC-128",
        4: "ENC",
        5: "ENC-MIC-32",
        6: "ENC-MIC-64",
        7: "ENC-MIC-128"
    }

    name = "802.15.4 Auxiliary Security Header"
    fields_desc = [
        BitField("sec_sc_reserved", 0, 3),
        BitEnumField("sec_sc_keyidmode", 0, 2, KEY_IDENTIFIER_MODE),
        BitEnumField("sec_sc_seclevel", 0, 3, SEC_LEVEL),
        XLEIntField("sec_framecounter", 0x00000000),
        # Key Identifier (variable length): identifies the key that is used for
        # cryptographic protection.
        # Key Source : length of sec_keyid_keysource varies btwn 0, 4, and 8
        # bytes depending on sec_sc_keyidmode.
        # 4 octets when sec_sc_keyidmode == 2
        ConditionalField(XLEIntField("sec_keyid_keysource", 0),
                         lambda pkt: pkt.getfieldval("sec_sc_keyidmode") == 2),
        # 8 octets when sec_sc_keyidmode == 3
        ConditionalField(LELongField("sec_keyid_keysource", 0),
                         lambda pkt: pkt.getfieldval("sec_sc_keyidmode") == 3),
        # Key Index (1 octet): allows unique identification of different keys
        # with the same originator.
        ConditionalField(XByteField("sec_keyid_keyindex", 0xFF),
                         lambda pkt: pkt.getfieldval("sec_sc_keyidmode") != 0),
    ]
Esempio n. 15
0
class ENIPTCP(Packet):
    """Ethernet/IP packet over TCP"""
    name = "ENIPTCP"
    fields_desc = [
        LEShortEnumField("commandId", None, _commandIdList),
        LEShortField("length", 0),
        XLEIntField("session", 0),
        LEIntEnumField("status", None, _statusList),
        LELongField("senderContext", 0),
        LEIntField("options", 0),
        MultipleTypeField(
            [
                # List Services Reply
                (PacketField("commandSpecificData", ENIPListServicesReply,
                             ENIPListServicesReply),
                 lambda pkt: pkt.commandId == 0x4),
                # List Identity Reply
                (PacketField("commandSpecificData", ENIPListIdentityReply,
                             ENIPListIdentityReply),
                 lambda pkt: pkt.commandId == 0x63),
                # List Interfaces Reply
                (PacketField("commandSpecificData", ENIPListInterfacesReply,
                             ENIPListInterfacesReply),
                 lambda pkt: pkt.commandId == 0x64),
                # Register Session
                (PacketField("commandSpecificData", ENIPRegisterSession,
                             ENIPRegisterSession),
                 lambda pkt: pkt.commandId == 0x65),
                # Send RR Data
                (PacketField("commandSpecificData", ENIPSendRRData,
                             ENIPSendRRData),
                 lambda pkt: pkt.commandId == 0x6f),
                # Send Unit Data
                (PacketField("commandSpecificData", ENIPSendUnitData,
                             ENIPSendUnitData),
                 lambda pkt: pkt.commandId == 0x70),
            ],
            PacketField(
                "commandSpecificData",
                None,
                CommandSpecificData)  # By default
        ),
    ]

    def post_build(self, pkt, pay):
        if self.length is None and pay:
            pkt = pkt[:2] + struct.pack("<H", len(pay)) + pkt[4:]
        return pkt + pay
Esempio n. 16
0
class SMBNegociate_Protocol_Response_Advanced_Security(Packet):
    name = "SMBNegociate Protocol Response Advanced Security"
    fields_desc = [
        StrFixedLenField("Start", b"\xffSMB", 4),
        ByteEnumField("Command", 0x72, {0x72: "SMB_COM_NEGOTIATE"}),
        ByteField("Error_Class", 0),
        ByteField("Reserved", 0),
        LEShortField("Error_Code", 0),
        ByteField("Flags", 0x98),
        LEShortField("Flags2", 0x0000),
        LEShortField("PIDHigh", 0x0000),
        LELongField("Signature", 0x0),
        LEShortField("Unused", 0x0),
        LEShortField("TID", 0),
        LEShortField("PID", 1),
        LEShortField("UID", 0),
        LEShortField("MID", 2),
        ByteField("WordCount", 17),
        LEShortField("DialectIndex", 7),
        ByteField("SecurityMode", 0x03),
        LEShortField("MaxMpxCount", 50),
        LEShortField("MaxNumberVC", 1),
        LEIntField("MaxBufferSize", 16144),
        LEIntField("MaxRawSize", 65536),
        LEIntField("SessionKey", 0x0000),
        LEShortField("ServerCapabilities", 0xf3f9),
        BitField("UnixExtensions", 0, 1),
        BitField("Reserved2", 0, 7),
        BitField("ExtendedSecurity", 1, 1),
        BitField("CompBulk", 0, 2),
        BitField("Reserved3", 0, 5),
        # There have been 127490112000000000 tenths of micro-seconds between 1st january 1601 and 1st january 2005. 127490112000000000=0x1C4EF94D6228000, so ServerTimeHigh=0xD6228000 and ServerTimeLow=0x1C4EF94.  # noqa: E501
        LEIntField("ServerTimeHigh", 0xD6228000),
        LEIntField("ServerTimeLow", 0x1C4EF94),
        LEShortField("ServerTimeZone", 0x3c),
        ByteField("EncryptionKeyLength", 0),
        LEFieldLenField("ByteCount",
                        None,
                        "SecurityBlob",
                        adjust=lambda pkt, x: x - 16),  # noqa: E501
        BitField("GUID", 0, 128),
        StrLenField("SecurityBlob", "", length_from=lambda x: x.ByteCount + 16)
    ]  # noqa: E501
Esempio n. 17
0
class NEGOEX_NEGO_MESSAGE(Packet):
    OFFSET = 92
    show_indent = 0
    fields_desc = [
        NEGOEX_MESSAGE_HEADER,
        XStrFixedLenField("Random", b"", length=32),
        LELongField("ProtocolVersion", 0),
        LEIntField("AuthSchemeBufferOffset", None),
        LEShortField("AuthSchemeCount", None),
        LEIntField("ExtensionBufferOffset", None),
        LEShortField("ExtensionCount", None),
        # Payload
        _NTLMPayloadField(
            'Payload',
            OFFSET, [
                FieldListField("AuthScheme", [],
                               UUIDEnumField("", None, _NEGOEX_AUTH_SCHEMES),
                               count_from=lambda pkt: pkt.AuthSchemeCount),
                PacketListField("Extension", [],
                                NEGOEX_EXTENSION_VECTOR,
                                count_from=lambda pkt: pkt.ExtensionCount),
            ],
            length_from=lambda pkt: pkt.cbMessageLength - 92),
        # TODO: dissect extensions
    ]

    def post_build(self, pkt, pay):
        # type: (bytes, bytes) -> bytes
        return _NEGOEX_post_build(self, pkt, self.OFFSET, {
            "AuthScheme": 96,
            "Extension": 102,
        }) + pay

    @classmethod
    def dispatch_hook(cls, _pkt=None, *args, **kargs):
        if _pkt and len(_pkt) >= 12:
            MessageType = struct.unpack("<I", _pkt[8:12])[0]
            if MessageType in [0, 1]:
                return NEGOEX_NEGO_MESSAGE
            elif MessageType in [2, 3]:
                return NEGOEX_EXCHANGE_MESSAGE
        return cls
Esempio n. 18
0
class SMBNegociate_Protocol_Request_Header(Packet):
    name = "SMBNegociate Protocol Request Header"
    fields_desc = [
        StrFixedLenField("Start", b"\xffSMB", 4),
        ByteEnumField("Command", 0x72, {0x72: "SMB_COM_NEGOTIATE"}),
        ByteField("Error_Class", 0),
        ByteField("Reserved", 0),
        LEShortField("Error_code", 0),
        ByteField("Flags", 0x18),
        LEShortField("Flags2", 0x0000),
        LEShortField("PIDHigh", 0x0000),
        LELongField("Signature", 0x0),
        LEShortField("Unused", 0x0),
        LEShortField("TID", 0),
        LEShortField("PID", 1),
        LEShortField("UID", 0),
        LEShortField("MID", 2),
        ByteField("WordCount", 0),
        LEShortField("ByteCount", 12)
    ]
Esempio n. 19
0
class SMBNegociate_Protocol_Response_No_Security(Packet):
    name = "SMBNegociate Protocol Response No Security"
    fields_desc = [
        StrFixedLenField("Start", b"\xffSMB", 4),
        ByteEnumField("Command", 0x72, {0x72: "SMB_COM_NEGOTIATE"}),
        ByteField("Error_Class", 0),
        ByteField("Reserved", 0),
        LEShortField("Error_Code", 0),
        ByteField("Flags", 0x98),
        LEShortField("Flags2", 0x0000),
        LEShortField("PIDHigh", 0x0000),
        LELongField("Signature", 0x0),
        LEShortField("Unused", 0x0),
        LEShortField("TID", 0),
        LEShortField("PID", 1),
        LEShortField("UID", 0),
        LEShortField("MID", 2),
        ByteField("WordCount", 17),
        LEShortField("DialectIndex", 7),
        ByteField("SecurityMode", 0x03),
        LEShortField("MaxMpxCount", 50),
        LEShortField("MaxNumberVC", 1),
        LEIntField("MaxBufferSize", 16144),
        LEIntField("MaxRawSize", 65536),
        LEIntField("SessionKey", 0x0000),
        LEShortField("ServerCapabilities", 0xf3f9),
        BitField("UnixExtensions", 0, 1),
        BitField("Reserved2", 0, 7),
        BitField("ExtendedSecurity", 0, 1),
        FlagsField("CompBulk", 0, 2, "CB"),
        BitField("Reserved3", 0, 5),
        # There have been 127490112000000000 tenths of micro-seconds between 1st january 1601 and 1st january 2005. 127490112000000000=0x1C4EF94D6228000, so ServerTimeHigh=0xD6228000 and ServerTimeLow=0x1C4EF94.  # noqa: E501
        LEIntField("ServerTimeHigh", 0xD6228000),
        LEIntField("ServerTimeLow", 0x1C4EF94),
        LEShortField("ServerTimeZone", 0x3c),
        ByteField("EncryptionKeyLength", 8),
        LEShortField("ByteCount", 24),
        BitField("EncryptionKey", 0, 64),
        StrNullField("DomainName", "WORKGROUP"),
        StrNullField("ServerName", "RMFF1")
    ]
Esempio n. 20
0
class SMB2_Header(Packet):
    name = "SMB2 Header"
    fields_desc = [
        StrFixedLenField("Start", b"\xfeSMB", 4),
        LEShortField("HeaderLength", 0),
        LEShortField("CreditCharge", 0),
        LEShortField("ChannelSequence", 0),
        LEShortField("Unused", 0),
        ShortEnumField("Command", 0, {0x0000: "SMB2_COM_NEGOCIATE"}),
        LEShortField("CreditsRequested", 0),
        # XLEIntField("Flags", 0),
        FlagsField("Flags", 0, 32, {
            24: "SMB2_FLAGS_SERVER_TO_REDIR",
        }),
        XLEIntField("ChainOffset", 0),
        LELongField("MessageID", 0),
        XLEIntField("ProcessID", 0),
        XLEIntField("TreeID", 0),
        XLELongField("SessionID", 0),
        XNBytesField("Signature", 0, 16),
    ]
Esempio n. 21
0
class USB(Packet):
    """
    Represents a USB packet saved by USBPcap.
    
    Based on packet format specified at http://desowin.org/usbpcap/captureformat.html.
    """
    name = "USBPcap"
    fields_desc = [
        LEShortField("headerLen", None),
        LELongField("irpId", None),
        LEIntField("status", None),

        LEShortField("function", None),
        ByteField("info", None),

        LEShortField("bus", 0),
        LEShortField("device", 0),

        BitEnumField("direction", 0, 1, {
            0: "OUT",
            1: "IN"
        }),
        BitField("endpoint", 0, 7),

        ByteEnumField("transfer", 0, {
            0: "isochronous",
            1: "interrupt",
            2: "control",
            3: "bulk"
        }),
        LEIntField("bodyLength", 0)
    ]

    def detail(self):
        if hasattr(self.payload, "detail"):
            return self.sprintf("USB ep=%USB.endpoint% %-3s,USB.direction%") + " | " + self.payload.detail()
        else:
            pass
Esempio n. 22
0
class SMBSession_Setup_AndX_Response(Packet):
    name = "Session Setup AndX Response"
    fields_desc = [
        StrFixedLenField("Start", b"\xffSMB", 4),
        ByteEnumField("Command", 0x73,
                      {0x73: "SMB_COM_SESSION_SETUP_ANDX"}),  # noqa: E501
        ByteField("Error_Class", 0),
        ByteField("Reserved", 0),
        LEShortField("Error_Code", 0),
        ByteField("Flags", 0x90),
        LEShortField("Flags2", 0x1001),
        LEShortField("PIDHigh", 0x0000),
        LELongField("Signature", 0x0),
        LEShortField("Unused", 0x0),
        LEShortField("TID", 0),
        LEShortField("PID", 1),
        LEShortField("UID", 0),
        LEShortField("MID", 2),
        ByteField("WordCount", 3),
        ByteEnumField("AndXCommand", 0x75,
                      {0x75: "SMB_COM_TREE_CONNECT_ANDX"}),  # noqa: E501
        ByteField("Reserved2", 0),
        LEShortField("AndXOffset", 66),
        LEShortField("Action", 0),
        LEShortField("ByteCount", 25),
        StrNullField("NativeOS", "Windows 4.0"),
        StrNullField("NativeLanManager", "Windows 4.0"),
        StrNullField("PrimaryDomain", ""),
        ByteField("WordCount2", 3),
        ByteEnumField("AndXCommand2", 0xFF, {0xFF: "SMB_COM_NONE"}),
        ByteField("Reserved3", 0),
        LEShortField("AndXOffset2", 80),
        LEShortField("OptionalSupport", 0x01),
        LEShortField("ByteCount2", 5),
        StrNullField("Service", "IPC"),
        StrNullField("NativeFileSystem", "")
    ]
Esempio n. 23
0
class SMBNetlogon_Protocol_Response_Header(Packet):
    name = "SMBNetlogon Protocol Response Header"
    fields_desc = [
        StrFixedLenField("Start", b"\xffSMB", 4),
        ByteEnumField("Command", 0x25, {0x25: "Trans"}),
        ByteField("Error_Class", 0x02),
        ByteField("Reserved", 0),
        LEShortField("Error_code", 4),
        ByteField("Flags", 0),
        LEShortField("Flags2", 0x0000),
        LEShortField("PIDHigh", 0x0000),
        LELongField("Signature", 0x0),
        LEShortField("Unused", 0x0),
        LEShortField("TID", 0),
        LEShortField("PID", 0),
        LEShortField("UID", 0),
        LEShortField("MID", 0),
        ByteField("WordCount", 17),
        LEShortField("TotalParamCount", 0),
        LEShortField("TotalDataCount", 112),
        LEShortField("MaxParamCount", 0),
        LEShortField("MaxDataCount", 0),
        ByteField("MaxSetupCount", 0),
        ByteField("unused2", 0),
        LEShortField("Flags3", 0),
        ByteField("TimeOut1", 0xe8),
        ByteField("TimeOut2", 0x03),
        LEShortField("unused3", 0),
        LEShortField("unused4", 0),
        LEShortField("ParamCount2", 0),
        LEShortField("ParamOffset", 0),
        LEShortField("DataCount", 112),
        LEShortField("DataOffset", 92),
        ByteField("SetupCount", 3),
        ByteField("unused5", 0)
    ]
Esempio n. 24
0
# TODO(ivanlei): This fields_desc does not cover chained present flags decode will fail in this cases
scapy.layers.dot11.RadioTap.name = '802.11 RadioTap'

# Greatly improved fields_desc for RadioTap which parses known present flags
scapy.layers.dot11.RadioTap.fields_desc = [
    ByteField('version', 0),
    ByteField('pad', 0),
    LEShortField('RadioTap_len', 0),
    FlagsField('present', None, -32, [
        'TSFT', 'Flags', 'Rate', 'Channel', 'FHSS', 'dBm_AntSignal',
        'dBm_AntNoise', 'Lock_Quality', 'TX_Attenuation', 'dB_TX_Attenuation',
        'dBm_TX_Power', 'Antenna', 'dB_AntSignal', 'dB_AntNoise', 'b14', 'b15',
        'b16', 'b17', 'b18', 'b19', 'b20', 'b21', 'b22', 'b23', 'b24', 'b25',
        'b26', 'b27', 'b28', 'b29', 'b30', 'Ext'
    ]),
    PresentFlagField(LELongField('TSFT', 0), 'TSFT'),
    PresentFlagField(ByteField('Flags', 0), 'Flags'),
    PresentFlagField(ByteField('Rate', 0), 'Rate'),
    PresentFlagField(ChannelFromMhzField('Channel', 0), 'Channel'),
    PresentFlagField(LEShortField('Channel_flags', 0), 'Channel'),
    PresentFlagField(ByteField('FHSS_hop_set', 0), 'FHSS'),
    PresentFlagField(ByteField('FHSS_hop_pattern', 0), 'FHSS'),
    PresentFlagField(SignedByteField('dBm_AntSignal', 0), 'dBm_AntSignal'),
    PresentFlagField(SignedByteField('dBm_AntNoise', 0), 'dBm_AntNoise'),
    PresentFlagField(LEShortField('Lock_Quality', 0), 'Lock_Quality'),
    PresentFlagField(LEShortField('TX_Attenuation', 0), 'TX_Attenuation'),
    PresentFlagField(LEShortField('db_TX_Attenuation', 0),
                     'dB_TX_Attenuation'),
    PresentFlagField(SignedByteField('dBm_TX_Power', 0), 'dBm_TX_Power'),
    PresentFlagField(ByteField('Antenna', 0), 'Antenna'),
    PresentFlagField(ByteField('dB_AntSignal', 0), 'dB_AntSignal'),
class RadioTap(Packet):
    name = "RadioTap dummy"
    fields_desc = [
        ByteField('version', 0),
        ByteField('pad', 0),
        LEShortField('len', None),
        FlagsField('present', None, -32, _rt_present),  # noqa: E501
        # Extended presence mask
        ConditionalField(
            PacketListField("Ext", [], next_cls_cb=_next_radiotap_extpm),
            lambda pkt: pkt.present and pkt.present.Ext),  # noqa: E501
        # RadioTap fields - each starts with a _RadiotapReversePadField
        # to handle padding

        # TSFT
        ConditionalField(
            _RadiotapReversePadField(LELongField("mac_timestamp", 0)),
            lambda pkt: pkt.present and pkt.present.TSFT),
        # Flags
        ConditionalField(
            _RadiotapReversePadField(FlagsField("Flags", None, -8, _rt_flags)),
            lambda pkt: pkt.present and pkt.present.Flags),
        # Rate
        ConditionalField(_RadiotapReversePadField(ByteField("Rate", 0)),
                         lambda pkt: pkt.present and pkt.present.Rate),
        # Channel
        ConditionalField(_RadiotapReversePadField(LEShortField("Channel", 0)),
                         lambda pkt: pkt.present and pkt.present.Channel),
        ConditionalField(
            FlagsField("ChannelFlags", None, -16, _rt_channelflags),
            lambda pkt: pkt.present and pkt.present.Channel),
        # dBm_AntSignal
        ConditionalField(
            _RadiotapReversePadField(_dbmField("dBm_AntSignal", -256)),
            lambda pkt: pkt.present and pkt.present.dBm_AntSignal),
        # dBm_AntNoise
        ConditionalField(
            _RadiotapReversePadField(_dbmField("dBm_AntNoise", -256)),
            lambda pkt: pkt.present and pkt.present.dBm_AntNoise),
        # Lock_Quality
        ConditionalField(
            _RadiotapReversePadField(LEShortField("Lock_Quality", 0), ),
            lambda pkt: pkt.present and pkt.present.Lock_Quality),
        # Antenna
        ConditionalField(_RadiotapReversePadField(ByteField("Antenna", 0)),
                         lambda pkt: pkt.present and pkt.present.Antenna),
        # RX Flags
        ConditionalField(
            _RadiotapReversePadField(
                FlagsField("RXFlags", None, -16, _rt_rxflags)),
            lambda pkt: pkt.present and pkt.present.RXFlags),
        # TX Flags
        ConditionalField(
            _RadiotapReversePadField(
                FlagsField("TXFlags", None, -16, _rt_txflags)),
            lambda pkt: pkt.present and pkt.present.TXFlags),
        # ChannelPlus
        ConditionalField(
            _RadiotapReversePadField(
                FlagsField("ChannelFlags2", None, -32, _rt_channelflags2)),
            lambda pkt: pkt.present and pkt.present.ChannelPlus),
        ConditionalField(LEShortField("ChannelFrequency", 0),
                         lambda pkt: pkt.present and pkt.present.ChannelPlus),
        ConditionalField(ByteField("ChannelNumber", 0),
                         lambda pkt: pkt.present and pkt.present.ChannelPlus),
        # MCS
        ConditionalField(
            _RadiotapReversePadField(
                FlagsField("knownMCS", None, -8, _rt_knownmcs)),
            lambda pkt: pkt.present and pkt.present.MCS),
        ConditionalField(BitField("Ness_LSB", 0, 1),
                         lambda pkt: pkt.present and pkt.present.MCS),
        ConditionalField(BitField("STBC_streams", 0, 2),
                         lambda pkt: pkt.present and pkt.present.MCS),
        ConditionalField(BitEnumField("FEC_type", 0, 1, {
            0: "BCC",
            1: "LDPC"
        }), lambda pkt: pkt.present and pkt.present.MCS),
        ConditionalField(
            BitEnumField("HT_format", 0, 1, {
                0: "mixed",
                1: "greenfield"
            }), lambda pkt: pkt.present and pkt.present.MCS),
        ConditionalField(
            BitEnumField("guard_interval", 0, 1, {
                0: "Long_GI",
                1: "Short_GI"
            }),  # noqa: E501
            lambda pkt: pkt.present and pkt.present.MCS),
        ConditionalField(BitEnumField("MCS_bandwidth", 0, 2, _rt_bandwidth),
                         lambda pkt: pkt.present and pkt.present.MCS),
        ConditionalField(ByteField("MCS_index", 0),
                         lambda pkt: pkt.present and pkt.present.MCS),
        # A_MPDU
        ConditionalField(_RadiotapReversePadField(LEIntField("A_MPDU_ref", 0)),
                         lambda pkt: pkt.present and pkt.present.A_MPDU),
        ConditionalField(
            FlagsField("A_MPDU_flags", None, -32, _rt_a_mpdu_flags),
            lambda pkt: pkt.present and pkt.present.A_MPDU),
        # VHT
        ConditionalField(
            _RadiotapReversePadField(
                FlagsField("KnownVHT", None, -16, _rt_knownvht)),
            lambda pkt: pkt.present and pkt.present.VHT),
        ConditionalField(FlagsField("PresentVHT", None, -8, _rt_presentvht),
                         lambda pkt: pkt.present and pkt.present.VHT),
        ConditionalField(ByteEnumField("VHT_bandwidth", 0, _rt_vhtbandwidth),
                         lambda pkt: pkt.present and pkt.present.VHT),
        ConditionalField(StrFixedLenField("mcs_nss", 0, length=5),
                         lambda pkt: pkt.present and pkt.present.VHT),
        ConditionalField(ByteField("GroupID", 0),
                         lambda pkt: pkt.present and pkt.present.VHT),
        ConditionalField(ShortField("PartialAID", 0),
                         lambda pkt: pkt.present and pkt.present.VHT),
        # timestamp
        ConditionalField(_RadiotapReversePadField(LELongField("timestamp", 0)),
                         lambda pkt: pkt.present and pkt.present.timestamp),
        ConditionalField(LEShortField("ts_accuracy", 0),
                         lambda pkt: pkt.present and pkt.present.timestamp),
        ConditionalField(ByteField("ts_position", 0),
                         lambda pkt: pkt.present and pkt.present.timestamp),
        ConditionalField(ByteField("ts_flags", 0),
                         lambda pkt: pkt.present and pkt.present.timestamp),
        # HE - XXX not complete
        ConditionalField(_RadiotapReversePadField(ShortField("he_data1", 0)),
                         lambda pkt: pkt.present and pkt.present.HE),
        ConditionalField(ShortField("he_data2", 0),
                         lambda pkt: pkt.present and pkt.present.HE),
        ConditionalField(ShortField("he_data3", 0),
                         lambda pkt: pkt.present and pkt.present.HE),
        ConditionalField(ShortField("he_data4", 0),
                         lambda pkt: pkt.present and pkt.present.HE),
        ConditionalField(ShortField("he_data5", 0),
                         lambda pkt: pkt.present and pkt.present.HE),
        ConditionalField(ShortField("he_data6", 0),
                         lambda pkt: pkt.present and pkt.present.HE),
        # HE_MU
        ConditionalField(
            _RadiotapReversePadField(LEShortField("hemu_flags1", 0)),
            lambda pkt: pkt.present and pkt.present.HE_MU),
        ConditionalField(LEShortField("hemu_flags2", 0),
                         lambda pkt: pkt.present and pkt.present.HE_MU),
        ConditionalField(
            FieldListField("RU_channel1", [],
                           ByteField,
                           count_from=lambda x: 4),
            lambda pkt: pkt.present and pkt.present.HE_MU),
        ConditionalField(
            FieldListField("RU_channel2", [],
                           ByteField,
                           count_from=lambda x: 4),
            lambda pkt: pkt.present and pkt.present.HE_MU),
        # HE_MU_other_user
        ConditionalField(
            _RadiotapReversePadField(LEShortField("hemuou_per_user_1",
                                                  0x7fff)),
            lambda pkt: pkt.present and pkt.present.HE_MU_other_user),
        ConditionalField(
            LEShortField("hemuou_per_user_2", 0x003f),
            lambda pkt: pkt.present and pkt.present.HE_MU_other_user),
        ConditionalField(
            ByteField("hemuou_per_user_position", 0),
            lambda pkt: pkt.present and pkt.present.HE_MU_other_user),
        ConditionalField(
            FlagsField("hemuou_per_user_known", 0, -16,
                       _rt_hemuother_per_user_known),
            lambda pkt: pkt.present and pkt.present.HE_MU_other_user),
        # L_SIG
        ConditionalField(
            _RadiotapReversePadField(
                FlagsField("lsig_data1", 0, -16, ["rate", "length"])),
            lambda pkt: pkt.present and pkt.present.L_SIG),
        ConditionalField(BitField("lsig_length", 0, 12),
                         lambda pkt: pkt.present and pkt.present.L_SIG),
        ConditionalField(BitField("lsig_rate", 0, 4),
                         lambda pkt: pkt.present and pkt.present.L_SIG),
        # Remaining
        StrLenField(
            'notdecoded',
            "",
            length_from=lambda pkt: max(pkt.len - pkt._tmp_dissect_pos, 0))
    ]

    def guess_payload_class(self, payload):
        if self.present and self.present.Flags and self.Flags.FCS:
            return Dot11FCS
        return Dot11

    def post_build(self, p, pay):
        if self.len is None:
            p = p[:2] + struct.pack("!H", len(p))[::-1] + p[4:]
        return p + pay
Esempio n. 26
0
class NTLMSSPLE(Packet):
    name = 'NTLM Secure Service Provider'
    fields_desc = [
        StrFixedLenField('identifier', 'NTLMSSP', length=8),
        LEIntEnumField('messageType', 3, {3: 'NTLMSSP_AUTH'}),
        LEShortField('lanManagerLen', 0),
        LEShortField('lanManagerMax', 0),
        LEIntField('lanManagerOffset', 0),
        LEShortField('NTLMRepLen', 0),
        LEShortField('NTLMRepMax', 0),
        LEIntField('NTLMRepOffset', 0),
        LEShortField('domainNameLen', 0),
        LEShortField('domainNameMax', 0),
        LEIntField('domainNameOffset', 0),
        LEShortField('userNameLen', 0),
        LEShortField('userNameMax', 0),
        LEIntField('userNameOffset', 0),
        LEShortField('hostNameLen', 0),
        LEShortField('hostNameMax', 0),
        LEIntField('hostNameOffset', 0),
        LEShortField('sessionKeyLen', 0),
        LEShortField('sessionKeyMax', 0),
        LEIntField('sessionKeyOffset', 0),
        FlagsField('negociateFlags', 0, 32, _negociate_flags),
        ByteField('versionMajor', 0),
        ByteField('versionMinor', 0),
        LEShortField('buildNumber', 0),
        ByteField('reserved', 0),
        ShortField('reserved2', 0),
        ByteField('NTLMCurrentRevision', 0),
        StrFixedLenField('MIC', '', 16),
        StrLenField('domainName',
                    '',
                    length_from=lambda pkt: pkt.domainNameLen),
        StrLenField('userName', '', length_from=lambda pkt: pkt.userNameLen),
        StrLenField('hostName', '', length_from=lambda pkt: pkt.hostNameLen),
        StrLenField('lanManager',
                    '',
                    length_from=lambda pkt: pkt.lanManagerLen),
        StrFixedLenField('NTLMRep', '', length=16),
        ByteField('responseVersion', 0),
        ByteField('hiResponseVersion', 0),
        StrFixedLenField('Z', '', 6),
        LELongField('timestamp', 0),  # Time in nanosecond
        StrFixedLenField('clientChallenge', '', 8),
        LEIntField('Z', 0),
        PacketField('attribute1', None, AttributeNameLE),
        PacketField('attribute2', None, AttributeNameLE),
        PacketField('attribute3', None, AttributeNameLE),
        PacketField('attribute4', None, AttributeNameLE),
        PacketField('attribute5', None, AttributeNameLE),
        PacketField('attribute6', None, AttributeNameLE),
        PacketField('attribute7', None, AttributeNameLE),
        PacketField('attribute8', None, AttributeNameLE),
        PacketField('attribute9', None, AttributeNameLE),
        PacketField('attribute10', None, AttributeNameLE),
        LEIntField('Z', 0),
        LEIntField('padding', 0),
        StrLenField('sessionKey',
                    '',
                    length_from=lambda pkt: pkt.sessionKeyLen),
    ]

    def extract_padding(self, p):
        return b"", p
Esempio n. 27
0
class SAPCARArchiveFilev200Format(PacketNoPadded):
    """SAP CAR file information format

    This is ued to parse files inside a SAP CAR archive.
    """
    name = "SAP CAR Archive File 2.00"

    version = SAPCAR_VERSION_200
    is_filename_null_terminated = False

    fields_desc = [
        StrFixedLenField("type", SAPCAR_TYPE_FILE, 2),
        LEIntField("perm_mode", 0),
        LELongField("file_length_low", 0),
        LEIntField("file_length_high", 0),
        LELongField("timestamp", 0),
        LEIntField("code_page", 0),
        FieldLenField("user_info_length", 0, length_of="user_info", fmt="<H"),
        FieldLenField("filename_length", 0, length_of="filename", fmt="<H"),
        StrNullFixedLenField("filename", None, length_from=lambda x: x.filename_length,
                             null_terminated=lambda x: x.is_filename_null_terminated),
        StrFixedLenField("user_info", None, length_from=lambda x: x.user_info_length),
        ConditionalField(PacketListStopField("blocks", None, SAPCARCompressedBlockFormat, stop=sapcar_is_last_block),
                         lambda x: x.type == SAPCAR_TYPE_FILE and x.file_length > 0),
    ]

    @property
    def file_length(self):
        """Getter for the file length fields. It converts the two length fields (low and high) as provided in the
        archive file into a long long integer.
        """
        return (self.file_length_high * SIZE_FOUR_GB) + self.file_length_low

    @file_length.setter
    def file_length(self, file_length):
        """Setter for the file length fields. It splits the long long integer int on the two length fields (low and
        high) as required by the archive file.
        """
        self.file_length_low = file_length & 0xffffffff
        self.file_length_high = file_length >> 32

    def extract(self, fd):
        """Extracts the archive file and writes the extracted file to the provided file object. Returns the checksum
        obtained from the archive. If blocks are uncompressed, the file is directly extracted. If the blocks are
        compressed, each block is added to a buffer, skipping the length field, and decompression is performed after
        the block marked as end of data. Expected length and compression header is obtained from the first block and
        checksum from the end of data block.

        :param fd: file-like object to write the extracted file to
        :type fd: file

        :return: checksum
        :rtype: int

        :raise DecompressError: If there's a decompression error
        :raise SAPCARInvalidFileException: If the file is invalid
        """

        if self.file_length == 0:
            return 0

        compressed = ""
        checksum = 0
        exp_length = None

        remaining_length = self.file_length
        for block in self.blocks:
            # Process uncompressed block types
            if block.type in [SAPCAR_BLOCK_TYPE_UNCOMPRESSED, SAPCAR_BLOCK_TYPE_UNCOMPRESSED_LAST]:
                fd.write(block.compressed)
                remaining_length -= len(block.compressed)
            # Store compressed block types for later decompression
            elif block.type in [SAPCAR_BLOCK_TYPE_COMPRESSED, SAPCAR_BLOCK_TYPE_COMPRESSED_LAST]:
                # Add compressed block to a buffer, skipping the first 4 bytes of each block (uncompressed length)
                compressed += str(block.compressed)[4:]
                # If the expected length wasn't already set, do it
                if not exp_length:
                    exp_length = block.compressed.uncompress_length
            else:
                raise SAPCARInvalidFileException("Invalid block type found")

            # Check end of data block, performing decompression if needed
            if sapcar_is_last_block(block):
                checksum = block.checksum
                # If there was at least one compressed block that set the expected length, decompress it
                if exp_length:
                    (_, block_length, block_buffer) = decompress(str(compressed), exp_length)
                    if block_length != exp_length or not block_buffer:
                        raise DecompressError("Error decompressing block")
                    fd.write(block_buffer)
                break

        return checksum
Esempio n. 28
0
class NEGOEX_EXTENSION_VECTOR(Packet):
    fields_desc = [
        LELongField("ExtensionArrayOffset", 0),
        LEShortField("ExtensionCount", 0)
    ]