Beispiel #1
0
class Loopback(Packet):
    r"""\*BSD loopback layer"""

    name = "Loopback"
    if consts.OPENBSD:
        fields_desc = [IntEnumField("type", 0x2, LOOPBACK_TYPES)]
    else:
        fields_desc = [LoIntEnumField("type", 0x2, LOOPBACK_TYPES)]
    __slots__ = ["_defrag_pos"]


class Dot1AD(Dot1Q):
    name = '802_1AD'


bind_layers(Dot3, LLC)
bind_layers(Ether, LLC, type=122)
bind_layers(Ether, LLC, type=34928)
bind_layers(Ether, Dot1Q, type=33024)
bind_layers(Ether, Dot1AD, type=0x88a8)
bind_layers(Dot1AD, Dot1AD, type=0x88a8)
bind_layers(Dot1AD, Dot1Q, type=0x8100)
bind_layers(Dot1Q, Dot1AD, type=0x88a8)
bind_layers(Ether, Ether, type=1)
bind_layers(Ether, ARP, type=2054)
bind_layers(CookedLinux, LLC, proto=122)
bind_layers(CookedLinux, Dot1Q, proto=33024)
bind_layers(CookedLinux, Dot1AD, type=0x88a8)
bind_layers(CookedLinux, Ether, proto=1)
bind_layers(CookedLinux, ARP, proto=2054)
bind_layers(MPacketPreamble, Ether)
Beispiel #2
0
        if self.has_ifindex and self.ifindex is None:
            warning('has_ifindex set but ifindex is not set.')
        if self.has_ipaddr and self.afi is None:
            warning('has_ipaddr set but afi is not set.')
        if self.has_ipaddr and self.ip4 is None and self.ip6 is None:
            warning('has_ipaddr set but ip4 or ip6 is not set.')
        if self.has_ifname and self.ifname is None:
            warning('has_ifname set but ifname is not set.')
        if self.has_mtu and self.mtu is None:
            warning('has_mtu set but mtu is not set.')

        return ICMPExtensionObject.self_build(self, field_pos_list=field_pos_list)


# Add the post_dissection() method to the existing ICMPv4 and
# ICMPv6 error messages
scapy.layers.inet.ICMPerror.post_dissection = ICMPExtension_post_dissection
scapy.layers.inet.TCPerror.post_dissection = ICMPExtension_post_dissection
scapy.layers.inet.UDPerror.post_dissection = ICMPExtension_post_dissection

scapy.layers.inet6.ICMPv6DestUnreach.post_dissection = ICMPExtension_post_dissection
scapy.layers.inet6.ICMPv6TimeExceeded.post_dissection = ICMPExtension_post_dissection


# ICMPExtensionHeader looks at fields from the upper layer object when
# determining which upper layer to use.
bind_layers(ICMPExtensionHeader, ICMPExtensionMPLS,
            classnum=1, classtype=1)
bind_layers(ICMPExtensionHeader, ICMPExtensionInterfaceInformation, classnum=2)
Beispiel #3
0
        ShortField('reserved', None),
        XIntField('spi', 0x0),
        IntField('seq', 0),
        StrField('icv', None),
        StrField('padding', None),
    ]

    overload_fields = {
        IP: {'proto': socket.IPPROTO_AH},
        IPv6: {'nh': socket.IPPROTO_AH},
        IPv6ExtHdrHopByHop: {'nh': socket.IPPROTO_AH},
        IPv6ExtHdrDestOpt: {'nh': socket.IPPROTO_AH},
        IPv6ExtHdrRouting: {'nh': socket.IPPROTO_AH},
    }

bind_layers(IP, AH, proto=socket.IPPROTO_AH)
bind_layers(IPv6, AH, nh=socket.IPPROTO_AH)

#------------------------------------------------------------------------------
class ESP(Packet):
    """
    Encapsulated Security Payload

    See https://tools.ietf.org/rfc/rfc4303.txt
    """
    name = 'ESP'

    fields_desc = [
        XIntField('spi', 0x0),
        IntField('seq', 0),
        StrField('data', None),
Beispiel #4
0
    name = "IKEv2 Certificate"
    fields_desc = [
        ByteEnumField("next_payload", None, IKEv2_payload_type),
        ByteField("res", 0),
        FieldLenField("length", None, "cert_data", "H", adjust=lambda pkt, x: x + 5),  # noqa: E501
        ByteEnumField("cert_type", 0, IKEv2CertificateEncodings),
        StrLenField("cert_data", "", length_from=lambda x:x.length - 5),
    ]


IKEv2_payload_type_overload = {}
for i, payloadname in enumerate(IKEv2_payload_type):
    name = "IKEv2_payload_%s" % payloadname
    if name in globals():
        IKEv2_payload_type_overload[globals()[name]] = {"next_payload": i}

del i, payloadname, name
IKEv2_class._overload_fields = IKEv2_payload_type_overload.copy()

split_layers(UDP, ISAKMP, sport=500)
split_layers(UDP, ISAKMP, dport=500)

bind_layers(UDP, IKEv2, dport=500, sport=500)  # TODO: distinguish IKEv1/IKEv2
bind_layers(UDP, IKEv2, dport=4500, sport=4500)


def ikev2scan(ip, **kwargs):
    """Send a IKEv2 SA to an IP and wait for answers."""
    return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8),
                                         exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs)  # noqa: E501
Beispiel #5
0
                   X3BytesField("vni", 0),
                   XByteField("reserved2", 0x00),
                   GENEVEOptionsField("options", "")]

    def post_build(self, p, pay):
        p += pay
        optionlen = self.optionlen
        if optionlen is None:
            optionlen = (len(self.options) + 3) // 4
            p = chb(optionlen & 0x2f | orb(p[0]) & 0xc0) + p[1:]
        return p

    def answers(self, other):
        if isinstance(other, GENEVE):
            if ((self.proto == other.proto) and (self.vni == other.vni)):
                return self.payload.answers(other.payload)
        else:
            return self.payload.answers(other)
        return 0

    def mysummary(self):
        return self.sprintf("GENEVE (vni=%GENEVE.vni%,"
                            "optionlen=%GENEVE.optionlen%,"
                            "proto=%GENEVE.proto%)")


bind_layers(UDP, GENEVE, dport=6081)
bind_layers(GENEVE, Ether, proto=0x6558)
bind_layers(GENEVE, IP, proto=0x0800)
bind_layers(GENEVE, IPv6, proto=0x86dd)
Beispiel #6
0
        # Setting length of packet to obfuscate if not filled by user

        if self.length is None and pay:
            p = p[:-4] + struct.pack('!I', len(pay))

        if self.flags == 0:

            pay = obfuscate(pay, SECRET, self.session_id, self.version, self.seq)  # noqa: E501
            return p + pay

        return p

    def hashret(self):
        return struct.pack('I', self.session_id)

    def answers(self, other):
        return (isinstance(other, TacacsHeader) and
                self.seq == other.seq + 1 and
                self.type == other.type and
                self.session_id == other.session_id)


bind_layers(TCP, TacacsHeader, dport=49)
bind_layers(TCP, TacacsHeader, sport=49)
bind_layers(TacacsHeader, TacacsAuthenticationStart, type=1, dport=49)
bind_layers(TacacsHeader, TacacsAuthenticationReply, type=1, sport=49)

if __name__ == '__main__':
    from scapy.main import interact
    interact(mydict=globals(), mybanner='tacacs+')
Beispiel #7
0
    0x012E: "UnSubscribeDtmfPayloadErrMessage",
    0x012F: "ServiceURLStatMessage",
    0x0130: "CallSelectStatMessage",
    0x0131: "OpenMultiMediaChannelMessage",
    0x0132: "StartMultiMediaTransmission",
    0x0133: "StopMultiMediaTransmission",
    0x0134: "MiscellaneousCommandMessage",
    0x0135: "FlowControlCommandMessage",
    0x0136: "CloseMultiMediaReceiveChannel",
    0x0137: "CreateConferenceReqMessage",
    0x0138: "DeleteConferenceReqMessage",
    0x0139: "ModifyConferenceReqMessage",
    0x013A: "AddParticipantReqMessage",
    0x013B: "DropParticipantReqMessage",
    0x013C: "AuditConferenceReqMessage",
    0x013D: "AuditParticipantReqMessage",
    0x013F: "UserToDeviceDataVersion1Message",
}


class Skinny(Packet):
    name = "Skinny"
    fields_desc = [LEIntField("len", 0),
                   LEIntField("res", 0),
                   LEIntEnumField("msg", 0, skinny_messages)]


bind_layers(TCP, Skinny, dport=2000)
bind_layers(TCP, Skinny, sport=2000)
bind_layers(TCP, Skinny, dport=2000, sport=2000)
Beispiel #8
0
        :param method: HTTP request method to use
        :type method: ``string``

        :return: the HTTP request to send as raw
        :rtype: ``string``

        :raise ImportError: if the requests library can't be imported
        """
        if Request is None:
            raise ImportError("requests library not available")

        protocol = 'https' if tls else 'http'
        url = "%s://%s:%d/%s" % (protocol, host, port, interpreter
                                 )  # forge url
        # using PreparedRequest to retrieve the raw http request
        req = Request(method, url, files=files).prepare()
        # update User-Agent header
        req.headers['User-Agent'] = 'pysap'
        # format the request than could be send with SAP NI
        req_format = ('{}\r\n{}\r\n\r\n{}'.format(
            req.method + ' ' + req.url + ' HTTP/1.1',
            '\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
            req.body))
        return req_format


# Bind SAP NI with the IGS ports
bind_layers(TCP, SAPNI, dport=40000)
bind_layers(TCP, SAPNI, dport=40080)
Beispiel #9
0
        BitField("cos", 0, 3),
        BitField("s", 1, 1),
        ByteField("ttl", 0)
    ]

    def guess_payload_class(self, payload):
        if len(payload) >= 1:
            if not self.s:
                return MPLS
            ip_version = (orb(payload[0]) >> 4) & 0xF
            if ip_version == 4:
                return IP
            elif ip_version == 5:
                return BIER
            elif ip_version == 6:
                return IPv6
            else:
                if orb(payload[0]) == 0 and orb(payload[1]) == 0:
                    return EoMCW
                else:
                    return Ether
        return Padding


bind_layers(Ether, MPLS, type=0x8847)
bind_layers(UDP, MPLS, dport=6635)
bind_layers(GRE, MPLS, proto=0x8847)
bind_layers(MPLS, MPLS, s=0)
bind_layers(MPLS, EoMCW)
bind_layers(EoMCW, Ether, zero=0, reserved=0)
Beispiel #10
0
    ]


class MQTTUnsubscribe(Packet):
    name = "MQTT unsubscribe"
    fields_desc = [ShortField("msgid", None), StrNullField("payload", "")]


class MQTTUnsuback(Packet):
    name = "MQTT unsuback"
    fields_desc = [ShortField("msgid", None)]


# LAYERS BINDINGS

bind_layers(TCP, MQTT, sport=1883)
bind_layers(TCP, MQTT, dport=1883)
bind_layers(MQTT, MQTTConnect, type=1)
bind_layers(MQTT, MQTTConnack, type=2)
bind_layers(MQTT, MQTTPublish, type=3)
bind_layers(MQTT, MQTTPuback, type=4)
bind_layers(MQTT, MQTTPubrec, type=5)
bind_layers(MQTT, MQTTPubrel, type=6)
bind_layers(MQTT, MQTTPubcomp, type=7)
bind_layers(MQTT, MQTTSubscribe, type=8)
bind_layers(MQTT, MQTTSuback, type=9)
bind_layers(MQTT, MQTTUnsubscribe, type=10)
bind_layers(MQTT, MQTTUnsuback, type=11)
bind_layers(MQTTConnect, MQTT)
bind_layers(MQTTConnack, MQTT)
bind_layers(MQTTPublish, MQTT)
Beispiel #11
0
                # A
                (IPField("rdata", "0.0.0.0"), lambda pkt: pkt.type == 1),
                # AAAA
                (IP6Field("rdata", "::"), lambda pkt: pkt.type == 28),
                # NS, MD, MF, CNAME, PTR
                (DNSStrField("rdata", "", length_from=lambda pkt: pkt.rdlen),
                 lambda pkt: pkt.type in [2, 3, 4, 5, 12]),
                # TEXT
                (DNSTextField("rdata", [], length_from=lambda pkt: pkt.rdlen),
                 lambda pkt: pkt.type == 16),
            ],
            StrLenField("rdata", "", length_from=lambda pkt: pkt.rdlen))
    ]


bind_layers(UDP, DNS, dport=5353)
bind_layers(UDP, DNS, sport=5353)
bind_layers(UDP, DNS, dport=53)
bind_layers(UDP, DNS, sport=53)
DestIPField.bind_addr(UDP, "224.0.0.251", dport=5353)
DestIP6Field.bind_addr(UDP, "ff02::fb", dport=5353)
bind_layers(TCP, DNS, dport=53)
bind_layers(TCP, DNS, sport=53)


@conf.commands.register
def dyndns_add(nameserver, name, rdata, type="A", ttl=10):
    """Send a DNS add message to a nameserver for "name" to have a new "rdata"
dyndns_add(nameserver, name, rdata, type="A", ttl=10) -> result code (0=ok)

example: dyndns_add("ns1.toto.com", "dyn.toto.com", "127.0.0.1")
Beispiel #12
0
    def recv_send(self, local, remote, process):
        """Receives data from one socket connection, process it and send to the
        remote connection.

        :param local: the local socket
        :type local: :class:`SAPNIStreamSocket`

        :param remote: the remote socket
        :type remote: :class:`SAPNIStreamSocket`

        :param process: the function that process the incoming data
        :type process: function
        """
        # Receive a native packet (not SAP NI)
        packet = local.ins.recv(self.mtu)
        log_saprouter.debug("Received %d native bytes", len(packet))

        # Handle close connection
        if len(packet) == 0:
            local.close()
            raise SocketError((100, "Underlying stream socket tore down"))

        # Send the packet to the remote peer
        remote.ins.sendall(packet)
        log_saprouter.debug("Sent %d native bytes", len(packet))


# Bind SAP NI with the SAP Router port
bind_layers(TCP, SAPNI, dport=3299)
Beispiel #13
0
        ShortEnumField("ctrl_msg_type", 14, _PPTP_ctrl_msg_type),
        XShortField("reserved_0", 0x0000),
        ShortField("peer_call_id", 1),
        XShortField("reserved_1", 0x0000),
        IntField("crc_errors", 0),
        IntField("framing_errors", 0),
        IntField("hardware_overruns", 0),
        IntField("buffer_overruns", 0),
        IntField("time_out_errors", 0),
        IntField("alignment_errors", 0)
    ]


class PPTPSetLinkInfo(PPTP):
    name = "PPTP Set Link Info"
    fields_desc = [
        LenField("len", 24),
        ShortEnumField("type", 1, _PPTP_msg_type),
        XIntField("magic_cookie", _PPTP_MAGIC_COOKIE),
        ShortEnumField("ctrl_msg_type", 15, _PPTP_ctrl_msg_type),
        XShortField("reserved_0", 0x0000),
        ShortField("peer_call_id", 1),
        XShortField("reserved_1", 0x0000),
        XIntField("send_accm", 0x00000000),
        XIntField("receive_accm", 0x00000000)
    ]


bind_layers(TCP, PPTP, sport=1723)
bind_layers(TCP, PPTP, dport=1723)
Beispiel #14
0
                   XBitField("type", 0x0403, 15),
                   ShortField("len", None),
                   IntField("id", 0),
                   FecTLVField("fec", None),
                   LabelTLVField("label", 0)]

# 3.1. LDP PDUs


class LDP(_LDP_Packet):
    name = "LDP"
    fields_desc = [ShortField("version", 1),
                   ShortField("len", None),
                   IPField("id", "127.0.0.1"),
                   ShortField("space", 0)]

    def post_build(self, p, pay):
        pay = pay or b""
        if self.len is None:
            tmp_len = len(p) + len(pay) - 4
            p = p[:2] + struct.pack("!H", tmp_len) + p[4:]
        return p + pay


bind_bottom_up(TCP, LDP, sport=646)
bind_bottom_up(TCP, LDP, dport=646)
bind_bottom_up(TCP, UDP, sport=646)
bind_bottom_up(TCP, UDP, dport=646)
bind_layers(TCP, LDP, sport=646, dport=646)
bind_layers(UDP, LDP, sport=646, dport=646)
Beispiel #15
0
class GTPSupportedExtensionHeadersNotification(Packet):
    name = "GTP Supported Extension Headers Notification"
    fields_desc = [PacketListField("IE_list", [IE_ExtensionHeaderList(),
                                               ], IE_Dispatcher)]


class GTPmorethan1500(Packet):
    # 3GPP TS 29.060 V9.1.0 (2009-12)
    name = "GTP More than 1500"
    fields_desc = [ByteEnumField("IE_Cause", "Cause", IEType),
                   BitField("IE", 1, 12000), ]


# Bind GTP-C
bind_layers(UDP, GTPHeader, dport=2123)
bind_layers(UDP, GTPHeader, sport=2123)
bind_layers(GTPHeader, GTPEchoRequest, gtp_type=1, S=1)
bind_layers(GTPHeader, GTPEchoResponse, gtp_type=2, S=1)
bind_layers(GTPHeader, GTPCreatePDPContextRequest, gtp_type=16)
bind_layers(GTPHeader, GTPCreatePDPContextResponse, gtp_type=17)
bind_layers(GTPHeader, GTPUpdatePDPContextRequest, gtp_type=18)
bind_layers(GTPHeader, GTPUpdatePDPContextResponse, gtp_type=19)
bind_layers(GTPHeader, GTPDeletePDPContextRequest, gtp_type=20)
bind_layers(GTPHeader, GTPDeletePDPContextResponse, gtp_type=21)
bind_layers(GTPHeader, GTPPDUNotificationRequest, gtp_type=27)
bind_layers(GTPHeader, GTPSupportedExtensionHeadersNotification, gtp_type=31, S=1)  # noqa: E501
bind_layers(GTPHeader, GTP_UDPPort_ExtensionHeader, next_ex=64, E=1)
bind_layers(GTPHeader, GTP_PDCP_PDU_ExtensionHeader, next_ex=192, E=1)

# Bind GTP-U
Beispiel #16
0
    results = {}
    for p in packet_list:
        cls = None
        if LoWPANFragmentationFirst in p:
            cls = LoWPANFragmentationFirst
        elif LoWPANFragmentationSubsequent in p:
            cls = LoWPANFragmentationSubsequent
        if cls:
            tag = p[cls].datagramTag
            results[tag] = results.get(tag, b"") + raw(
                p[cls][LoWPAN_IPHC].payload)
    return {tag: IPv6(x) for tag, x in results.items()}


bind_layers(
    SixLoWPAN,
    LoWPANFragmentationFirst,
)
bind_layers(
    SixLoWPAN,
    LoWPANFragmentationSubsequent,
)
bind_layers(
    SixLoWPAN,
    LoWPANMesh,
)
bind_layers(
    SixLoWPAN,
    LoWPAN_IPHC,
)
bind_layers(
    LoWPANMesh,
Beispiel #17
0
                   ByteEnumField("descr", None, _tls_alert_description)]

    def post_dissection_tls_session_update(self, msg_str):
        pass

    def post_build_tls_session_update(self, msg_str):
        pass


###############################################################################
#   TLS Application Data                                                      #
###############################################################################

class TLSApplicationData(_GenericTLSSessionInheritance):
    name = "TLS Application Data"
    fields_desc = [StrField("data", "")]

    def post_dissection_tls_session_update(self, msg_str):
        pass

    def post_build_tls_session_update(self, msg_str):
        pass


###############################################################################
#   Bindings                                                                  #
###############################################################################

bind_layers(TCP, TLS, sport=443)
bind_layers(TCP, TLS, dport=443)
Beispiel #18
0
    0x012E: "UnSubscribeDtmfPayloadErrMessage",
    0x012F: "ServiceURLStatMessage",
    0x0130: "CallSelectStatMessage",
    0x0131: "OpenMultiMediaChannelMessage",
    0x0132: "StartMultiMediaTransmission",
    0x0133: "StopMultiMediaTransmission",
    0x0134: "MiscellaneousCommandMessage",
    0x0135: "FlowControlCommandMessage",
    0x0136: "CloseMultiMediaReceiveChannel",
    0x0137: "CreateConferenceReqMessage",
    0x0138: "DeleteConferenceReqMessage",
    0x0139: "ModifyConferenceReqMessage",
    0x013A: "AddParticipantReqMessage",
    0x013B: "DropParticipantReqMessage",
    0x013C: "AuditConferenceReqMessage",
    0x013D: "AuditParticipantReqMessage",
    0x013F: "UserToDeviceDataVersion1Message",
}


class Skinny(Packet):
    name = "Skinny"
    fields_desc = [LEIntField("len", 0),
                   LEIntField("res", 0),
                   LEIntEnumField("msg", 0, skinny_messages)]


bind_layers(TCP, Skinny, dport=2000)
bind_layers(TCP, Skinny, sport=2000)
bind_layers(TCP, Skinny, dport=2000, sport=2000)
Beispiel #19
0
class Read10(Packet):
    name = "Read(10) "
    fields_desc = [ XByteField("Reserved1", 0),
                    XIntField("LogicalBlockAddr", 0),
                    XByteField("Reserved2", 0),
                    ShortField("TransferLength", 1), # Number of blocks
                    XByteField("Control", 0) ]


class ReadTOC(Packet):
    name = "ReadTOC "
    fields_desc = [ ByteEnumField("MSF", 0, {0:"", 2:""}),
                    XByteField("Format-A", 0),
                    XByteField("Reserved1", 0),
                    XByteField("Reserved2", 0),
                    XByteField("Reserved3", 0),
                    XByteField("Reserved4", 0),
                    ShortField("AllocationLength", 12),
                    XByteField("Format-B", 0x40)]


bind_layers(SCSICmd, RequestSense, {"OperationCode":0x03})
bind_layers(SCSICmd, FormatUnit, {"OperationCode":0x04})
bind_layers(SCSICmd, Read6, {"OperationCode":0x0A})
bind_layers(SCSICmd, Inquiry, {"OperationCode":0x12})
bind_layers(SCSICmd, ReadCapacity10, {"OperationCode":0x25})
bind_layers(SCSICmd, Read10, {"OperationCode":0x28})
bind_layers(SCSICmd, ReadTOC, {"OperationCode":0x43})

Beispiel #20
0
        XByteField("reserved2", 0x00),
        GENEVEOptionsField("options", "")
    ]

    def post_build(self, p, pay):
        p += pay
        optionlen = self.optionlen
        if optionlen is None:
            optionlen = (len(self.options) + 3) // 4
            p = chb(optionlen & 0x2f | orb(p[0]) & 0xc0) + p[1:]
        return p

    def answers(self, other):
        if isinstance(other, GENEVE):
            if ((self.proto == other.proto) and (self.vni == other.vni)):
                return self.payload.answers(other.payload)
        else:
            return self.payload.answers(other)
        return 0

    def mysummary(self):
        return self.sprintf("GENEVE (vni=%GENEVE.vni%,"
                            "optionlen=%GENEVE.optionlen%,"
                            "proto=%GENEVE.proto%)")


bind_layers(UDP, GENEVE, dport=6081)
bind_layers(GENEVE, Ether, proto=0x6558)
bind_layers(GENEVE, IP, proto=0x0800)
bind_layers(GENEVE, IPv6, proto=0x86dd)
Beispiel #21
0
                  0x18: "IPv6", 0x1c: "IPv6", 0x1e: "IPv6"}


class Loopback(Packet):
    """*BSD loopback layer"""

    name = "Loopback"
    fields_desc = [LoIntEnumField("type", 0x2, LOOPBACK_TYPES)]
    __slots__ = ["_defrag_pos"]


class Dot1AD(Dot1Q):
    name = '802_1AD'


bind_layers(Dot3, LLC,)
bind_layers(Ether, LLC, type=122)
bind_layers(Ether, LLC, type=34928)
bind_layers(Ether, Dot1Q, type=33024)
bind_layers(Ether, Dot1AD, type=0x88a8)
bind_layers(Dot1AD, Dot1AD, type=0x88a8)
bind_layers(Dot1AD, Dot1Q, type=0x8100)
bind_layers(Dot1Q, Dot1AD, type=0x88a8)
bind_layers(Ether, Ether, type=1)
bind_layers(Ether, ARP, type=2054)
bind_layers(CookedLinux, LLC, proto=122)
bind_layers(CookedLinux, Dot1Q, proto=33024)
bind_layers(CookedLinux, Dot1AD, type=0x88a8)
bind_layers(CookedLinux, Ether, proto=1)
bind_layers(CookedLinux, ARP, proto=2054)
bind_layers(GRE, LLC, proto=122)
Beispiel #22
0
    def post_dissection_tls_session_update(self, msg_str):
        pass

    def post_build_tls_session_update(self, msg_str):
        pass


###############################################################################
#   TLS Application Data                                                      #
###############################################################################


class TLSApplicationData(_GenericTLSSessionInheritance):
    name = "TLS Application Data"
    fields_desc = [StrField("data", "")]

    def post_dissection_tls_session_update(self, msg_str):
        pass

    def post_build_tls_session_update(self, msg_str):
        pass


###############################################################################
#   Bindings                                                                  #
###############################################################################

bind_layers(TCP, TLS, sport=443)
bind_layers(TCP, TLS, dport=443)
Beispiel #23
0
class _ISIS_PSNP_Base(_ISIS_PduBase):
    fields_desc = [
        _ISIS_PduLengthField(),
        ISIS_NodeIdField("sourceid", "0102.0304.0506.00"),
        _ISIS_TlvListField()
    ]


class ISIS_L1_PSNP(_ISIS_PSNP_Base):
    name = "ISIS L1 Partial Sequence Number Packet"

    def answers(self, other):
        return _snp_answers(self, other, "ISIS_L1_LSP")


class ISIS_L2_PSNP(_ISIS_PSNP_Base):
    name = "ISIS L2 Partial Sequence Number Packet"

    def answers(self, other):
        return _snp_answers(self, other, "ISIS_L2_LSP")

register_cln_protocol(0x83, ISIS_CommonHdr)
bind_layers(ISIS_CommonHdr, ISIS_L1_LAN_Hello, hdrlen=27, pdutype=15)
bind_layers(ISIS_CommonHdr, ISIS_L2_LAN_Hello, hdrlen=27, pdutype=16)
bind_layers(ISIS_CommonHdr, ISIS_P2P_Hello, hdrlen=20, pdutype=17)
bind_layers(ISIS_CommonHdr, ISIS_L1_LSP, hdrlen=27, pdutype=18)
bind_layers(ISIS_CommonHdr, ISIS_L2_LSP, hdrlen=27, pdutype=20)
bind_layers(ISIS_CommonHdr, ISIS_L1_CSNP, hdrlen=33, pdutype=24)
bind_layers(ISIS_CommonHdr, ISIS_L2_CSNP, hdrlen=33, pdutype=25)
bind_layers(ISIS_CommonHdr, ISIS_L1_PSNP, hdrlen=17, pdutype=26)
bind_layers(ISIS_CommonHdr, ISIS_L2_PSNP, hdrlen=17, pdutype=27)
Beispiel #24
0
from scapy.sessions import IPSession, DefaultSession

from scapy.layers.inet import UDP
from scapy.layers.inet6 import IP6Field


class NetflowHeader(Packet):
    name = "Netflow Header"
    fields_desc = [ShortField("version", 1)]


for port in [2055, 2056, 9995, 9996, 6343]:  # Classic NetFlow ports
    bind_bottom_up(UDP, NetflowHeader, dport=port)
    bind_bottom_up(UDP, NetflowHeader, sport=port)
# However, we'll default to 2055, classic among classics :)
bind_layers(UDP, NetflowHeader, dport=2055, sport=2055)

###########################################
# Netflow Version 1
###########################################


class NetflowHeaderV1(Packet):
    name = "Netflow Header v1"
    fields_desc = [ShortField("count", 0),
                   IntField("sysUptime", 0),
                   UTCTimeField("unixSecs", 0),
                   UTCTimeField("unixNanoSeconds", 0, use_nano=True)]


class NetflowRecordV1(Packet):
Beispiel #25
0
    def guess_payload_class(self, payload):
        ''' Decides if the payload is an HTTP Request or Response, or
            something else '''
        try:
            prog = re.compile(
                r"^(?:OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT) "
                r"(?:.+?) "
                r"HTTP/\d\.\d$"
            )
            crlfIndex = payload.index("\r\n".encode())
            req = payload[:crlfIndex].decode("utf-8")
            result = prog.match(req)
            if result:
                return HTTPRequest
            else:
                prog = re.compile(r"^HTTP/\d\.\d \d\d\d .*$")
                result = prog.match(req)
                if result:
                    return HTTPResponse
        except:
            pass
        return Packet.guess_payload_class(self, payload)

bind_layers(TCP, HTTP, dport=80)
bind_layers(TCP, HTTP, sport=80)

#For Proxy
bind_layers(TCP, HTTP, sport=8080)
bind_layers(TCP, HTTP, dport=8080)
Beispiel #26
0
        ConditionalField(
            cond=lambda p: p.getfieldval("F_Block_ID") & 0b110 == 0b010,
            fld=ShortField("F_WD_Time_2", 0)),
        ConditionalField(
            cond=lambda p: p.getfieldval("F_Block_ID") & 0b101 == 0b001,
            fld=XIntField("F_iPar_CRC", 0)),
        XShortField("F_Par_CRC", 0)
    ]
    overload_fields = {
        IODWriteReq: {
            "index": 0x100,  # commonly used index for F-Parameters block
        }
    }


bind_layers(IODWriteReq, FParametersBlock, index=0x0100)
bind_layers(FParametersBlock, conf.padding_layer)


#     IODWriteMultipleRe{q,s}
class PadFieldWithLen(PadField):
    """PadField which handles the i2len function to include padding"""
    def i2len(self, pkt, val):
        """get the length of the field, including the padding length"""
        fld_len = self.fld.i2len(pkt, val)
        return fld_len + self.padlen(fld_len)


class IODWriteMultipleReq(Block):
    """IODWriteMultiple request"""
    fields_desc = [
Beispiel #27
0
            g_log_loading.info(_crypto_loading_failure_message)
            return None

        packed_hdr = struct.pack("!B", self.code)
        packed_hdr += struct.pack("!B", self.id)
        packed_hdr += struct.pack("!H", self.len)
        packed_attrs = ''
        for index in range(0, len(self.attributes)):
            packed_attrs = packed_attrs + str(self.attributes[index])
        packed_data = packed_hdr + packed_request_auth + packed_attrs +\
            shared_secret

        digest = hashes.Hash(hashes.MD5(), backend=default_backend())
        digest.update(packed_data)
        return digest.finalize()


    def post_build(self, p, pay):
        p += pay
        length = self.len
        if length is None:
            length = len(p)
            p = p[:2] + struct.pack("!H", length) + p[4:]
        return p


bind_layers(UDP, Radius, sport=1812)
bind_layers(UDP, Radius, dport=1812)
bind_layers(UDP, Radius, sport=1813)
bind_layers(UDP, Radius, dport=1813)
Beispiel #28
0
        ByteField("win", 0),
        #Conditional Field for the optional header
        ConditionalField(ByteField("blen", 0), lambda pkt: pkt.hlen >= 9),
        ConditionalField(ByteField("ledge1", 0), lambda pkt: pkt.hlen >= 9),
        ConditionalField(ByteField("len1", 0), lambda pkt: pkt.hlen >= 9),
        ConditionalField(ByteField("padding1", 0), lambda pkt: pkt.hlen >= 12),
        ConditionalField(ByteField("ledge2", 0), lambda pkt: pkt.hlen >= 12),
        ConditionalField(ByteField("len2", 0), lambda pkt: pkt.hlen >= 12),
        ConditionalField(ByteField("padding2", 0), lambda pkt: pkt.hlen == 15),
        ConditionalField(ByteField("ledge3", 0), lambda pkt: pkt.hlen == 15),
        ConditionalField(ByteField("len3", 0), lambda pkt: pkt.hlen == 15)
    ]


# GBN header is coming after the IP header
bind_layers(IP, GBN, frag=0, proto=222)


class GBNSender(Automaton):
    """Sender implementation for the GBN protocol using a Scapy automaton.

    Attributes:
        win: Maximum window size of the sender
        n_bits: number of bits used to encode sequence number
        receiver: IP address of the receiver
        sender: IP address of the sender
        q: Queue for all payload messages
        buffer: buffer to save sent but not acknowledged segments
        current: Sequence number of next data packet to send
        unack: First unacked segment
        receiver_win: Current window advertised by receiver, initialized with
Beispiel #29
0
# This file is part of Scapy
# Scapy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# any later version.
#
# Scapy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Scapy. If not, see <http://www.gnu.org/licenses/>.

# scapy.contrib.description = EtherIP
# scapy.contrib.status = loads

from scapy.fields import BitField
from scapy.packet import Packet, bind_layers
from scapy.layers.inet import IP
from scapy.layers.l2 import Ether

class EtherIP(Packet):
    name = "EtherIP / RFC 3378"
    fields_desc = [ BitField("version", 3, 4),
                    BitField("reserved", 0, 12)]

bind_layers( IP,            EtherIP,       frag=0, proto=0x61)
bind_layers( EtherIP,       Ether)

Beispiel #30
0
        ConditionalField(SignedIntField("rev", 0),
                         lambda pkt: pkt.code == 1 or pkt.code == 2),
        # updater identity
        ConditionalField(IPField("uid", "192.168.0.1"),
                         lambda pkt: pkt.code == 1),
        ConditionalField(VTPTimeStampField("timestamp", '930301000000'),
                         lambda pkt: pkt.code == 1),
        ConditionalField(StrFixedLenField("md5", b"\x00" * 16, 16),
                         lambda pkt: pkt.code == 1),
        ConditionalField(PacketListField("vlaninfo", [], VTPVlanInfo),
                         lambda pkt: pkt.code == 2),
        ConditionalField(ShortField("startvalue", 0),
                         lambda pkt: pkt.code == 3)
    ]

    def post_build(self, p, pay):
        if self.domnamelen is None:
            domnamelen = len(self.domname.strip(b"\x00"))
            p = p[:3] + chr(domnamelen & 0xff) + p[4:]

        p += pay

        return p


bind_layers(SNAP, VTP, code=0x2003)

if __name__ == '__main__':
    from scapy.main import interact
    interact(mydict=globals(), mybanner="VTP")
Beispiel #31
0
#!/usr/bin/env python

# Text message transfer SDU

from scapy.packet import Packet, bind_layers
from scapy.fields import BitField, ConditionalField

from .sdstl import SDS_TRANSFER

# Table 446: Text message transfer SDU contents
class TEXT_MESSAGE_TRANSFER(Packet):
    name = 'Text Message Transfer SDU'
    fields_desc = [
        BitField('tstp_used', 0, 1),
        BitField('text_coding', 0, 7),
        ConditionalField(BitField('timestamp', 0, 24), lambda pkt: pkt.tstp_used == 1),
    ]

# FIXME : this is just wrong. We should rely on the value of D_SDS_DATA.proto
# but Scapy does not allow us to use the fields of an "ancestor" layer.
bind_layers(SDS_TRANSFER, TEXT_MESSAGE_TRANSFER)
Beispiel #32
0
    ]


class ScapyNestedOtterPacket1(Packet):
    name = "nested_otter_packet_1"
    fields_desc = [
        PacketField("nested_otter_1_1", ScapyBasicOtterPacket1(),
                    ScapyBasicOtterPacket1),
        PacketField("nested_otter_1_3", ScapyBasicOtterPacket3(),
                    ScapyBasicOtterPacket3),
        PacketField("nested_otter", ScapyNestedOtterPacket2(),
                    ScapyNestedOtterPacket2)
    ]


class ScapyOtterGuessPayloadPacket1(Packet):
    name = "guess_otter_1"
    fields_desc = [ByteField("payload_identifier", None)]

    def guess_payload_class(self, payload):
        if self.payload_identifier == 0x01:
            return ScapyBasicOtterPacket1
        elif self.payload_identifier == 0x02:
            return ScapyBasicOtterPacket2
        else:
            return None


bind_layers(ScapyBasicOtterPacket1, ScapyBasicOtterPacket2)
bind_layers(ScapyBasicOtterPacket2, ScapyBasicOtterPacket4)
Beispiel #33
0
# Imported from scapy at revision 1270:113ef25f9583
# This file is not included in the Ubuntu packages of scapy, so it is checked
# in to our repo to simplify installation. This file is under the GPLv2.

# http://trac.secdev.org/scapy/ticket/31 

# scapy.contrib.description = MPLS
# scapy.contrib.status = loads

from scapy.packet import Packet,bind_layers
from scapy.fields import BitField,ByteField
from scapy.layers.l2 import Ether

class MPLS(Packet): 
   name = "MPLS" 
   fields_desc =  [ BitField("label", 3, 20), 
                    BitField("cos", 0, 3), 
                    BitField("s", 1, 1), 
                    ByteField("ttl", 0)  ] 

bind_layers(Ether, MPLS, type=0x8847)

# Not in upstream scapy
bind_layers(MPLS, MPLS, s=0)
Beispiel #34
0
# http://trac.secdev.org/scapy/ticket/297

# scapy.contrib.description = EtherIP
# scapy.contrib.status = loads

from scapy.fields import BitField
from scapy.packet import Packet, bind_layers
from scapy.layers.inet import IP
from scapy.layers.l2 import Ether


class EtherIP(Packet):
    name = "EtherIP / RFC 3378"
    fields_desc = [BitField("version", 3, 4), BitField("reserved", 0, 12)]


bind_layers(IP, EtherIP, frag=0, proto=0x61)
bind_layers(EtherIP, Ether)
Beispiel #35
0
                isinstance(other, TFTP_WRQ) or
                isinstance(other, TFTP_ACK))

    def mysummary(self):
        return self.sprintf("ERROR %errorcode%: %errormsg%"), [UDP]


class TFTP_OACK(Packet):
    name = "TFTP Option Ack"
    fields_desc = []

    def answers(self, other):
        return isinstance(other, TFTP_WRQ) or isinstance(other, TFTP_RRQ)


bind_layers(UDP, TFTP, dport=69)
bind_layers(TFTP, TFTP_RRQ, op=1)
bind_layers(TFTP, TFTP_WRQ, op=2)
bind_layers(TFTP, TFTP_DATA, op=3)
bind_layers(TFTP, TFTP_ACK, op=4)
bind_layers(TFTP, TFTP_ERROR, op=5)
bind_layers(TFTP, TFTP_OACK, op=6)
bind_layers(TFTP_RRQ, TFTP_Options)
bind_layers(TFTP_WRQ, TFTP_Options)
bind_layers(TFTP_OACK, TFTP_Options)


class TFTP_read(Automaton):
    def parse_args(self, filename, server, sport=None, port=69, **kargs):
        Automaton.parse_args(self, **kargs)
        self.filename = filename
Beispiel #36
0
             8: "iwf-startup",
             9: "iwf-operation",
             10: "iwf-mapping",
             11: "iwf-delay-control"}

class ECPRI(Packet):
    name = "eCPRI"
    fields_desc = [BitField("revision", 1, 4),
                   BitField("reserved", 0, 3),
                   BitField("c", 0, 1),
                   ByteEnumField("type", 0, ecpritypes),
                   ShortField("size", None),
                   ConditionalField(ShortField("pcid", 0), lambda pkt:pkt.type == 0),
                   ConditionalField(ShortField("rtcid", 0), lambda pkt:pkt.type == 2),
                   ConditionalField(ShortField("msrid", 0), lambda pkt:pkt.type == 5),
                   ConditionalField(ShortField("seqid", 0), lambda pkt:pkt.type in [0, 2, 5])
                   ]

    def post_build(self, p, pay):
        tmp_len = len(pay) + len(p) - 4
        pay += b"\0" * ((-len(pay)) % 4)  # pad eCPRI payload if needed
        if self.size is None:
            p = p[:2] + struct.pack("!H", tmp_len) + p[4:]
        return p + pay

    def mysummary(self):
            return self.sprintf("eCPRI %ECPRI.type%")

bind_layers(Ether, ECPRI, type=0xAEFE)
bind_layers(Dot1Q, ECPRI, type=0xAEFE)
Beispiel #37
0
    def default_payload_class(self, payload):
        return conf.padding_layer


class IGMPv3mr(Packet):
    """IGMP Membership Report extension for IGMPv3.
    Payload of IGMPv3 when type=0x22"""
    name = "IGMPv3mr"
    fields_desc = [XShortField("res2", 0),
                   FieldLenField("numgrp", None, count_of="records"),
                   PacketListField("records", [], IGMPv3gr, count_from=lambda x: x.numgrp)]  # noqa: E501


class IGMPv3mra(Packet):
    """IGMP Multicas Router Advertisement extension for IGMPv3.
    Payload of IGMPv3 when type=0x30"""
    name = "IGMPv3mra"
    fields_desc = [ShortField("qryIntvl", 0),
                   ShortField("robust", 0)]


bind_layers(IP, IGMPv3, frag=0,
            proto=2,
            ttl=1,
            tos=0xc0,
            dst='224.0.0.22')

bind_layers(IGMPv3, IGMPv3mq, type=0x11)
bind_layers(IGMPv3, IGMPv3mr, type=0x22, mrcode=0x0)
bind_layers(IGMPv3, IGMPv3mra, type=0x30)
Beispiel #38
0
from scapy.compat import raw
from scapy.fields import IntEnumField, ConditionalField, PacketField
from scapy.packet import Packet, bind_layers, Padding

from syncalong.common.signal_packet import SignalPacket
from syncalong.common.file_sync_packet import FileSyncPacket

# All of the possible packets in the program.
all_layers = [SignalPacket, FileSyncPacket]

layers_dict = {}

for idx, layer in enumerate(all_layers):
    bind_layers(layer, Padding)
    layers_dict.update({idx: layer.__name__})


def condition(layer_cls) -> ConditionalField:
    """
    Create a conditional layer field. the layer must be present in `all_layers`.
    :param layer_cls: Layer class to create conditional field for.
    :return: Conditional field representing the given layer.
    """
    return ConditionalField(PacketField(layer_cls._name, layer_cls(), layer_cls),
                            lambda pkt: pkt.layer_type == all_layers.index(layer_cls))


class GeneralPacket(Packet):
    """
    Packet that holds messages of specific types.
    This packet was made in order to make communication with the multiple protocols easy, and handle different requests
Beispiel #39
0
# scapy.contrib.status = loads

from scapy.packet import Packet, bind_layers
from scapy.fields import ByteEnumField, ByteField, IP6Field, ShortField
from scapy.layers.inet import UDP


class RIPng(Packet):
    name = "RIPng header"
    fields_desc = [
        ByteEnumField("cmd", 1, {1: "req", 2: "resp"}),
        ByteField("ver", 1),
        ShortField("null", 0)
    ]


class RIPngEntry(Packet):
    name = "RIPng entry"
    fields_desc = [
        IP6Field("prefix_or_nh", "::"),
        ShortField("routetag", 0),
        ByteField("prefixlen", 0),
        ByteEnumField("metric", 1, {16: "Unreach",
                                    255: "next-hop entry"})
    ]


bind_layers(UDP, RIPng, sport=521, dport=521)
bind_layers(RIPng, RIPngEntry)
bind_layers(RIPngEntry, RIPngEntry)
Beispiel #40
0
        ConditionalField(ByteEnumKeysField("file_reload", 0, ms_file_reload_values), lambda pkt:pkt.opcode == 0x1f),
        ConditionalField(StrFixedLenField("file_filler", "\x00\x00\x00", 3), lambda pkt:pkt.opcode == 0x1f),

        # Get/Set/Del Logon fields
        ConditionalField(PacketField("logon", None, SAPMSLogon), lambda pkt:pkt.opcode in [0x2b, 0x2c, 0x2d]),

        # Server Disconnect/Shutdown fields
        ConditionalField(PacketField("shutdown_client", None, SAPMSClient3), lambda pkt:pkt.opcode in [0x2e, 0x2f, 0x30, 0x4a]),
        ConditionalField(FieldLenField("shutdown_reason_length", None, length_of="shutdown_reason", fmt="!H"), lambda pkt:pkt.opcode in [0x2e, 0x2f, 0x30, 0x4a]),
        ConditionalField(StrLenField("shutdown_reason", "", length_from=lambda pkt:pkt.shutdown_reason_length), lambda pkt:pkt.opcode in [0x2e, 0x2f, 0x30, 0x4a]),

        # Get/Set Property fields
        ConditionalField(PacketField("property", None, SAPMSProperty), lambda pkt:pkt.opcode in [0x43, 0x44, 0x45]),

        # IP/Port to name fields
        ConditionalField(IPField("ip_to_name_address4", "0.0.0.0"), lambda pkt:pkt.opcode == 0x46 and pkt.opcode_version == 0x01),
        ConditionalField(IP6Field("ip_to_name_address6", "::"), lambda pkt:pkt.opcode == 0x46 and pkt.opcode_version == 0x02),
        ConditionalField(ShortField("ip_to_name_port", 0), lambda pkt:pkt.opcode == 0x46),
        ConditionalField(FieldLenField("ip_to_name_length", None, length_of="ip_to_name", fmt="!I"), lambda pkt:pkt.opcode == 0x46),
        ConditionalField(StrLenField("ip_to_name", "", length_from=lambda pkt:pkt.logonname_length), lambda pkt:pkt.opcode == 0x46),

        # Check ACL fields
        ConditionalField(ShortField("error_code", 0), lambda pkt:pkt.opcode == 0x47),
        ConditionalField(StrFixedLenField("acl", "", 46), lambda pkt:pkt.opcode == 0x47),
    ]


# Bind SAP NI with the MS ports (both internal & external)
bind_layers(TCP, SAPNI, dport=3600)
bind_layers(TCP, SAPNI, dport=3900)
Beispiel #41
0
# IR

class IrLAPHead(Packet):
    name = "IrDA Link Access Protocol Header"
    fields_desc = [XBitField("Address", 0x7f, 7),
                   BitEnumField("Type", 1, 1, {"Response": 0,
                                               "Command": 1})]


class IrLAPCommand(Packet):
    name = "IrDA Link Access Protocol Command"
    fields_desc = [XByteField("Control", 0),
                   XByteField("Format identifier", 0),
                   XIntField("Source address", 0),
                   XIntField("Destination address", 0xffffffff),
                   XByteField("Discovery flags", 0x1),
                   ByteEnumField("Slot number", 255, {"final": 255}),
                   XByteField("Version", 0)]


class IrLMP(Packet):
    name = "IrDA Link Management Protocol"
    fields_desc = [XShortField("Service hints", 0),
                   XByteField("Character set", 0),
                   StrField("Device name", "")]


bind_layers(CookedLinux, IrLAPHead, proto=23)
bind_layers(IrLAPHead, IrLAPCommand, Type=1)
bind_layers(IrLAPCommand, IrLMP,)
Beispiel #42
0
    name = "IKEv2 Certificate"
    fields_desc = [
        ByteEnumField("next_payload", None, IKEv2_payload_type),
        ByteField("res", 0),
        FieldLenField("length", None, "cert_data", "H", adjust=lambda pkt, x: x + 5),  # noqa: E501
        ByteEnumField("cert_type", 0, IKEv2CertificateEncodings),
        StrLenField("cert_data", "", length_from=lambda x:x.length - 5),
    ]


IKEv2_payload_type_overload = {}
for i, payloadname in enumerate(IKEv2_payload_type):
    name = "IKEv2_payload_%s" % payloadname
    if name in globals():
        IKEv2_payload_type_overload[globals()[name]] = {"next_payload": i}

del i, payloadname, name
IKEv2_class._overload_fields = IKEv2_payload_type_overload.copy()

split_layers(UDP, ISAKMP, sport=500)
split_layers(UDP, ISAKMP, dport=500)

bind_layers(UDP, IKEv2, dport=500, sport=500)  # TODO: distinguish IKEv1/IKEv2
bind_layers(UDP, IKEv2, dport=4500, sport=4500)


def ikev2scan(ip, **kwargs):
    """Send a IKEv2 SA to an IP and wait for answers."""
    return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8),
                                         exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs)  # noqa: E501
Beispiel #43
0
import logging
from time import sleep
from socket import error as SocketError
from optparse import OptionParser, OptionGroup
# External imports
from scapy.config import conf
from scapy.packet import bind_layers
# Custom imports
import pysap
from pysap.SAPNI import SAPNI
from pysap.SAPDiagClient import SAPDiagConnection
from pysap.SAPDiag import SAPDiag, SAPDiagDP, SAPDiagItem


# Bind the SAPDiag layer
bind_layers(SAPNI, SAPDiag,)
bind_layers(SAPNI, SAPDiagDP,)
bind_layers(SAPDiagDP, SAPDiag,)
bind_layers(SAPDiag, SAPDiagItem,)
bind_layers(SAPDiagItem, SAPDiagItem,)


# Set the verbosity to 0
conf.verb = 0


# Command line options parser
def parse_options():

    description = "This example script can be used to tests against Denial of Service vulnerabilities affecting the " \
                  "Dispatcher service. Currently 5 different vulnerabilities can be triggered."
Beispiel #44
0
class HTTPv1(Packet):
    name = "HTTPv1"
    fields_desc = [StrField("HTTP-payload", None, fmt="H")]


class HTTP(Packet):
    """
    Generic HTTP packet. Contains specific version of HTTP protocol
    """
    name = "HTTP"

    def guess_payload_class(self, payload):
        """
        Guess the version of HTTP protocol
        """
        try:
            # naive guess, HTTPv1 if payload can be parsed as utf-8
            payload.decode("utf-8")
            return HTTPv1
        except:
            return None
        return None


#Bind to port 80
bind_layers(TCP, HTTP, dport=80)
bind_layers(TCP, HTTP, sport=80)

#For Proxy
bind_layers(TCP, HTTP, sport=8080)
bind_layers(TCP, HTTP, dport=8080)
Beispiel #45
0
from scapy.fields import BitField, BitEnumField, ConditionalField

from .cmce import D_SDS_DATA

# Table 446: Text message transfer SDU contents
class SDS_TRANSFER(Packet):
    name = 'SDS-Transfer'
    fields_desc = [
        BitField('delivery_report_request', 0, 2),
        BitField('short_form_report', 0, 1),
        BitField('storage', 0, 1),
        BitField('message_ref', 0, 8),
        ConditionalField(BitField('validity_period', 0, 5), lambda pkt: pkt.storage == 1),
        ConditionalField(BitField('fwd_addr_type', 0, 5), lambda pkt: pkt.storage == 1),
        # FIXME : More conditionnal fields
    ]

# Table 428: PDU layout
class SDS_TL_PDU(Packet):
    name = 'SDS-TL'
    fields_desc = [
        BitEnumField('message_type', 0, 4, {
            0: 'SDS-TRANSFER'
        }),
    ]

# Table 439: Protocol identifier information element contents
# FIXME : SDS-TL is only used for protocols >=128 (except 134...)
bind_layers(D_SDS_DATA, SDS_TL_PDU, proto=130)
bind_layers(SDS_TL_PDU, SDS_TRANSFER, message_type=0)
Beispiel #46
0
        """ Implements the swap-bytes functionality when building

        this is based on a copy of the Packet.self_build default method.
        The goal is to affect only the CAN layer data and keep
        under layers (e.g LinuxCooked) unchanged
        """
        if conf.contribs['CAN']['swap-bytes']:
            return CAN.inv_endianness(pkt) + pay
        return pkt + pay

    def extract_padding(self, p):
        return b'', p


conf.l2types.register(DLT_CAN_SOCKETCAN, CAN)
bind_layers(CookedLinux, CAN, proto=12)


def rdcandump(filename,
              count=None,
              is_not_log_file_format=False,
              interface=None):
    """Read a candump log file and return a packet list

count: read only <count> packets
is_not_log_file_format: read input with candumps stdout format
interfaces: return only packets from a specified interface

    """
    try:
        if isinstance(filename, six.string_types):
Beispiel #47
0
                    return False
            elif ((self.type == 0x17) and isValidMCAddr(gaddr)):
                underlayer.dst = "224.0.0.2"                           # IP rule 2  # noqa: E501
            elif ((self.type == 0x12) or (self.type == 0x16)) and (isValidMCAddr(gaddr)):  # noqa: E501
                underlayer.dst = gaddr                                 # IP rule 3b  # noqa: E501
            else:
                warning("Invalid IGMP Type detected !")
                return False
            if not any(isinstance(x, IPOption_Router_Alert) for x in underlayer.options):  # noqa: E501
                underlayer.options.append(IPOption_Router_Alert())
            _root = self.firstlayer()
            if _root.haslayer(Ether):
                # Force recalculate Ether dst
                _root[Ether].dst = getmacbyip(underlayer.dst)          # Ether rule 1  # noqa: E501
        from scapy.contrib.igmpv3 import IGMPv3
        if isinstance(self, IGMPv3):
            self.encode_maxrespcode()
        return True

    def mysummary(self):
        """Display a summary of the IGMP object."""
        if isinstance(self.underlayer, IP):
            return self.underlayer.sprintf("IGMP: %IP.src% > %IP.dst% %IGMP.type% %IGMP.gaddr%")  # noqa: E501
        else:
            return self.sprintf("IGMP %IGMP.type% %IGMP.gaddr%")


bind_layers(IP, IGMP, frag=0,
            proto=2,
            ttl=1)
    prog = 'sap_ms_dispatcher_mitm'
    if args.quiet:
        logger = init_logger(prog, logging.NOTSET)
    elif args.debug:
        logger = init_logger(prog, logging.DEBUG)
    else:
        logger = init_logger(prog, logging.INFO)

    # update our default conf with customized version:
    attacked_as["host"] = args.host
    attacked_as["msport"] = args.port

    conf.L3Socket = StreamSocket
    # SAPMS layer
    bind_layers(TCP, SAPNI)
    bind_layers(TCP, SAPNI)
    bind_layers(SAPNI, SAPMS)
    # SAPDIAG layer
    bind_layers(
        SAPDiagDP,
        SAPDiag,
    )
    bind_layers(
        SAPDiag,
        SAPDiagItem,
    )
    bind_layers(
        SAPDiagItem,
        SAPDiagItem,
    )
Beispiel #49
0
## GNU General Public License for more details.
##==============

# Standard imports
import logging
from optparse import OptionParser, OptionGroup
# External imports
from scapy.config import conf
from scapy.packet import bind_layers, Raw
# Custom imports
from pysap.SAPMS import SAPMS
from pysap.SAPNI import SAPNI, SAPNIStreamSocket


# Bind SAP NI with MS packets
bind_layers(SAPNI, SAPMS, )

# Set the verbosity to 0
conf.verb = 0


# Command line options parser
def parse_options():

    description = \
    """This example script connects with the Message Server service and sends
    a message to another client.

    """

    epilog = \
Beispiel #50
0
class SAPDiagError(PacketNoPadded):
    """SAP Diag Error packet

    This packet holds Diag error packets.
    """
    name = "SAP Diag Error"
    # TODO: Need to figure out the meaning of the packets
    fields_desc = [
        StrNullFixedLenField("msg", "**DPTMMSG**", length=12),
        StrField("padd", None),
    ]


# Bind SAP NI with the Diag port
bind_layers(TCP, SAPNI, dport=3200)


def diag_guess_diagdp_header(self, payload):
    """Guess if the payload is a :class:`SAPDiag` or :class:`SAPDiagDP`, base on the mode field.
    Use this function as guess_payload_class for the :class:`SAPNI` packet if need to
    dissect :class:`SAPDiag` packets.
    """
    if self.length == 14 and payload.startswith("**DPTMMSG**\x00"):
        return SAPDiagError
    elif self.length == 17 and payload.startswith("**DPTMOPC**\x00"):
        return SAPDiagError
    elif self.length > 200 + 8 and payload[0] == "\xff":
        return SAPDiagDP
    else:
        return SAPDiag
Beispiel #51
0
        return pkt

    def build_hmac_sha1(self, pw=b'\x00' * 20, ip4l=[], ip6l=[]):
        h = hmac.new(pw, digestmod=hashlib.sha1)
        # XXX: this is a dirty hack. it needs to pack version and type into a single 8bit field  # noqa: E501
        h.update(b'\x21')
        # XXX: mac addy if different from special link layer. comes before vhid
        h.update(struct.pack('!B', self.vhid))

        sl = []
        for i in ip4l:
            # sort ips from smallest to largest
            sl.append(inet_aton(i))
        sl.sort()

        for i in sl:
            h.update(i)

        # XXX: do ip6l sorting

        return h.digest()


warning("CARP overwrites VRRP !")
# This cancel the bindings done in vrrp.py
split_layers(IP, VRRP, proto=IPPROTO_VRRP)
split_layers(IP, VRRPv3, proto=IPPROTO_VRRP)
# CARP bindings
bind_layers(IP, CARP, proto=112, dst='224.0.0.18')
Beispiel #52
0
    ]


class GTPmorethan1500(Packet):
    # 3GPP TS 29.060 V9.1.0 (2009-12)
    name = "GTP More than 1500"
    fields_desc = [
        ByteEnumField("IE_Cause", "Cause", IEType),
        BitField("IE", 1, 12000),
    ]


# Bind GTP-C
bind_bottom_up(UDP, GTPHeader, dport=2123)
bind_bottom_up(UDP, GTPHeader, sport=2123)
bind_layers(UDP, GTPHeader, dport=2123, sport=2123)
bind_layers(GTPHeader, GTPEchoRequest, gtp_type=1, S=1)
bind_layers(GTPHeader, GTPEchoResponse, gtp_type=2, S=1)
bind_layers(GTPHeader, GTPCreatePDPContextRequest, gtp_type=16)
bind_layers(GTPHeader, GTPCreatePDPContextResponse, gtp_type=17)
bind_layers(GTPHeader, GTPUpdatePDPContextRequest, gtp_type=18)
bind_layers(GTPHeader, GTPUpdatePDPContextResponse, gtp_type=19)
bind_layers(GTPHeader, GTPDeletePDPContextRequest, gtp_type=20)
bind_layers(GTPHeader, GTPDeletePDPContextResponse, gtp_type=21)
bind_layers(GTPHeader, GTPPDUNotificationRequest, gtp_type=27)
bind_layers(GTPHeader,
            GTPSupportedExtensionHeadersNotification,
            gtp_type=31,
            S=1)  # noqa: E501
bind_layers(GTPHeader, GTP_UDPPort_ExtensionHeader, next_ex=64, E=1)
bind_layers(GTPHeader, GTP_PDCP_PDU_ExtensionHeader, next_ex=192, E=1)
Beispiel #53
0
def isdnssecRR(obj):
    return isinstance(obj, DNSSEC_CLASSES)


class DNSRR(InheritOriginDNSStrPacket):
    name = "DNS Resource Record"
    show_indent = 0
    fields_desc = [DNSStrField("rrname", ""),
                   ShortEnumField("type", 1, dnstypes),
                   ShortEnumField("rclass", 1, dnsclasses),
                   IntField("ttl", 0),
                   RDLenField("rdlen"),
                   RDataField("rdata", "", length_from=lambda pkt:pkt.rdlen)]


bind_layers(UDP, DNS, dport=5353)
bind_layers(UDP, DNS, sport=5353)
bind_layers(UDP, DNS, dport=53)
bind_layers(UDP, DNS, sport=53)
DestIPField.bind_addr(UDP, "224.0.0.251", dport=5353)
DestIP6Field.bind_addr(UDP, "ff02::fb", dport=5353)
bind_layers(TCP, DNS, dport=53)
bind_layers(TCP, DNS, sport=53)


@conf.commands.register
def dyndns_add(nameserver, name, rdata, type="A", ttl=10):
    """Send a DNS add message to a nameserver for "name" to have a new "rdata"
dyndns_add(nameserver, name, rdata, type="A", ttl=10) -> result code (0=ok)

example: dyndns_add("ns1.toto.com", "dyn.toto.com", "127.0.0.1")
Beispiel #54
0
        ByteField("PN2", 0),
        ByteField("PN3", 0),
        ByteField("PN4", 0),
        ByteField("PN5", 0),
        # data
        StrField("data", None),
    ]


class Dot11Ack(Packet):
    name = "802.11 Ack packet"


bind_top_down(RadioTap, Dot11FCS, present=2, Flags=16)

bind_layers(PrismHeader, Dot11,)
bind_layers(Dot11, LLC, type=2)
bind_layers(Dot11QoS, LLC,)
bind_layers(Dot11, Dot11AssoReq, subtype=0, type=0)
bind_layers(Dot11, Dot11AssoResp, subtype=1, type=0)
bind_layers(Dot11, Dot11ReassoReq, subtype=2, type=0)
bind_layers(Dot11, Dot11ReassoResp, subtype=3, type=0)
bind_layers(Dot11, Dot11ProbeReq, subtype=4, type=0)
bind_layers(Dot11, Dot11ProbeResp, subtype=5, type=0)
bind_layers(Dot11, Dot11Beacon, subtype=8, type=0)
bind_layers(Dot11, Dot11ATIM, subtype=9, type=0)
bind_layers(Dot11, Dot11Disas, subtype=10, type=0)
bind_layers(Dot11, Dot11Auth, subtype=11, type=0)
bind_layers(Dot11, Dot11Deauth, subtype=12, type=0)
bind_layers(Dot11, Dot11Ack, subtype=13, type=1)
bind_layers(Dot11Beacon, Dot11Elt,)
Beispiel #55
0
import logging
from socket import error as SocketError
from optparse import OptionParser, OptionGroup
# External imports
from scapy.config import conf
from scapy.packet import bind_layers
# Custom imports
import pysap
from pysap.SAPNI import SAPNI
from pysap.SAPRouter import (SAPRouter, SAPRouteException,
                             SAPRouterNativeProxy,
                             SAPRouterNativeRouterHandler)


# Bind the SAPRouter layer
bind_layers(SAPNI, SAPRouter, )

# Set the verbosity to 0
conf.verb = 0


# Command line options parser
def parse_options():

    description = "This example script routes a connection through a SAP Router service. Similar to Bizploit's " \
                  "'saprouterNative', for more information check: " \
                  "https://blog.onapsis.com/blog/assessing-a-saprouters-security-with-onapsis-bizploit-part-i/ and "\
                  "https://blog.onapsis.com/blog/assessing-a-saprouters-security-with-onapsis-bizploit-part-ii/"

    epilog = "pysap %(version)s - %(url)s - %(repo)s" % {"version": pysap.__version__,
                                                         "url": pysap.__url__,
Beispiel #56
0
        IPv6: {
            'nh': socket.IPPROTO_AH
        },
        IPv6ExtHdrHopByHop: {
            'nh': socket.IPPROTO_AH
        },
        IPv6ExtHdrDestOpt: {
            'nh': socket.IPPROTO_AH
        },
        IPv6ExtHdrRouting: {
            'nh': socket.IPPROTO_AH
        },
    }


bind_layers(IP, AH, proto=socket.IPPROTO_AH)
bind_layers(IPv6, AH, nh=socket.IPPROTO_AH)


#------------------------------------------------------------------------------
class ESP(Packet):
    """
    Encapsulated Security Payload

    See https://tools.ietf.org/rfc/rfc4303.txt
    """
    name = 'ESP'

    fields_desc = [
        XIntField('spi', 0x0),
        IntField('seq', 0),
Beispiel #57
0
    payloads = [payload[i: i+size] for i in range(0, len(payload), size)]
    if record is None:
        return payloads
    else:
        fragments = []
        for payload in payloads:
            fragments.append(TLSRecord(content_type=record.content_type, version=record.version, length=len(payload)) /
                             payload)
            try:
                stack = TLS.from_records(fragments, ctx=record.tls_ctx)
            except struct.error as se:
                raise TLSFragmentationError("Fragment size must be a power of 2: %s" % se)
        return stack

# bind magic
bind_layers(TCP, SSL, dport=443)
bind_layers(TCP, SSL, sport=443)
bind_layers(UDP, SSL, dport=4433)
bind_layers(UDP, SSL, sport=4433)

# TLSRecord
bind_layers(TLSRecord, TLSChangeCipherSpec, {'content_type': TLSContentType.CHANGE_CIPHER_SPEC})
bind_layers(TLSRecord, TLSCiphertext, {"content_type": TLSContentType.APPLICATION_DATA})
bind_layers(TLSRecord, TLSHeartBeat, {'content_type': TLSContentType.HEARTBEAT})
bind_layers(TLSRecord, TLSAlert, {'content_type': TLSContentType.ALERT})
bind_layers(TLSRecord, TLSHandshake, {'content_type': TLSContentType.HANDSHAKE})

# --> handshake proto
bind_layers(TLSHandshake, TLSHelloRequest, {'type':TLSHandshakeType.HELLO_REQUEST})
bind_layers(TLSHandshake, TLSClientHello, {'type':TLSHandshakeType.CLIENT_HELLO})
bind_layers(TLSHandshake, TLSServerHello, {'type':TLSHandshakeType.SERVER_HELLO})
Beispiel #58
0
BTLE_Corp_IDs = {
    0xf: 'Broadcom Corporation'
}


class CtrlPDU(Packet):
    name = "CtrlPDU"
    fields_desc = [
        XByteField("optcode", 0),
        ByteEnumField("version", 0, BTLE_Versions),
        LEShortEnumField("Company", 0, BTLE_Corp_IDs),
        XShortField("subversion", 0)
    ]


bind_layers(BTLE, BTLE_ADV, access_addr=0x8E89BED6)
bind_layers(BTLE, BTLE_DATA)
bind_layers(BTLE_ADV, BTLE_ADV_IND, PDU_type=0)
bind_layers(BTLE_ADV, BTLE_ADV_DIRECT_IND, PDU_type=1)
bind_layers(BTLE_ADV, BTLE_ADV_NONCONN_IND, PDU_type=2)
bind_layers(BTLE_ADV, BTLE_SCAN_REQ, PDU_type=3)
bind_layers(BTLE_ADV, BTLE_SCAN_RSP, PDU_type=4)
bind_layers(BTLE_ADV, BTLE_CONNECT_REQ, PDU_type=5)
bind_layers(BTLE_ADV, BTLE_ADV_SCAN_IND, PDU_type=6)

bind_layers(BTLE_DATA, L2CAP_Hdr, LLID=2)  # BTLE_DATA / L2CAP_Hdr / ATT_Hdr
# LLID=1 -> Continue
bind_layers(BTLE_DATA, CtrlPDU, LLID=3)

conf.l2types.register(DLT_BLUETOOTH_LE_LL, BTLE)
conf.l2types.register(DLT_BLUETOOTH_LE_LL_WITH_PHDR, BTLE_RF)
Beispiel #59
0
    
    def encrypt_stream(self):
        '''
              HMAC_hash(MAC_write_secret, seq_num + TLSCompressed.type +
                     TLSCompressed.version + TLSCompressed.length +
                     TLSCompressed.fragment));
        '''
        pass
    
    def decrypt(self, master_secret): pass
    
    def compress(self): pass
    def decompress(self): pass
 
# bind magic
bind_layers(TCP, SSL, dport=443)
bind_layers(TCP, SSL, sport=443)
bind_layers(UDP, SSL, dport=4433)
bind_layers(UDP, SSL, sport=4433)

# TLSRecord
bind_layers(TLSRecord, TLSChangeCipherSpec, {'content_type':0x14})
bind_layers(TLSRecord, TLSHeartBeat, {'content_type':0x18})
bind_layers(TLSRecord, TLSAlert, {'content_type':0x15})

bind_layers(TLSRecord, TLSHandshake, {'content_type':0x16})
# --> handshake proto
bind_layers(TLSHandshake,TLSClientHello, {'type':0x01})
bind_layers(TLSHandshake,TLSServerHello, {'type':0x02})
bind_layers(TLSHandshake,TLSCertificateList, {'type':0x0b})
bind_layers(TLSHandshake,TLSClientKeyExchange, {'type':0x10})
Beispiel #60
0
from scapy.packet import bind_layers
# Custom imports
import pysap
from pysap.SAPNI import SAPNI, SAPNIStreamSocket
from pysap.utils.fields import saptimestamp_to_datetime
from pysap.SAPRouter import (SAPRouter, router_is_error, get_router_version,
                             SAPRouterInfoClients, SAPRouterInfoServer)
# Optional imports
try:
    from tabulate import tabulate
except ImportError:
    tabulate = None

# Bind the SAPRouter layer
bind_layers(
    SAPNI,
    SAPRouter,
)

# Set the verbosity to 0
conf.verb = 0


# Command line options parser
def parse_options():

    description = "This example script connects with a SAP Router server and allows perform administrative tasks. " \
                  "The options are the ones found on the regular SAP Router tool with the addition of some " \
                  "undocumented operation codes."

    epilog = "pysap %(version)s - %(url)s - %(repo)s" % {
        "version": pysap.__version__,