Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi
## This program is published under a GPLv2 license
from scapy.data import KnowledgeBase
from scapy.config import conf
conf.IPCountry_base = "GeoIPCountry4Scapy.gz"
conf.countryLoc_base = "countryLoc.csv"
conf.gnuplot_world = "world.dat"
##########################
## IP location database ##
##########################
class IPCountryKnowledgeBase(KnowledgeBase):
"""
How to generate the base :
db = []
for l in open("GeoIPCountryWhois.csv").readlines():
s,e,c = l.split(",")[2:5]
db.append((int(s[1:-1]),int(e[1:-1]),c[1:-1]))
cPickle.dump(gzip.open("xxx","w"),db)
@conf.commands.register
def srp1flood(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs): # noqa: E501
"""Flood and receive packets at layer 2 and return only the first answer
prn: function applied to packets received
verbose: set verbosity level
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF filter
iface: listen answers only on the given interface"""
s = conf.L2socket(promisc=promisc, filter=filter, nofilter=nofilter, iface=iface) # noqa: E501
ans, _ = sndrcvflood(s, x, *args, **kargs)
s.close()
if len(ans) > 0:
return ans[0][1]
else:
return None
from scapy.compat import plain_str
from scapy.data import ETH_P_ALL
from scapy.config import conf
from scapy.error import warning
from scapy.packet import Gen, Packet
from scapy.utils import get_temp_file, tcpdump, wrpcap, \
ContextManagerSubprocess, PcapReader
from scapy.plist import PacketList, SndRcvList
from scapy.error import log_runtime, log_interactive, Scapy_Exception
from scapy.base_classes import SetGen
from scapy.modules import six
from scapy.modules.six.moves import map
from scapy.sessions import DefaultSession
from scapy.supersocket import SuperSocket
if conf.route is None:
# unused import, only to initialize conf.route
import scapy.route # noqa: F401
#################
# Debug class #
#################
class debug:
recv = []
sent = []
match = []
crashed_on = None
####################
def _bgp_dispatcher(payload):
"""
Returns the right class for a given BGP message.
"""
cls = conf.raw_layer
# By default, calling BGP() will build a BGPHeader.
if payload is None:
cls = _get_cls("BGPHeader", conf.raw_layer)
else:
if len(payload) >= _BGP_HEADER_SIZE and\
payload[:16] == _BGP_HEADER_MARKER:
# Get BGP message type
message_type = orb(payload[18])
if message_type == 4:
cls = _get_cls("BGPKeepAlive")
else:
cls = _get_cls("BGPHeader")
def compute_master_secret(self):
if self.pre_master_secret is None:
warning("Missing pre_master_secret while computing master_secret!")
if self.client_random is None:
warning("Missing client_random while computing master_secret!")
if self.server_random is None:
warning("Missing server_random while computing master_secret!")
ms = self.pwcs.prf.compute_master_secret(self.pre_master_secret,
self.client_random,
self.server_random)
self.master_secret = ms
if conf.debug_tls:
log_runtime.debug("TLS: master secret: %s", repr_hex(ms))
def select(sockets, remain=conf.recv_poll_rate):
return select_objects(sockets, remain), None
return mac
try:
res = srp1(Ether(dst=ETHER_BROADCAST) / ARP(op="who-has", pdst=ip),
type=ETH_P_ARP,
iface=iff,
timeout=2,
verbose=0,
chainCC=chainCC,
nofilter=1)
except Exception as ex:
warning("getmacbyip failed on %s" % ex)
return None
if res is not None:
mac = res.payload.hwsrc
conf.netcache.arp_cache[ip] = mac
return mac
return None
# Detect Pcap version
version = pcap_lib_version()
if b"winpcap" in version.lower():
if os.path.exists(NPCAP_PATH + "\\wpcap.dll"):
warning("Winpcap is installed over Npcap. "
"Will use Winpcap (see 'Winpcap/Npcap conflicts' "
"in Scapy's docs)")
elif platform.release() != "XP":
warning("WinPcap is now deprecated (not maintained). "
"Please use Npcap instead")
elif b"npcap" in version.lower():
conf.use_npcap = True
LOOPBACK_NAME = scapy.consts.LOOPBACK_NAME = "Npcap Loopback Adapter" # noqa: E501
except OSError:
conf.use_winpcapy = False
if conf.interactive:
log_loading.warning("wpcap.dll is not installed. "
"Restricted mode enabled ! "
"Visit the Scapy's doc to install it")
if conf.use_winpcapy:
def get_if_list():
"""Returns all pcap names"""
if not conf.cache_iflist:
load_winpcapy()
return list(conf.cache_iflist)
else:
get_if_list = lambda: []
class _PcapWrapper_winpcap: # noqa: F811
"""Wrapper for the WinPcap calls"""
def answers(self, other):
if not conf.checkIPinIP: # skip IP in IP and IPv6 in IP
if self.proto in [4, 41]:
return self.payload.answers(other)
if isinstance(other, IP) and other.proto in [4, 41]:
return self.answers(other.payload)
if conf.ipv6_enabled \
and isinstance(other, scapy.layers.inet6.IPv6) \
and other.nh in [4, 41]:
return self.answers(other.payload)
if not isinstance(other, IP):
return 0
if conf.checkIPaddr:
if other.dst == "224.0.0.251" and self.dst == "224.0.0.251": # mDNS # noqa: E501
return self.payload.answers(other.payload)
elif (self.dst != other.src):
return 0
if ((self.proto == socket.IPPROTO_ICMP) and
from scapy.config import conf, crypto_validator
import scapy.modules.six as six
from scapy.modules.six.moves import range
from scapy.error import warning
from scapy.utils import binrepr
from scapy.asn1.asn1 import ASN1_BIT_STRING
from scapy.asn1.mib import hash_by_oid
from scapy.layers.x509 import (X509_SubjectPublicKeyInfo,
RSAPublicKey, RSAPrivateKey,
ECDSAPublicKey, ECDSAPrivateKey,
RSAPrivateKey_OpenSSL, ECDSAPrivateKey_OpenSSL,
X509_Cert, X509_CRL)
from scapy.layers.tls.crypto.pkcs1 import pkcs_os2ip, _get_hash, \
_EncryptAndVerifyRSA, _DecryptAndSignRSA
from scapy.compat import raw, bytes_encode
if conf.crypto_valid:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa, ec
if conf.crypto_valid_recent:
from cryptography.hazmat.backends.openssl.ec import InvalidSignature
# Maximum allowed size in bytes for a certificate file, to avoid
# loading huge file when importing a cert
_MAX_KEY_SIZE = 50 * 1024
_MAX_CERT_SIZE = 50 * 1024
_MAX_CRL_SIZE = 10 * 1024 * 1024 # some are that big
#####################################################################
# Some helpers