INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 Certific...
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 This function depending on the arguments returns the amount of bits to be used by the source address. Keyword arguments: pkt -- packet object instance
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 This function depending on the arguments returns the amount of bits to be used by the destiny address. Keyword arguments: pkt -- packet object instance
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. params: - source: if True, the address is the source one. Otherwise, it is the destination. returns: the packed & processed address
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. The packet payload needs to be decompressed and depending on the arguments, several conversions should be done.
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. ex: >>> bind_bottom_up(Ether, SNAP, type=0x1234)...
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. ex: >>> bind_top_down(Ether, SNAP, type=0x1234) >>> Ether()/SNAP() <Ether type=0x1234 |<SNAP |>>
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. This functions calls both bind_bottom_up and bind_top_down, with all passed arguments. # noqa: E501 Please have a look at their docs: - help(bind_bottom_up) ...
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. Please have a look at their docs: - help(split_bottom_up) - help(split_top_down)
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. params: - layer: If specified, the function will explore the layer. If not, the GUI mode will be activated, to browse the available layers examples: >>> explor...
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...
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...
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)
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 :param field_pos_list:
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 :return: a string of the packet with the payload
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 :return: string of the packet with the payload
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 :param str s: the raw layer
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. :param str payload: the layer's payload :return: the payload class
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...
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 lvl: additional information about the layer lvl :param str label_lvl: a...
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.) :param dump: determine if it prints or returns the string value :param int indent: the size of indentation for each layer ...
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...
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. Also, we do not manage extensions at all.
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.) Optional arguments: @channel: used by the interface. Default 6, autodetected on windows Krack attacks options: ...
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 @client_nonce to compute and install PTK, KCK, KEK, TK, MIC (AP -> STA), MIC (STA -> AP)
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 @data, using IV @iv, sequence number @seqnum, MIC key @mic_key
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...
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): - secret : the key to be used. If RFC 4868 is to be believed, the length must match hm.key_len. Actually, python hmac t...
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: 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 should not be more than 26 x 16 = 416.
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: PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed) Parameters are: - secret: the secret used by the HMAC in the 2 expansion functions (S1 and...
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: PRF(secret, label, seed) = P_SHA256(secret, label + seed) Parameters are: - secret: the secret used by the HMAC in the 2 expansion functions (S1 and S2 are the halves of this secret). - label: s...
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. Every TLS 1.2 cipher suite has a verify_data of length 12. Note also: "This PRF with the SHA-256 hash function is used for all cipher suites defined i...
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 ...
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. Example:: $ git describe --always v2.3.2-346-g164a52c075c8 The tag prefix (``v``) and the git commit sha1 (``-g164a52c075c8``) are removed if p...
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). XXX A proper way to...
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 params: - plist: the list of mixed NetflowV9/10 packets. - verb: verbose print (0/1)
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. If you are used to OpenSSL tools, this function builds a CAfile that can be used for certificate and CRL check.
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). There is a small inheritance tric...
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
Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL and is now valid again in a new CRL and bot ar...
def isRevoked(self, crl_list): """ Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL and...
Export certificate in 'fmt' format (DER or PEM) to file 'filename'
def export(self, filename, fmt="DER"): """ Export certificate in 'fmt' format (DER or PEM) to file 'filename' """ f = open(filename, "wb") if fmt == "DER": f.write(self.der) elif fmt == "PEM": f.write(self.pem) f.close()
Perform verification of certificate chains for that certificate. A list of anchors is required. The certificates in the optional untrusted list may be used as additional elements to the final chain. On par with chain instantiation, only one chain constructed with the untrusted candidates...
def verifyChain(self, anchors, untrusted=None): """ Perform verification of certificate chains for that certificate. A list of anchors is required. The certificates in the optional untrusted list may be used as additional elements to the final chain. On par with chain instantiati...
Does the same job as .verifyChain() but using the list of anchors from the cafile. As for .verifyChain(), a list of untrusted certificates can be passed (as a file, this time).
def verifyChainFromCAFile(self, cafile, untrusted_file=None): """ Does the same job as .verifyChain() but using the list of anchors from the cafile. As for .verifyChain(), a list of untrusted certificates can be passed (as a file, this time). """ try: f = open...
Does the same job as .verifyChainFromCAFile() but using the list of anchors in capath directory. The directory should (only) contain certificates files in PEM format. As for .verifyChainFromCAFile(), a list of untrusted certificates can be passed as a file (concatenation of the certifica...
def verifyChainFromCAPath(self, capath, untrusted_file=None): """ Does the same job as .verifyChainFromCAFile() but using the list of anchors in capath directory. The directory should (only) contain certificates files in PEM format. As for .verifyChainFromCAFile(), a list of untr...
DEV: true if self is an answer from other
def answers(self, other): """DEV: true if self is an answer from other""" if other.__class__ == self.__class__: return (other.service + 0x40) == self.service or \ (self.service == 0x7f and self.request_service_id == other.service) return False
Function used in the sending thread of sndrcv()
def _sndrcv_snd(pks, timeout, inter, verbose, tobesent, hsent, timessent, stopevent): # noqa: E501 """Function used in the sending thread of sndrcv()""" try: i = 0 rec_time = timessent is not None if verbose: print("Begin emission:") for p in tobesent: # ...
Function used to receive packets and check their hashret
def _sndrcv_rcv(pks, hsent, stopevent, nbrecv, notans, verbose, chainCC, multi, _storage_policy=None): """Function used to receive packets and check their hashret""" if not _storage_policy: _storage_policy = lambda x, y: (x, y) ans = [] def _get_pkt(): # SuperSocket.sele...
Scapy raw function to send a packet and receive its answer. WARNING: This is an internal function. Using sr/srp/sr1/srp is more appropriate in many cases.
def sndrcv(pks, pkt, timeout=None, inter=0, verbose=None, chainCC=False, retry=0, multi=False, rcv_pks=None, store_unanswered=True, process=None, prebuild=False): """Scapy raw function to send a packet and receive its answer. WARNING: This is an internal function. Using sr/srp/sr1/srp is ...
Send packets at layer 3 send(packets, [inter=0], [loop=0], [count=None], [verbose=conf.verb], [realtime=None], [return_packets=False], # noqa: E501 [socket=None]) -> None
def send(x, inter=0, loop=0, count=None, verbose=None, realtime=None, return_packets=False, socket=None, *args, **kargs): """Send packets at layer 3 send(packets, [inter=0], [loop=0], [count=None], [verbose=conf.verb], [realtime=None], [return_packets=False], # noqa: E501 [socket=None]) -> N...