### setup() Source: https://tlslite-ng.readthedocs.io/en/latest/genindex.html Sets up the TLSXMLRPCRequestHandler. ```APIDOC ## setup() ### Description Sets up the TLSXMLRPCRequestHandler. ### Method This is a method of the TLSXMLRPCRequestHandler class. ### Parameters (Parameters not specified in the source) ### Request Example (No example provided in the source) ### Response (Response details not specified in the source) ``` -------------------------------- ### Example Usage with Medusa Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.integration.tlsasyncdispatchermixin.html An example demonstrating how to use TLSAsyncDispatcherMixIn with the Medusa framework by creating a custom http_tls_channel class. ```APIDOC from tlslite import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) cert_chain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) class http_tls_channel(TLSAsyncDispatcherMixIn, http_server.http_channel): ac_in_buffer_size = 16384 def __init__ (self, server, conn, addr): http_server.http_channel.__init__(self, server, conn, addr) TLSAsyncDispatcherMixIn.__init__(self, conn) self.tlsConnection.ignoreAbruptClose = True self.setServerHandshakeOp(certChain=cert_chain, privateKey=privateKey) hs.channel_class = http_tls_channel ``` -------------------------------- ### Integrating TLSAsyncDispatcherMixIn with http_server Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.integration.tlsasyncdispatchermixin.html Example demonstrating how to combine TLSAsyncDispatcherMixIn with http_server.http_channel to create an HTTP TLS channel. Ensure the input buffer size is at least 16K. This setup is for use with Medusa. ```python from tlslite import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) cert_chain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) class http_tls_channel(TLSAsyncDispatcherMixIn, http_server.http_channel): ac_in_buffer_size = 16384 def __init__ (self, server, conn, addr): http_server.http_channel.__init__(self, server, conn, addr) TLSAsyncDispatcherMixIn.__init__(self, conn) self.tlsConnection.ignoreAbruptClose = True self.setServerHandshakeOp(certChain=cert_chain, privateKey=privateKey) hs.channel_class = http_tls_channel ``` -------------------------------- ### Threaded HTTPS Server Example Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.integration.tlssocketservermixin.html Example of a threaded HTTPS server using TLSSocketServerMixIn. It demonstrates setting up certificates, private keys, and handling TLS handshakes. ```python from SocketServer import * from BaseHTTPServer import * from SimpleHTTPServer import * from tlslite import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) cert_chain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) sessionCache = SessionCache() class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn, HTTPServer): def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=cert_chain, privateKey=privateKey, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except TLSError, error: print "Handshake failure:", str(error) return False httpd = MyHTTPServer(('localhost', 443), SimpleHTTPRequestHandler) httpd.serve_forever() ``` -------------------------------- ### Initialize Key-Related Settings Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/handshakesettings.html Sets default values for key exchange parameters, signature hashes, and elliptic curves. Includes conditional setup for ML-KEM if available. ```python def _init_key_settings(self): """Create default variables for key-related settings.""" self.minKeySize = 1023 self.maxKeySize = 8193 self.rsaSigHashes = list(RSA_SIGNATURE_HASHES) self.rsaSchemes = list(RSA_SCHEMES) self.dsaSigHashes = list(DSA_SIGNATURE_HASHES) self.virtual_hosts = [] # DH key settings self.eccCurves = list(CURVE_NAMES) self.dhParams = None self.dhGroups = list(ALL_DH_GROUP_NAMES) self.defaultCurve = "secp256r1" if ML_KEM_AVAILABLE: self.keyShares = ["x25519mlkem768"] else: self.keyShares = [] self.keyShares += ["secp256r1", "x25519"] self.padding_cb = None self.use_heartbeat_extension = True self.heartbeat_response_callback = None ``` -------------------------------- ### Start Write Operation - AsyncStateMachine Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/asyncstatemachine.html Initiates an asynchronous write operation to send data over the TLS connection. The provided `writeBuffer` is passed to `tlsConnection.writeAsync()`. Includes error handling for setup. ```python def setWriteOp(self, writeBuffer): """Start a write operation. :param str writeBuffer: The string to transmit. """ try: self._checkAssert(0) self.writer = self.tlsConnection.writeAsync(writeBuffer) self._doWriteOp() except: self._clear() raise ``` -------------------------------- ### Start Server Handshake Operation - AsyncStateMachine Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/asyncstatemachine.html Starts a server-side handshake operation by forwarding arguments to `TLSConnection.handshakeServerAsync`. This is a convenience method for setting up server handshakes. ```python def setServerHandshakeOp(self, **args): """Start a handshake operation. The arguments passed to this function will be forwarded to :py:obj:`~tlslite.tlsconnection.TLSConnection.handshakeServerAsync`. """ handshaker = self.tlsConnection.handshakeServerAsync(**args) self.setHandshakeOp(handshaker) ``` -------------------------------- ### Get All Usernames Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/basedb.html Returns a list of all usernames (keys) present in the database, excluding any keys that start with '--Reserved--'. This operation is thread-safe. ```python def keys(self): """ Return a list of usernames in the database. :rtype: list :returns: The usernames in the database. """ if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: usernames = self.db.keys() finally: self.lock.release() usernames = [u for u in usernames if not u.startswith("--Reserved--")] return usernames ``` -------------------------------- ### Initialize ServerCertTypeExtension Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Creates an instance of ServerCertTypeExtension. Use this when you need to manage server certificate types. ```python super(ServerCertTypeExtension, self).__init__( 1, 'cert_type', ext_type=ExtensionType.cert_type, item_enum=CertificateType) self.serverType = True ``` -------------------------------- ### Start Close Operation - AsyncStateMachine Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/asyncstatemachine.html Initiates an asynchronous TLS connection closing operation. It calls `tlsConnection.closeAsync()` and handles the generator's progression. Errors during setup will clear the state. ```python def setCloseOp(self): """Start a close operation. """ try: self._checkAssert(0) self.closer = self.tlsConnection.closeAsync() self._doCloseOp() except: self._clear() raise ``` -------------------------------- ### Create SNIExtension with Hostnames Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes an SNIExtension with provided hostname, host names, or raw server names. Handles cases where parameters are None, empty lists, or multiple parameters are specified. ```python if hostname is None and hostNames is None and serverNames is None: self.serverNames = None return self else: self.serverNames = [] if hostname: self.serverNames += [SNIExtension.ServerName(NameType.host_name, hostname)] if hostNames: self.serverNames += [SNIExtension.ServerName(NameType.host_name, x) for x in hostNames] if serverNames: self.serverNames += serverNames return self ``` -------------------------------- ### ClientKeyShareExtension Initialization Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes the ClientKeyShareExtension for handling client hello key shares. Sets the extension type to key_share. ```python super(ClientKeyShareExtension, self).__init__(extType=ExtensionType. key_share) self.client_shares = None ``` -------------------------------- ### Initialize SNIExtension Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Creates an instance of SNIExtension. Use this to initialize the extension. ```python super(SNIExtension, self).__init__(extType=ExtensionType.server_name) self.serverNames = None ``` -------------------------------- ### ServerKeyShareExtension Initialization Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes the ServerKeyShareExtension for handling server hello key shares. Sets the extension type and marks it as server-side. ```python super(ServerKeyShareExtension, self).__init__(extType=ExtensionType. key_share, server=True) self.server_share = None ``` -------------------------------- ### __init__ Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.tlsrecordlayer.html Initializes the TLSRecordLayer object. ```APIDOC ## __init__(_sock_) ### Description Initializes the TLSRecordLayer object with the given socket. ### Parameters - **_sock_** (_socket.socket_) - The underlying socket object for the connection. ``` -------------------------------- ### tlslite.utils.datefuncs.getNow() Source: https://tlslite-ng.readthedocs.io/en/latest/genindex.html Gets the current date and time. ```APIDOC ## getNow() ### Description Gets the current date and time. ### Method `getNow()` ### Returns - (datetime) - The current datetime object. ``` -------------------------------- ### Initialize Defragmenter Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/defragmenter.html Sets up an empty defragmenter with empty priorities, buffers, and decoders. ```python self.priorities = [] self.buffers = {} self.decoders = {} ``` -------------------------------- ### tlslite.utils.codec.Parser.getRemainingLength() Source: https://tlslite-ng.readthedocs.io/en/latest/genindex.html Gets the remaining number of bytes to be parsed. ```APIDOC ## Parser.getRemainingLength() ### Description Gets the remaining number of bytes to be parsed. ### Method `getRemainingLength()` ### Returns - (int) - The number of remaining bytes. ``` -------------------------------- ### ClientHelper Constructor Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/clienthelper.html Initializes the ClientHelper with authentication credentials, certificate information, and optional settings for TLS connections. ```APIDOC ## ClientHelper.__init__ ### Description Initializes the ClientHelper with authentication credentials, certificate information, and optional settings for TLS connections. The constructor does not perform the TLS handshake itself but stores arguments for later use. ### Parameters - **username** (str) - Optional - SRP username. Requires the 'password' argument. - **password** (str) - Optional - SRP password for mutual authentication. Requires the 'username' argument. - **certChain** (X509CertChain) - Optional - Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes SRP arguments. - **privateKey** (RSAKey) - Optional - Private key for client authentication. Requires the 'certChain' argument. Excludes SRP arguments. - **checker** (Checker) - Optional - Callable object called after handshaking to evaluate the connection and raise an Exception if necessary. - **settings** (HandshakeSettings) - Optional - Various settings to control ciphersuites, certificate types, and SSL/TLS versions offered by the client. - **anon** (bool) - Optional - Set to True to advertise only anonymous TLS ciphersuites. Mutually exclusive with client certificate authentication or SRP authentication. - **host** (str or None) - Optional - The hostname that the connection is made to. Can be an IP address or include the port. ``` -------------------------------- ### getCipherName Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.tlsrecordlayer.html Gets the name of the cipher used for this connection. ```APIDOC ## getCipherName() ### Description Get the name of the cipher used with this connection. ### Return Type str ### Returns ``` -------------------------------- ### ClientKeyShareExtension create Method Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Sets the client shares to be advertised in the extension. Takes a list of KeyShareEntry objects. ```python self.client_shares = client_shares return self ``` -------------------------------- ### Version Property Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.tlsrecordlayer.html Get the SSL protocol version of the connection. ```APIDOC ## property version ### Description Get the SSL protocol version of connection ``` -------------------------------- ### getCipherImplementation Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.tlsrecordlayer.html Gets the name of the cipher implementation used for this connection. ```APIDOC ## getCipherImplementation() ### Description Get the name of the cipher implementation used with this connection. ### Return Type str ### Returns The name of the cipher implementation used with this connection. Either ‘python’, ‘openssl’, or ‘pycrypto’. ``` -------------------------------- ### ServerHello Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.messages.html Handles Server Hello messages. ```APIDOC ## Class: ServerHello ### Description Handles Server Hello messages, inheriting from HelloMessage. ### Variables - `server_version` (tuple): Protocol version encoded as a two-integer tuple. - `random` (bytearray): Server random value. - `session_id` (bytearray): Session identifier for resumption. - `cipher_suite` (int): Server selected cipher suite. - `compression_method` (int): Server selected compression method. - `next_protos` (list of bytearray): List of advertised protocols in NPN extension. - `next_protos_advertised` (list of bytearray): List of protocols advertised in NPN extension. - `certificate_type` (int): Certificate type selected by server. - `extensions` (list): List of TLS extensions present in the server_hello message. ### Methods - `__init__()`: Initialize ServerHello object. - `__repr__()`: Return repr(self). - `__str__()`: Return str(self). - `create(_version_, _random_, _session_id_, _cipher_suite_, _certificate_type=None_, _tackExt=None_, _next_protos_advertised=None_, _extensions=None_)`: Initialize the object for deserialization. Parameters `version`, `random`, `session_id`, `cipher_suite` are required. `certificate_type`, `tackExt`, `next_protos_advertised`, `extensions` are optional. - `parse(_p_)`: Parse the message. - `write()`: Serialize the message. ### Properties - `certificate_type` (int): Return the certificate type selected by the server. - `next_protos` (list of bytearrays): Return the advertised protocols in the NPN extension. - `next_protos_advertised` (list of bytearrays): Return the advertised protocols in the NPN extension. - `tackExt`: Return the TACK extension. ``` -------------------------------- ### ServerKeyShareExtension Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.extensions.html Handles the Server Hello variant of the Key Share extension. This extension is used for sending the key shares from the server to the client. ```APIDOC ## class tlslite.extensions.ServerKeyShareExtension ### Description Class for handling the Server Hello variant of the Key Share extension. Extension for sending the key shares to client. ### Methods #### `__init__()` Creates an instance of the object. #### `create(_server_share_)` Sets the advertised server share in the extension. #### `parse(_parser_)` Parses the extension from its on-the-wire format. **Parameters**: - `parser` (Parser): Data to be parsed. **Returns**: - ServerKeyShareExtension: The parsed ServerKeyShareExtension instance. ### Properties #### `extData` Serializes the payload of the extension. **Returns**: - bytearray: The serialized extension payload. ``` -------------------------------- ### setServerHandshakeOp Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/asyncstatemachine.html Starts a server-side handshake operation. Arguments are forwarded to `TLSConnection.handshakeServerAsync`. ```APIDOC ## setServerHandshakeOp(**args) ### Description Start a handshake operation. The arguments passed to this function will be forwarded to :py:obj:`~tlslite.tlsconnection.TLSConnection.handshakeServerAsync`. ### Method `setServerHandshakeOp` ``` -------------------------------- ### Create PreSharedKey Extension Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Sets the list of offered PSKs (identities and binders) for the PreSharedKeyExtension. ```python def create(self, identities, binders): """Set list of offered PSKs.""" self.identities = identities self.binders = binders return self ``` -------------------------------- ### setWriteOp Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/asyncstatemachine.html Starts an asynchronous write operation, sending the provided buffer over the TLS connection. ```APIDOC ## setWriteOp(writeBuffer) ### Description Start a write operation. :param str writeBuffer: The string to transmit. ### Method `setWriteOp` ``` -------------------------------- ### Get Socket Name Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/bufferedsocket.html Emulates the socket.getsockname() method, returning the socket's own address. ```python def getsockname(self): """Return the socket's own address (socket emulation).""" return self.socket.getsockname() ``` -------------------------------- ### ClientHelper Initialization with SRP Authentication Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/clienthelper.html Initialize ClientHelper for SRP authentication using username and password. This constructor stores arguments for a later TLS handshake and does not perform it immediately. Ensure correct SRP credentials are provided. ```python from tlslite.checker import Checker from tlslite.utils.dns_utils import is_valid_hostname class ClientHelper(object): """This is a helper class used to integrate TLS Lite with various TLS clients (e.g. poplib, smtplib, httplib, etc.)""" def __init__(self, username=None, password=None, certChain=None, privateKey=None, checker=None, settings=None, anon=False, host=None): """ For client authentication, use one of these argument combinations: - username, password (SRP) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP, or you can do certificate-based server authentication with one of these argument combinations: - x509Fingerprint Certificate-based server authentication is compatible with SRP or certificate-based client authentication. The constructor does not perform the TLS handshake itself, but simply stores these arguments for later. The handshake is performed only when this class needs to connect with the server. Then you should be prepared to handle TLS-specific exceptions. See the client handshake functions in :py:class:`~tlslite.tlsconnection.TLSConnection` for details on which exceptions might be raised. :param str username: SRP username. Requires the 'password' argument. :param str password: SRP password for mutual authentication. Requires the 'username' argument. :param X509CertChain certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP arguments. :param RSAKey privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP arguments. :param Checker checker: Callable object called after handshaking to evaluate the connection and raise an Exception if necessary. :type settings: HandshakeSettings :param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. :param bool anon: set to True if the negotiation should advertise only anonymous TLS ciphersuites. Mutually exclusive with client certificate authentication or SRP authentication :type host: str or None :param host: the hostname that the connection is made to. Can be an IP address (in which case the SNI extension won't be sent). Can include the port (in which case the port will be stripped and ignored). """ self.username = None self.password = None self.certChain = None self.privateKey = None self.checker = None self.anon = anon #SRP Authentication if username and password and not \ (certChain or privateKey): self.username = username self.password = password #Certificate Chain Authentication elif certChain and privateKey and not \ (username or password): self.certChain = certChain self.privateKey = privateKey #No Authentication elif not password and not username and not \ certChain and not privateKey: pass else: raise ValueError("Bad parameters") self.checker = checker self.settings = settings self.tlsSession = None if host is not None and not self._isIP(host): # name for SNI so port can't be sent colon = host.find(':') if colon > 0: host = host[:colon] self.serverName = host if host and not is_valid_hostname(host): raise ValueError("Invalid hostname: {0}".format(host)) else: self.serverName = None @staticmethod def _isIP(address): """Return True if the address is an IPv4 address""" if not address: return False vals = address.split('.') if len(vals) != 4: return False for i in vals: if not i.isdigit(): return False j = int(i) if not 0 <= j <= 255: return False return True def _handshake(self, tlsConnection): if self.username and self.password: tlsConnection.handshakeClientSRP(username=self.username, ``` -------------------------------- ### TLSXMLRPCRequestHandler Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.integration.xmlrpcserver.html A request handler for XML-RPC over TLS. It extends SimpleXMLRPCRequestHandler and handles TLS setup for incoming connections. ```APIDOC ## Class: TLSXMLRPCRequestHandler ### Description XMLRPCRequestHandler using TLS. ### Methods - do_POST() Handle the HTTPS POST request. - setup() Setup the connection for TLS. ``` -------------------------------- ### ALPNExtension Create Method Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Creates an instance of ALPNExtension with the specified list of protocol names. ```python def create(self, protocol_names=None): """ Create an instance of ALPNExtension with specified protocols :param list protocols: list of protocol names that are to be sent """ self.protocol_names = protocol_names return self ``` -------------------------------- ### ServerKeyShareExtension create Method Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Sets the server share to be advertised in the extension. Takes a single KeyShareEntry object. ```python self.server_share = server_share return self ``` -------------------------------- ### Get Peer Name Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/bufferedsocket.html Emulates the socket.getpeername() method, returning the address of the remote endpoint the socket is connected to. ```python def getpeername(self): """ Return the remote address to which the socket is connected (socket emulation) """ return self.socket.getpeername() ``` -------------------------------- ### setHandshakeOp Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/asyncstatemachine.html Starts a handshake operation using a provided generator. This is a core method for initiating asynchronous TLS handshakes. ```APIDOC ## setHandshakeOp(handshaker) ### Description Start a handshake operation. :param generator handshaker: A generator created by using one of the asynchronous handshake functions (i.e. :py:meth:`~.TLSConnection.handshakeServerAsync` , or handshakeClientxxx(..., async_=True). ### Method `setHandshakeOp` ``` -------------------------------- ### Get Hostnames from SNIExtension Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Retrieves a tuple of hostnames (bytearrays) from the SNIExtension. Returns an empty tuple if serverNames is None. ```python if self.serverNames is None: return tuple() return tuple([x.name for x in self.serverNames if x.name_type == NameType.host_name]) ``` -------------------------------- ### Initialize NPNExtension Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Creates an instance of NPNExtension, used for the Next Protocol Negotiation TLS extension. Initializes protocols to None. ```python super(NPNExtension, self).__init__(extType=ExtensionType.supports_npn) self.protocols = None ``` -------------------------------- ### Get Socket Timeout Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/bufferedsocket.html Emulates the socket.gettimeout() method, returning the current timeout value associated with socket operations. ```python def gettimeout(self): """ Return the timeout associated with socket operations (socket emulation) """ return self.socket.gettimeout() ``` -------------------------------- ### Create TACKExtension Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes a TACKExtension instance with provided tacks and activation flags. Used to set the extension's data before serialization. ```python def create(self, tacks, activation_flags): """ Initialize the instance of TACKExtension :rtype: TACKExtension """ self.tacks = tacks self.activation_flags = activation_flags return self ``` -------------------------------- ### Initialize Miscellaneous Extensions Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/handshakesettings.html Configures default settings for various TLS extensions, including certificate types, fallback SCSV, and encryption modes. Also initializes settings for PSKs and session tickets. ```python def _init_misc_extensions(self): """Default variables for assorted extensions.""" self.certificateTypes = list(CERTIFICATE_TYPES) self.useExperimentalTackExtension = False self.sendFallbackSCSV = False self.useEncryptThenMAC = True self.ecdsaSigHashes = list(ECDSA_SIGNATURE_HASHES) self.more_sig_schemes = list(SIGNATURE_SCHEMES) self.usePaddingExtension = True self.useExtendedMasterSecret = True self.requireExtendedMasterSecret = False # PSKs self.pskConfigs = [] self.psk_modes = list(PSK_MODES) # session tickets self.ticketKeys = [] self.ticketCipher = "aes256gcm" self.ticketLifetime = 24 * 60 * 60 self.max_early_data = 2 ** 14 + 16 # full record + tag # send two tickets so that client can quickly ramp up number of # resumed connections (as tickets are single-use in TLS 1.3 self.ticket_count = 2 self.record_size_limit = 2**14 + 1 # TLS 1.3 includes content type ``` -------------------------------- ### parsePEMKey Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.utils.keyfactory.html Parses a PEM-formatted key, which can be either public or private. Supports password-encrypted private keys if OpenSSL and M2Crypto are installed. ```APIDOC ## parsePEMKey ### Description Parse a PEM-format key. The PEM format is used by OpenSSL and other tools. The format is typically used to store both the public and private components of a key. ### Parameters #### Arguments * **s** (str) – A string containing a PEM-encoded public or private key. * **private** (bool, optional) – If True, a `SyntaxError` will be raised if the private key component is not present. * **public** (bool, optional) – If True, the private key component (if present) will be discarded, so this function will always return a public key. * **passwordCallback** (callable, optional) – This function will be called, with no arguments, if the PEM-encoded private key is password-encrypted. The callback should return the password string. If the password is incorrect, SyntaxError will be raised. If no callback is passed and the key is password-encrypted, a prompt will be displayed at the console. * **implementations** (list[str], optional) – List of cryptographic implementations to use. Defaults to `['openssl', 'python']`. ### Returns * **RSAKey** – An RSA key. ### Raises * **SyntaxError** – If the key is not properly formatted. ``` -------------------------------- ### Copying Cipher Settings Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/handshakesettings.html Copies cipher-related settings from one HandshakeSettings object to another. This is typically used internally during handshake setup. ```python other.record_size_limit = self.record_size_limit other.certificate_compression_send = self.certificate_compression_send other.certificate_compression_receive = \ self.certificate_compression_receive other.dc_sig_algs = self.dc_sig_algs other.dc_valid_time = self.dc_valid_time ``` -------------------------------- ### Getting Certificate Types as IDs Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/handshakesettings.html Retrieves the configured certificate types and returns them as their corresponding integer IDs. Currently, only 'x509' is supported. ```python [docs] def getCertificateTypes(self): """Get list of certificate types as IDs""" ret = [] for ct in self.certificateTypes: if ct == "x509": ret.append(CertificateType.x509) else: raise AssertionError() return ret ``` -------------------------------- ### SMTP_TLS starttls Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.html Initiates the STARTTLS command for SMTP connections. ```APIDOC ## SMTP_TLS ### Description Provides TLS support for SMTP clients. ### Methods - `starttls()`: Initiates the STARTTLS command to upgrade the SMTP connection to TLS. ``` -------------------------------- ### HTTPTLSConnection.connect Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.integration.httptlsconnection.html Establishes a connection to the server specified during initialization. ```APIDOC ## connect() Connect to the host and port specified in __init__. ``` -------------------------------- ### Get All SRP Cipher Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Retrieves all SRP cipher suites, encompassing both certificate-based and non-certificate-based authentication methods, that match the given settings. ```python @classmethod def getSrpAllSuites(cls, settings, version=None): """Return all SRP cipher suites matching settings""" return cls._filterSuites(CipherSuite.srpAllSuites, settings, version) ``` -------------------------------- ### Import all from tlslite.api Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.html Import all useful objects from the tlslite.api module for convenient access to the library's features. This is a common way to start using tlslite. ```python from tlslite.api import * ``` -------------------------------- ### Create On-Disk Database Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/basedb.html Creates a new on-disk database file. It opens the database in 'n' mode (create if not exists, truncate if exists), sets a reserved type, and attempts to sync the changes. This method is designed to handle potential errors during database creation. ```python def create(self): """ Create a new on-disk database. :raises anydbm.error: If there's a problem creating the database. """ logger = logging.getLogger(__name__) if self.filename: logger.debug('server %s - create - will open db', time.time()) self.db = anydbm.open(self.filename, "n") #raises anydbm.error logger.debug('server %s - create - setting type', time.time()) self.db["--Reserved--type"] = self.type logger.debug('server %s - create - syncing', time.time()) try: self.db.sync() except AttributeError: # some backends, like the py3.13 default sqlite , don't support # sync() method, so ignore it missing pass logger.debug('server %s - create - fun exit', time.time()) else: logger.debug('server %s - create - using dict() as DB', time.time()) self.db = {} ``` -------------------------------- ### ClientKeyShareExtension Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.extensions.html Class for handling the Client Hello version of the Key Share extension. It is used for sending key shares to the server. ```APIDOC ## ClientKeyShareExtension ### Description Class for handling the Client Hello version of the Key Share extension. Extension for sending the key shares to server. ### Methods - **__init__()**: Create instance of the object. - **__repr__()**: Output human readable representation of the object. - **create(_client_shares_)**: Set the advertised client shares in the extension. - **extData**: property that returns the on the wire raw encoding of the extension (bytearray). - **parse(_parser_)**: Parse the extension from on the wire format. - Parameters: - **parser** (Parser): data to be parsed - Raises: - **DecodeError**: when the data does not match the definition - Return type: ClientKeyShareExtension ``` -------------------------------- ### deprecated_class_name Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.utils.deprecations.html Class decorator to deprecate the usage of a class. It registers a deprecated name that will raise warnings if used, guiding users to the new class name. ```APIDOC ## deprecated_class_name ### Description Class decorator to deprecate a use of class. ### Parameters #### Path Parameters - **old_name** (str) - The deprecated name that will be registered, but will raise warnings if used. - **warn** (str) - DeprecationWarning format string for informing the user what is the current class name, uses ‘old_name’ for the deprecated keyword name and the ‘new_name’ for the current one. Example: “Old name: {old_nam}, use ‘{new_name}’ instead”. ### Parameters - **old_name** (_str_) - **warn** (_str_) ``` -------------------------------- ### RSAKey.__init__ Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.utils.rsakey.html Initializes a new RSA key. Can be initialized with existing modulus (n) and public exponent (e), or generated. ```APIDOC ## RSAKey.__init__ ### Description Create a new RSA key. If n and e are passed in, the new key will be initialized. ### Parameters * **n** (int) - RSA modulus. * **e** (int) - RSA public exponent. * **key_type** (str) - type of the RSA key, “rsa” for rsaEncryption (universal, able to perform all operations) or “rsa-pss” for a RSASSA-PSS key (able to perform only RSA-PSS signature verification and creation) ``` -------------------------------- ### OpenSSL Command for RSA Key Generation Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.utils.keyfactory.html Example command to generate a 2048-bit RSA private key using OpenSSL and save it to a file named key.pem. ```bash openssl genrsa 2048 > key.pem ``` -------------------------------- ### ServerHello2 Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.messages.html Represents the SERVER-HELLO message from SSLv2. ```APIDOC ## Class: ServerHello2 ### Description Represents the SERVER-HELLO message from SSLv2, inheriting from HandshakeMsg. ### Variables - `session_id_hit` (int): Non-zero if the client provided session ID was matched in the server’s session cache. - `certificate_type` (int): Type of certificate sent. - `server_version` (tuple of ints): Protocol version selected by the server. - `certificate` (bytearray): Certificate sent by the server. - `ciphers` (array of int): List of ciphers supported by the server. - `session_id` (bytearray): Identifier of the negotiated session. ### Methods - `__init__()`: Constructor for ServerHello2. - `create(_session_id_hit_, _certificate_type_, _server_version_, _certificate_, _ciphers_, _session_id_)`: Initialize fields of the SERVER-HELLO message. All parameters are required. ``` -------------------------------- ### Open Pre-existing On-Disk Database Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/basedb.html Opens an existing on-disk database in read/write mode ('w'). It verifies that the database is of the correct type by checking a reserved key. Raises ValueError if the file cannot be opened, is not a recognized database, or is of the wrong type. ```python def open(self): """ Open a pre-existing on-disk database. :raises anydbm.error: If there's a problem opening the database. :raises ValueError: If the database is not of the right type. """ if not self.filename: raise ValueError("Can only open on-disk databases") self.db = anydbm.open(self.filename, "w") #raises anydbm.error try: if self.db["--Reserved--type"] != self.type: raise ValueError("Not a %s database" % self.type) except KeyError: raise ValueError("Not a recognized database") ``` -------------------------------- ### Get ECDSA Certificate Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Filters ECDSA authenticated cipher suites based on settings and TLS version. This is used to select appropriate ECDSA-based cipher suites. ```python @classmethod def getEcdsaSuites(cls, settings, version=None): """Provide ECDSA authenticated ciphersuites matching settings""" return cls._filterSuites(CipherSuite.ecdheEcdsaSuites, settings, version) ``` -------------------------------- ### IntExtension: __init__ Method Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes an extension handler for payloads containing a single integer of a specified byte length. ```python def __init__(self, elem_length, field_name, ext_type, item_enum=None): """Create handler for extension that has a single integer as payload. :param str field_name: name of the field that will store the value :param int elem_length: size (in bytes) of the value in the extension :param int ext_tyoe: numerical ID of the extension encoded :param class item_enum: TLSEnum class that defines entries in the extension """ super(IntExtension, self).__init__(field_name, extType=ext_type) self._elem_length = elem_length self._item_enum = item_enum ``` -------------------------------- ### Get Raw Extension Data Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Returns the raw bytearray encoding of the extension data, excluding the type and length headers. Returns an empty bytearray if serverNames is None. ```python if self.serverNames is None: return bytearray(0) w2 = Writer() for server_name in self.serverNames: w2.add(server_name.name_type, 1) w2.add(len(server_name.name), 2) w2.bytes += server_name.name # note that when the array is empty we write it as array of length 0 w = Writer() w.add(len(w2.bytes), 2) w.bytes += w2.bytes return w.bytes ``` -------------------------------- ### ClientHelper Initialization Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.html Constructor for the ClientHelper class, used in TLS client integrations. ```APIDOC ## ClientHelper ### Description Helper class for TLS client integrations. ### Methods - `__init__()`: Initializes the ClientHelper. ``` -------------------------------- ### Get Item from Database Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/basedb.html Retrieves a value from the database using a username as the key. It acquires a lock before accessing the database and releases it afterward. The retrieved string value is then processed by _getItem. ```python def __getitem__(self, username): if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: valueStr = self.db[username] finally: self.lock.release() return self._getItem(username, valueStr) ``` -------------------------------- ### Get Anonymous DH Cipher Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Retrieves a list of anonymous Diffie-Hellman cipher suites that match the provided settings. Used for establishing secure connections without client authentication. ```python @classmethod def getAnonSuites(cls, settings, version=None): """Provide anonymous DH ciphersuites matching settings""" return cls._filterSuites(CipherSuite.anonSuites, settings, version) ``` -------------------------------- ### Create PskIdentity Instance Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes a PskIdentity instance with an identity and obfuscated ticket age. ```python def create(self, identity, obf_ticket_age): """Initialise instance.""" self.identity = identity self.obfuscated_ticket_age = obf_ticket_age return self ``` -------------------------------- ### Get DHE DSA Certificate Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Filters DHE cipher suites with DSA authentication based on settings and TLS version. This method helps in selecting appropriate DHE-DSA suites. ```python @classmethod def getDheDsaSuites(cls, settings, version=None): """Provide DSA authenticated ciphersuites matching settings""" return cls._filterSuites(CipherSuite.dheDsaSuites, settings, version) ``` -------------------------------- ### Poly1305.__init__ Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.utils.poly1305.html Set the authenticator key. ```APIDOC __init__(_key_) """Set the authenticator key""" ``` -------------------------------- ### Get SRP Cipher Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Retrieves SRP cipher suites that match the given settings. This method filters the predefined SRP suites based on the provided settings and TLS version. ```python @classmethod def getSrpSuites(cls, settings, version=None): """Return SRP cipher suites matching settings""" return cls._filterSuites(CipherSuite.srpSuites, settings, version) ``` -------------------------------- ### RenegotiationInfoExtension Initialization Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes the RenegotiationInfoExtension for secure renegotiation as defined in RFC 5746. The 'renegotiated_connection' field should be empty for initial connections. ```python def __init__(self): """Create instance""" extType = ExtensionType.renegotiation_info super(RenegotiationInfoExtension, self).__init__( 'renegotiated_connection', 1, extType) ``` -------------------------------- ### POP3_TLS Class Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.integration.pop3_tls.html Initializes a new POP3_TLS client with TLS support. It extends poplib.POP3 and ClientHelper, allowing for secure POP3 connections. ```APIDOC ## Class: POP3_TLS ### Description This class extends `poplib.POP3` with TLS support, enabling secure connections to POP3 servers. ### Parameters * **host** (_str_) – Server to connect to. * **port** (_int_) – Port to connect to. Defaults to 995. * **timeout** (_object_) – Connection timeout. Defaults to an object. * **username** (_str_) – SRP username for client authentication. Used in combination with `password`. * **password** (_str_) – SRP password for mutual authentication. Requires the `username` argument. * **certChain** (_X509CertChain_) – Certificate chain for client authentication. Requires the `privateKey` argument. Excludes SRP arguments. * **privateKey** (_RSAKey_) – Private key for client authentication. Requires the `certChain` argument. Excludes SRP arguments. * **checker** (_Checker_) – A callable object invoked after handshaking to validate the connection and potentially raise an Exception. * **settings** (_HandshakeSettings_) – Various settings to control ciphersuites, certificate types, and SSL/TLS versions offered by the client. ### Client Authentication For client authentication, use one of these argument combinations: * `username`, `password` (SRP) * `certChain`, `privateKey` (certificate) ### Server Authentication For server authentication, you can rely on SRP's implicit mutual authentication or use certificate-based server authentication with: * `x509Fingerprint` Certificate-based server authentication is compatible with SRP or certificate-based client authentication. ### Exception Handling The caller should be prepared to handle TLS-specific exceptions. Refer to the client handshake functions in `TLSConnection` for details on potential exceptions. ``` -------------------------------- ### Start Handshake Operation - AsyncStateMachine Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/integration/asyncstatemachine.html Initiates an asynchronous handshake operation. This method expects a generator created by an asynchronous handshake function. It includes error handling to clear the state if an exception occurs. ```python def setHandshakeOp(self, handshaker): """Start a handshake operation. :param generator handshaker: A generator created by using one of the asynchronous handshake functions (i.e. :py:meth:`~.TLSConnection.handshakeServerAsync` , or handshakeClientxxx(..., async_=True). """ try: self._checkAssert(0) self.handshaker = handshaker self._doHandshakeOp() except: self._clear() raise ``` -------------------------------- ### RecordSizeLimitExtension Initialization Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes the RecordSizeLimitExtension class for handling the record_size_limit extension as defined in RFC 8449. ```python class RecordSizeLimitExtension(IntExtension): """Class for handling the record_size_limit extension from RFC 8449.""" [docs] def __init__(self): """Create instance.""" super(RecordSizeLimitExtension, self).__init__( 2, 'record_size_limit', ExtensionType.record_size_limit) ``` -------------------------------- ### Get ECDHE Certificate Suites (RSA Auth) Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Filters ECDHE cipher suites with RSA authentication based on settings and TLS version. Use this to select appropriate ECDHE-RSA suites for a connection. ```python @classmethod def getEcdheCertSuites(cls, settings, version=None): """Provide authenticated ECDHE ciphersuites matching settings""" return cls._filterSuites(CipherSuite.ecdheCertSuites, settings, version) ``` -------------------------------- ### Get DHE Certificate Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Filters DHE cipher suites based on provided settings and TLS version. This method is useful for dynamically selecting appropriate cipher suites for a DHE-based connection. ```python @classmethod def getDheCertSuites(cls, settings, version=None): """Provide authenticated DHE ciphersuites matching settings""" return cls._filterSuites(CipherSuite.dheCertSuites, settings, version) ``` -------------------------------- ### Create NPNExtension Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Creates an instance of NPNExtension with a specified list of supported protocols. This is used to advertise supported protocols. ```python self.protocols = protocols return self ``` -------------------------------- ### ClientCertTypeExtension: Initialization Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Initializes the Client Certificate Type extension. This extension handles the types of client certificates supported. ```python def __init__(self): """ Create an instance of ClientCertTypeExtension See also: :py:meth:`create` and :py:meth:`parse` """ super(ClientCertTypeExtension, self).__init__( 1, 1, 'certTypes', ExtensionType.cert_type, CertificateType) ``` -------------------------------- ### Get SRP DSA Cipher Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Retrieves SRP DSA cipher suites that use server certificates. This method filters the predefined SRP DSA suites, though they are noted as unsupported. ```python @classmethod def getSrpDsaSuites(cls, settings, version=None): """Return SRP DSA cipher suites that use server certificates""" return cls._filterSuites(CipherSuite.srpCertSuites, settings, version) ``` -------------------------------- ### Get Anonymous ECDH Cipher Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Retrieves a list of anonymous ECDH cipher suites that match the provided settings. This method is useful for configuring TLS connections that use ECDH for key exchange. ```python @classmethod def getEcdhAnonSuites(cls, settings, version=None): """Provide anonymous ECDH ciphersuites matching settings""" return cls._filterSuites(CipherSuite.ecdhAnonSuites, settings, version) ``` -------------------------------- ### RenegotiationInfoExtension Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/extensions.html Handles the Client and Server Hello secure renegotiation extension from RFC 5746. Should have an empty renegotiated_connection field in case of initial connection. ```APIDOC ## RenegotiationInfoExtension ### Description Client and Server Hello secure renegotiation extension from RFC 5746. Should have an empty renegotiated_connection field in case of initial connection. ### Method __init__ ### Parameters None ### Returns Instance of class. ``` -------------------------------- ### Get RSA Authentication Cipher Suites Source: https://tlslite-ng.readthedocs.io/en/latest/_modules/tlslite/constants.html Retrieves cipher suites that use RSA for authentication. This method filters the predefined list of RSA-based cipher suites based on the provided settings and TLS version. ```python @classmethod def getCertSuites(cls, settings, version=None): ``` -------------------------------- ### SMTP_TLS Methods Source: https://tlslite-ng.readthedocs.io/en/latest/tlslite.integration.html Provides STARTTLS support for SMTP clients. ```APIDOC ## SMTP_TLS ### Description Facilitates secure SMTP communication by initiating STARTTLS. ### Methods - `starttls()`: Initiates the STARTTLS command for a secure SMTP session. ```