INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Process a received Flow Control frame | def _recv_fc(self, data):
"""Process a received 'Flow Control' frame"""
if (self.tx_state != ISOTP_WAIT_FC and
self.tx_state != ISOTP_WAIT_FIRST_FC):
return 0
self.tx_timer.cancel()
if len(data) < 3:
self.tx_state = ISOTP_IDLE
self.tx... |
Process a received Single Frame frame | def _recv_sf(self, data):
"""Process a received 'Single Frame' frame"""
self.rx_timer.cancel()
if self.rx_state != ISOTP_IDLE:
warning("RX state was reset because single frame was received")
self.rx_state = ISOTP_IDLE
length = six.indexbytes(data, 0) & 0xf
... |
Process a received First Frame frame | def _recv_ff(self, data):
"""Process a received 'First Frame' frame"""
self.rx_timer.cancel()
if self.rx_state != ISOTP_IDLE:
warning("RX state was reset because first frame was received")
self.rx_state = ISOTP_IDLE
if len(data) < 7:
return 1
... |
Process a received Consecutive Frame frame | def _recv_cf(self, data):
"""Process a received 'Consecutive Frame' frame"""
if self.rx_state != ISOTP_WAIT_DATA:
return 0
self.rx_timer.cancel()
# CFs are never longer than the FF
if len(data) > self.rx_ll_dl:
return 1
# CFs have usually the LL... |
Begins sending an ISOTP message. This method does not block. | def begin_send(self, x):
"""Begins sending an ISOTP message. This method does not block."""
with self.tx_mutex:
if self.tx_state != ISOTP_IDLE:
raise Scapy_Exception("Socket is already sending, retry later")
self.tx_done.clear()
self.tx_exception = No... |
Send an ISOTP frame and block until the message is sent or an error happens. | def send(self, p):
"""Send an ISOTP frame and block until the message is sent or an error
happens."""
with self.send_mutex:
self.begin_send(p)
# Wait until the tx callback is called
self.tx_done.wait()
if self.tx_exception is not None:
... |
Receive an ISOTP frame blocking if none is available in the buffer for at most timeout seconds. | def recv(self, timeout=None):
"""Receive an ISOTP frame, blocking if none is available in the buffer
for at most 'timeout' seconds."""
try:
return self.rx_queue.get(timeout is None or timeout > 0, timeout)
except queue.Empty:
return None |
If the server sent a CertificateRequest we send a Certificate message. If no certificate is available an empty Certificate message is sent: - this is a SHOULD in RFC 4346 ( Section 7. 4. 6 ) - this is a MUST in RFC 5246 ( Section 7. 4. 6 ) | def should_add_ClientCertificate(self):
"""
If the server sent a CertificateRequest, we send a Certificate message.
If no certificate is available, an empty Certificate message is sent:
- this is a SHOULD in RFC 4346 (Section 7.4.6)
- this is a MUST in RFC 5246 (Section 7.4.6)
... |
XXX Section 7. 4. 7. 1 of RFC 5246 states that the CertificateVerify message is only sent following a client certificate that has signing capability ( i. e. not those containing fixed DH params ). We should verify that before adding the message. We should also handle the case when the Certificate message was empty. | def should_add_ClientVerify(self):
"""
XXX Section 7.4.7.1 of RFC 5246 states that the CertificateVerify
message is only sent following a client certificate that has signing
capability (i.e. not those containing fixed DH params).
We should verify that before adding the message. W... |
The user may type in: GET/ HTTP/ 1. 1 \ r \ nHost: testserver. com \ r \ n \ r \ n Special characters are handled so that it becomes a valid HTTP request. | def add_ClientData(self):
"""
The user may type in:
GET / HTTP/1.1\r\nHost: testserver.com\r\n\r\n
Special characters are handled so that it becomes a valid HTTP request.
"""
if not self.data_to_send:
data = six.moves.input().replace('\\r', '\r').replace('\\n'... |
Returns the right parameter set class. | def dispatch_hook(cls, _pkt=None, *args, **kargs):
"""
Returns the right parameter set class.
"""
cls = conf.raw_layer
if _pkt is not None:
ptype = orb(_pkt[0])
return globals().get(_param_set_cls.get(ptype), conf.raw_layer)
return cls |
source_addr_mode | def source_addr_mode2(pkt):
"""source_addr_mode
This function depending on the arguments returns the amount of bits to be
used by the source address.
Keyword arguments:
pkt -- packet object instance
"""
if pkt.sac == 0x0:
if pkt.sam == 0x0:
return 16
elif pkt.sa... |
destiny_addr_mode | def destiny_addr_mode(pkt):
"""destiny_addr_mode
This function depending on the arguments returns the amount of bits to be
used by the destiny address.
Keyword arguments:
pkt -- packet object instance
"""
if pkt.m == 0 and pkt.dac == 0:
if pkt.dam == 0x0:
return 16
... |
This function extracts the source/ destination address of a 6LoWPAN from its upper Dot15d4Data ( 802. 15. 4 data ) layer. | def _extract_dot15d4address(pkt, source=True):
"""This function extracts the source/destination address of a 6LoWPAN
from its upper Dot15d4Data (802.15.4 data) layer.
params:
- source: if True, the address is the source one. Otherwise, it is the
destination.
returns: the packed & pr... |
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 ) | 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]
... |
Add an internal value to a string | def addfield(self, pkt, s, val):
"""Add an internal value to a string"""
tmp_len = self.length_of(pkt)
if tmp_len == 0:
return s
internal = self.i2m(pkt, val)[-tmp_len:]
return s + struct.pack("!%ds" % tmp_len, internal) |
Add an internal value to a string | def addfield(self, pkt, s, val):
"""Add an internal value to a string"""
if self.length_of(pkt) == 8:
return s + struct.pack(self.fmt[0] + "B", val)
if self.length_of(pkt) == 16:
return s + struct.pack(self.fmt[0] + "H", val)
if self.length_of(pkt) == 32:
... |
dissect the IPv6 package compressed into this IPHC packet. | def post_dissect(self, data):
"""dissect the IPv6 package compressed into this IPHC packet.
The packet payload needs to be decompressed and depending on the
arguments, several conversions should be done.
"""
# uncompress payload
packet = IPv6()
packet.version = ... |
Page 6 draft feb 2011 | def _getTrafficClassAndFlowLabel(self):
"""Page 6, draft feb 2011 """
if self.tf == 0x0:
return (self.tc_ecn << 6) + self.tc_dscp, self.flowlabel
elif self.tf == 0x1:
return (self.tc_ecn << 6), self.flowlabel
elif self.tf == 0x2:
return (self.tc_ecn <<... |
Depending on the payload content the frame type we should interpretate | def dispatch_hook(cls, _pkt=b"", *args, **kargs):
"""Depending on the payload content, the frame type we should interpretate""" # noqa: E501
if _pkt and len(_pkt) >= 1:
if orb(_pkt[0]) == 0x41:
return LoWPANUncompressedIPv6
if orb(_pkt[0]) == 0x42:
... |
Returns a one - line string containing every type/ value in a rather specific order. sorted () built - in ensures unicity. | def get_issuer_str(self):
"""
Returns a one-line string containing every type/value
in a rather specific order. sorted() built-in ensures unicity.
"""
name_str = ""
attrsDict = self.get_issuer()
for attrType, attrSymbol in _attrName_mapping:
if attrTyp... |
DEV: entry point. Will be called by sniff () for each received packet ( that passes the filters ). | def on_packet_received(self, pkt):
"""DEV: entry point. Will be called by sniff() for each
received packet (that passes the filters).
"""
if not pkt:
return
if self.store:
self.lst.append(pkt)
if self.prn:
result = self.prn(pkt)
... |
Bind 2 layers for dissection. The upper layer will be chosen for dissection on top of the lower layer if ALL the passed arguments are validated. If multiple calls are made with the same # noqa: E501 layers the last one will be used as default. | def bind_bottom_up(lower, upper, __fval=None, **fval):
"""Bind 2 layers for dissection.
The upper layer will be chosen for dissection on top of the lower layer, if
ALL the passed arguments are validated. If multiple calls are made with the same # noqa: E501
layers, the last one will be used as default.... |
Bind 2 layers for building. When the upper layer is added as a payload of the lower layer all the arguments # noqa: E501 will be applied to them. | def bind_top_down(lower, upper, __fval=None, **fval):
"""Bind 2 layers for building.
When the upper layer is added as a payload of the lower layer, all the arguments # noqa: E501
will be applied to them.
ex:
>>> bind_top_down(Ether, SNAP, type=0x1234)
>>> Ether()/SNAP()
<Ether ... |
Bind 2 layers on some specific fields values. It makes the packet being built # noqa: E501 and dissected when the arguments are present. | def bind_layers(lower, upper, __fval=None, **fval):
"""Bind 2 layers on some specific fields' values. It makes the packet being built # noqa: E501
and dissected when the arguments are present.
This functions calls both bind_bottom_up and bind_top_down, with all passed arguments. # noqa: E501
Please h... |
This call un - links an association that was made using bind_bottom_up. Have a look at help ( bind_bottom_up ) | def split_bottom_up(lower, upper, __fval=None, **fval):
"""This call un-links an association that was made using bind_bottom_up.
Have a look at help(bind_bottom_up)
"""
if __fval is not None:
fval.update(__fval)
def do_filter(params, cls):
params_is_invalid = any(
k not ... |
This call un - links an association that was made using bind_top_down. Have a look at help ( bind_top_down ) | def split_top_down(lower, upper, __fval=None, **fval):
"""This call un-links an association that was made using bind_top_down.
Have a look at help(bind_top_down)
"""
if __fval is not None:
fval.update(__fval)
if lower in upper._overload_fields:
ofval = upper._overload_fields[lower]
... |
Split 2 layers previously bound. This call un - links calls bind_top_down and bind_bottom_up. It is the opposite of # noqa: E501 bind_layers. | def split_layers(lower, upper, __fval=None, **fval):
"""Split 2 layers previously bound.
This call un-links calls bind_top_down and bind_bottom_up. It is the opposite of # noqa: E501
bind_layers.
Please have a look at their docs:
- help(split_bottom_up)
- help(split_top_down)
"""
if ... |
Function used to discover the Scapy layers and protocols. It helps to see which packets exists in contrib or layer files. | def explore(layer=None):
"""Function used to discover the Scapy layers and protocols.
It helps to see which packets exists in contrib or layer files.
params:
- layer: If specified, the function will explore the layer. If not,
the GUI mode will be activated, to browse the available layers... |
List available layers or infos on a given layer class or name. params: - obj: Packet/ packet name to use - case_sensitive: if obj is a string is it case sensitive? - verbose | def ls(obj=None, case_sensitive=False, verbose=False):
"""List available layers, or infos on a given layer class or name.
params:
- obj: Packet / packet name to use
- case_sensitive: if obj is a string, is it case sensitive?
- verbose
"""
is_string = isinstance(obj, six.string_types)
... |
Transform a layer into a fuzzy layer by replacing some default values by random objects | def fuzz(p, _inplace=0):
"""Transform a layer into a fuzzy layer by replacing some default values by random objects""" # noqa: E501
if not _inplace:
p = p.copy()
q = p
while not isinstance(q, NoPayload):
for f in q.fields_desc:
if isinstance(f, PacketListField):
... |
Initialize each fields of the fields_desc dict | def init_fields(self):
"""
Initialize each fields of the fields_desc dict
"""
if self.class_dont_cache.get(self.__class__, False):
self.do_init_fields(self.fields_desc)
else:
self.do_init_cached_fields() |
Initialize each fields of the fields_desc dict | def do_init_fields(self, flist):
"""
Initialize each fields of the fields_desc dict
"""
for f in flist:
self.default_fields[f.name] = copy.deepcopy(f.default)
self.fieldtype[f.name] = f
if f.holds_packets:
self.packetfields.append(f) |
Initialize each fields of the fields_desc dict or use the cached fields information | def do_init_cached_fields(self):
"""
Initialize each fields of the fields_desc dict, or use the cached
fields information
"""
cls_name = self.__class__
# Build the fields information
if Packet.class_default_fields.get(cls_name, None) is None:
self.pr... |
Prepare the cached fields of the fields_desc dict | def prepare_cached_fields(self, flist):
"""
Prepare the cached fields of the fields_desc dict
"""
cls_name = self.__class__
# Fields cache initialization
if flist:
Packet.class_default_fields[cls_name] = dict()
Packet.class_default_fields_ref[cls... |
DEV: will be called after a dissection is completed | def dissection_done(self, pkt):
"""DEV: will be called after a dissection is completed"""
self.post_dissection(pkt)
self.payload.dissection_done(pkt) |
Returns a deep copy of the instance. | def copy(self):
"""Returns a deep copy of the instance."""
clone = self.__class__()
clone.fields = self.copy_fields_dict(self.fields)
clone.default_fields = self.copy_fields_dict(self.default_fields)
clone.overloaded_fields = self.overloaded_fields.copy()
clone.underlayer... |
Return a list of slots and methods including those from subclasses. | def _superdir(self):
"""
Return a list of slots and methods, including those from subclasses.
"""
attrs = set()
cls = self.__class__
if hasattr(cls, '__all_slots__'):
attrs.update(cls.__all_slots__)
for bcls in cls.__mro__:
if hasattr(bcls,... |
Clear the raw packet cache for the field and all its subfields | def clear_cache(self):
"""Clear the raw packet cache for the field and all its subfields"""
self.raw_packet_cache = None
for _, fval in six.iteritems(self.fields):
if isinstance(fval, Packet):
fval.clear_cache()
self.payload.clear_cache() |
Create the default layer regarding fields_desc dict | def self_build(self, field_pos_list=None):
"""
Create the default layer regarding fields_desc dict
:param field_pos_list:
"""
if self.raw_packet_cache is not None:
for fname, fval in six.iteritems(self.raw_packet_cache_fields):
if self.getfieldval(fna... |
Create the default version of the layer | def do_build(self):
"""
Create the default version of the layer
:return: a string of the packet with the payload
"""
if not self.explicit:
self = next(iter(self))
pkt = self.self_build()
for t in self.post_transforms:
pkt = t(pkt)
... |
Create the current layer | def build(self):
"""
Create the current layer
:return: string of the packet with the payload
"""
p = self.do_build()
p += self.build_padding()
p = self.build_done(p)
return p |
Perform the dissection of the layer s payload | def do_dissect_payload(self, s):
"""
Perform the dissection of the layer's payload
:param str s: the raw layer
"""
if s:
cls = self.guess_payload_class(s)
try:
p = cls(s, _internal=1, _underlayer=self)
except KeyboardInterrupt:... |
DEV: Guesses the next payload class from layer bonds. Can be overloaded to use a different mechanism. | def guess_payload_class(self, payload):
"""
DEV: Guesses the next payload class from layer bonds.
Can be overloaded to use a different mechanism.
:param str payload: the layer's payload
:return: the payload class
"""
for t in self.aliastypes:
for fval... |
Removes fields values that are the same as default values. | def hide_defaults(self):
"""Removes fields' values that are the same as default values."""
# use list(): self.fields is modified in the loop
for k, v in list(six.iteritems(self.fields)):
v = self.fields[k]
if k in self.default_fields:
if self.default_field... |
returns a list of layer classes ( including subclasses ) in this packet | def layers(self):
"""returns a list of layer classes (including subclasses) in this packet""" # noqa: E501
layers = []
lyr = self
while lyr:
layers.append(lyr.__class__)
lyr = lyr.payload.getlayer(0, _subclass=True)
return layers |
Return the nb^th layer that is an instance of cls matching flt values. | def getlayer(self, cls, nb=1, _track=None, _subclass=None, **flt):
"""Return the nb^th layer that is an instance of cls, matching flt
values.
"""
if _subclass is None:
_subclass = self.match_subclass or None
if _subclass:
match = lambda cls1, cls2: issubclass(cls1... |
Internal method that shows or dumps a hierarchical view of a packet. Called by show. | def _show_or_dump(self, dump=False, indent=3, lvl="", label_lvl="", first_call=True): # noqa: E501
"""
Internal method that shows or dumps a hierarchical view of a packet.
Called by show.
:param dump: determine if it prints or returns the string value
:param int indent: the siz... |
Prints or returns ( when dump is true ) a hierarchical view of the packet. | def show(self, dump=False, indent=3, lvl="", label_lvl=""):
"""
Prints or returns (when "dump" is true) a hierarchical view of the
packet.
:param dump: determine if it prints or returns the string value
:param int indent: the size of indentation for each layer
:param str... |
Prints or returns ( when dump is true ) a hierarchical view of an assembled version of the packet so that automatic fields are calculated ( checksums etc. ) | def show2(self, dump=False, indent=3, lvl="", label_lvl=""):
"""
Prints or returns (when "dump" is true) a hierarchical view of an
assembled version of the packet, so that automatic fields are
calculated (checksums, etc.)
:param dump: determine if it prints or returns the string... |
sprintf ( format [ relax = 1 ] ) - > str where format is a string that can include directives. A directive begins and ends by % and has the following format % [ fmt [ r ] ] [ cls [: nb ]. ] field%. | def sprintf(self, fmt, relax=1):
"""sprintf(format, [relax=1]) -> str
where format is a string that can include directives. A directive begins and
ends by % and has the following format %[fmt[r],][cls[:nb].]field%.
fmt is a classic printf directive, "r" can be appended for raw substitution
(ex: IP.flags=0x18 i... |
Returns a string representing the command you have to type to obtain the same packet | def command(self):
"""
Returns a string representing the command you have to type to
obtain the same packet
"""
f = []
for fn, fv in six.iteritems(self.fields):
fld = self.get_field(fn)
if isinstance(fv, (list, dict, set)) and len(fv) == 0:
... |
XXX We should offer the right key according to the client s suites. For now server_rsa_key is only used for RSAkx but we should try to replace every server_key with both server_rsa_key and server_ecdsa_key. | def INIT_TLS_SESSION(self):
"""
XXX We should offer the right key according to the client's suites. For
now server_rsa_key is only used for RSAkx, but we should try to replace
every server_key with both server_rsa_key and server_ecdsa_key.
"""
self.cur_session = tlsSessio... |
We extract cipher suites candidates from the client s proposition. | def should_check_ciphersuites(self):
"""
We extract cipher suites candidates from the client's proposition.
"""
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.mykey, PrivKeyECDSA):
kx = "ECDSA"
if get_usable_ciphersuites(sel... |
Selecting a cipher suite should be no trouble as we already caught the None case previously. | def should_add_ServerHello(self):
"""
Selecting a cipher suite should be no trouble as we already caught
the None case previously.
Also, we do not manage extensions at all.
"""
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.myk... |
Mandatory arguments: @iface: interface to use ( must be in monitor mode ) @ap_mac: AP s MAC @ssid: AP s SSID @passphrase: AP s Passphrase ( min 8 char. ) | def parse_args(self, ap_mac, ssid, passphrase,
channel=None,
# KRACK attack options
double_3handshake=True,
encrypt_3handshake=True,
wait_3handshake=0,
double_gtk_refresh=True,
arp_target... |
Compute and install the PMK | def install_PMK(self):
"""Compute and install the PMK"""
self.pmk = PBKDF2HMAC(
algorithm=hashes.SHA1(),
length=32,
salt=self.ssid.encode(),
iterations=4096,
backend=default_backend(),
).derive(self.passphrase.encode()) |
Use the client nonce | def install_unicast_keys(self, client_nonce):
"""Use the client nonce @client_nonce to compute and install
PTK, KCK, KEK, TK, MIC (AP -> STA), MIC (STA -> AP)
"""
pmk = self.pmk
anonce = self.anonce
snonce = client_nonce
amac = mac2str(self.mac)
smac = mac... |
Compute a new GTK and install it alongs MIC ( AP - > Group = broadcast + multicast ) | def install_GTK(self):
"""Compute a new GTK and install it alongs
MIC (AP -> Group = broadcast + multicast)
"""
# Compute GTK
self.gtk_full = self.gen_nonce(32)
self.gtk = self.gtk_full[:16]
# Extract derivated keys
self.mic_ap_to_group = self.gtk_full[1... |
Build a packet with info describing the current AP For beacon/ proberesp use | def build_ap_info_pkt(self, layer_cls, dest):
"""Build a packet with info describing the current AP
For beacon / proberesp use
"""
return RadioTap() \
/ Dot11(addr1=dest, addr2=self.mac, addr3=self.mac) \
/ layer_cls(timestamp=0, beacon_interval=100,
... |
Build the Key Data Encapsulation for GTK KeyID: 0 Ref: 802. 11i p81 | def build_GTK_KDE(self):
"""Build the Key Data Encapsulation for GTK
KeyID: 0
Ref: 802.11i p81
"""
return b''.join([
b'\xdd', # Type KDE
chb(len(self.gtk_full) + 6),
b'\x00\x0f\xac', # OUI
b'\x01', # GTK KDE
b'\x00\x0... |
Send an encrypted packet with content | 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 Non... |
Send an Ethernet packet using the WPA channel Extra arguments will be ignored and are just left for compatibility | def send_ether_over_wpa(self, pkt, **kwargs):
"""Send an Ethernet packet using the WPA channel
Extra arguments will be ignored, and are just left for compatibility
"""
payload = LLC() / SNAP() / pkt[Ether].payload
dest = pkt.dst
if dest == "ff:ff:ff:ff:ff:ff":
... |
The purpose of the function is to make next message ( s ) available in self. buffer_in. If the list is not empty nothing is done. If not in order to fill it the function uses the data already available in self. remain_in from a previous call and waits till there are enough to dissect a TLS packet. Once dissected the co... | def get_next_msg(self, socket_timeout=2, retry=2):
"""
The purpose of the function is to make next message(s) available in
self.buffer_in. If the list is not empty, nothing is done. If not, in
order to fill it, the function uses the data already available in
self.remain_in from a... |
If the next message to be processed has type pkt_cls raise state. If there is no message waiting to be processed we try to get one with the default get_next_msg parameters. | def raise_on_packet(self, pkt_cls, state, get_next_msg=True):
"""
If the next message to be processed has type 'pkt_cls', raise 'state'.
If there is no message waiting to be processed, we try to get one with
the default 'get_next_msg' parameters.
"""
# Maybe we already pa... |
Add a new TLS or SSLv2 or TLS 1. 3 record to the packets buffered out. | def add_record(self, is_sslv2=None, is_tls13=None):
"""
Add a new TLS or SSLv2 or TLS 1.3 record to the packets buffered out.
"""
if is_sslv2 is None and is_tls13 is None:
v = (self.cur_session.tls_version or
self.cur_session.advertised_tls_version)
... |
Add a TLS message ( e. g. TLSClientHello or TLSApplicationData ) inside the latest record to be sent through the socket. We believe a good automaton should not use the first test. | def add_msg(self, pkt):
"""
Add a TLS message (e.g. TLSClientHello or TLSApplicationData)
inside the latest record to be sent through the socket.
We believe a good automaton should not use the first test.
"""
if not self.buffer_out:
self.add_record()
r... |
Send all buffered records and update the session accordingly. | def flush_records(self):
"""
Send all buffered records and update the session accordingly.
"""
s = b"".join(p.raw_stateful() for p in self.buffer_out)
self.socket.send(s)
self.buffer_out = [] |
A source PAN ID is included if and only if both src addr mode ! = 0 and PAN ID Compression in FCF == 0 | def util_srcpanid_present(pkt):
'''A source PAN ID is included if and only if both src addr mode != 0 and PAN ID Compression in FCF == 0''' # noqa: E501
if (pkt.underlayer.getfieldval("fcf_srcaddrmode") != 0) and (pkt.underlayer.getfieldval("fcf_panidcompress") == 0): # noqa: E501
return True
else... |
Convert internal value to a nice representation | def i2repr(self, pkt, x):
"""Convert internal value to a nice representation"""
if len(hex(self.i2m(pkt, x))) < 7: # short address
return hex(self.i2m(pkt, x))
else: # long address
x = "%016x" % self.i2m(pkt, x)
return ":".join(["%s%s" % (x[i], x[i + 1]) for... |
Add an internal value to a string | def addfield(self, pkt, s, val):
"""Add an internal value to a string"""
if self.adjust(pkt, self.length_of) == 2:
return s + struct.pack(self.fmt[0] + "H", val)
elif self.adjust(pkt, self.length_of) == 8:
return s + struct.pack(self.fmt[0] + "Q", val)
else:
... |
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 ): | 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 ... |
Provides the implementation of SSLv3 PRF function: | def _ssl_PRF(secret, seed, req_len):
"""
Provides the implementation of SSLv3 PRF function:
SSLv3-PRF(secret, seed) =
MD5(secret || SHA-1("A" || secret || seed)) ||
MD5(secret || SHA-1("BB" || secret || seed)) ||
MD5(secret || SHA-1("CCC" || secret || seed)) || ...
req_len sho... |
Provides the implementation of TLS PRF function as defined in section 5 of RFC 4346: | def _tls_PRF(secret, label, seed, req_len):
"""
Provides the implementation of TLS PRF function as defined in
section 5 of RFC 4346:
PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
P_SHA-1(S2, label + seed)
Parameters are:
- secret: the secret used by the... |
Provides the implementation of TLS 1. 2 PRF function as defined in section 5 of RFC 5246: | def _tls12_SHA256PRF(secret, label, seed, req_len):
"""
Provides the implementation of TLS 1.2 PRF function as
defined in section 5 of RFC 5246:
PRF(secret, label, seed) = P_SHA256(secret, label + seed)
Parameters are:
- secret: the secret used by the HMAC in the 2 expansion
fun... |
Return the 48 - byte master_secret computed from pre_master_secret client_random and server_random. See RFC 5246 section 6. 3. | def compute_master_secret(self, pre_master_secret,
client_random, server_random):
"""
Return the 48-byte master_secret, computed from pre_master_secret,
client_random and server_random. See RFC 5246, section 6.3.
"""
seed = client_random + server_ran... |
Perform the derivation of master_secret into a key_block of req_len requested length. See RFC 5246 section 6. 3. | def derive_key_block(self, master_secret, server_random,
client_random, req_len):
"""
Perform the derivation of master_secret into a key_block of req_len
requested length. See RFC 5246, section 6.3.
"""
seed = server_random + client_random
if self... |
Return verify_data based on handshake messages connection end master secret and read_or_write position. See RFC 5246 section 7. 4. 9. | def compute_verify_data(self, con_end, read_or_write,
handshake_msg, master_secret):
"""
Return verify_data based on handshake messages, connection end,
master secret, and read_or_write position. See RFC 5246, section 7.4.9.
Every TLS 1.2 cipher suite has a v... |
Postprocess cipher key for EXPORT ciphersuite i. e. weakens it. An export key generation example is given in section 6. 3. 1 of RFC 2246. See also page 86 of EKR s book. | def postprocess_key_for_export(self, key, client_random, server_random,
con_end, read_or_write, req_len):
"""
Postprocess cipher key for EXPORT ciphersuite, i.e. weakens it.
An export key generation example is given in section 6.3.1 of RFC 2246.
See als... |
Generate IV for EXPORT ciphersuite i. e. weakens it. An export IV generation example is given in section 6. 3. 1 of RFC 2246. See also page 86 of EKR s book. | def generate_iv_for_export(self, client_random, server_random,
con_end, read_or_write, req_len):
"""
Generate IV for EXPORT ciphersuite, i.e. weakens it.
An export IV generation example is given in section 6.3.1 of RFC 2246.
See also page 86 of EKR's book.
... |
Parse/ etc/ protocols and return values as a dictionary. | def load_protocols(filename, _integer_base=10):
""""Parse /etc/protocols and return values as a dictionary."""
spaces = re.compile(b"[ \t]+|\n")
dct = DADict(_name=filename)
try:
with open(filename, "rb") as fdesc:
for line in fdesc:
try:
shrp = li... |
Load manuf file from Wireshark. param: - filename: the file to load the manuf file from | def load_manuf(filename):
"""Load manuf file from Wireshark.
param:
- filename: the file to load the manuf file from"""
manufdb = ManufDA(_name=filename)
with open(filename, "rb") as fdesc:
for line in fdesc:
try:
line = line.strip()
if not line o... |
Find OUI name matching to a MAC | def lookup(self, mac):
"""Find OUI name matching to a MAC"""
oui = ":".join(mac.split(":")[:3]).upper()
return self[oui] |
Find all MACs registered to a OUI params: - name: the OUI name - case_sensitive: default to False returns: a dict of mac: tuples ( Name Extended Name ) | def reverse_lookup(self, name, case_sensitive=False):
"""Find all MACs registered to a OUI
params:
- name: the OUI name
- case_sensitive: default to False
returns: a dict of mac:tuples (Name, Extended Name)
"""
if case_sensitive:
filtr = lambda x, l:... |
In CCP the payload of a DTO packet is dependent on the cmd field of a corresponding CRO packet. Two packets correspond if there ctr field is equal. If answers detect the corresponding CRO it will interpret the payload of a DTO with the correct class. In CCP there is no other way to determine the class of a DTO payload.... | def answers(self, other):
"""In CCP, the payload of a DTO packet is dependent on the cmd field
of a corresponding CRO packet. Two packets correspond, if there
ctr field is equal. If answers detect the corresponding CRO, it will
interpret the payload of a DTO with the correct class. In CC... |
Read the version from git describe. It returns the latest tag with an optional suffix if the current directory is not exactly on the tag. | def _version_from_git_describe():
"""
Read the version from ``git describe``. It returns the latest tag with an
optional suffix if the current directory is not exactly on the tag.
Example::
$ git describe --always
v2.3.2-346-g164a52c075c8
The tag prefix (``v``) and the git commit ... |
We need to select the correct one on dissection. We use the length for that as 1 for client version would emply an empty list. | def _TLS_Ext_CertTypeDispatcher(m, *args, **kargs):
"""
We need to select the correct one on dissection. We use the length for
that, as 1 for client version would emply an empty list.
"""
tmp_len = struct.unpack("!H", m[2:4])[0]
if tmp_len == 1:
cls = TLS_Ext_ServerCertType
else:
... |
Reproduced from packet. py | def _show_or_dump(self, dump=False, indent=3,
lvl="", label_lvl="", first_call=True):
""" Reproduced from packet.py """
ct = AnsiColorTheme() if dump else conf.color_theme
s = "%s%s %s %s \n" % (label_lvl, ct.punct("###["),
ct.layer_name(self.... |
We try to compute a length usually from a msglen parsed earlier. If this length is 0 we consider selection_present ( from RFC 5246 ) to be False. This means that there should not be any length field. However with TLS 1. 3 zero lengths are always explicit. | def getfield(self, pkt, s):
"""
We try to compute a length, usually from a msglen parsed earlier.
If this length is 0, we consider 'selection_present' (from RFC 5246)
to be False. This means that there should not be any length field.
However, with TLS 1.3, zero lengths are always... |
There is a hack with the _ExtensionsField. i2len. It works only because we expect _ExtensionsField. i2m to return a string of the same size ( if not of the same value ) upon successive calls ( e. g. through i2len here then i2m when directly building the _ExtensionsField ). | def addfield(self, pkt, s, i):
"""
There is a hack with the _ExtensionsField.i2len. It works only because
we expect _ExtensionsField.i2m to return a string of the same size (if
not of the same value) upon successive calls (e.g. through i2len here,
then i2m when directly building ... |
Internal function used to generate the Records from their template. | def _GenNetflowRecordV9(cls, lengths_list):
"""Internal function used to generate the Records from
their template.
"""
_fields_desc = []
for j, k in lengths_list:
_f_data = NetflowV9TemplateFieldDecoders.get(k, None)
_f_type, _f_args = (
_f_data if isinstance(_f_data, tup... |
Used internally to process a single packet during defragmenting | def _netflowv9_defragment_packet(pkt, definitions, definitions_opts, ignored):
"""Used internally to process a single packet during defragmenting"""
# Dataflowset definitions
if NetflowFlowsetV9 in pkt:
current = pkt
while NetflowFlowsetV9 in current:
current = current[NetflowFlo... |
Process all NetflowV9/ 10 Packets to match IDs of the DataFlowsets with the Headers | def netflowv9_defragment(plist, verb=1):
"""Process all NetflowV9/10 Packets to match IDs of the DataFlowsets
with the Headers
params:
- plist: the list of mixed NetflowV9/10 packets.
- verb: verbose print (0/1)
"""
if not isinstance(plist, (PacketList, list)):
plist = [plist]
... |
Convert DER octet string to PEM format ( with optional header ) | def der2pem(der_string, obj="UNKNOWN"):
"""Convert DER octet string to PEM format (with optional header)"""
# Encode a byte string in PEM format. Header advertizes <obj> type.
pem_string = ("-----BEGIN %s-----\n" % obj).encode()
base64_string = base64.b64encode(der_string)
chunks = [base64_string[i:... |
Convert PEM string to DER format | def pem2der(pem_string):
"""Convert PEM string to DER format"""
# Encode all lines between the first '-----\n' and the 2nd-to-last '-----'.
pem_string = pem_string.replace(b"\r", b"")
first_idx = pem_string.find(b"-----\n") + 6
if pem_string.find(b"-----BEGIN", first_idx) != -1:
raise Except... |
Split PEM objects. Useful to process concatenated certificates. | def split_pem(s):
"""
Split PEM objects. Useful to process concatenated certificates.
"""
pem_strings = []
while s != b"":
start_idx = s.find(b"-----BEGIN")
if start_idx == -1:
break
end_idx = s.find(b"-----END")
end_idx = s.find(b"\n", end_idx) + 1
... |
Concatenate all the certificates ( PEM format for the export ) in anchor_list and write the result to file filename. On success filename is returned None otherwise. | def _create_ca_file(anchor_list, filename):
"""
Concatenate all the certificates (PEM format for the export) in
'anchor_list' and write the result to file 'filename'. On success
'filename' is returned, None otherwise.
If you are used to OpenSSL tools, this function builds a CAfile
that can be u... |
Verifies either a Cert or an X509_Cert. | 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') |
Note that this will always copy the signature field from the tbsCertificate into the signatureAlgorithm field of the result regardless of the coherence between its contents ( which might indicate ecdsa - with - SHA512 ) and the result ( e. g. RSA signing MD2 ). | def signTBSCert(self, tbsCert, h="sha256"):
"""
Note that this will always copy the signature field from the
tbsCertificate into the signatureAlgorithm field of the result,
regardless of the coherence between its contents (which might
indicate ecdsa-with-SHA512) and the result (e... |
Return True if the certificate is self - signed: - issuer and subject are the same - the signature of the certificate is valid. | def isSelfSigned(self):
"""
Return True if the certificate is self-signed:
- issuer and subject are the same
- the signature of the certificate is valid.
"""
if self.issuer_hash == self.subject_hash:
return self.isIssuerCert(self)
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.