class ConfClass(object):
class Interceptor(object):
class ProgPath(ConfClass):
class ConfigFieldList:
class Emphasize(ConfigFieldList):
class Resolve(ConfigFieldList):
class Num2Layer:
class LayersList(List[Type['scapy.packet.Packet']]):
class CommandsList(List[Callable[..., Any]]):
class CacheInstance(Dict[str, Any], object):
class NetCache:
class Conf(ConfClass):
    def configure(self, cnf):
    def __repr__(self):
    def __str__(self):
    def __init__(self,
                 name,  # type: str
                 default,  # type: Any
                 hook,  # type: Callable[..., Any]
                 args=None,  # type: Optional[List[Any]]
                 kargs=None  # type: Optional[Dict[str, Any]]
                 ):
    def __get__(self, obj, typ=None):
    def set_from_hook(obj, name, val):
    def __set__(self, obj, val):
def _readonly(name):
    def __init__(self):
    def _is_field(f):
    def _recalc_layer_list(self):
    def add(self, *flds):
    def remove(self, *flds):
    def __contains__(self, elt):
    def __repr__(self):
    def __init__(self):
    def register(self, num, layer):
    def register_num2layer(self, num, layer):
    def register_layer2num(self, num, layer):
    def __getitem__(self, item):
    def __contains__(self, item):
    def get(self,
            item,  # type: Union[int, Type[Packet]]
            default=None,  # type: Optional[Type[Packet]]
            ):
    def __repr__(self):
    def __init__(self):
    def __repr__(self):
    def register(self, layer):
    def layers(self):
    def filter(self, items):
    def unfilter(self):
    def __repr__(self):
    def register(self, cmd):
def lsc():
    def __init__(self, name="noname", timeout=None):
    def flush(self):
    def __getitem__(self, item):
    def get(self, item, default=None):
    def __setitem__(self, item, v):
    def update(self,  # type: ignore
               other,  # type: Any
               **kwargs  # type: Any
               ):
    def iteritems(self):
    def iterkeys(self):
    def __iter__(self):
    def itervalues(self):
    def items(self):
    def keys(self):
    def values(self):
    def __len__(self):
    def summary(self):
    def __repr__(self):
    def copy(self):
    def __init__(self):
    def add_cache(self, cache):
    def new_cache(self, name, timeout=None):
    def __delattr__(self, attr):
    def update(self, other):
    def flush(self):
    def __repr__(self):
def _version_checker(module, minver):
def isCryptographyValid():
def isCryptographyAdvanced():
def isPyPy():
def _prompt_changer(attr, val, old):
def _set_conf_sockets():
def _socket_changer(attr, val, old):
def _loglevel_changer(attr, val, old):
def _iface_changer(attr, val, old):
    def __getattribute__(self, attr):
def crypto_validator(func):
    def func_in(*args, **kwargs):
def scapy_delete_temp_files(): class ByteEnumField(EnumField[int]):
    def __init__(self, name, default, enum):
        # type: (str, Optional[int], Dict[int, str]) -> None
        EnumField.__init__(self, name, default, enum, "B") class PacketListField(_PacketField[List[BasePacket]]):
    """PacketListField represents a list containing a series of Packet instances
    that might occur right in the middle of another Packet field.
    This field type may also be used to indicate that a series of Packet
    instances have a sibling semantic instead of a parent/child relationship
    (i.e. a stack of layers).
    """
    __slots__ = ["count_from", "length_from", "next_cls_cb"]
    islist = 1

    def __init__(
            self,
            name,  # type: str
            default,  # type: Optional[List[BasePacket]]
            pkt_cls=None,  # type: Optional[Union[Callable[[bytes], Packet], Type[Packet]]]  # noqa: E501
            count_from=None,  # type: Optional[Callable[[Packet], int]]
            length_from=None,  # type: Optional[Callable[[Packet], int]]
            next_cls_cb=None,  # type: Optional[Callable[[Packet, List[BasePacket], Optional[Packet], bytes], Type[Packet]]]  # noqa: E501
    ):
        # type: (...) -> None
        """
        The number of Packet instances that are dissected by this field can
        be parametrized using one of three different mechanisms/parameters:

            * count_from: a callback that returns the number of Packet
              instances to dissect. The callback prototype is::

                count_from(pkt:Packet) -> int

            * length_from: a callback that returns the number of bytes that
              must be dissected by this field. The callback prototype is::

                length_from(pkt:Packet) -> int

            * next_cls_cb: a callback that enables a Scapy developer to
              dynamically discover if another Packet instance should be
              dissected or not. See below for this callback prototype.

        The bytes that are not consumed during the dissection of this field
        are passed to the next field of the current packet.

        For the serialization of such a field, the list of Packets that are
        contained in a PacketListField can be heterogeneous and is
        unrestricted.

        The type of the Packet instances that are dissected with this field is
        specified or discovered using one of the following mechanism:

            * the pkt_cls parameter may contain a callable that returns an
              instance of the dissected Packet. This may either be a
              reference of a Packet subclass (e.g. DNSRROPT in layers/dns.py)
              to generate an homogeneous PacketListField or a function
              deciding the type of the Packet instance
              (e.g. _CDPGuessAddrRecord in contrib/cdp.py)

            * the pkt_cls parameter may contain a class object with a defined
              ``dispatch_hook`` classmethod. That method must return a Packet
              instance. The ``dispatch_hook`` callmethod must implement the
                following prototype::

                dispatch_hook(cls,
                              _pkt:Optional[Packet],
                              *args, **kargs
                ) -> Type[Packet]

                The _pkt parameter may contain a reference to the packet
                instance containing the PacketListField that is being
                dissected.

            * the ``next_cls_cb`` parameter may contain a callable whose
              prototype is::

                cbk(pkt:Packet,
                    lst:List[Packet],
                    cur:Optional[Packet],
                    remain:str
                ) -> Optional[Type[Packet]]

              The pkt argument contains a reference to the Packet instance
              containing the PacketListField that is being dissected.
              The lst argument is the list of all Packet instances that were
              previously parsed during the current ``PacketListField``
              dissection, saved for the very last Packet instance.
              The cur argument contains a reference to that very last parsed
              ``Packet`` instance. The remain argument contains the bytes
              that may still be consumed by the current PacketListField
              dissection operation.

              This callback returns either the type of the next Packet to
              dissect or None to indicate that no more Packet are to be
              dissected.

              These four arguments allows a variety of dynamic discovery of
              the number of Packet to dissect and of the type of each one of
              these Packets, including: type determination based on current
              Packet instances or its underlayers, continuation based on the
              previously parsed Packet instances within that PacketListField,
              continuation based on a look-ahead on the bytes to be
              dissected...

        The pkt_cls and next_cls_cb parameters are semantically exclusive,
        although one could specify both. If both are specified, pkt_cls is
        silently ignored. The same is true for count_from and next_cls_cb.

        length_from and next_cls_cb are compatible and the dissection will
        end, whichever of the two stop conditions comes first.

        :param name: the name of the field
        :param default: the default value of this field; generally an empty
            Python list
        :param pkt_cls: either a callable returning a Packet instance or a
            class object defining a ``dispatch_hook`` class method
        :param count_from: a callback returning the number of Packet
            instances to dissect.
        :param length_from: a callback returning the number of bytes to dissect
        :param next_cls_cb: a callback returning either None or the type of
            the next Packet to dissect.
        """
        if default is None:
            default = []  # Create a new list for each instance
        super(PacketListField, self).__init__(
            name,
            default,
            pkt_cls  # type: ignore
        )
        self.count_from = count_from
        self.length_from = length_from
        self.next_cls_cb = next_cls_cb

    def any2i(self, pkt, x):
        # type: (Optional[Packet], Any) -> List[BasePacket]
        if not isinstance(x, list):
            return [x]
        else:
            return x

    def i2count(self,
                pkt,  # type: Optional[Packet]
                val,  # type: List[BasePacket]
                ):
        # type: (...) -> int
        if isinstance(val, list):
            return len(val)
        return 1

    def i2len(self,
              pkt,  # type: Optional[Packet]
              val,  # type: List[Packet]
              ):
        # type: (...) -> int
        return sum(len(p) for p in val)

    def getfield(self, pkt, s):
        # type: (Packet, bytes) -> Tuple[bytes, List[BasePacket]]
        c = len_pkt = cls = None
        if self.length_from is not None:
            len_pkt = self.length_from(pkt)
        elif self.count_from is not None:
            c = self.count_from(pkt)
        if self.next_cls_cb is not None:
            cls = self.next_cls_cb(pkt, [], None, s)
            c = 1
            if cls is None:
                c = 0

        lst = []  # type: List[BasePacket]
        ret = b""
        remain = s
        if len_pkt is not None:
            remain, ret = s[:len_pkt], s[len_pkt:]
        while remain:
            if c is not None:
                if c <= 0:
                    break
                c -= 1
            try:
                if cls is not None:
                    p = cls(remain)
                else:
                    p = self.m2i(pkt, remain)
            except Exception:
                if conf.debug_dissector:
                    raise
                p = conf.raw_layer(load=remain)
                remain = b""
            else:
                if conf.padding_layer in p:
                    pad = p[conf.padding_layer]
                    remain = pad.load
                    del(pad.underlayer.payload)
                    if self.next_cls_cb is not None:
                        cls = self.next_cls_cb(pkt, lst, p, remain)
                        if cls is not None:
                            c = 0 if c is None else c
                            c += 1
                else:
                    remain = b""
            lst.append(p)
        return remain + ret, lst

    def addfield(self, pkt, s, val):
        # type: (Packet, bytes, Any) -> bytes
        return s + b"".join(bytes_encode(v) for v in val) class StrField(_StrField[bytes]):
    pass def raw(x):
    # type: (Union[Packet]) -> bytes
    """
    Builds a packet and returns its bytes representation.
    This function is and will always be cross-version compatible
    """
    if hasattr(x, "__bytes__"):
        return x.__bytes__()
    return bytes(x) def chb(x):
    # type: (int) -> bytes
    if isinstance(x, str):
        return x
    return chr(x) def orb(x):
    # type: (Union[int, str, bytes]) -> int
    """Return ord(x) when not already an int."""
    if isinstance(x, int):
        return x
    return ord(x) def randstring(length):
    # type: (int) -> bytes
    """
    Returns a random string of length (length >= 0)
    """
    return b"".join(struct.pack('B', random.randint(0, 255))
                    for _ in range(length)) class Raw(Packet):
    name = "Raw"
    fields_desc = [StrField("load", b"")]

    def __init__(self, _pkt=b"", *args, **kwargs):
        # type: (bytes, *Any, **Any) -> None
        if _pkt and not isinstance(_pkt, bytes):
            _pkt = bytes_encode(_pkt)
        super(Raw, self).__init__(_pkt, *args, **kwargs)

    def answers(self, other):
        # type: (Packet) -> int
        return 1

    def mysummary(self):
        # type: () -> str
        cs = conf.raw_summary
        if cs:
            if callable(cs):
                return "Raw %s" % cs(self.load)
            else:
                return "Raw %r" % self.load
        return Packet.mysummary(self) class Padding(Raw):
    name = "Padding"

    def self_build(self, field_pos_list=None):
        # type: (Optional[Any]) -> bytes
        return b""

    def build_padding(self):
        # type: () -> bytes
        return (
            bytes_encode(self.load) if self.raw_packet_cache is None
            else self.raw_packet_cache
        ) + self.payload.build_padding() @conf.commands.register
def bind_layers(lower,  # type: Type[Packet]
                upper,  # type: Type[Packet]
                __fval=None,  # type: Optional[Dict[str, int]]
                **fval  # type: Any
                ):
    # type: (...) -> None
    """Bind 2 layers on some specific fields' values.

    It makes the packet being built and dissected when the arguments
    are present.

    This function calls both bind_bottom_up and bind_top_down, with
    all passed arguments.

    Please have a look at their docs:
     - help(bind_bottom_up)
     - help(bind_top_down)
     """
    if __fval is not None:
        fval.update(__fval)
    bind_top_down(lower, upper, **fval)
    bind_bottom_up(lower, upper, **fval) class TCP(Packet):
    name = "TCP"
    fields_desc = [ShortEnumField("sport", 20, TCP_SERVICES),
                   ShortEnumField("dport", 80, TCP_SERVICES),
                   IntField("seq", 0),
                   IntField("ack", 0),
                   BitField("dataofs", None, 4),
                   BitField("reserved", 0, 3),
                   FlagsField("flags", 0x2, 9, "FSRPAUECN"),
                   ShortField("window", 8192),
                   XShortField("chksum", None),
                   ShortField("urgptr", 0),
                   TCPOptionsField("options", "")]

    def post_build(self, p, pay):
        p += pay
        dataofs = self.dataofs
        if dataofs is None:
            opt_len = len(self.get_field("options").i2m(self, self.options))
            dataofs = 5 + ((opt_len + 3) // 4)
            dataofs = (dataofs << 4) | orb(p[12]) & 0x0f
            p = p[:12] + chb(dataofs & 0xff) + p[13:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                ck = in4_chksum(socket.IPPROTO_TCP, self.underlayer, p)
                p = p[:16] + struct.pack("!H", ck) + p[18:]
            elif conf.ipv6_enabled and isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):  # noqa: E501
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_TCP, self.underlayer, p)  # noqa: E501
                p = p[:16] + struct.pack("!H", ck) + p[18:]
            else:
                log_runtime.info(
                    "No IP underlayer to compute checksum. Leaving null."
                )
        return p

    def hashret(self):
        if conf.checkIPsrc:
            return struct.pack("H", self.sport ^ self.dport) + self.payload.hashret()  # noqa: E501
        else:
            return self.payload.hashret()

    def answers(self, other):
        if not isinstance(other, TCP):
            return 0
        # RST packets don't get answers
        if other.flags.R:
            return 0
        # We do not support the four-way handshakes with the SYN+ACK
        # answer split in two packets (one ACK and one SYN): in that
        # case the ACK will be seen as an answer, but not the SYN.
        if self.flags.S:
            # SYN packets without ACK are not answers
            if not self.flags.A:
                return 0
            # SYN+ACK packets answer SYN packets
            if not other.flags.S:
                return 0
        if conf.checkIPsrc:
            if not ((self.sport == other.dport) and
                    (self.dport == other.sport)):
                return 0
        # Do not check ack value for SYN packets without ACK
        if not (other.flags.S and not other.flags.A) \
           and abs(other.ack - self.seq) > 2:
            return 0
        # Do not check ack value for RST packets without ACK
        if self.flags.R and not self.flags.A:
            return 1
        if abs(other.seq - self.ack) > 2 + len(other.payload):
            return 0
        return 1

    def mysummary(self):
        if isinstance(self.underlayer, IP):
            return self.underlayer.sprintf("TCP %IP.src%:%TCP.sport% > %IP.dst%:%TCP.dport% %TCP.flags%")  # noqa: E501
        elif conf.ipv6_enabled and isinstance(self.underlayer, scapy.layers.inet6.IPv6):  # noqa: E501
            return self.underlayer.sprintf("TCP %IPv6.src%:%TCP.sport% > %IPv6.dst%:%TCP.dport% %TCP.flags%")  # noqa: E501
        else:
            return self.sprintf("TCP %TCP.sport% > %TCP.dport% %TCP.flags%") class _GenericTLSSessionInheritance(Packet):
    """
    Many classes inside the TLS module need to get access to session-related
    information. For instance, an encrypted TLS record cannot be parsed without
    some knowledge of the cipher suite being used and the secrets which have
    been negotiated. Passing information is also essential to the handshake.
    To this end, various TLS objects inherit from the present class.
    """
    __slots__ = ["tls_session", "rcs_snap_init", "wcs_snap_init"]
    name = "Dummy Generic TLS Packet"
    fields_desc = []

    def __init__(self, _pkt="", post_transform=None, _internal=0,
                 _underlayer=None, tls_session=None, **fields):
        try:
            setme = self.tls_session is None
        except Exception:
            setme = True

        newses = False
        if setme:
            if tls_session is None:
                newses = True
                self.tls_session = tlsSession()
            else:
                self.tls_session = tls_session

        self.rcs_snap_init = self.tls_session.rcs.snapshot()
        self.wcs_snap_init = self.tls_session.wcs.snapshot()

        if isinstance(_underlayer, TCP):
            tcp = _underlayer
            self.tls_session.sport = tcp.sport
            self.tls_session.dport = tcp.dport
            try:
                self.tls_session.ipsrc = tcp.underlayer.src
                self.tls_session.ipdst = tcp.underlayer.dst
            except AttributeError:
                pass

            # Load a NSS Key Log file
            if conf.tls_nss_filename is not None:
                if conf.tls_nss_keys is None:
                    conf.tls_nss_keys = load_nss_keys(conf.tls_nss_filename)

            if conf.tls_session_enable:
                if newses:
                    s = conf.tls_sessions.find(self.tls_session)
                    if s:
                        if conf.tls_nss_keys is not None:
                            s.nss_keys = conf.tls_nss_keys
                        if s.dport == self.tls_session.dport:
                            self.tls_session = s
                        else:
                            self.tls_session = s.mirror()
                    else:
                        if conf.tls_nss_keys is not None:
                            self.tls_session.nss_keys = conf.tls_nss_keys
                        conf.tls_sessions.add(self.tls_session)
            if self.tls_session.connection_end == "server":
                srk = conf.tls_sessions.server_rsa_key
                if not self.tls_session.server_rsa_key and \
                        srk:
                    self.tls_session.server_rsa_key = srk

        Packet.__init__(self, _pkt=_pkt, post_transform=post_transform,
                        _internal=_internal, _underlayer=_underlayer,
                        **fields)

    def __getattr__(self, attr):
        """
        The tls_session should be found only through the normal mechanism.
        """
        if attr == "tls_session":
            return None
        return super(_GenericTLSSessionInheritance, self).__getattr__(attr)

    def tls_session_update(self, msg_str):
        """
        post_{build, dissection}_tls_session_update() are used to update the
        tlsSession context. The default definitions below, along with
        tls_session_update(), may prevent code duplication in some cases.
        """
        pass

    def post_build_tls_session_update(self, msg_str):
        self.tls_session_update(msg_str)

    def post_dissection_tls_session_update(self, msg_str):
        self.tls_session_update(msg_str)

    def copy(self):
        pkt = Packet.copy(self)
        pkt.tls_session = self.tls_session
        return pkt

    def clone_with(self, payload=None, **kargs):
        pkt = Packet.clone_with(self, payload=payload, **kargs)
        pkt.tls_session = self.tls_session
        return pkt

    def raw_stateful(self):
        return super(_GenericTLSSessionInheritance, self).__bytes__()

    def str_stateful(self):
        return self.raw_stateful()

    def __bytes__(self):
        """
        The __bytes__ call has to leave the connection states unchanged.
        We also have to delete raw_packet_cache in order to access post_build.

        For performance, the pending connStates are not snapshotted.
        This should not be an issue, but maybe pay attention to this.

        The previous_freeze_state prevents issues with calling a raw() calling
        in turn another raw(), which would unfreeze the session too soon.
        """
        s = self.tls_session
        rcs_snap = s.rcs.snapshot()
        wcs_snap = s.wcs.snapshot()
        rpc_snap = self.raw_packet_cache
        rpcf_snap = self.raw_packet_cache_fields

        s.wcs = self.rcs_snap_init

        self.raw_packet_cache = None
        previous_freeze_state = s.frozen
        s.frozen = True
        built_packet = super(_GenericTLSSessionInheritance, self).__bytes__()
        s.frozen = previous_freeze_state

        s.rcs = rcs_snap
        s.wcs = wcs_snap
        self.raw_packet_cache = rpc_snap
        self.raw_packet_cache_fields = rpcf_snap

        return built_packet
    __str__ = __bytes__

    def show2(self):
        """
        Rebuild the TLS packet with the same context, and then .show() it.
        We need self.__class__ to call the subclass in a dynamic way.

        Howether we do not want the tls_session.{r,w}cs.seq_num to be updated.
        We have to bring back the init states (it's possible the cipher context
        has been updated because of parsing) but also to keep the current state
        and restore it afterwards (the raw() call may also update the states).
        """
        s = self.tls_session
        rcs_snap = s.rcs.snapshot()
        wcs_snap = s.wcs.snapshot()

        s.rcs = self.rcs_snap_init

        built_packet = raw(self)
        s.frozen = True
        self.__class__(built_packet, tls_session=s).show()
        s.frozen = False

        s.rcs = rcs_snap
        s.wcs = wcs_snap

    def mysummary(self):
        return "TLS %s / %s" % (repr(self.tls_session),
                                getattr(self, "_name", self.name))

    @classmethod
    def tcp_reassemble(cls, data, metadata):
        # Used with TLSSession
        from scapy.layers.tls.record import TLS
        from scapy.layers.tls.record_tls13 import TLS13
        if cls in (TLS, TLS13):
            length = struct.unpack("!H", data[3:5])[0] + 5
            if len(data) == length:
                return cls(data)
            elif len(data) > length:
                pkt = cls(data)
                if hasattr(pkt.payload, "tcp_reassemble"):
                    if pkt.payload.tcp_reassemble(data[length:], metadata):
                        return pkt
                else:
                    return pkt
        else:
            return cls(data) class _TLSHandshake(_GenericTLSSessionInheritance):
class TLSHelloRequest(_TLSHandshake):
class _GMTUnixTimeField(UTCTimeField):
class _TLSRandomBytesField(StrFixedLenField):
class _SessionIDField(StrLenField):
class _CipherSuitesField(StrLenField):
class _CompressionMethodsField(_CipherSuitesField):
class TLSClientHello(_TLSHandshake):
class TLS13ClientHello(_TLSHandshake):
class TLSServerHello(_TLSHandshake):
class TLS13ServerHello(TLSServerHello):
class TLS13HelloRetryRequest(_TLSHandshake):
class TLSEncryptedExtensions(_TLSHandshake):
class _ASN1CertLenField(FieldLenField):
class _ASN1CertListField(StrLenField):
class _ASN1CertField(StrLenField):
class TLSCertificate(_TLSHandshake):
class _ASN1CertAndExt(_GenericTLSSessionInheritance):
class _ASN1CertAndExtListField(PacketListField):
class TLS13Certificate(_TLSHandshake):
class TLSServerKeyExchange(_TLSHandshake):
class _CertTypesField(_CipherSuitesField):
class _CertAuthoritiesField(StrLenField):
class TLSCertificateRequest(_TLSHandshake):
class TLS13CertificateRequest(_TLSHandshake):
class TLSServerHelloDone(_TLSHandshake):
class TLSCertificateVerify(_TLSHandshake):
class _TLSCKExchKeysField(PacketField):
class TLSClientKeyExchange(_TLSHandshake):
class _VerifyDataField(StrLenField):
class TLSFinished(_TLSHandshake):
class TLSHelloVerifyRequest(_TLSHandshake):
class URLAndOptionalHash(Packet):
class TLSCertificateURL(_TLSHandshake):
class ThreeBytesLenField(FieldLenField):
class _StatusField(PacketLenField):
class TLSCertificateStatus(_TLSHandshake):
class SupDataEntry(Packet):
class UserMappingData(Packet):
class SupDataEntryUM(Packet):
class TLSSupplementalData(_TLSHandshake):
class TLSNewSessionTicket(_TLSHandshake):
class TLS13NewSessionTicket(_TLSHandshake):
class TLS13EndOfEarlyData(_TLSHandshake):
class TLS13KeyUpdate(_TLSHandshake):
    def post_build(self, p, pay):
    def guess_payload_class(self, p):
    def tls_session_update(self, msg_str):
    def tls_session_update(self, msg_str):
    def i2h(self, pkt, x):
    def i2m(self, pkt, x):
    def i2repr(self, pkt, x):
    def __init__(self, name, default, dico, length_from=None, itemfmt="!H"):
    def any2i_one(self, pkt, x):
    def i2repr_one(self, pkt, x):
    def any2i(self, pkt, x):
    def i2repr(self, pkt, x):
    def i2m(self, pkt, val):
    def m2i(self, pkt, m):
    def i2len(self, pkt, i):
    def any2i_one(self, pkt, x):
    def post_build(self, p, pay):
    def tls_session_update(self, msg_str):
    def post_build(self, p, pay):
    def tls_session_update(self, msg_str):
    def dispatch_hook(cls, _pkt=None, *args, **kargs):
    def post_build(self, p, pay):
    def tls_session_update(self, msg_str):
    def dispatch_hook(cls, _pkt=None, *args, **kargs):
    def post_build(self, p, pay):
    def tls_session_update(self, msg_str):
    def build(self):
    def tls_session_update(self, msg_str):
    def post_build_tls_session_update(self, msg_str):
    def post_dissection_tls_session_update(self, msg_str):
    def __init__(self, name, default, length_of=None, adjust=lambda pkt, x: x):
    def i2m(self, pkt, x):
    def addfield(self, pkt, s, val):
    def getfield(self, pkt, s):
    def i2len(self, pkt, i):
    def getfield(self, pkt, s):
    def i2m(self, pkt, i):
        def i2m_one(i):
    def any2i(self, pkt, x):
    def i2len(self, pkt, i):
    def getfield(self, pkt, s):
    def i2m(self, pkt, i):
        def i2m_one(i):
    def any2i(self, pkt, x):
    def dispatch_hook(cls, _pkt=None, *args, **kargs):
    def post_dissection_tls_session_update(self, msg_str):
    def extract_padding(self, s):
    def m2i(self, pkt, m):
    def post_dissection_tls_session_update(self, msg_str):
    def build(self, *args, **kargs):
    def post_dissection(self, pkt):
    def getfield(self, pkt, s):
    def m2i(self, pkt, m):
    def i2m(self, pkt, i):
    def addfield(self, pkt, s, val):
    def i2len(self, pkt, val):
    def build(self, *args, **kargs):
    def post_dissection(self, pkt):
    def __init__(self, name, length_from=None):
    def m2i(self, pkt, m):
    def build(self, *args, **kargs):
    def tls_session_update(self, msg_str):
    def getfield(self, pkt, s):
    def build(self, *args, **kargs):
    def post_dissection(self, pkt):
    def post_build_tls_session_update(self, msg_str):
    def post_dissection_tls_session_update(self, msg_str):
    def guess_payload_class(self, p):
    def __init__(self, name, default, length_of=None, adjust=lambda pkt, x: x):
    def i2repr(self, pkt, x):
    def addfield(self, pkt, s, val):
    def getfield(self, pkt, s):
    def m2i(self, pkt, m):
    def guess_payload_class(self, p):
    def guess_payload_class(self, p):
    def guess_payload_class(self, p):
    def dispatch_hook(cls, _pkt=None, *args, **kargs):
    def post_dissection_tls_session_update(self, msg_str):
    def build(self):
    def post_dissection_tls_session_update(self, msg_str):
    def post_build_tls_session_update(self, msg_str):
    def post_dissection_tls_session_update(self, msg_str):
import struct
import scapy.modules.six as six
from scapy.config import conf
from scapy.error import log_runtime
from scapy.fields import ByteEnumField, PacketListField, StrField
from scapy.compat import raw, chb, orb
from scapy.utils import randstring
from scapy.packet import Raw, Padding, bind_layers
from scapy.layers.inet import TCP
from scapy.layers.tls.session import _GenericTLSSessionInheritance
from scapy.layers.tls.handshake import (_tls_handshake_cls, _TLSHandshake,
                                        _tls13_handshake_cls, TLS13ServerHello,
                                        TLS13ClientHello)
from scapy.layers.tls.basefields import (_TLSVersionField, _tls_version,
                                         _TLSIVField, _TLSMACField,
                                         _TLSPadField, _TLSPadLenField,
                                         _TLSLengthField, _tls_type)
from scapy.layers.tls.crypto.pkcs1 import pkcs_i2osp
from scapy.layers.tls.crypto.cipher_aead import AEADTagError
from scapy.layers.tls.crypto.cipher_stream import Cipher_NULL
from scapy.layers.tls.crypto.common import CipherError
from scapy.layers.tls.crypto.h_mac import HMACError
    from scapy.layers.tls.crypto.cipher_aead import Cipher_CHACHA20_POLY1305
    from scapy.layers.tls.handshake_sslv2 import _sslv2_handshake_type
                        from scapy.layers.tls.record_sslv2 import SSLv2
                        from scapy.layers.tls.record_tls13 import TLS13
# This file is part of Scapy
# Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
#               2015, 2016, 2017 Maxence Tury
#               2019 Romain Perez
#               2019 Gabriel Potter
# This program is published under a GPLv2 license

"""
Common TLS fields & bindings.

This module covers the record layer, along with the ChangeCipherSpec, Alert and
ApplicationData submessages. For the Handshake type, see tls_handshake.py.

See the TLS class documentation for more information.
"""


if conf.crypto_valid_advanced:

# Util


def _tls_version_check(version, min):
    """Returns if version >= min, or False if version == None"""
    if version is None:
        return False
    return version >= min

###############################################################################
#   TLS Record Protocol                                                       #
###############################################################################


class _TLSEncryptedContent(Raw, _GenericTLSSessionInheritance):
    """
    When the content of a TLS record (more precisely, a TLSCiphertext) could
    not be deciphered, we use this class to represent the encrypted data.
    The MAC will still be parsed from the whole message, even though it could
    not been verified. When present (depending on cipher type and protocol
    version), the nonce_explicit, IV and/or padding will also be parsed.
    """
    name = "Encrypted Content"
    match_subclass = True


class _TLSMsgListField(PacketListField):
    """
    This is the actual content of the TLS record. As a TLS record may pack
    multiple sublayer messages (notably, several handshake messages),
    we inherit from PacketListField.
    """

    def __init__(self, name, default, length_from=None):
        if not length_from:
            length_from = self._get_length
        super(_TLSMsgListField, self).__init__(name, default, None,
                                               length_from=length_from)

    def _get_length(self, pkt):
        if pkt.deciphered_len is None:
            return pkt.len
        return pkt.deciphered_len

    def m2i(self, pkt, m):
        """
        Try to parse one of the TLS subprotocols (ccs, alert, handshake or
        application_data). This is used inside a loop managed by .getfield().
        """
        cls = Raw
        if pkt.type == 22:
            if len(m) >= 1:
                msgtype = orb(m[0])
                # If a version was agreed on by both client and server,
                # we use it (tls_session.tls_version)
                # Otherwise, if the client advertised for TLS 1.3, we try to
                # dissect the following packets (most likely, server hello)
                # using TLS 1.3. The serverhello is able to fallback on
                # TLS 1.2 if necessary. In any case, this will set the agreed
                # version so that all future packets are correct.
                if ((pkt.tls_session.advertised_tls_version == 0x0304 and
                        pkt.tls_session.tls_version is None) or
                        pkt.tls_session.tls_version == 0x0304):
                    cls = _tls13_handshake_cls.get(msgtype, Raw)
                else:

                    cls = _tls_handshake_cls.get(msgtype, Raw)