SSL (ex_ssl v1.0.0)

Copy Markdown View Source

OTP :ssl-compatible client and TLS 1.3 server facade for the implemented ex_ssl feature subset.

This experimental client supports TLS 1.3 and explicit bounded TLS 1.2, binary raw sockets, passive and active-once delivery, application ownership transfer, authenticated ALPN, bounded streaming writes, and peer verification by default. These restricted defaults differ from OTP. Unsupported options return explicit {:error, {:options, reason}} errors.

STARTTLS callers must own a passive binary/raw TCP or SSL.Socket carrier, fully consume and validate the application's upgrade response, and reject any buffered plaintext. Supply server_name_indication as the certificate reference DNS name, or use ex_ssl: [reference_identity: {:ip, address} | {:dns_id, name}] to verify a separate IP/DNS identity independently of SNI and the TCP destination. Once upgrade is attempted, an owned socket is closed on failure; plaintext must never resume. A socket belonging to another process is left untouched.

The TCP server API (listen/2, transport_accept/2, handshake/2, handshake/3) is TLS 1.3 only and issues no session tickets. Server carriers default to send_timeout: 30_000, send_timeout_close: true unless the caller sets either key.

Summary

Functions

Permanently abandons application writes while retaining response reads.

Closes the connection or listen socket. Closing an already closed handle succeeds.

Upgrades an owned passive binary/raw TCP or SSL.Socket carrier with a prepared snapshot.

Attaches lifecycle authority to one prepared upgrade, without overriding policy.

Returns supported connection metadata. The default keys contain no secrets.

Transfers application ownership while the TLS process retains the TCP socket.

Enables bounded response reads during an application send.

Reads carrier socket options of a server connection or listen socket.

Returns all carrier :inet.getstat/1 counters of a server connection.

Returns the requested carrier :inet.getstat/2 counters of a server connection.

Runs the TLS 1.3 server handshake on a socket from transport_accept/2.

Upgrades an owned :gen_tcp socket to a TLS 1.3 server connection.

Opens a TLS 1.3 server listen socket.

Returns the authenticated ALPN selection, if the server negotiated one.

Returns the authenticated peer (server, or mTLS client) leaf certificate as DER.

Returns the live TCP peer address and port.

Resolves and validates TLS configuration for a later TCP or TLS-carrier upgrade.

Receives available bytes for length 0, or exactly length bytes. Timeout retains buffered data.

Writes iodata as one ordered logical write. Concurrent writes return :busy.

Writes iodata under an absolute monotonic millisecond deadline.

Changes supported delivery, send, and mutable TCP options after validation.

Shuts down one or both directions of a server connection.

Returns the live local TCP address and port.

Accepts a TCP connection and starts its TLS server process without handshaking.

Functions

abandon_send(socket)

@spec abandon_send(SSL.Socket.t()) :: :ok | {:error, term()}

Permanently abandons application writes while retaining response reads.

Only the controlling owner may call this on an established connection. An admitted send settles as {:error, :write_abandoned}; unsent plaintext is discarded and future sends are rejected. A bounded already-protected application output job may still finish its original transport write under its original finite deadline. The job may include an automatic KeyUpdate followed by one application record. It is never re-encrypted or replayed. At most one already-protected mandatory control response may wait behind it, retaining committed traffic-key epochs and the original finite deadline. Reads keep their existing byte bounds. Explicit close, cancellation and owner loss abort both outputs.

Call close/1 after consuming the response, or to abort the pending record. Ordinary sender death continues to fail the connection closed unless the owner explicitly abandons writes before the sender dies.

close(listen)

@spec close(SSL.Socket.t() | SSL.ListenSocket.t()) :: :ok | {:error, term()}

Closes the connection or listen socket. Closing an already closed handle succeeds.

connect(tcp_socket, options)

@spec connect(:gen_tcp.socket() | SSL.Socket.t(), list()) ::
  {:ok, SSL.Socket.t()} | {:error, term()}

connect(host, port, options)

@spec connect(term(), term(), term()) :: {:ok, SSL.Socket.t()} | {:error, term()}

connect(host, port, options, timeout)

@spec connect(term(), :inet.port_number(), list(), timeout()) ::
  {:ok, SSL.Socket.t()} | {:error, term()}

connect_prepared(tcp_socket, prepared, timeout \\ :infinity)

@spec connect_prepared(
  :gen_tcp.socket() | SSL.Socket.t(),
  SSL.PreparedUpgrade.t(),
  timeout()
) ::
  {:ok, SSL.Socket.t()} | {:error, term()}

Upgrades an owned passive binary/raw TCP or SSL.Socket carrier with a prepared snapshot.

Uses the resolved policy without rereading files or resolving options/profiles. Ownership, pending-plaintext rejection, timeout and close-on-failure semantics are the same as connect/3. Future runtime or handshake failures remain possible.

connect_prepared(tcp, prepared, attempt_options, timeout)

@spec connect_prepared(
  :gen_tcp.socket(),
  SSL.PreparedUpgrade.t(),
  keyword(),
  timeout()
) ::
  {:ok, SSL.Socket.t()} | {:error, term()}

Attaches lifecycle authority to one prepared upgrade, without overriding policy.

connection_information(socket)

@spec connection_information(SSL.Socket.t()) :: {:ok, keyword()} | {:error, term()}

Returns supported connection metadata. The default keys contain no secrets.

Explicit :session_data returns a bounded ExSSL-owned TLS1.2 resumption capability. Treat it as a credential; it is valid only within this VM, its original authentication context, cache retention and absolute session lifetime. Pass it as reuse_session: {session_id, session_data}. OTP-private serialized session bytes are not accepted. TLS1.3 uses the separate session-ticket API.

connection_information(socket, keys)

@spec connection_information(SSL.Socket.t(), term()) ::
  {:ok, keyword()} | {:error, term()}

controlling_process(listen, owner)

@spec controlling_process(SSL.Socket.t() | SSL.ListenSocket.t(), pid()) ::
  :ok | {:error, term()}

Transfers application ownership while the TLS process retains the TCP socket.

For a listen socket, transfers ownership of the listening TCP port.

enable_duplex_reads(socket)

@spec enable_duplex_reads(SSL.Socket.t()) :: :ok | {:error, term()}

Enables bounded response reads during an application send.

This owner-only, idempotent operation applies to an established open socket. It requires a finite send timeout and rejects later infinite-timeout sends. Reads may progress while one already-protected application output job is pending. At most one already-protected mandatory control response may wait behind that job under the original absolute write deadline. Handshake, control and shutdown output barriers remain in place; waiting grants no new budget. Normal sender death still fails the connection closed.

getopts(listen, keys)

@spec getopts(SSL.Socket.t() | SSL.ListenSocket.t(), [atom()]) ::
  {:ok, keyword()} | {:error, term()}

Reads carrier socket options of a server connection or listen socket.

For a connection, :active is the TLS delivery mode. For an SSL.ListenSocket, the options are those of the listening TCP port, as :inet.getopts/2 reports them.

getstat(socket)

@spec getstat(SSL.Socket.t()) :: {:ok, keyword()} | {:error, term()}

Returns all carrier :inet.getstat/1 counters of a server connection.

getstat(socket, keys)

@spec getstat(SSL.Socket.t(), [atom()]) :: {:ok, keyword()} | {:error, term()}

Returns the requested carrier :inet.getstat/2 counters of a server connection.

handshake(socket, timeout)

@spec handshake(SSL.Socket.t(), timeout()) :: {:ok, SSL.Socket.t()} | {:error, term()}

Runs the TLS 1.3 server handshake on a socket from transport_accept/2.

On failure or timeout the connection process stops and its carrier closes.

handshake(tcp, options, timeout)

@spec handshake(:gen_tcp.socket(), keyword(), timeout()) ::
  {:ok, SSL.Socket.t(), []} | {:error, term()}

Upgrades an owned :gen_tcp socket to a TLS 1.3 server connection.

Options are those of listen/2; carrier options are applied with :inet.setopts/2, with :binary and active: false enforced; other active/mode values are rejected. Bare address families (:inet, :inet6, :local) are fixed when the socket opens, so they are not passed to :inet.setopts/2. An option error leaves the socket open and owned by the caller. Once the connection process takes the socket, a failed handshake closes it.

listen(port, options)

@spec listen(:inet.port_number(), [atom() | {atom(), term()}]) ::
  {:ok, SSL.ListenSocket.t()} | {:error, term()}

Opens a TLS 1.3 server listen socket.

Options are validated before the port is opened. TLS options are the certificate identity (certfile/keyfile, cert/key, certs_keys with several identities, each validated here and chosen per handshake by the client's signature algorithms, password), sni_hosts, sni_fun, alpn_preferred_protocols, ciphers, versions: [:"tlsv1.3"], active_chunk_size and client authentication. OTP :ssl-only options are errors; every other option is a :gen_tcp listen option, including the bare address families :inet, :inet6 and :local. :binary and active: false are enforced; active other than false and mode other than :binary (including :list) return {:error, {:unsupported_option, key}}.

active_chunk_size (a positive integer, default :infinity) bounds the plaintext bytes in each active-once {:ssl, socket, bytes} message; bytes beyond it stay buffered and are delivered in order by later arms. recv/3 is not bounded by it. setopts/2 can change it on server and client sockets.

sni_hosts: [{name, identity_options}] identities are loaded here, so a bad certificate fails listen/2. sni_hosts names match ASCII case-insensitively (RFC 4343); names differing only in case are duplicates. sni_fun.(name) receives the name as sent; it runs in the connection process per handshake and returns identity options or :undefined. Selection order is sni_hosts[name], sni_fun.(name), then the default identity; with none the handshake fails with unrecognized_name. A failing sni_fun is internal_error.

verify: :verify_peer requests a client certificate validated against cacerts (DER list) or cacertfile (PEM), with at most depth (default 10) intermediate CAs and no hostname check; fail_if_no_peer_cert: true requires one. The default verify: :verify_none sends no CertificateRequest; any other verify value is {:error, {:invalid_option, :verify}}. Failures abort the handshake with certificate_required (no certificate when required), unknown_ca (untrusted chain or longer than depth), certificate_expired, bad_certificate, illegal_parameter (CertificateVerify scheme not offered or unfit for the key) or decrypt_error (bad CertificateVerify signature). peercert/1 then returns the client leaf and connection_information/1 reports peer_authenticated: :client | false.

negotiated_protocol(socket)

@spec negotiated_protocol(SSL.Socket.t()) :: {:ok, binary()} | {:error, term()}

Returns the authenticated ALPN selection, if the server negotiated one.

peercert(socket)

@spec peercert(SSL.Socket.t()) :: {:ok, binary()} | {:error, term()}

Returns the authenticated peer (server, or mTLS client) leaf certificate as DER.

peername(socket)

@spec peername(SSL.Socket.t()) ::
  {:ok, {:inet.ip_address(), :inet.port_number()}} | {:error, term()}

Returns the live TCP peer address and port.

prepare_upgrade(options)

@spec prepare_upgrade(term()) :: {:ok, SSL.PreparedUpgrade.t()} | {:error, term()}

Resolves and validates TLS configuration for a later TCP or TLS-carrier upgrade.

Loads trust and client credentials and freezes the upgrade reference, SNI and concrete wire profile. No socket, connection process or ephemeral keys are allocated. The returned opaque snapshot can be reused deliberately; connection randomness, ephemeral keys and session-ticket binders are generated at attach. This configuration snapshot is not an attempt/adoption or cleanup receipt.

recv(socket, length, timeout \\ :infinity)

@spec recv(SSL.Socket.t(), non_neg_integer(), timeout()) ::
  {:ok, binary()} | {:error, term()}

Receives available bytes for length 0, or exactly length bytes. Timeout retains buffered data.

On a socket whose peer has closed, an exact-length read that the remaining buffered plaintext cannot satisfy returns {:error, :timeout} at once and keeps the bytes; the close (:closed after close_notify, otherwise :econnreset) is reported only after the buffer is drained.

send(socket, data)

@spec send(SSL.Socket.t(), iodata()) :: :ok | {:error, term()}

Writes iodata as one ordered logical write. Concurrent writes return :busy.

{:error, :busy} means another caller holds the write reservation; nothing of this write was sent and the socket is unaffected, so it may be retried. Callers should still serialize writes in one process, because there is no notification when the reservation frees. On a server socket a reservation made while another write is in flight waits for that write instead of returning :busy. A server write that waits on the carrier does not stop receive delivery or other socket calls; only the writer waits, bounded by send_timeout and an {:abs_ms, _} deadline, and a timeout closes the connection.

send(socket, data, arg3)

@spec send(SSL.Socket.t(), iodata(), {:abs_ms, integer()}) :: :ok | {:error, term()}

Writes iodata under an absolute monotonic millisecond deadline.

The deadline includes reservation and every protected record of this logical write. The controlling owner's configured send timeout may shorten it. This operation does not change the socket's owner or configured timeout.

setopts(socket, options)

@spec setopts(SSL.Socket.t(), list()) :: :ok | {:error, term()}

Changes supported delivery, send, and mutable TCP options after validation.

shutdown(socket, how)

@spec shutdown(SSL.Socket.t(), :read | :write | :read_write) :: :ok | {:error, term()}

Shuts down one or both directions of a server connection.

Write shutdown sends close_notify before the TCP shutdown; reads continue.

sockname(listen)

@spec sockname(SSL.Socket.t() | SSL.ListenSocket.t()) ::
  {:ok, {:inet.ip_address(), :inet.port_number()}} | {:error, term()}

Returns the live local TCP address and port.

transport_accept(listen, timeout \\ :infinity)

@spec transport_accept(SSL.ListenSocket.t(), timeout()) ::
  {:ok, SSL.Socket.t()} | {:error, term()}

Accepts a TCP connection and starts its TLS server process without handshaking.