Beispiel #1
0
class _ESPPlain(Packet):
    """
    Internal class to represent unencrypted ESP packets.
    """
    name = 'ESP'

    fields_desc = [
        XIntField('spi', 0x0),
        IntField('seq', 0),

        StrField('iv', ''),
        PacketField('data', '', Raw),
        StrField('padding', ''),

        ByteField('padlen', 0),
        ByteEnumField('nh', 0, IP_PROTOS),
        StrField('icv', ''),
    ]

    def data_for_encryption(self):
        return raw(self.data) + self.padding + struct.pack("BB", self.padlen, self.nh)  # noqa: E501
Beispiel #2
0
class RTPSSubMessage_INFO_DST(EPacket):
    """
    0...2...........7...............15.............23...............31
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |   INFO_DST    |     flags     |      octetsToNextHeader       |
    +---------------+---------------+---------------+---------------+
    |                                                               |
    + GuidPrefix guidPrefix                                         +
    |                                                               |
    +---------------+---------------+---------------+---------------+
    """

    name = "RTPS INFO_DTS (0x0e)"
    endianness = ">"

    fields_desc = [
        XByteField("submessageId", 0x0E),
        XByteField("submessageFlags", 0),
        EField(ShortField("octetsToNextHeader", 0)),
        PacketField("guidPrefix", "", GUIDPrefixPacket),
    ]
Beispiel #3
0
class GetDescriptor(RequestDescriptor):
    fields_desc = [
        PacketField("bmRequestType", bmRequestType(), bmRequestType),
        ByteEnumField("bRequest", URBDefs.Request.GET_DESCRIPTOR,
                      URBDefs.Request.desc),
        ByteField("descriptor_index", 0),
        ByteEnumField(
            "bDescriptorType",
            USBDefs.DescriptorType.DEVICE_DESCRIPTOR,
            USBDefs.DescriptorType.desc,
        ),
        ShortEnumField("language_id", URBDefs.Language.NONE_SPECIFIED,
                       URBDefs.Language.desc),
        LEShortField("wLength", 0),
    ]

    def desc(self):
        return "GetDescriptor %s [sz:%u]" % (
            USBDefs.DescriptorType[self.bDescriptorType],
            self.wLength,
        )
Beispiel #4
0
class _ESPPlain(Packet):
    """
    Internal class to represent unencrypted ESP packets.
    """
    name = 'ESP'

    fields_desc = [
        XIntField('spi', 0x0),
        IntField('seq', 0),

        StrField('iv', ''),
        PacketField('data', '', Raw),
        StrField('padding', ''),

        ByteField('padlen', 0),
        ByteEnumField('nh', 0, IP_PROTOS),
        StrField('icv', ''),
    ]

    def data_for_encryption(self):
        return bytes(self.data) + self.padding + chr(self.padlen).encode('ascii') + chr(self.nh).encode('ascii')
Beispiel #5
0
class CEMI(Packet):
    name = "CEMI"
    fields_desc = [
        ByteEnumField("message_code", None, MESSAGE_CODES),
        MultipleTypeField(
            [(PacketField("cemi_data", LcEMI(),
                          LcEMI), lambda pkt: pkt.message_code == 0x11),
             (PacketField("cemi_data", LcEMI(),
                          LcEMI), lambda pkt: pkt.message_code == 0x2e),
             (PacketField("cemi_data", DPcEMI(),
                          DPcEMI), lambda pkt: pkt.message_code == 0xFC),
             (PacketField("cemi_data", DPcEMI(),
                          DPcEMI), lambda pkt: pkt.message_code == 0xFB),
             (PacketField("cemi_data", DPcEMI(),
                          DPcEMI), lambda pkt: pkt.message_code == 0xF6),
             (PacketField("cemi_data", DPcEMI(),
                          DPcEMI), lambda pkt: pkt.message_code == 0xF5)],
            PacketField("cemi_data", LcEMI(), LcEMI))
    ]
Beispiel #6
0
class FlowTableEntryMatchParam(Packet):
    fields_desc = [
        PacketField('outer_headers', FlowTableEntryMatchSetLyr24(),
                    FlowTableEntryMatchSetLyr24),
        PacketField('misc_parameters', FlowTableEntryMatchSetMisc(),
                    FlowTableEntryMatchSetMisc),
        PacketField('inner_headers', FlowTableEntryMatchSetLyr24(),
                    FlowTableEntryMatchSetLyr24),
        PacketField('misc_parameters_2', FlowTableEntryMatchSetMisc2(),
                    FlowTableEntryMatchSetMisc2),
        PacketField('misc_parameters_3', FlowTableEntryMatchSetMisc3(),
                    FlowTableEntryMatchSetMisc3),
        PacketField('misc_parameters_4', FlowTableEntryMatchSetMisc4(),
                    FlowTableEntryMatchSetMisc4),
        PacketField('misc_parameters_5', FlowTableEntryMatchSetMisc5(),
                    FlowTableEntryMatchSetMisc5),
        # Keep reserved commented out since SW steering checks the size with
        # supported fields only.
        # StrFixedLenField('reserved1', None, length=128),
    ]
Beispiel #7
0
class CreateQpIn(Packet):
    fields_desc = [
        ShortField('opcode', DevxOps.MLX5_CMD_OP_CREATE_QP),
        ShortField('uid', 0),
        ShortField('reserved1', 0),
        ShortField('op_mod', 0),
        ByteField('reserved2', 0),
        BitField('input_qpn', 0, 24),
        BitField('reserved3', 0, 1),
        BitField('cmd_on_behalf', 0, 1),
        BitField('reserved4', 0, 14),
        ShortField('vhca_id', 0),
        IntField('opt_param_mask', 0),
        StrFixedLenField('reserved5', None, length=4),
        PacketField('sw_qpc', SwQpc(), SwQpc),
        LongField('e_mtt_pointer_or_wq_umem_offset', 0),
        IntField('wq_umem_id', 0),
        BitField('wq_umem_valid', 0, 1),
        BitField('reserved6', 0, 31),
        PacketListField('pas', [SwPas() for x in range(0)], SwPas,
                        count_from=lambda pkt: 0),
    ]
Beispiel #8
0
class AV_PAIR(Packet):
    name = "NTLM AV Pair"
    fields_desc = [
        LEShortEnumField(
            'AvId', 0, {
                0x0000: "MsvAvEOL",
                0x0001: "MsvAvNbComputerName",
                0x0002: "MsvAvNbDomainName",
                0x0003: "MsvAvDnsComputerName",
                0x0004: "MsvAvDnsDomainName",
                0x0005: "MsvAvDnsTreeName",
                0x0006: "MsvAvFlags",
                0x0007: "MsvAvTimestamp",
                0x0008: "MsvAvSingleHost",
                0x0009: "MsvAvTargetName",
                0x000A: "MsvAvChannelBindings",
            }),
        FieldLenField('AvLen', None, length_of="Value", fmt="<H"),
        MultipleTypeField([
            (LEIntEnumField(
                'Value', 1, {
                    0x0001: "constrained",
                    0x0002: "MIC integrity",
                    0x0004: "SPN from untrusted source"
                }), lambda pkt: pkt.AvId == 0x0006),
            (UTCTimeField("Value",
                          None,
                          epoch=[1601, 1, 1, 0, 0, 0],
                          custom_scaling=1e7,
                          fmt="<Q"), lambda pkt: pkt.AvId == 0x0007),
            (PacketField('Value', Single_Host_Data(),
                         Single_Host_Data), lambda pkt: pkt.AvId == 0x0008),
            (XStrLenField('Value', b"", length_from=lambda pkt: pkt.AvLen),
             lambda pkt: pkt.AvId == 0x000A),
        ], StrLenFieldUtf16('Value', b"", length_from=lambda pkt: pkt.AvLen))
    ]

    def default_payload_class(self, payload):
        return conf.padding_layer
Beispiel #9
0
class MACsec(Packet):
    """representation of one MACsec frame"""
    name = '802.1AE'
    deprecated_fields = {
        'an': ("AN", "2.4.4"),
        'pn': ("PN", "2.4.4"),
        'sci': ("SCI", "2.4.4"),
        'shortlen': ("SL", "2.4.4"),
    }
    # 802.1AE-2018 - Section 9
    fields_desc = [
        # 802.1AE-2018 - Section 9.5
        BitField('Ver', 0, 1),
        BitField('ES', 0, 1),  # End Station
        BitField('SC', 0, 1),  # Secure Channel
        BitField('SCB', 0, 1),  # Single Copy Broadcast
        BitField('E', 0, 1),  # Encryption
        BitField('C', 0, 1),  # Changed Text
        BitField('AN', 0, 2),  # Association Number
        # 802.1AE-2018 - Section 9.7
        BitField('reserved', 0, 2),
        BitField('SL', 0, 6),  # Short Length
        # 802.1AE-2018 - Section 9.8
        IntField("PN", 1),  # Packet Number
        # 802.1AE-2018 - Section 9.9
        ConditionalField(PacketField("SCI", None, MACsecSCI),
                         lambda pkt: pkt.SC),
        # Off-spec. Used for conveniency (only present if passed manually)
        ConditionalField(XShortEnumField("type", None, ETHER_TYPES),
                         lambda pkt: "type" in pkt.fields)
    ]

    def mysummary(self):
        summary = self.sprintf("an=%MACsec.an%, pn=%MACsec.pn%")
        if self.SC:
            summary += self.sprintf(", sci=%MACsec.sci%")
        if self.type is not None:
            summary += self.sprintf(", %MACsec.type%")
        return summary
Beispiel #10
0
class READDIR_Reply(Packet):
    name = 'READDIR Reply'
    fields_desc = [
        IntEnumField('status', 0, nfsstat3),
        IntField('attributes_follow', 0),
        ConditionalField(PacketField('attributes', Fattr3(), Fattr3),
                         lambda pkt: pkt.attributes_follow == 1),
        ConditionalField(XLongField('verifier', 0),
                         lambda pkt: pkt.status == 0),
        ConditionalField(IntField('value_follows', 0),
                         lambda pkt: pkt.status == 0),
        ConditionalField(
            PacketListField(
                'files',
                None,
                cls=File_From_Dir,
                next_cls_cb=lambda pkt, lst, cur, remain: File_From_Dir
                if pkt.value_follows == 1 and
                (len(lst) == 0 or cur.value_follows == 1) and len(
                    remain) > 4 else None), lambda pkt: pkt.status == 0),
        ConditionalField(IntField('eof', 0), lambda pkt: pkt.status == 0)
    ]
class Dot11EltMicrosoftWPA(Dot11Elt):
    name = "802.11 Microsoft WPA"
    fields_desc = [
        ByteField("ID", 221),
        ByteField("len", None),
        X3BytesField("oui", 0x0050f2),
        XByteField("type", 0x01),
        LEShortField("version", 1),
        PacketField("group_cipher_suite", RSNCipherSuite(), RSNCipherSuite),
        LEFieldLenField("nb_pairwise_cipher_suites",
                        1,
                        count_of="pairwise_cipher_suites"),
        PacketListField("pairwise_cipher_suites",
                        RSNCipherSuite(),
                        RSNCipherSuite,
                        count_from=lambda p: p.nb_pairwise_cipher_suites),
        LEFieldLenField("nb_akm_suites", 1, count_of="akm_suites"),
        PacketListField("akm_suites",
                        AKMSuite(),
                        AKMSuite,
                        count_from=lambda p: p.nb_akm_suites)
    ]
Beispiel #12
0
class SMB2_Session_Setup_Response(Packet):
    name = "SMB2 Session Setup Response"
    OFFSET = 8 + 64
    fields_desc = [
        XLEShortField("StructureSize", 0),
        FlagsField("SessionFlags", 0, -16, {
            0x0001: "IS_GUEST",
            0x0002: "IS_NULL",
            0x0004: "ENCRYPT_DATE",
        }),
        XLEShortField("SecurityBufferOffset", None),
        FieldLenField("SecurityLen", None, fmt="<H", length_of="Security"),
        _NTLMPayloadField('Buffer', OFFSET, [
            PacketField("Security", None, GSSAPI_BLOB),
        ])
    ]

    def post_build(self, pkt, pay):
        # type: (bytes, bytes) -> bytes
        return _SMB2_post_build(self, pkt, self.OFFSET, {
            "Security": 4,
        }) + pay
Beispiel #13
0
class OFPTFlowRemoved(_ofp_header):
    name = "OFPT_FLOW_REMOVED"
    fields_desc = [
        ByteEnumField("version", 0x01, ofp_version),
        ByteEnumField("type", 11, ofp_type),
        ShortField("len", None),
        IntField("xid", 0),
        PacketField("match", OFPMatch(), OFPMatch),
        LongField("cookie", 0),
        ShortField("priority", 0),
        ByteEnumField("reason", 0, {
            0: "OFPRR_IDLE_TIMEOUT",
            1: "OFPRR_HARD_TIMEOUT",
            2: "OFPRR_DELETE"
        }),
        XByteField("pad1", 0),
        IntField("duration_sec", 0),
        IntField("duration_nsec", 0),
        ShortField("idle_timeout", 0),
        XShortField("pad2", 0),
        LongField("packet_count", 0),
        LongField("byte_count", 0)
    ]
Beispiel #14
0
class FSINFO_Reply(Packet):
    name = 'FSINFO Reply'
    fields_desc = [
        IntEnumField('status', 0, nfsstat3),
        IntField('attributes_follow', 0),
        ConditionalField(PacketField('attributes', Fattr3(), Fattr3),
                         lambda pkt: pkt.attributes_follow == 1),
        ConditionalField(IntField('rtmax', 0), lambda pkt: pkt.status == 0),
        ConditionalField(IntField('rtpref', 0), lambda pkt: pkt.status == 0),
        ConditionalField(IntField('rtmult', 0), lambda pkt: pkt.status == 0),
        ConditionalField(IntField('wtmax', 0), lambda pkt: pkt.status == 0),
        ConditionalField(IntField('wtpref', 0), lambda pkt: pkt.status == 0),
        ConditionalField(IntField('wtmult', 0), lambda pkt: pkt.status == 0),
        ConditionalField(IntField('dtpref', 0), lambda pkt: pkt.status == 0),
        ConditionalField(LongField('maxfilesize', 0),
                         lambda pkt: pkt.status == 0),
        ConditionalField(IntField('timedelta_s', 0),
                         lambda pkt: pkt.status == 0),
        ConditionalField(IntField('timedelta_ns', 0),
                         lambda pkt: pkt.status == 0),
        ConditionalField(XIntField('properties', 0),
                         lambda pkt: pkt.status == 0),
    ]
Beispiel #15
0
class Dot15d4Data(Packet):
    name = "802.15.4 Data"
    fields_desc = [
        XLEShortField("dest_panid", 0xFFFF),
        dot15d4AddressField("dest_addr", 0xFFFF, length_of="fcf_destaddrmode"),
        ConditionalField(XLEShortField("src_panid", 0x0),
                         lambda pkt:util_srcpanid_present(pkt)),
        ConditionalField(dot15d4AddressField("src_addr", None, length_of="fcf_srcaddrmode"),  # noqa: E501
                         lambda pkt:pkt.underlayer.getfieldval("fcf_srcaddrmode") != 0),  # noqa: E501
        # Security field present if fcf_security == True
        ConditionalField(PacketField("aux_sec_header", Dot15d4AuxSecurityHeader(), Dot15d4AuxSecurityHeader),  # noqa: E501
                         lambda pkt:pkt.underlayer.getfieldval("fcf_security") is True),  # noqa: E501
    ]

    def guess_payload_class(self, payload):
        # TODO: See how it's done in wireshark:
        # https://github.com/wireshark/wireshark/blob/93c60b3b7c801dddd11d8c7f2a0ea4b7d02d700a/epan/dissectors/packet-ieee802154.c#L2061  # noqa: E501
        # it's too magic to me
        from scapy.layers.sixlowpan import SixLoWPAN
        from scapy.layers.zigbee import ZigbeeNWK
        if conf.dot15d4_protocol == "sixlowpan":
            return SixLoWPAN
        elif conf.dot15d4_protocol == "zigbee":
            return ZigbeeNWK
        else:
            if conf.dot15d4_protocol is None:
                _msg = "Please set conf.dot15d4_protocol to select a " + \
                       "802.15.4 protocol. Values must be in the list: "
            else:
                _msg = "Unknown conf.dot15d4_protocol value: must be in "
            warning(_msg +
                    "['sixlowpan', 'zigbee']" +
                    " Defaulting to SixLoWPAN")
            return SixLoWPAN

    def mysummary(self):
        return self.sprintf("802.15.4 Data ( %Dot15d4Data.src_panid%:%Dot15d4Data.src_addr% -> %Dot15d4Data.dest_panid%:%Dot15d4Data.dest_addr% )")  # noqa: E501
Beispiel #16
0
class MKABasicParamSet(Packet):
    """
    Basic Parameter Set (802.1X-2010, section 11.11).
    """

    #########################################################################
    #
    # IEEE 802.1X-2010 standard
    # Section 11.11
    #########################################################################
    #

    name = "Basic Parameter Set"
    fields_desc = [
        ByteField("mka_version_id", 0),
        ByteField("key_server_priority", 0),
        BitField("key_server", 0, 1),
        BitField("macsec_desired", 0, 1),
        BitField("macsec_capability", 0, 2),
        BitField("param_set_body_len", 0, 12),
        PacketField("SCI", MACsecSCI(), MACsecSCI),
        XStrFixedLenField("actor_member_id", "", length=12),
        XIntField("actor_message_number", 0),
        XIntField("algorithm_agility", 0),
        PadField(
            XStrLenField(
                "cak_name",
                "",
                length_from=lambda pkt: (pkt.param_set_body_len - 28)
            ),
            4,
            padwith=b"\x00"
        )
    ]

    def extract_padding(self, s):
        return "", s
Beispiel #17
0
class SMB2_Negotiate_Protocol_Request(Packet):
    name = "SMB2 Negotiate Protocol Request"
    fields_desc = [
        XLEShortField("StructureSize", 0),
        FieldLenField("DialectCount", None, fmt="<H", count_of="Dialects"),
        # SecurityMode
        FlagsField(
            "SecurityMode", 0, -16, {
                0x01: "SMB2_NEGOTIATE_SIGNING_ENABLED",
                0x02: "SMB2_NEGOTIATE_SIGNING_REQUIRED",
            }),
        LEShortField("Reserved", 0),
        # Capabilities
        FlagsField("Capabilities", 0, -32, SMB2_CAPABILITIES),
        UUIDField("ClientGUID", 0x0, uuid_fmt=UUIDField.FORMAT_LE),
        # XXX TODO If we ever want to properly dissect the offsets, we have
        # a _NTLMPayloadField in scapy/layers/ntlm.py that does precisely that
        XLEIntField("NegotiateContextOffset", 0x0),
        FieldLenField("NegotiateCount",
                      None,
                      fmt="<H",
                      count_of="NegotiateContexts"),
        ShortField("Reserved2", 0),
        FieldListField("Dialects", [0x0202],
                       LEShortEnumField("", 0x0, SMB_DIALECTS),
                       count_from=lambda pkt: pkt.DialectCount),
        # Field only exists if Dialects contains 0x0311
        # Each negotiate context must be 8-byte aligned
        ConditionalField(
            FieldListField("NegotiateContexts", [],
                           ReversePadField(
                               PacketField("Context", None,
                                           SMB2_Negotiate_Context), 8),
                           count_from=lambda pkt: pkt.NegotiateCount),
            lambda x: 0x0311 in x.Dialects),
    ]
Beispiel #18
0
class MACsec(Packet):
    """representation of one MACsec frame"""
    name = '802.1AE'
    fields_desc = [BitField('Ver', 0, 1),
                   BitField('ES', 0, 1),
                   BitField('SC', 0, 1),
                   BitField('SCB', 0, 1),
                   BitField('E', 0, 1),
                   BitField('C', 0, 1),
                   BitField('an', 0, 2),
                   BitField('reserved', 0, 2),
                   BitField('shortlen', 0, 6),
                   IntField("pn", 1),
                   ConditionalField(PacketField("sci", None, MACsecSCI), lambda pkt: pkt.SC),  # noqa: E501
                   ConditionalField(XShortEnumField("type", None, ETHER_TYPES),
                                    lambda pkt: pkt.type is not None)]

    def mysummary(self):
        summary = self.sprintf("an=%MACsec.an%, pn=%MACsec.pn%")
        if self.SC:
            summary += self.sprintf(", sci=%MACsec.sci%")
        if self.type is not None:
            summary += self.sprintf(", %MACsec.type%")
        return summary
Beispiel #19
0
class SMB2_Session_Setup_Request(Packet):
    name = "SMB2 Session Setup Request"
    OFFSET = 16 + 64
    fields_desc = [
        XLEShortField("StructureSize", 0),
        FlagsField("Flags", 0, -8, ["SMB2_SESSION_FLAG_BINDING"]),
        FlagsField("SecurityMode", 0, -8, {
            0x1: "Signing Required",
            0x2: "Signing Enabled",
        }),
        FlagsField("Capabilities", 0, -32, SMB2_CAPABILITIES),
        LEIntField("Channel", 0),
        XLEShortField("SecurityBufferOffset", None),
        FieldLenField("SecurityLen", None, fmt="<H", length_of="Security"),
        _NTLMPayloadField('Buffer', OFFSET, [
            PacketField("Security", None, GSSAPI_BLOB),
        ])
    ]

    def post_build(self, pkt, pay):
        # type: (bytes, bytes) -> bytes
        return _SMB2_post_build(self, pkt, self.OFFSET, {
            "Security": 12,
        }) + pay
Beispiel #20
0
class OFPTFlowMod(_ofp_header):
    name = "OFPT_FLOW_MOD"
    fields_desc = [ByteEnumField("version", 0x01, ofp_version),
                   ByteEnumField("type", 14, ofp_type),
                   ShortField("len", None),
                   IntField("xid", 0),
                   PacketField("match", OFPMatch(), OFPMatch),
                   LongField("cookie", 0),
                   ShortEnumField("cmd", 0, {0: "OFPFC_ADD",
                                             1: "OFPFC_MODIFY",
                                             2: "OFPFC_MODIFY_STRICT",
                                             3: "OFPFC_DELETE",
                                             4: "OFPFC_DELETE_STRICT"}),
                   ShortField("idle_timeout", 0),
                   ShortField("hard_timeout", 0),
                   ShortField("priority", 0),
                   IntEnumField("buffer_id", "NO_BUFFER", ofp_buffer),
                   ShortEnumField("out_port", "NONE", ofp_port_no),
                   FlagsField("flags", 0, 16, ["SEND_FLOW_REM",
                                               "CHECK_OVERLAP",
                                               "EMERG"]),
                   PacketListField("actions", [], OFPAT,
                                   ofp_action_cls,
                                   length_from=lambda pkt:pkt.len - 72)]
Beispiel #21
0
class ServerECDHExplicitPrimeParams(_GenericTLSSessionInheritance):
    """
    We provide parsing abilities for ExplicitPrimeParams, but there is no
    support from the cryptography library, hence no context operations.
    """
    name = "Server ECDH parameters - Explicit Prime"
    fields_desc = [ByteEnumField("curve_type", 1, _tls_ec_curve_types),
                   FieldLenField("plen", None, length_of="p", fmt="B"),
                   StrLenField("p", "", length_from=lambda pkt: pkt.plen),
                   PacketField("curve", None, ECCurvePkt),
                   FieldLenField("baselen", None, length_of="base", fmt="B"),
                   StrLenField("base", "",
                               length_from=lambda pkt: pkt.baselen),
                   FieldLenField("orderlen", None,
                                 length_of="order", fmt="B"),
                   StrLenField("order", "",
                               length_from=lambda pkt: pkt.orderlen),
                   FieldLenField("cofactorlen", None,
                                 length_of="cofactor", fmt="B"),
                   StrLenField("cofactor", "",
                               length_from=lambda pkt: pkt.cofactorlen),
                   FieldLenField("pointlen", None,
                                 length_of="point", fmt="B"),
                   StrLenField("point", "",
                               length_from=lambda pkt: pkt.pointlen)]

    def fill_missing(self):
        """
        Note that if it is not set by the user, the cofactor will always
        be 1. It is true for most, but not all, TLS elliptic curves.
        """
        if self.curve_type is None:
            self.curve_type = _tls_ec_curve_types["explicit_prime"]

    def guess_payload_class(self, p):
        return Padding
Beispiel #22
0
class OmciFrame(Packet):
    name = "OmciFrame"
    fields_desc = [
        ShortField("transaction_id", 0),
        ByteField("message_type", None),
        ByteField("omci", 0x0a),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciCreate),
                          align=36),
            lambda pkt: pkt.message_type == OmciCreate.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciCreateResponse),
                          align=36),
            lambda pkt: pkt.message_type == OmciCreateResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciDelete),
                          align=36),
            lambda pkt: pkt.message_type == OmciDelete.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciDeleteResponse),
                          align=36),
            lambda pkt: pkt.message_type == OmciDeleteResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciSet),
                          align=36),
            lambda pkt: pkt.message_type == OmciSet.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciSetResponse),
                          align=36),
            lambda pkt: pkt.message_type == OmciSetResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciGet),
                          align=36),
            lambda pkt: pkt.message_type == OmciGet.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciGetResponse),
                          align=36),
            lambda pkt: pkt.message_type == OmciGetResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciGetAllAlarms),
                          align=36),
            lambda pkt: pkt.message_type == OmciGetAllAlarms.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciGetAllAlarmsResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciGetAllAlarmsResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciGetAllAlarmsNext),
                          align=36),
            lambda pkt: pkt.message_type == OmciGetAllAlarmsNext.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciGetAllAlarmsNextResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciGetAllAlarmsNextResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciMibUpload),
                          align=36),
            lambda pkt: pkt.message_type == OmciMibUpload.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciMibUploadResponse),
                          align=36),
            lambda pkt: pkt.message_type == OmciMibUploadResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciMibUploadNext),
                          align=36),
            lambda pkt: pkt.message_type == OmciMibUploadNext.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciMibUploadNextResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciMibUploadNextResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciMibReset),
                          align=36),
            lambda pkt: pkt.message_type == OmciMibReset.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciMibResetResponse),
                          align=36),
            lambda pkt: pkt.message_type == OmciMibResetResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciAlarmNotification),
                          align=36),
            lambda pkt: pkt.message_type == OmciAlarmNotification.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciAttributeValueChange),
                          align=36), lambda pkt: pkt.message_type ==
            OmciAttributeValueChange.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciTestResult),
                          align=36),
            lambda pkt: pkt.message_type == OmciTestResult.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciReboot),
                          align=36),
            lambda pkt: pkt.message_type == OmciReboot.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciRebootResponse),
                          align=36),
            lambda pkt: pkt.message_type == OmciRebootResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciGetNext),
                          align=36),
            lambda pkt: pkt.message_type == OmciGetNext.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciGetNextResponse),
                          align=36),
            lambda pkt: pkt.message_type == OmciGetNextResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciSynchronizeTime),
                          align=36),
            lambda pkt: pkt.message_type == OmciSynchronizeTime.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciSynchronizeTimeResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciSynchronizeTimeResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciGetCurrentData),
                          align=36),
            lambda pkt: pkt.message_type == OmciGetCurrentData.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciGetCurrentDataResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciGetCurrentDataResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciStartSoftwareDownload),
                          align=36), lambda pkt: pkt.message_type ==
            OmciStartSoftwareDownload.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciStartSoftwareDownloadResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciStartSoftwareDownloadResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciDownloadSection),
                          align=36),
            lambda pkt: pkt.message_type == OmciDownloadSection.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciDownloadSectionLast),
                          align=36), lambda pkt: pkt.message_type ==
            OmciDownloadSectionLast.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciDownloadSectionResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciDownloadSectionResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciEndSoftwareDownload),
                          align=36), lambda pkt: pkt.message_type ==
            OmciEndSoftwareDownload.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciEndSoftwareDownloadResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciEndSoftwareDownloadResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciActivateImage),
                          align=36),
            lambda pkt: pkt.message_type == OmciActivateImage.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciActivateImageResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciActivateImageResponse.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None, OmciCommitImage),
                          align=36),
            lambda pkt: pkt.message_type == OmciCommitImage.message_id),
        ConditionalField(
            FixedLenField(PacketField("omci_message", None,
                                      OmciCommitImageResponse),
                          align=36), lambda pkt: pkt.message_type ==
            OmciCommitImageResponse.message_id),

        # TODO add entries for remaining OMCI message types
        IntField("omci_trailer", 0x00000028)
    ]

    # We needed to patch the do_dissect(...) method of Packet, because
    # it wiped out already dissected conditional fields with None if they
    # referred to the same field name. We marked the only new line of code
    # with "Extra condition added".
    def do_dissect(self, s):
        raw = s
        self.raw_packet_cache_fields = {}
        for f in self.fields_desc:
            if not s:
                break
            s, fval = f.getfield(self, s)
            # We need to track fields with mutable values to discard
            # .raw_packet_cache when needed.
            if f.islist or f.holds_packets:
                self.raw_packet_cache_fields[f.name] = f.do_copy(fval)
            # Extra condition added
            if fval is not None or f.name not in self.fields:
                self.fields[f.name] = fval
        assert (raw.endswith(s))
        self.raw_packet_cache = raw[:-len(s)] if s else raw
        self.explicit = 1
        return s
Beispiel #23
0
 def __init__(self, name, default, length_from=None, remain=0):
     self.length_from = length_from
     PacketField.__init__(self, name, default, None, remain=remain)
Beispiel #24
0
class GMLAN_RFRDPR_RFRP(Packet):
    name = 'ReadFailureRecordDataPositiveResponse_readFailureRecordParameters'
    fields_desc = [PacketField("dtc", b'', GMLAN_DTC)]
Beispiel #25
0
class ECDSAPrivateKey_OpenSSL(Packet):
    name = "ECDSA Params + Private Key"
    fields_desc = [
        _PacketFieldRaw("ecparam", ECParameters(), ECParameters),
        PacketField("privateKey", ECDSAPrivateKey(), ECDSAPrivateKey)
    ]
Beispiel #26
0
class LinkADRAns(Packet):
    name = "LinkADRAns"
    fields_desc = [
        PacketField("status", LinkADRAns_Status(), LinkADRAns_Status)
    ]
Beispiel #27
0
 def __init__(self, name, default, length_from=None, **kargs):
     self.length_from = length_from
     PacketField.__init__(self, name, default, Ticket, **kargs)
Beispiel #28
0
class TLS_Ext_KeyShare_SH(TLS_Ext_Unknown):
    name = "TLS Extension - Key Share (for ServerHello)"
    fields_desc = [
        ShortEnumField("type", 0x33, _tls_ext),
        ShortField("len", None),
        PacketField("server_share", None, KeyShareEntry)
    ]

    def post_build(self, pkt, pay):
        if not self.tls_session.frozen and self.server_share.privkey:
            # if there is a privkey, we assume the crypto library is ok
            privshare = self.tls_session.tls13_server_privshare
            if len(privshare) > 0:
                pkt_info = pkt.firstlayer().summary()
                log_runtime.info(
                    "TLS: overwriting previous server key share [%s]",
                    pkt_info)  # noqa: E501
            group_name = _tls_named_groups[self.server_share.group]
            privshare[group_name] = self.server_share.privkey

            if group_name in self.tls_session.tls13_client_pubshares:
                privkey = self.server_share.privkey
                pubkey = self.tls_session.tls13_client_pubshares[group_name]
                if group_name in six.itervalues(_tls_named_ffdh_groups):
                    pms = privkey.exchange(pubkey)
                elif group_name in six.itervalues(_tls_named_curves):
                    if group_name == "x25519":
                        pms = privkey.exchange(pubkey)
                    else:
                        pms = privkey.exchange(ec.ECDH(), pubkey)
                self.tls_session.tls13_dhe_secret = pms
        return super(TLS_Ext_KeyShare_SH, self).post_build(pkt, pay)

    def post_dissection(self, r):
        if not self.tls_session.frozen and self.server_share.pubkey:
            # if there is a pubkey, we assume the crypto library is ok
            pubshare = self.tls_session.tls13_server_pubshare
            if pubshare:
                pkt_info = r.firstlayer().summary()
                log_runtime.info(
                    "TLS: overwriting previous server key share [%s]",
                    pkt_info)  # noqa: E501
            group_name = _tls_named_groups[self.server_share.group]
            pubshare[group_name] = self.server_share.pubkey

            if group_name in self.tls_session.tls13_client_privshares:
                pubkey = self.server_share.pubkey
                privkey = self.tls_session.tls13_client_privshares[group_name]
                if group_name in six.itervalues(_tls_named_ffdh_groups):
                    pms = privkey.exchange(pubkey)
                elif group_name in six.itervalues(_tls_named_curves):
                    if group_name == "x25519":
                        pms = privkey.exchange(pubkey)
                    else:
                        pms = privkey.exchange(ec.ECDH(), pubkey)
                self.tls_session.tls13_dhe_secret = pms
            elif group_name in self.tls_session.tls13_server_privshare:
                pubkey = self.tls_session.tls13_client_pubshares[group_name]
                privkey = self.tls_session.tls13_server_privshare[group_name]
                if group_name in six.itervalues(_tls_named_ffdh_groups):
                    pms = privkey.exchange(pubkey)
                elif group_name in six.itervalues(_tls_named_curves):
                    if group_name == "x25519":
                        pms = privkey.exchange(pubkey)
                    else:
                        pms = privkey.exchange(ec.ECDH(), pubkey)
                self.tls_session.tls13_dhe_secret = pms
        return super(TLS_Ext_KeyShare_SH, self).post_dissection(r)
Beispiel #29
0
 def __init__(self, name, default, basis_type_from, clsdict):
     self.clsdict = clsdict
     self.basis_type_from = basis_type_from
     PacketField.__init__(self, name, default, None)
Beispiel #30
0
 def __init__(self, name, default, length_from=None):
     self.length_from = length_from
     PacketField.__init__(self, name, default, None)
Beispiel #31
0
class SAPRouter(Packet):
    """SAP Router packet

    This packet is used for general SAP Router packets. There are (at least)
    five types of SAP Router packets:

        1. Route packets. For requesting the routing of a connection to a
        remote hosts. The packet contains some general information and a
        connection string with a list of routing hops (:class:`SAPRouterRouteHop`).

        2. Administration packets. This packet is used for the SAP Router to
        send administrative commands. It's suppose to be used only from the
        hosts running the SAP Router or when an specific route is included in
        the routing table. Generally administration packets are not accepted
        from the external binding.

        3. Error Information packets. Packets sent when an error occurred.

        4. Control Message packets. Used to perform some control activities,
        like retrieving the current SAPRouter version or to perform the SNC
        handshake. They have the same structure that error information
        packets.

        5. Route accepted packet. Used to acknowledge a route request
        ("NI_PONG").


    Routed packets and some responses doesn't fill in these five packet
    types. For identifying those cases, you should check the type using the
    function :class:`router_is_known_type`.

    NI Versions found (unconfirmed):
        - 30: Release 40C
        - 36: Release <6.20
        - 38: Release 7.00/7.10
        - 39: Release 7.11
        - 40: Release 7.20/7.21
    """

    # Default router version to use
    SAPROUTER_DEFAULT_VERSION = 40

    # Constants for router types
    SAPROUTER_ROUTE = "NI_ROUTE"
    """ :cvar: Constant for route packets
        :type: C{string} """

    SAPROUTER_ADMIN = "ROUTER_ADM"
    """ :cvar: Constant for administration packets
        :type: C{string} """

    SAPROUTER_ERROR = "NI_RTERR"
    """ :cvar: Constant for error information packets
        :type: C{string} """

    SAPROUTER_CONTROL = "NI_RTERR"
    """ :cvar: Constant for control messages packets
        :type: C{string} """

    SAPROUTER_PONG = "NI_PONG"
    """ :cvar: Constant for route accepted packets
        :type: C{string} """

    router_type_values = [
        SAPROUTER_ADMIN,
        SAPROUTER_ERROR,
        SAPROUTER_CONTROL,
        SAPROUTER_ROUTE,
        SAPROUTER_PONG,
    ]
    """ :cvar: List of known packet types
        :type: ``list`` of C{string} """

    name = "SAP Router"
    fields_desc = [
        # General fields present in all SAP Router packets
        StrNullField("type", SAPROUTER_ROUTE),
        ConditionalField(
            ByteField("version", 2),
            lambda pkt: router_is_known_type(pkt) and not router_is_pong(pkt)),

        # Route packets
        ConditionalField(
            ByteField("route_ni_version", SAPROUTER_DEFAULT_VERSION),
            router_is_route),
        ConditionalField(ByteField("route_entries", 0), router_is_route),
        ConditionalField(
            ByteEnumKeysField("route_talk_mode", 0,
                              router_ni_talk_mode_values), router_is_route),
        ConditionalField(ShortField("route_padd", 0), router_is_route),
        ConditionalField(ByteField("route_rest_nodes", 0), router_is_route),
        ConditionalField(
            FieldLenField("route_length", 0, length_of="route_string",
                          fmt="I"), router_is_route),
        ConditionalField(IntField("route_offset", 0), router_is_route),
        ConditionalField(
            PacketListField("route_string",
                            None,
                            SAPRouterRouteHop,
                            length_from=lambda pkt: pkt.route_length),
            router_is_route),

        # Admin packets
        ConditionalField(
            ByteEnumKeysField("adm_command", 0x02, router_adm_commands),
            router_is_admin),
        ConditionalField(
            ShortField("adm_unused", 0x00), lambda pkt: router_is_admin(pkt)
            and pkt.adm_command not in [10, 11, 12, 13]),

        # Info Request fields
        ConditionalField(
            StrNullFixedLenField("adm_password", "", 19),
            lambda pkt: router_is_admin(pkt) and pkt.adm_command in [2]),

        # Cancel Route fields
        ConditionalField(
            FieldLenField("adm_client_count",
                          None,
                          count_of="adm_client_ids",
                          fmt="H"),
            lambda pkt: router_is_admin(pkt) and pkt.adm_command in [6]),
        # Trace Connection fields
        ConditionalField(
            FieldLenField("adm_client_count",
                          None,
                          count_of="adm_client_ids",
                          fmt="I"),
            lambda pkt: router_is_admin(pkt) and pkt.adm_command in [12, 13]),

        # Cancel Route or Trace Connection fields
        ConditionalField(
            FieldListField("adm_client_ids", [0x00],
                           IntField("", 0),
                           count_from=lambda pkt: pkt.adm_client_count), lambda
            pkt: router_is_admin(pkt) and pkt.adm_command in [6, 12, 13]),

        # Set/Clear Peer Trace fields  # TODO: Check whether this field should be a IPv6 address or another proper field
        ConditionalField(
            StrFixedLenField("adm_address_mask", "", 32),
            lambda pkt: router_is_admin(pkt) and pkt.adm_command in [10, 11]),

        # Error Information/Control Messages fields
        ConditionalField(
            ByteEnumKeysField("opcode", 0, router_control_opcodes),
            lambda pkt: router_is_error(pkt) or router_is_control(pkt)),
        ConditionalField(
            ByteField("opcode_padd", 0),
            lambda pkt: router_is_error(pkt) or router_is_control(pkt)),
        ConditionalField(
            SignedIntEnumField("return_code", 0, router_return_codes),
            lambda pkt: router_is_error(pkt) or router_is_control(pkt)),

        # Error Information fields
        ConditionalField(
            FieldLenField("err_text_length",
                          None,
                          length_of="err_text_value",
                          fmt="!I"),
            lambda pkt: router_is_error(pkt) and pkt.opcode == 0),
        ConditionalField(
            PacketField("err_text_value", SAPRouterError(),
                        SAPRouterError), lambda pkt: router_is_error(pkt) and
            pkt.opcode == 0 and pkt.err_text_length > 0),
        ConditionalField(IntField("err_text_unknown", 0),
                         lambda pkt: router_is_error(pkt) and pkt.opcode == 0),

        # Control Message fields
        ConditionalField(
            IntField("control_text_length", 0),
            lambda pkt: router_is_control(pkt) and pkt.opcode != 0),
        ConditionalField(
            StrField("control_text_value", "*ERR"),
            lambda pkt: router_is_control(pkt) and pkt.opcode != 0),

        # SNC Frame fields
        ConditionalField(
            PacketField("snc_frame", None, SAPSNCFrame),
            lambda pkt: router_is_control(pkt) and pkt.opcode in [70, 71])
    ]
Beispiel #32
0
 def __init__(self, name, default, basis_type_from, clsdict, remain=0):
     self.clsdict = clsdict
     self.basis_type_from = basis_type_from
     PacketField.__init__(self, name, default, None, remain=remain)
Beispiel #33
0
 def __init__(self, name, default, length_from=None, **kargs):
     self.length_from = length_from
     PacketField.__init__(self, name, default, Ticket, **kargs)
Beispiel #34
0
 def __init__(self, name, default, cls):
     PacketField.__init__(self, name, default, cls)