本文整理汇总了Python中scapy.compat.raw函数的典型用法代码示例。如果您正苦于以下问题:Python raw函数的具体用法?Python raw怎么用?Python raw使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了raw函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: verifyCert
def verifyCert(self, cert):
""" Verifies either a Cert or an X509_Cert. """
tbsCert = cert.tbsCertificate
sigAlg = tbsCert.signature
h = hash_by_oid[sigAlg.algorithm.val]
sigVal = raw(cert.signatureValue)
return self.verify(raw(tbsCert), sigVal, h=h, t='pkcs')
开发者ID:commial,项目名称:scapy,代码行数:7,代码来源:cert.py
示例2: i2m
def i2m(self, pkt, p):
"""
Update the context with information from the built packet.
If no type was given at the record layer, we try to infer it.
"""
cur = b""
if isinstance(p, _GenericTLSSessionInheritance):
if pkt.type is None:
if isinstance(p, TLSChangeCipherSpec):
pkt.type = 20
elif isinstance(p, TLSAlert):
pkt.type = 21
elif isinstance(p, _TLSHandshake):
pkt.type = 22
elif isinstance(p, TLSApplicationData):
pkt.type = 23
p.tls_session = pkt.tls_session
if not pkt.tls_session.frozen:
cur = p.raw_stateful()
p.post_build_tls_session_update(cur)
else:
cur = raw(p)
else:
pkt.type = 23
cur = raw(p)
return cur
开发者ID:commial,项目名称:scapy,代码行数:26,代码来源:record.py
示例3: import_from_asn1pkt
def import_from_asn1pkt(self, cert):
error_msg = "Unable to import certificate"
self.x509Cert = cert
tbsCert = cert.tbsCertificate
self.tbsCertificate = tbsCert
if tbsCert.version:
self.version = tbsCert.version.val + 1
else:
self.version = 1
self.serial = tbsCert.serialNumber.val
self.sigAlg = tbsCert.signature.algorithm.oidname
self.issuer = tbsCert.get_issuer()
self.issuer_str = tbsCert.get_issuer_str()
self.issuer_hash = hash(self.issuer_str)
self.subject = tbsCert.get_subject()
self.subject_str = tbsCert.get_subject_str()
self.subject_hash = hash(self.subject_str)
self.authorityKeyID = None
self.notBefore_str = tbsCert.validity.not_before.pretty_time
notBefore = tbsCert.validity.not_before.val
if notBefore[-1] == "Z":
notBefore = notBefore[:-1]
try:
self.notBefore = time.strptime(notBefore, "%y%m%d%H%M%S")
except Exception:
raise Exception(error_msg)
self.notBefore_str_simple = time.strftime("%x", self.notBefore)
self.notAfter_str = tbsCert.validity.not_after.pretty_time
notAfter = tbsCert.validity.not_after.val
if notAfter[-1] == "Z":
notAfter = notAfter[:-1]
try:
self.notAfter = time.strptime(notAfter, "%y%m%d%H%M%S")
except Exception:
raise Exception(error_msg)
self.notAfter_str_simple = time.strftime("%x", self.notAfter)
self.pubKey = PubKey(raw(tbsCert.subjectPublicKeyInfo))
if tbsCert.extensions:
for extn in tbsCert.extensions:
if extn.extnID.oidname == "basicConstraints":
self.cA = False
if extn.extnValue.cA:
self.cA = not (extn.extnValue.cA.val == 0)
elif extn.extnID.oidname == "keyUsage":
self.keyUsage = extn.extnValue.get_keyUsage()
elif extn.extnID.oidname == "extKeyUsage":
self.extKeyUsage = extn.extnValue.get_extendedKeyUsage()
elif extn.extnID.oidname == "authorityKeyIdentifier":
self.authorityKeyID = extn.extnValue.keyIdentifier.val
self.signatureValue = raw(cert.signatureValue)
self.signatureLen = len(self.signatureValue)
开发者ID:commial,项目名称:scapy,代码行数:59,代码来源:cert.py
示例4: post_build
def post_build(self, pkt, pay):
"""
need to set the length of the whole PDU manually
to avoid any bit fiddling use a dummy class to build the layer content
also add padding if frame is < 64 bytes
Note: padding only handles Ether/n*Dot1Q/EtherCat
(no special mumbo jumbo)
:param pkt: raw string containing the current layer
:param pay: raw string containing the payload
:return: <new current layer> + payload
"""
class _EtherCatLengthCalc(Packet):
"""
dummy class used to generate str representation easily
"""
fields_desc = [
LEBitField('length', None, 11),
LEBitField('_reserved', 0, 1),
LEBitField('type', 0, 4),
]
payload_len = len(pay)
# length field is 11 bit
if payload_len > 2047:
raise ValueError('payload size {} exceeds maximum length {} '
'of EtherCat message.'.format(payload_len, 2047))
self.length = payload_len
vlan_headers_total_size = 0
upper_layer = self.underlayer
# add size occupied by VLAN tags
while upper_layer and isinstance(upper_layer, Dot1Q):
vlan_headers_total_size += 4
upper_layer = upper_layer.underlayer
if not isinstance(upper_layer, Ether):
raise Exception('missing Ether layer')
pad_len = EtherCat.ETHER_FRAME_MIN_LEN - (EtherCat.ETHER_HEADER_LEN +
vlan_headers_total_size +
EtherCat.ETHERCAT_HEADER_LEN + # noqa: E501
payload_len +
EtherCat.ETHER_FSC_LEN)
if pad_len > 0:
pad = Padding()
pad.load = b'\x00' * pad_len
return raw(_EtherCatLengthCalc(length=self.length,
type=self.type)) + pay + raw(pad)
return raw(_EtherCatLengthCalc(length=self.length,
type=self.type)) + pay
开发者ID:plorinquer,项目名称:scapy,代码行数:59,代码来源:ethercat.py
示例5: _encrypt_esp
def _encrypt_esp(self, pkt, seq_num=None, iv=None):
if iv is None:
iv = self.crypt_algo.generate_iv()
else:
if len(iv) != self.crypt_algo.iv_size:
raise TypeError('iv length must be %s' % self.crypt_algo.iv_size)
esp = _ESPPlain(spi=self.spi, seq=seq_num or self.seq_num, iv=iv)
if self.tunnel_header:
tunnel = self.tunnel_header.copy()
if tunnel.version == 4:
del tunnel.proto
del tunnel.len
del tunnel.chksum
else:
del tunnel.nh
del tunnel.plen
pkt = tunnel.__class__(raw(tunnel / pkt))
ip_header, nh, payload = split_for_transport(pkt, socket.IPPROTO_ESP)
esp.data = payload
esp.nh = nh
esp = self.crypt_algo.pad(esp)
esp = self.crypt_algo.encrypt(self, esp, self.crypt_key)
self.auth_algo.sign(esp, self.auth_key)
if self.nat_t_header:
nat_t_header = self.nat_t_header.copy()
nat_t_header.chksum = 0
del nat_t_header.len
if ip_header.version == 4:
del ip_header.proto
else:
del ip_header.nh
ip_header /= nat_t_header
if ip_header.version == 4:
ip_header.len = len(ip_header) + len(esp)
del ip_header.chksum
ip_header = ip_header.__class__(raw(ip_header))
else:
ip_header.plen = len(ip_header.payload) + len(esp)
# sequence number must always change, unless specified by the user
if seq_num is None:
self.seq_num += 1
return ip_header / esp
开发者ID:6WIND,项目名称:scapy,代码行数:54,代码来源:ipsec.py
示例6: i2m
def i2m(self, pkt, p):
cur = b""
if isinstance(p, _GenericTLSSessionInheritance):
p.tls_session = pkt.tls_session
if not pkt.tls_session.frozen:
cur = p.raw_stateful()
p.post_build_tls_session_update(cur)
else:
cur = raw(p)
else:
cur = raw(p)
return cur
开发者ID:commial,项目名称:scapy,代码行数:12,代码来源:record_sslv2.py
示例7: _encrypt_ah
def _encrypt_ah(self, pkt, seq_num=None):
ah = AH(spi=self.spi, seq=seq_num or self.seq_num,
icv = b"\x00" * self.auth_algo.icv_size)
if self.tunnel_header:
tunnel = self.tunnel_header.copy()
if tunnel.version == 4:
del tunnel.proto
del tunnel.len
del tunnel.chksum
else:
del tunnel.nh
del tunnel.plen
pkt = tunnel.__class__(raw(tunnel / pkt))
ip_header, nh, payload = split_for_transport(pkt, socket.IPPROTO_AH)
ah.nh = nh
if ip_header.version == 6 and len(ah) % 8 != 0:
# For IPv6, the total length of the header must be a multiple of
# 8-octet units.
ah.padding = b"\x00" * (-len(ah) % 8)
elif len(ah) % 4 != 0:
# For IPv4, the total length of the header must be a multiple of
# 4-octet units.
ah.padding = b"\x00" * (-len(ah) % 4)
# RFC 4302 - Section 2.2. Payload Length
# This 8-bit field specifies the length of AH in 32-bit words (4-byte
# units), minus "2".
ah.payloadlen = len(ah) // 4 - 2
if ip_header.version == 4:
ip_header.len = len(ip_header) + len(ah) + len(payload)
del ip_header.chksum
ip_header = ip_header.__class__(raw(ip_header))
else:
ip_header.plen = len(ip_header.payload) + len(ah) + len(payload)
signed_pkt = self.auth_algo.sign(ip_header / ah / payload, self.auth_key)
# sequence number must always change, unless specified by the user
if seq_num is None:
self.seq_num += 1
return signed_pkt
开发者ID:6WIND,项目名称:scapy,代码行数:49,代码来源:ipsec.py
示例8: parse_args
def parse_args(self, server="127.0.0.1", dport=4433, server_name=None,
mycert=None, mykey=None,
client_hello=None, version=None,
data=None,
**kargs):
super(TLSClientAutomaton, self).parse_args(mycert=mycert,
mykey=mykey,
**kargs)
tmp = socket.getaddrinfo(server, dport)
self.remote_name = None
try:
if ':' in server:
inet_pton(socket.AF_INET6, server)
else:
inet_pton(socket.AF_INET, server)
except Exception:
self.remote_name = socket.getfqdn(server)
if self.remote_name != server:
tmp = socket.getaddrinfo(self.remote_name, dport)
if server_name:
self.remote_name = server_name
self.remote_family = tmp[0][0]
self.remote_ip = tmp[0][4][0]
self.remote_port = dport
self.local_ip = None
self.local_port = None
self.socket = None
self.client_hello = client_hello
self.advertised_tls_version = None
if version:
v = _tls_version_options.get(version, None)
if not v:
self.vprint("Unrecognized TLS version option.")
else:
self.advertised_tls_version = v
self.linebreak = False
if isinstance(data, bytes):
self.data_to_send = [data]
elif isinstance(data, six.string_types):
self.data_to_send = [raw(data)]
elif isinstance(data, list):
self.data_to_send = list(raw(d) for d in reversed(data))
else:
self.data_to_send = []
开发者ID:commial,项目名称:scapy,代码行数:48,代码来源:automaton_cli.py
示例9: self_build
def self_build(self, field_pos_list=None):
""" 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 self.raw_packet_cache is not None:
for fname, fval in six.iteritems(self.raw_packet_cache_fields):
if self.getfieldval(fname) != fval:
self.raw_packet_cache = None
self.raw_packet_cache_fields = None
break
if self.raw_packet_cache is not None:
if conf.contribs['CAN']['swap-bytes']:
return CAN.inv_endianness(self.raw_packet_cache)
return self.raw_packet_cache
p = b""
for f in self.fields_desc:
val = self.getfieldval(f.name)
if isinstance(val, RawVal):
sval = raw(val)
p += sval
if field_pos_list is not None:
field_pos_list.append((f.name,
sval.encode('string_escape'),
len(p), len(sval)))
else:
p = f.addfield(self, p, val)
if conf.contribs['CAN']['swap-bytes']:
return CAN.inv_endianness(p)
return p
开发者ID:netkey,项目名称:scapy,代码行数:32,代码来源:can.py
示例10: send_wpa_enc
def send_wpa_enc(self, data, iv, seqnum, dest, mic_key,
key_idx=0, additionnal_flag=["from-DS"],
encrypt_key=None):
"""Send an encrypted packet with content @data, using IV @iv,
sequence number @seqnum, MIC key @mic_key
"""
if encrypt_key is None:
encrypt_key = self.tk
rep = RadioTap()
rep /= Dot11(
addr1=dest,
addr2=self.mac,
addr3=self.mac,
FCfield="+".join(['wep'] + additionnal_flag),
SC=(next(self.seq_num) << 4),
subtype=0,
type="Data",
)
# Assume packet is send by our AP -> use self.mac as source
# Encapsule in TKIP with MIC Michael and ICV
data_to_enc = build_MIC_ICV(raw(data), mic_key, self.mac, dest)
# Header TKIP + payload
rep /= Raw(build_TKIP_payload(data_to_enc, iv, self.mac, encrypt_key))
self.send(rep)
return rep
开发者ID:6WIND,项目名称:scapy,代码行数:31,代码来源:automaton.py
示例11: sixlowpan_fragment
def sixlowpan_fragment(packet, datagram_tag=1):
"""Split a packet into different links to transmit as 6lowpan packets.
Usage example:
>>> ipv6 = ..... (very big packet)
>>> pkts = sixlowpan_fragment(ipv6, datagram_tag=0x17)
>>> send = [Dot15d4()/Dot15d4Data()/x for x in pkts]
>>> wireshark(send)
"""
if not packet.haslayer(IPv6):
raise Exception("SixLoWPAN only fragments IPv6 packets !")
str_packet = raw(packet[IPv6])
if len(str_packet) <= MAX_SIZE:
return [packet]
def chunks(l, n):
return [l[i:i + n] for i in range(0, len(l), n)]
new_packet = chunks(str_packet, MAX_SIZE)
new_packet[0] = LoWPANFragmentationFirst(datagramTag=datagram_tag, datagramSize=len(str_packet)) / new_packet[0] # noqa: E501
i = 1
while i < len(new_packet):
new_packet[i] = LoWPANFragmentationSubsequent(datagramTag=datagram_tag, datagramSize=len(str_packet), datagramOffset=MAX_SIZE // 8 * i) / new_packet[i] # noqa: E501
i += 1
return new_packet
开发者ID:segment-routing,项目名称:scapy,代码行数:28,代码来源:sixlowpan.py
示例12: i2m
def i2m(self, pkt, x):
if x is None:
s = b""
else:
s = raw(x)
return BER_tagging_enc(s, implicit_tag=self.implicit_tag,
explicit_tag=self.explicit_tag)
开发者ID:commial,项目名称:scapy,代码行数:7,代码来源:asn1fields.py
示例13: send
def send(self, x):
try:
sx = raw(x)
x.sent_time = time.time()
self.outs.sendto(sx, (x.dst, 0))
except socket.error as msg:
log_runtime.error(msg)
开发者ID:commial,项目名称:scapy,代码行数:7,代码来源:supersocket.py
示例14: _decrypt_ah
def _decrypt_ah(self, pkt, verify=True):
if verify:
self.check_spi(pkt)
self.auth_algo.verify(pkt, self.auth_key)
ah = pkt[AH]
payload = ah.payload
payload.remove_underlayer(None) # useless argument...
if self.tunnel_header:
return payload
else:
ip_header = pkt
if ip_header.version == 4:
ip_header.proto = ah.nh
del ip_header.chksum
ip_header.remove_payload()
ip_header.len = len(ip_header) + len(payload)
# recompute checksum
ip_header = ip_header.__class__(raw(ip_header))
else:
ah.underlayer.nh = ah.nh
ah.underlayer.remove_payload()
ip_header.plen = len(ip_header.payload) + len(payload)
# reassemble the ip_header with the AH payload
return ip_header / payload
开发者ID:6WIND,项目名称:scapy,代码行数:29,代码来源:ipsec.py
示例15: post_build
def post_build(self, p, pay):
if self.properties == []:
p += raw(OFPQTNone())
if self.len is None:
l = len(p) + len(pay)
p = p[:4] + struct.pack("!H", l) + p[6:]
return p + pay
开发者ID:plorinquer,项目名称:scapy,代码行数:7,代码来源:openflow.py
示例16: _tls_P_hash
def _tls_P_hash(secret, seed, req_len, hm):
"""
Provides the implementation of P_hash function defined in
section 5 of RFC 4346 (and section 5 of RFC 5246). Two
parameters have been added (hm and req_len):
- secret : the key to be used. If RFC 4868 is to be believed,
the length must match hm.key_len. Actually,
python hmac takes care of formatting every key.
- seed : the seed to be used.
- req_len : the length of data to be generated by iterating
the specific HMAC function (hm). This prevents
multiple calls to the function.
- hm : the hmac function class to use for iteration (either
Hmac_MD5 or Hmac_SHA1 in TLS <= 1.1 or
Hmac_SHA256 or Hmac_SHA384 in TLS 1.2)
"""
hash_len = hm.hash_alg.hash_len
n = (req_len + hash_len - 1) // hash_len
res = b""
a = hm(secret).digest(seed) # A(1)
while n > 0:
res += hm(secret).digest(a + raw(seed))
a = hm(secret).digest(a)
n -= 1
return res[:req_len]
开发者ID:commial,项目名称:scapy,代码行数:29,代码来源:prf.py
示例17: send
def send(self, x):
data = raw(x)
if self.cls not in x:
raise Scapy_Exception("L3WinSocket can only send IP/IPv6 packets !"
" Install Npcap/Winpcap to send more")
dst_ip = str(x[self.cls].dst)
self.outs.sendto(data, (dst_ip, 0))
开发者ID:commial,项目名称:scapy,代码行数:7,代码来源:native.py
示例18: build
def build(self, pkt):
val = getattr(pkt, self.name)
if isinstance(val, ASN1_Object) and val.tag == ASN1_Class_UNIVERSAL.RAW: # noqa: E501
s = val
elif val is None:
s = b""
else:
s = b"".join(raw(i) for i in val)
return self.i2m(pkt, s)
开发者ID:commial,项目名称:scapy,代码行数:9,代码来源:asn1fields.py
示例19: __call__
def __call__(cls, key_path=None):
"""
key_path may be the path to either:
_an RSAPrivateKey_OpenSSL (as generated by openssl);
_an ECDSAPrivateKey_OpenSSL (as generated by openssl);
_an RSAPrivateKey;
_an ECDSAPrivateKey.
"""
if key_path is None:
obj = type.__call__(cls)
if cls is PrivKey:
cls = PrivKeyECDSA
obj.__class__ = cls
obj.frmt = "original"
obj.fill_and_store()
return obj
obj = _PKIObjMaker.__call__(cls, key_path, _MAX_KEY_SIZE)
multiPEM = False
try:
privkey = RSAPrivateKey_OpenSSL(obj.der)
privkey = privkey.privateKey
obj.__class__ = PrivKeyRSA
marker = b"PRIVATE KEY"
except Exception:
try:
privkey = ECDSAPrivateKey_OpenSSL(obj.der)
privkey = privkey.privateKey
obj.__class__ = PrivKeyECDSA
marker = b"EC PRIVATE KEY"
multiPEM = True
except Exception:
try:
privkey = RSAPrivateKey(obj.der)
obj.__class__ = PrivKeyRSA
marker = b"RSA PRIVATE KEY"
except Exception:
try:
privkey = ECDSAPrivateKey(obj.der)
obj.__class__ = PrivKeyECDSA
marker = b"EC PRIVATE KEY"
except Exception:
raise Exception("Unable to import private key")
try:
obj.import_from_asn1pkt(privkey)
except ImportError:
pass
if obj.frmt == "DER":
if multiPEM:
# this does not restore the EC PARAMETERS header
obj.pem = der2pem(raw(privkey), marker)
else:
obj.pem = der2pem(obj.der, marker)
return obj
开发者ID:commial,项目名称:scapy,代码行数:55,代码来源:cert.py
示例20: send
def send(self, x):
try:
return SuperSocket.send(self, x)
except socket.error as msg:
if msg.errno == 22 and len(x) < conf.min_pkt_size:
padding = b"\x00" * (conf.min_pkt_size - len(x))
if isinstance(x, Packet):
return SuperSocket.send(self, x / Padding(load=padding))
else:
return SuperSocket.send(self, raw(x) + padding)
raise
开发者ID:commial,项目名称:scapy,代码行数:11,代码来源:linux.py
注:本文中的scapy.compat.raw函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论