Current section

Files

Jump to
ex_ssl README.md
Raw

README.md

# ex_ssl

`ex_ssl` is an experimental TLS implementation for Elixir/OTP with two primary goals:

1. provide a client API that is behaviorally compatible with Erlang/OTP `:ssl` where implemented;
2. provide programmable TLS ClientHello wire profiles for applications that need precise control over observable TLS handshake behavior.

The OTP application is `:ex_ssl`. The public compatibility module is `SSL` (`Elixir.SSL`), which does not conflict with Erlang's built-in `:ssl` module.

This app was imported from `gsmlg-dev/ex_quic@14974913390e12d03a78a2903d18e55a04fa89d6` into the `http_fetch` umbrella. Its original TLS source provenance is recorded in [the QUIC TLS contract](../../docs/quic/ex-ssl-quic-contract.md). The original import inventory used `0.16.1`; current coordinated versions and exact sibling requirements are declared in [mix.exs](mix.exs).

> **Status:** experimental TLS 1.3 client runtime with authenticated connections,
> passive and active-once binary/raw traffic, application ownership transfer,
> ALPN lookup, bounded streaming writes, initial-handshake client authentication,
> and TCP-to-TLS upgrades. See the
> [compatibility matrix](docs/COMPATIBILITY.md) for exact restrictions. Current
> umbrella HTTP clients default to ExSSL and reject legacy OTP backend selection.
> The [migration checklist](../../docs/tls-migration-plan.md) separates accepted
> compatibility/default stages from pending production-release and publication gates.

Version 0.4 also supports ordered TLS 1.3 algorithm options, explicit
certificate-chain signature restrictions, one client identity, and a validated
TCP option allowlist. These additions require ex_ssl 0.4 or newer;
see [compatibility](docs/COMPATIBILITY.md) and the
[implementation ledger](docs/EX_SSL_HTTP_FETCH_PROGRESS.md) for executed gates.

## Installation

Add the `ex_ssl` package to your dependencies:

```elixir
def deps do
  [
    {:ex_ssl, "== 1.0.0"}
  ]
end
```

The Hex package name is [`ex_ssl`](https://hex.pm/packages/ex_ssl).

## Why ex_ssl?

OTP `:ssl` is the correct default TLS implementation for normal Erlang/Elixir applications. `ex_ssl` exists for cases where an application also needs deterministic or profile-driven control of the ClientHello wire representation, including characteristics such as:

- cipher-suite ordering;
- extension ordering;
- supported versions/groups;
- KeyShare shape and placement;
- signature algorithm ordering;
- ALPN ordering;
- GREASE placement/policy;
- legacy session-id/compatibility behavior;
- padding and selected record-shaping behavior.

The library treats these as a **wire profile**, not as a JA3 configuration. JA3 and JA4 are derived fingerprints of the emitted/parsed ClientHello.

## Naming

```text
Package:              ex_ssl
Repository:           gsmlg-dev/http_fetch
OTP application:      :ex_ssl
Public API:            SSL
Internal namespace:    SSL.*
```

Migration is intended to look like:

```elixir
# OTP
:ssl.connect(host, port, options)

# ex_ssl
SSL.connect(host, port, options)
```

Custom behavior is additive and namespaced:

```elixir
SSL.connect(host, port,
  verify: :verify_peer,
  server_name_indication: host,
  ex_ssl: [
    profile: :default
  ]
)
```

To verify an IP certificate after connecting a TCP socket to a different address,
supply the original reference separately from SNI:

```elixir
SSL.connect(tcp_socket,
  verify: :verify_peer,
  server_name_indication: :disable,
  ex_ssl: [reference_identity: {:ip, "127.0.0.1"}]
)
```

The custom reference accepts IPv4/IPv6 tuples or strings, or
`{:dns_id, "service.example"}`. It selects certificate verification only;
SNI follows `server_name_indication` and the usual direct-dial defaults.
Trust, peer identity and handshake verification remain mandatory.

Without `cacerts`, `cacertfile` or `verify: :verify_none`, a client trusts the OS
store returned by `:public_key.cacerts_get/0`. The `:ex_ssl` application loads that
store once when it starts, so a connection's timeout never includes the cold load.
On a host without an OS store the application still starts, and such connections
fail with `{:error, {:options, {:cacerts, :invalid}}}`.

## Runtime baseline

The supported runtime baselines are Elixir 1.18 on Erlang/OTP 28, Elixir 1.19 on
Erlang/OTP 28, and Elixir 1.20 on Erlang/OTP 29. CI covers all three tuples. OTP 29
remains the behavioral reference target for the implemented `:ssl`-compatible client
feature subset.

The [validation and security evidence map](docs/SECURITY_REVIEW_EVIDENCE.md)
documents mandatory peer/runtime gates and the reproducible pinned downstream
source-candidate/package check. Independent human security review remains incomplete.

## Compatibility target

The initial compatibility baseline is the Erlang/OTP 29 `:ssl` client API.

Implemented client functions are `connect/2,3,4`, `send/2`, `recv/2,3`,
`close/1`, `setopts/2`, `controlling_process/2`, and
`negotiated_protocol/1`, `connection_information/1,2`, `peercert/1`,
`peername/1`, and `sockname/1`. Full handshakes verify CertificateVerify and
Finished; resumed handshakes verify the ticket-bound Finished. Connect succeeds
after the client Finished is transmitted. The connection runs
as a temporary supervised `:gen_statem`; a failed session is never restarted.

Defaults are deliberately restricted to binary, passive, raw, verified TLS 1.3.
They differ from OTP's defaults. Supported options and receive/upgrade ownership
rules are documented in the [compatibility matrix](docs/COMPATIBILITY.md).

TLS 1.3 resumption is opt-in with `session_tickets: :auto`; the default is
`:disabled`. Auto requires TLS 1.3-only versions, `verify: :verify_peer`, and no
configured client identity. Tickets remain in a bounded in-memory cache,
partitioned by endpoint and loaded trust/security policy. Each use revalidates
the saved peer certificate chain and performs fresh ECDHE. A server declining
PSK continues normal full authentication on that connection. No early data,
automatic reconnect, or request replay occurs. See the [resumption
policy](docs/ADR_TLS13_RESUMPTION.md) and [compatibility
details](docs/COMPATIBILITY.md).

`shutdown/2`, `getopts/2` and `getstat/1,2` are implemented for server sockets
(see [TCP TLS 1.3 server](#tcp-tls-13-server)); on client sockets they return
`{:error, :enotsup}`. The wider roadmap (not implemented API) includes:

```text
close/2
shutdown/2, getopts/2, getstat/1,2 (client sockets)
update_keys/2
export_key_materials/4,5
format_error/1
versions/0
```

Compatibility means observable behavior, not only matching names and arities.

For implemented features, `ex_ssl` aims to match:

- success/error tuple forms;
- timeout semantics;
- active/passive socket semantics;
- controlling-process behavior;
- standard TLS/socket option behavior;
- STARTTLS-style upgrade of an existing TCP socket;
- active message forms.

The active message contract targets OTP forms:

```elixir
{:ssl, socket, data}
{:ssl_closed, socket}
{:ssl_error, socket, reason}
{:ssl_passive, socket}
```

## Protocol scope

The primary TCP protocol target is a **TLS client**, using RFC 9846 as the normative
TLS 1.3 specification. A bounded TCP TLS 1.3 server is described in
[TCP TLS 1.3 server](#tcp-tls-13-server). The separate `SSL.QUIC` engine also implements the
record-free TLS 1.3 server role; its acceptance status is documented separately.

Initial target features:

- TLS 1.3 ClientHello/ServerHello;
- HelloRetryRequest;
- EncryptedExtensions;
- server Certificate / CertificateVerify / Finished;
- client Finished;
- X.509 path and service-identity verification;
- ALPN;
- TLS alerts and close_notify;
- NewSessionTicket parsing;
- KeyUpdate;
- passive and OTP-style active receive modes;
- STARTTLS upgrade;
- programmable ClientHello WireProfile;
- GREASE (RFC 8701);
- JA3 and JA4 introspection.

Initial target cipher suites:

```text
TLS_AES_128_GCM_SHA256
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
```

Initial target groups:

```text
X25519
secp256r1
secp384r1
```

Runtime support depends on the crypto provider available to OTP. Implemented
TLS 1.3 handshake signatures are P-256/P-384 ECDSA, Ed25519, and RSA-PSS-RSAE /
RSA-PSS-PSS SHA-256/384/512, with strict key and parameter checks. See
[the compatibility matrix](docs/COMPATIBILITY.md) for the bounded subset; client
certificates and explicit bounded TLS 1.2 are implemented in version 0.4.
The current migration candidate also supports TLS1.2 RSA-PKCS1 SHA256/384/512
server and client handshake signatures. These schemes remain excluded from
TLS1.3 CertificateVerify and QUIC.

## TCP TLS 1.3 server

`SSL.listen/2`, `SSL.transport_accept/2`, `SSL.handshake/2` and the server
upgrade `SSL.handshake(tcp, options, timeout)` (returning `{:ok, socket, []}`)
provide an OTP-shaped TCP TLS server. Accepted sockets use the ordinary
`SSL.send/recv/setopts/controlling_process/close` calls, plus server-socket
`SSL.getopts/2`, `SSL.getstat/1,2` and `SSL.shutdown/2`. Client sockets return
`{:error, :enotsup}` for those server-only calls. `close/1`, `sockname/1`,
`getopts/2` and `controlling_process/2` also accept an `SSL.ListenSocket`;
`getopts/2` then reads the listening TCP port's options.

```elixir
{:ok, listen} = SSL.listen(4443, certfile: "cert.pem", keyfile: "key.pem")
{:ok, socket} = SSL.transport_accept(listen)
{:ok, socket} = SSL.handshake(socket, 5_000)
```

Scope:

- TLS 1.3 only. `versions` other than `[:"tlsv1.3"]` return
  `{:error, {:unsupported_option, :versions}}`; there is no TLS 1.2 server.
- Supported TLS options: `certfile`/`keyfile`, `cert`/`key`, `certs_keys`,
  `password`, `sni_hosts`, `sni_fun`, `alpn_preferred_protocols`, `ciphers`
  (TLS 1.3 suites), `verify`, `cacerts`/`cacertfile`, `fail_if_no_peer_cert`
  and `depth`. Every other option is a
  `:gen_tcp` option; `:binary` and `active: false` are enforced on the carrier.
  `active` other than `false`, `mode` other than `:binary` (including `:list`)
  and OTP `:ssl`-only options are errors. Options are validated before the port opens.
- `certs_keys` takes several identities (for example RSA and ECDSA). Every
  entry is loaded and validated by `listen/2`; an invalid entry fails it with
  `{:error, {:invalid_option, :certs_keys}}` or the loader's error. Per
  handshake the server picks, among the identities selected for the SNI name
  (`sni_hosts`/`sni_fun` entries may carry their own `certs_keys`), the first in
  list order that can sign one of the client's `signature_algorithms`,
  preferring one whose chain fits `signature_algorithms_cert`. If none can sign,
  the first entry is used and the handshake fails with `handshake_failure`.
- SNI: `sni_hosts: [{name, identity_options}]` identities are loaded when the
  options are validated, so a bad certificate, a non-identity key or a
  duplicate name fails `listen/2` with `{:error, {:invalid_option, :sni_hosts}}`.
  `sni_fun.(name)` runs for each handshake in a monitored helper process that is
  killed when the `SSL.handshake/2` deadline expires (the call then returns
  `{:error, :timeout}`), and returns identity options or `:undefined`. Selection order is `sni_hosts[name]`, then
  `sni_fun.(name)`, then the default identity. `sni_hosts` names match
  ASCII case-insensitively (RFC 4343), so names differing only in case are
  duplicates; `sni_fun` receives the name exactly as the client sent it. An
  empty `sni_hosts` with neither a default identity nor `sni_fun` fails with
  `{:error, :server_identity_required}`. With no
  identity the handshake fails with `unrecognized_name`; an `sni_fun` raise,
  throw, exit or invalid result fails it with `internal_error`.
- If the chain does not match the client's `signature_algorithms_cert` (or
  `signature_algorithms`), the server still sends it (RFC 8446 §4.4.2.2); the
  CertificateVerify scheme must still be one the client offered.
- Client-certificate authentication (mTLS): `verify: :verify_peer` with
  `cacerts` (DER list) or `cacertfile` (PEM) sends a CertificateRequest
  (`signature_algorithms`, and `certificate_authorities` when the trust list
  is small). `fail_if_no_peer_cert: true` requires a certificate (default
  `false`); `depth` (default 10) bounds the intermediate CAs below a trust
  anchor. The client chain gets path validation without a hostname check, and a
  leaf extendedKeyUsage, when present, must allow clientAuth. Failures abort the
  handshake with a fatal alert returned by `SSL.handshake/2` as
  `{:error, {:tls_alert, {alert, _}}}`: `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) and `decrypt_error` (bad
  CertificateVerify signature or Finished). `SSL.peercert/1` returns the client
  leaf DER or `{:error, :no_peercert}`; `SSL.connection_information/1` reports
  `peer_authenticated: :client | false`. `verify: :verify_none` (default) sends
  no CertificateRequest; any other `verify` value is
  `{:error, {:invalid_option, :verify}}`. `SSL.QUIC` servers do not request
  client certificates. Client chains get no revocation check (no CRL or OCSP);
  only the client side of ex_ssl supports revocation policy, so a server that
  needs revocation must pin a short-lived CA or check `SSL.peercert/1` itself.
- No session tickets or resumption: the server sends no NewSessionTicket, and a
  client offering a PSK gets a full handshake. 0-RTT is not accepted: when the
  ClientHello offers `early_data`, up to 16 KiB of early-data records are
  skipped (RFC 8446 §4.2.10), bounded to 16 KiB and 64 records, and the client
  must resend after the handshake.
- Pre-authentication limits: a ClientHello is buffered up to 64 KiB (real
  hellos are well under 4 KiB), not the 1 MiB used for later handshake
  messages. After the handshake a partial handshake message (KeyUpdate) must
  not be interleaved with application data or alerts (RFC 8446 §5.1); that
  is an `unexpected_message` alert. A second `SSL.handshake/2` while one runs
  returns `{:error, :already_started}`. The handshake deadline also bounds the
  server flight write, whatever the carrier `send_timeout`.
- Hostname verification (client side) rejects a presented wildcard with fewer
  than two labels after `*` (`*.com`); there is no public-suffix list, so
  `*.co.uk` still matches.
- Receive backpressure: while about 1 MiB of plaintext is buffered unread, the
  server stops reading its carrier until the application drains it.
- After the peer closes (server and client sockets), buffered plaintext stays
  readable. An exact-length `SSL.recv/3` that the remaining bytes cannot
  satisfy returns
  `{:error, :timeout}` at once and keeps them; the terminal is reported only
  once the buffer is drained: `{:error, :closed}` (or `{:ssl_closed, socket}`)
  after close_notify, `{:error, :econnreset}` after a TCP close without it.
  OTP `:ssl.shutdown(socket, :write)` on TLS 1.3 sends no close_notify.
- Server carriers default to `send_timeout: 30_000, send_timeout_close: true`
  unless the caller sets either key, so a peer that never reads cannot hold a
  writer forever. This differs from OTP's infinite default.
- Writes run in a separate writer process. While one waits on the carrier,
  received records are still decrypted and delivered (within the receive
  buffer limit) and `setopts`, `getopts`, `peercert`, `recv` and `close` answer;
  only the writer waits, until `send_timeout` or its `SSL.send/3` deadline,
  either of which closes the connection. A reservation made by another process
  while a write is in flight waits for it; one made while a write is reserved
  but not yet sent returns `{:error, :busy}`, which leaves the socket unaffected
  and may be retried. `close/1`, owner exit or a peer close_notify during a
  write settle it as `{:error, :closed}` and discard its unsent bytes (no
  close_notify follows an unfinished write); a TCP close lets the writer settle
  it first.
- A handshake timeout, a TLS failure or a peer TCP close returns `{:error, _}`,
  and the connection process stops and closes its carrier.

## Architecture

`SSL.QUIC` provides an experimental record-free TLS 1.3 client/server handshake
API with caller-owned state and ordered traffic-secret actions. The TCP client
shares its ClientHello/HRR and authentication core. This adds no QUIC
networking (the TCP server API is described above). See the [interface](docs/QUIC_TLS_INTERFACE.md)
and [implementation ledger](docs/QUIC_TLS_IMPLEMENTATION.md). The pinned
[aioquic comparison](e2e/quic_tls/README.md) exercises both roles and compares
traffic secrets without QUIC networking.

`SSL.Fingerprint.client_hello(bytes, :tcp | :quic)` computes JA3/JA4 from actual
naked ClientHello bytes; `new/1` and `feed/2` support bounded fragmented
observation. Unknown IDs and wire ordering remain available separately from the
analytical projections. See [fingerprint API and references](docs/FINGERPRINTS.md).

```text
Application
    │
    ▼
   SSL                     OTP-compatible facade
    │
    ▼
SSL.Connection             :gen_statem per connection
    │
    ├── SSL.Protocol.*     records / handshake / transcript
    ├── SSL.Crypto.*       HKDF / AEAD / key schedule / ECDHE
    ├── SSL.PKIX.*         certificate + identity verification
    ├── SSL.ClientHello.*  WireProfile / GREASE / serializer
    ├── SSL.Fingerprint.*  JA3 / JA4 / wire inspection
    └── SSL.Packet         application packet modes
    │
    ▼
:gen_tcp
```

Opt-in record-free resumption now uses `SSL.QUIC.continue/3` and private
session lookup/commit/store/receipt actions. TLS binder/PSK-DHE/HRR and optional
early traffic-secret derivation are accepted through the QUIC runtime's
independent R1/R2 gates, so `SSL.QUIC.capabilities()` reports `resumption` and
`zero_rtt` as true; both stay opt-in per connection. TCP options and early-data policy are unchanged. See the
[continuation contract](../../docs/quic/tls-continuation-contract.md) and
[validation evidence](../../docs/quic/tls-resumption-validation.md).

QUIC 0-RTT replay protection is not enforced inside `ex_ssl`: it checks the
ticket age window and offers early data only after the caller's
`:session_commit` answer is `{:ok, :early_data}`, so single use depends on the
caller's session store consuming the ticket atomically in that commit. The
in-tree consumer, `elixir_quic`'s endpoint `Quic.ResumptionStore`, deletes the
entry on a successful commit, so a replayed ticket gets `:miss` and a full
handshake. That store is in-memory and endpoint-local: replay across
endpoints, nodes or restarts is not detected, and a custom store must provide
the same atomic single-use guarantee.

The raw TCP socket is controlled by `SSL.Connection`, normally using internal `active: :once`. Application-visible `active` mode is implemented above TLS so handshake/record processing cannot be disabled by application socket mode.

## Wire profiles

The profile is the source of truth for what `ex_ssl` attempts to emit.

Conceptually:

```text
WireProfile
  │
  ▼
validate against TLS/runtime capabilities
  │
  ▼
materialize per-connection randomness, GREASE and fresh KeyShare
  │
  ▼
ordered ClientHello AST
  │
  ├──► JA3
  ├──► JA4
  └──► exact-wire inspection
  │
  ▼
serialize
```

Profiles may describe KeyShare group/order/position but may **not** reuse actual ephemeral private/public key material between real connections.

## Important limitations

### Not a complete device impersonation layer

A matching TLS ClientHello does not guarantee that a remote service will see a client as identical to a browser or mobile application. Other observable layers can include TCP/IP behavior, HTTP/2 SETTINGS and framing, header behavior, QUIC/HTTP/3 behavior, application protocol details, and timing.

`ex_ssl` focuses on the TLS layer.

### Explicit bounded TLS 1.2

Version 0.4 accepts explicit TLS1.2-only or mixed version lists while
keeping TLS1.3 as the default. Generated default profiles advertise mixed versions
highest first for either public list order; explicit WireProfiles retain their
ordered version contract. TLS1.2 requires ECDHE, AES-GCM and secure-renegotiation
indication. EMS is always offered and used when acknowledged. Legacy peers
without EMS can complete an authenticated full handshake, but their sessions
cannot be retained, cached or exported as `session_data`. This mode lacks EMS's
handshake-context binding; renegotiation, key exporters and channel bindings
remain unsupported. OTP full/mTLS and OpenSSL EMS exchanges validate these
boundaries. See the compatibility matrix and progress ledger for evidence.

### BEAM secret zeroization

Elixir/Erlang immutable binaries and garbage collection do not provide deterministic memory zeroization. `ex_ssl` minimizes secret lifetime and scope but does not claim guaranteed erasure of every in-memory copy.

## Security model

Fingerprint fidelity never overrides TLS authentication.

`ex_ssl` must fail closed for:

- invalid certificate chains;
- service identity mismatch;
- invalid CertificateVerify signatures;
- invalid Finished values;
- AEAD authentication failures;
- invalid protocol state;
- record/sequence limit violations.

The implementation uses OTP `:crypto` and `:public_key` for cryptographic primitives and X.509 functionality rather than reimplementing those primitives in Elixir.

## Development status

The authenticated TLS 1.3 client, passive/active-once raw application traffic,
STARTTLS, ownership transfer, public ALPN, KeyUpdate handling, and bounded
multi-record writes are implemented. Development continues toward broader OTP
API/options, active modes, packet modes, exporters, verified
real-world profiles, performance work, and independent security review.

See:

- [ARCHITECTURE.md](docs/ARCHITECTURE.md)
- [DESIGN.md](docs/DESIGN.md)
- [PRD.md](docs/PRD.md)
- [IMPLEMENTATION_PLAN.md](docs/IMPLEMENTATION_PLAN.md)
- [AGENTS.md](AGENTS.md)

## Testing philosophy

The project uses four complementary test classes:

### Protocol/vector tests

Cryptographic and transcript operations are checked against independent known results.

### Property/fragmentation tests

Parsers are tested across arbitrary TCP, record, and handshake fragmentation boundaries.

### Interoperability tests

Integration tests connect ex_ssl to generated local OTP `:ssl` peers and
OpenSSL. The dedicated Caddy workflow validates fingerprint behavior.

### Differential compatibility tests

Focused scenarios compare OTP `:ssl` and `SSL` behavior for implemented receive,
path-depth, ownership, timeout, and active-mode semantics.

A compatibility claim is not complete until covered by tests.

## Standards and references

Primary references:

- TLS 1.3: RFC 9846 — https://www.rfc-editor.org/info/rfc9846/
- GREASE: RFC 8701 — https://www.rfc-editor.org/info/rfc8701/
- TLS service identity: RFC 9525 — https://www.rfc-editor.org/info/rfc9525/
- Erlang/OTP `:ssl`: https://www.erlang.org/doc/apps/ssl/ssl.html
- Erlang/OTP `:crypto`: https://www.erlang.org/doc/apps/crypto/crypto.html
- Erlang/OTP `:public_key`: https://www.erlang.org/doc/apps/public_key/public_key.html
- JA4 technical details: https://github.com/FoxIO-LLC/ja4/blob/main/technical_details/JA4.md

## License

Licensed under the [Apache License 2.0](LICENSE).