tlslp.server

TLS server for querying a client’s information.

This CLI starts a TCP listener and sends a simple newline-delimited UTF-8 command protocol over TLS. The server:

  1. Accepts a TLS connection (optionally requiring a client certificate for mTLS).

  2. Performs a small handshake: - Sends HELLO and expects HELLOBACK. - Sends WORK <token> <n_bits> and expects a suffix that yields a SHA256 hash with the required number of trailing zero bits.

  3. Sends a sequence of body requests (e.g., FULL_NAME, EMAIL1, …). The client responds with <cksum> <value> where cksum = SHA256(token + random_string).

  4. Finishes with DONE and expects OK.

Timeouts: - WORK has a long timeout (default: 30 minutes). - Other steps use a shorter timeout (default: 10 seconds).

The server is primarily intended for localhost/dev usage and a deterministic --tutorial mode that sends each body message once and then exits.

raises ProtocolError:

For protocol violations (framing/encoding errors).

raises TransportError:

For network/TLS errors (disconnects, timeouts, etc.).

Functions

args_to_server_config(ns)

Convert parsed CLI args into a ServerConfig.

build_server_parser()

Build the CLI argument parser for tlslp-server.

handle_one_session(is_secure, cfg, secure_sock)

Handle a single connected client session.

main([argv])

Run the tlslp-server CLI.

prepare_server_socket(server_host, port, ...)

Create a listening TCP socket and an SSL context for server-side TLS.

send_and_receive(token, to_send, secure_sock)

Send one command and receive the client's reply, with protocol validation.

send_fail(to_send, secure_sock)

Best-effort send of an FAIL ... message.

Classes

ServerConfig(server_host, port, server_cert, ...)

class tlslp.server.ServerConfig(server_host: str, port: int, server_cert: str, server_key: str, ca_cert: str, work_timeout: int, other_timeout: int, insecure: bool, token: str, random_string: str, n_bits: int, log_level: str, tutorial: bool)

Bases: object

ca_cert: str
insecure: bool
log_level: str
n_bits: int
other_timeout: int
port: int
random_string: str
server_cert: str
server_host: str
server_key: str
token: str
tutorial: bool
work_timeout: int
tlslp.server.args_to_server_config(ns: Namespace) ServerConfig

Convert parsed CLI args into a ServerConfig.

Parameters:

ns (argparse.Namespace) – Returned by ArgumentParser.parse_args.

Returns:

The flags/parameters.

Return type:

(ServerConfig)

tlslp.server.build_server_parser() ArgumentParser

Build the CLI argument parser for tlslp-server.

Returns:

(argparse.ArgumentParser) configured with server options.

Examples

>>> p = build_server_parser()
>>> ns = p.parse_args(["--port", "1234", "--tutorial"])
>>> ns.port
1234
tlslp.server.handle_one_session(is_secure: bool, cfg: ServerConfig, secure_sock: SSLSocket) None

Handle a single connected client session.

Runs the handshake (HELLO + WORK), then sends a series of body requests, and finishes with DONE unless a FAIL condition is triggered.

Parameters:
  • is_secure (bool) – True if mTLS is expected (client cert required).

  • cfg (ServerConfig) – Parsed and normalized server configuration.

  • secure_sock (ssl.SSLSocket) – TLS-wrapped client socket.

Raises:
  • RuntimeError – If mTLS is enabled and the client presents no certificate.

  • ProtocolError/TransportError/ValueError – Propagated from the underlying send/receive and validation logic.

tlslp.server.main(argv: Sequence[str] | None = None) int

Run the tlslp-server CLI.

Parameters:

argv (Sequence[str] | None) – Optional argument vector (defaults to sys.argv[1:]).

Returns:

Exit code (0 on success).

Return type:

(int)

Side effects:

Binds a TCP port, accepts connections, writes logs, prints status lines.

tlslp.server.prepare_server_socket(server_host: str, port: int, ca_cert_path: str, server_cert_path: str, server_key_path: str, is_secure: bool = False) tuple[socket, SSLContext]

Create a listening TCP socket and an SSL context for server-side TLS.

Parameters:
  • server_host (str) – Host interface to bind to (e.g., "localhost").

  • port (int) – TCP port to bind to.

  • ca_cert_path (str) – CA certificate used to verify client certificates (mTLS).

  • server_cert_path (str) – Server certificate (PEM).

  • server_key_path (str) – Server private key (PEM).

  • is_secure (bool) – If True, require and verify a client certificate (mTLS). If False, the server does not request/verify a client certificate.

Returns:

(server_socket, ssl_context) where server_socket is bound and listening.

Return type:

(socket.socket, ssl.SSLContext)

Raises:

ValueError – If insecure mode is requested for a non-localhost bind.

Examples: Insecure TLS is refused for non-local hosts: >>> prepare_server_socket(“example.com”, 0, “ca.pem”, “srv.pem”, “key.pem”, is_secure=False) Traceback (most recent call last): … ValueError: Refusing insecure TLS to example.com. For non-local hosts, enable certificate verification.

tlslp.server.send_and_receive(token: str, to_send: str, secure_sock: socket, timeout: float = 6.0) str

Send one command and receive the client’s reply, with protocol validation.

  • Sends to_send using tlslp.protocol.send_message.

  • Receives a single-line reply using tlslp.protocol.receive_message.

  • For WORK commands, validates the suffix n_bits requirement.

  • For body commands, validates the checksum.

  • For FAIL commands, no reply is expected (returns "").

Parameters:
  • token (str) – Authentication data used for checksum/suffix validation.

  • to_send (str) – Command to send (newline will be ensured by send_message).

  • secure_sock (socket.socket) – Connected socket.

  • timeout (float) – Receive timeout in seconds for this step.

Returns:

The received message (without trailing newline), or "" for FAIL sends.

Return type:

(str)

Raises:
  • ProtocolError – If the peer violates protocol framing/encoding.

  • TransportError – On network/TLS failures (timeouts, disconnects, etc.).

  • ValueError – If WORK suffix or checksum validation fails.

Examples

>>> import socket
>>> from tlslp.server import send_and_receive
>>> a, b = socket.socketpair()
>>> try:
...     # peer responds to HELLO with HELLOBACK
...     _ = b.recv(1024)  # consume HELLO (sent by send_and_receive)
... except Exception:
...     pass
... finally:
...     a.close(); b.close()
...
tlslp.server.send_fail(to_send: str, secure_sock: socket) None

Best-effort send of an FAIL ... message.

This is used to notify the client after a failure (e.g., bad checksum). Any exception while sending is caught and logged.

Parameters:
  • to_send (str) – Error message to send (typically starts with "FAIL").

  • secure_sock (socket.socket) – Connected socket to send on.