TLSClient

class mtf.network_port.tls.tls_client.TLSClient

A class representing a TLS/DTLS client for secure communication.

This class provides methods to create, start, and manage a TLS/DTLS client connection using the specified configuration. It supports both DTLS (UDP) and TLS (TCP) protocols.

__init__(config: TLSConfigurator)
classmethod create(config: TLSConfigurator)

Creates a new instance of the TLSClient class with the provided configuration.

Args:

config (TLSConfigurator): The configuration for the client.

Returns:

TLSClient: A new instance of the TLSClient class.

psk_client_callback(ssl_conn, hint)
log_key_material_dict()

Log the contents of the key material dictionary.

This function prints each label and the associated key material stored in the key_material_dict. It helps in debugging and verifying the key material collected during the TLS sessions.

Returns:

None

start_client(session: Session | None = None)

Starts the client and initiates the connection.

This method sets up the socket, initiates the SSL/TLS handshake, and sends a “Client Hello” message to the server. It handles both DTLS (UDP) and TLS (TCP) connections.

Args:

session (Optional[Session]): A session defines certain connection parameters which may be re-used to speed up the setup of subsequent connections.

connect()

Establishes a connection to the specified server address using the provided configuration.

This method creates a root node that represents the connection to the server. The server’s address, port, and other connection parameters (such as the TLS record version and timeout) are derived from the object’s configuration. The root node is then assigned to the node attribute for further interactions.

Attributes:

node (ConnectCommand): The root node representing the established connection to the server.

generate_client_hello(ciphers: List[Any] | None = None, version: ProtocolVersion | None = None, session_id: bytearray | None = None, random: bytearray | None = None, compression: List[str] | None = None, ssl2: bool = False, modifiers: List[str] | None = None)

Generates a TLS ClientHello message with the specified parameters and adds it as a child node to the current connection node.

This method constructs a TLS ClientHello message, which is the initial message sent by the client during the TLS handshake. It can be customized with various parameters including supported ciphers, TLS version, session ID, random bytes, compression methods, and whether SSLv2 format is used. The generated ClientHello message is then added as a child node to the current connection node.

Args:

ciphers (Optional[List[Any]]): A list of supported cipher suites to include in the ClientHello message. If not provided, default is None. version (Optional[ProtocolVersion]): The TLS version to use in the ClientHello message. If not provided, default is None. session_id (Optional[bytearray]): The session ID to include in the ClientHello message. If not provided, default is None. random (Optional[bytearray]): The random bytes used in the ClientHello message. If not provided, default is None. compression (Optional[List[str]]): A list of supported compression methods to include in the ClientHello message. If not provided, default is None. ssl2 (bool): Whether to generate the ClientHello message in SSLv2 format. Default is False. modifiers (Optional[List[str]]): A list of modifiers to alter the ClientHello generation process. If not provided, default is None.

Attributes:

node (ClientHelloGenerator): The node representing the generated ClientHello message, which is added as a child node to the existing connection node.

Notes:
  • If the socket type is DTLS, the method will trigger a send action for the ClientHello message.

  • For other socket types, the ClientHello message is created using the provided parameters and added as a child node to last_node.

generate_client_key_exchange(version: ProtocolVersion | None = None, identity: bytes | None = None)

Generates a Client Key Exchange message for the TLS handshake.

This method creates a key exchange message based on the specified parameters, which are used during the TLS handshake to establish shared secrets between the client and server.

Parameters:

version (Optional[ProtocolVersion]): The TLS version to be used. If not specified, a default version will be used. identity (Optional[bytes], optional): The identity or keying material for the ServerKeyExchange message. Defaults to None

expect_server_key_exchange(version: ProtocolVersion | None = None, cipher_suite: Any | None = None, valid_sig_algs: List[int] | None = None, valid_groups: List[int] | None = None, valid_params: Set[tuple[int, int]] | None = None)

Configures the expectation for a Server Key Exchange message in the TLS handshake.

This method sets up the expected attributes of the Server Key Exchange message, including version, cipher suite, valid signature algorithms, valid groups, and parameters.

Parameters:

version (Optional[ProtocolVersion]): The TLS version expected in the Server Key Exchange message. If not specified, defaults to the version used in the handshake. cipher_suite (Optional[Any]): The expected cipher suite for the key exchange. If not specified, defaults to any valid cipher suite. valid_sig_algs (Optional[List[int]]): List of valid signature algorithms expected in the Server Key Exchange message. If not specified, defaults to all valid algorithms. valid_groups (Optional[List[int]]): List of valid groups (e.g., elliptic curves) for key exchange expected in the Server Key Exchange message. If not specified, defaults to all valid groups. valid_params (Optional[Set[tuple[int, int]]]): Set of explicit expected parameters used by the server, where the first element of the tuple is the expected generator and the second is the prime used for the DH calculation. Applicable only to ciphersuites that use FFDHE key exchange.

Note:
  • In DTLS (Datagram TLS), this method expects a PSK (Pre-Shared Key) Server Key Exchange message. The

provided arguments such as version, cipher_suite, valid_sig_algs, valid_groups, and valid_params are not used in this case. - For regular TLS handshakes, the provided arguments help define the expected structure of the Server Key Exchange message.

expect_alert(level: AlertLevel | None = None, description: AlertDescription | None = None)

Adds a node to expect a specific TLS alert.

Parameters:

level (AlertLevel): The level of the alert (e.g., warning or fatal) represented as an AlertLevel enum. description (AlertDescription): The description code for the alert represented as an AlertDescription enum.

Notes:
  • Ensure that level and description correspond to valid TLS alert codes as defined in the AlertLevel and AlertDescription enums.

expect_server_hello(extensions: List[int | TlsExtensionType] | None = None, version: ProtocolVersion | None = None, resume: bool = False, cipher: Any | None = None, server_max_protocol: ProtocolVersion | None = None, force_resume: bool = False, description: Any | None = None)

Adds a node to expect a ServerHello message with the specified parameters.

Parameters:

extensions Optional[List[Union[int, TlsExtensionType]]]: List of expected extensions in the ServerHello message. Defaults to None. version (Optional[ProtocolVersion]): Expected TLS version. Defaults to None. resume (bool): Whether the server should resume the session. Defaults to False. cipher (Optional[Any]): Expected cipher suite. Defaults to None. server_max_protocol (Optional[ProtocolVersion]): Maximum protocol version supported by the server. Defaults to None. force_resume (bool): Whether to force session resumption. Defaults to False. description (Optional[Any]): Description or custom data for the ServerHello. Defaults to None.

Note:
  • In DTLS (Datagram TLS) mode, this method expects a standard SERVER_HELLO message but does not rely

on the provided parameters like extensions or version. - For standard TLS, the provided parameters guide the expectations for the ServerHello message, such as extensions, protocol versions, and session resumption.

expect_server_hello_done()

Adds a node to expect a ServerHelloDone message.

Notes:
  • The ServerHelloDone message indicates that the server has finished sending its messages

for the first phase of the handshake.

generate_alert(level: AlertLevel, description: AlertDescription)

Adds a node to generate a TLS alert with the specified level and description.

Parameters:

level (AlertLevel): The severity level of the alert, such as ‘warning’ or ‘fatal’. description (AlertDescription): The specific description of the alert, such as ‘close_notify’ or ‘unexpected_message’.

expect_change_cipher_spec()

Adds a node to expect a ChangeCipherSpec message.

This method configures the current node to expect a ChangeCipherSpec message during the TLS handshake. It sets up the expectation for this specific message type.

Note:
  • In TLS, this method adds a child node to the workflow to expect the ChangeCipherSpec message.

  • In DTLS (Datagram TLS), the ChangeCipherSpec message is expected via the DTLS manager.

Returns:

None: This method updates the internal state of the object by adding an ExpectChangeCipherSpec child to the current node.

generate_change_cipher_spec(extended_master_secret: Any | None = None, fake: bool = False)

Adds a node to generate a ChangeCipherSpec message with optional parameters.

This method configures the current node to generate a ChangeCipherSpec message during the TLS handshake. The message can be customized with an optional extended master secret and can be flagged as fake if needed.

Args:

extended_master_secret (Optional[Any], optional): An optional extended master secret for the ChangeCipherSpec message. Defaults to None. fake (bool, optional): Whether to generate a fake ChangeCipherSpec message. Defaults to False.

Note:
  • In DTLS, the ChangeCipherSpec message is handled by the DTLS manager.

  • In standard TLS, a ChangeCipherSpecGenerator child node is added to the workflow to generate the message.

Returns:

None: This method updates the internal state of the object by adding a ChangeCipherSpecGenerator child to the current node.

generate_finished(trunc_start: int = 0, trunc_end: int | None = None, pad_byte: int = 0, pad_left: int = 0, pad_right: int = 0, verify_data: bytes | None = None) None

Adds a node to generate a Finished message with options to corrupt the verify_data.

This method configures the current node to generate a Finished message during the TLS handshake and allows optional corruption of the verify_data via truncation or padding.

Args:

trunc_start (int): The starting index for truncating the verify_data. Default is 0. trunc_end (Optional[int]): The ending index for truncating the verify_data. Default is None (no truncation). pad_byte (int): The byte value used for padding. Default is 0. pad_left (int): The number of padding bytes to add to the left of the verify_data. Default is 0. pad_right (int): The number of padding bytes to add to the right of the verify_data. Default is 0. verify_data (bytes, optional): Data to set in the Finished message’s verifyData field.

In DTLS (Datagram TLS), this method uses the DTLS manager to send the Finished message. In standard TLS, it adds a FinishedGenerator node to the workflow to generate the message.

Returns:

None: This method updates the internal state of the object by adding a FinishedGenerator child to the current node.

expect_finished()

Adds a node to expect a Finished message.

This method configures the current node to expect a Finished message during the TLS handshake.

In DTLS (Datagram TLS), the method uses the DTLS manager to handle the expected Finished message. In standard TLS, it adds an ExpectFinished node to the workflow to anticipate the message.

Returns:

None: This method updates the internal state of the object by adding an ExpectFinished child to the current node.

expect_hello_verify_request()

Configures the DTLS manager to expect a HelloVerifyRequest message.

This method sets up the DTLS manager to expect a HelloVerifyRequest message during the DTLS handshake process. This method is only relevant for DTLS connections and does not modify the behavior for non-DTLS protocols.

Returns:

None: The DTLS manager is configured to expect the HelloVerifyRequest message.

expect_message_sequence(messages: List[TlsMessage]) None

Receives a sequence of TLS messages specifically for DTLS.

This method is used in DTLS to expect a sequence of TlsMessage objects. Unlike TLS, no nodes are added to the workflow. Instead, messages are expected using the dtls_manager.

Args:

messages (List[TlsMessage]): A list of TlsMessage objects to be expected sequentially.

Returns:

None

generate_application_data(data: bytearray | None = bytearray(b''))

Adds a node to generate an Application Data message.

This method configures the current node to generate an Application Data message during the TLS connection.

Args:

data (bytearray, optional): The application data to send. Default is an empty byte string.

Returns:

None: This method updates the internal state of the object by adding an ApplicationDataGenerator child to the current node.

expect_application_data()

Adds a node to expect an Application Data message.

This method configures the current node to expect an Application Data message during the TLS connection.

Returns:

None: This method updates the internal state of the object by adding an ExpectApplicationData child to the current node.

start_handshake()

Starts the TLS handshake process by running the handshake sequence with the current root node.

Raises:

Exception: If an error occurs during the handshake process.

log_handshake_progress(conn)

Log the current state of the SSL handshake.

Parameters:

conn – The SSL connection object.

is_running()

Checks if the client is currently running.

Returns:

bool: True if the client is running, False otherwise.

stop_client()

Stops the client and closes the connection.

This method shuts down the socket, if connected, and cleans up resources.

cleanup()
send_message(message)

Sends a message to the server.

Args:

message (bytes): The message to be sent.

send_hello_message()

Sends Hello from client! message to the server.

check_message(expected_message)

Checks if the received message matches the expected message.

Args:

expected_message (bytes): The expected message to be received.

set_expected_message(message)

Sets the expected message to be received.

Args:

message (bytes): The expected message.

get_session()

Retrieves the current TLS session.

This method returns the current TLS session object, which can be used for session resumption or other purposes.

Returns:

SSL.Session: The current TLS session object.