3 Using SSL application API

To see relevant version information for ssl, call ssl:versions/0 .

To see all supported cipher suites, call ssl:cipher_suites(all). The available cipher suites for a connection depend on your certificate. Specific cipher suites that you want your connection to use can also be specified. Default is to use the strongest available.

3.1  Setting up Connections

This section shows a small example of how to set up client/server connections using the Erlang shell. The returned value of the sslsocket is abbreviated with [...] as it can be fairly large and is opaque.

Minimal Example

Note

The minimal setup is not the most secure setup of SSL/TLS/DTLS.

To set up client/server connections:

Step 1: Start the server side:

1 server> ssl:start().
ok

Step 2: Create an TLS listen socket: (To run DTLS add the option {protocol, dtls})

2 server> {ok, ListenSocket} =
ssl:listen(9999, [{certfile, "cert.pem"}, {keyfile, "key.pem"},{reuseaddr, true}]).
{ok,{sslsocket, [...]}}

Step 3: Do a transport accept on the TLS listen socket:

3 server> {ok, TLSTransportSocket} = ssl:transport_accept(ListenSocket).
{ok,{sslsocket, [...]}}

Step 4: Start the client side:

1 client> ssl:start().
ok

To run DTLS add the option {protocol, dtls} to third argument.

2 client> {ok, Socket} = ssl:connect("localhost", 9999,  [], infinity).
{ok,{sslsocket, [...]}}

Step 5: Do the TLS handshake:

4 server> {ok, Socket} = ssl:handshake(TLSTransportSocket).
ok

Step 6: Send a message over TLS:

5 server> ssl:send(Socket, "foo").
ok

Step 7: Flush the shell message queue to see that the message was sent on the server side:

3 client> flush().
Shell got {ssl,{sslsocket,[...]},"foo"}
ok

Upgrade Example - TLS only

Note

To upgrade a TCP/IP connection to an SSL connection, the client and server must agree to do so. The agreement can be accomplished by using a protocol, for example, the one used by HTTP specified in RFC 2817.

To upgrade to an SSL connection:

Step 1: Start the server side:

1 server> ssl:start().
ok

Step 2: Create a normal TCP listen socket:

2 server> {ok, ListenSocket} = gen_tcp:listen(9999, [{reuseaddr, true}]).
{ok, #Port<0.475>}

Step 3: Accept client connection:

3 server> {ok, Socket} = gen_tcp:accept(ListenSocket).
{ok, #Port<0.476>}

Step 4: Start the client side:

1 client> ssl:start().
ok
2 client> {ok, Socket} = gen_tcp:connect("localhost", 9999,  [], infinity).

Step 5: Ensure active is set to false before trying to upgrade a connection to an SSL connection, otherwise SSL handshake messages can be delivered to the wrong process:

4 server> inet:setopts(Socket, [{active, false}]).
ok

Step 6: Do the TLS handshake:

5 server> {ok, TLSSocket} = ssl:handshake(Socket, [{cacertfile, "cacerts.pem"},
{certfile, "cert.pem"}, {keyfile, "key.pem"}]).
{ok,{sslsocket,[...]}}

Step 7: Upgrade to an TLS connection. The client and server must agree upon the upgrade. The server must call ssl:handshake/2 before the client calls ssl:connect/3.

3 client>{ok, TLSSocket} = ssl:connect(Socket, [{cacertfile, "cacerts.pem"},
{certfile, "cert.pem"}, {keyfile, "key.pem"}], infinity).
{ok,{sslsocket,[...]}}

Step 8: Send a message over TLS:

4 client> ssl:send(TLSSocket, "foo").
ok

Step 9: Set active true on the TLS socket:

4 server> ssl:setopts(TLSSocket, [{active, true}]).
ok

Step 10: Flush the shell message queue to see that the message was sent on the client side:

5 server> flush().
Shell got {ssl,{sslsocket,[...]},"foo"}
ok

3.2  Customizing cipher suits

Fetch default cipher suite list for an TLS/DTLS version. Change default to all to get all possible cipher suites.

1>  Default = ssl:cipher_suites(default, 'tlsv1.2').
    [#{cipher => aes_256_gcm,key_exchange => ecdhe_ecdsa,
    mac => aead,prf => sha384}, ....]

In OTP 20 it is desirable to remove all cipher suites that uses rsa kexchange (removed from default in 21)

2> NoRSA =
    ssl:filter_cipher_suites(Default,
                            [{key_exchange, fun(rsa) -> false;
			                       (_) -> true end}]).
    [...]

Pick just a few suites

 3> Suites =
    ssl:filter_cipher_suites(Default,
                            [{key_exchange, fun(ecdh_ecdsa) -> true;
			                       (_) -> false end},
                             {cipher, fun(aes_128_cbc) ->true;
			                  (_) ->false end}]).
    [#{cipher => aes_128_cbc,key_exchange => ecdh_ecdsa,
     mac => sha256,prf => sha256},
     #{cipher => aes_128_cbc,key_exchange => ecdh_ecdsa,mac => sha,
     prf => default_prf}]

Make some particular suites the most preferred, or least preferred by changing prepend to append.

 4>ssl:prepend_cipher_suites(Suites, Default).
  [#{cipher => aes_128_cbc,key_exchange => ecdh_ecdsa,
     mac => sha256,prf => sha256},
   #{cipher => aes_128_cbc,key_exchange => ecdh_ecdsa,mac => sha,
     prf => default_prf},
   #{cipher => aes_256_cbc,key_exchange => ecdhe_ecdsa,
     mac => sha384,prf => sha384}, ...]

3.3  Using an Engine Stored Key

Erlang ssl application is able to use private keys provided by OpenSSL engines using the following mechanism:

1> ssl:start().
ok

Load a crypto engine, should be done once per engine used. For example dynamically load the engine called MyEngine:

2> {ok, EngineRef} =
crypto:engine_load(<<"dynamic">>,
                   [{<<"SO_PATH">>, "/tmp/user/engines/MyEngine"},<<"LOAD">>],[]).
{ok,#Ref<0.2399045421.3028942852.173962>}

Create a map with the engine information and the algorithm used by the engine:

3> PrivKey =
 #{algorithm => rsa,
   engine => EngineRef,
   key_id => "id of the private key in Engine"}.

Use the map in the ssl key option:

4> {ok, SSLSocket} =
ssl:connect("localhost", 9999,
            [{cacertfile, "cacerts.pem"},
             {certfile, "cert.pem"},
             {key, PrivKey}], infinity).

See also crypto documentation

3.4  Session Tickets and Session Resumption in TLS 1.3

TLS 1.3 introduces a new secure way of resuming sessions by using session tickets. A session ticket is an opaque data structure that is sent in the pre_shared_key extension of a ClientHello, when a client attempts to resume a session with keying material from a previous successful handshake.

Session tickets can be stateful or stateless. A stateful session ticket is a database reference (session ticket store) and used with stateful servers, while a stateless ticket is a self-encrypted and self-authenticated data structure with cryptographic keying material and state data, enabling session resumption with stateless servers.

The choice between stateful or stateless depends on the server requirements as the session tickets are opaque for the clients. Generally, stateful tickets are smaller and the server can guarantee that tickets are only used once. Stateless tickets contain additional data, require less storage on the server side, but they offer different guarantees against anti-replay. See also Anti-Replay Protection in TLS 1.3

Session tickets are sent by servers on newly estalished TLS connections. The number of tickets sent and their lifetime are configurable by application variables. See also SSL's configuration.

Session tickets are protected by application traffic keys, and in stateless tickets, the opaque data structure itself is self-encrypted.

An example with automatic and manual session resumption:

Step 1 (server): Start the server:

      {ok, _} = application:ensure_all_started(ssl).
      LOpts = [{certfile, "cert.pem"},
               {keyfile, "key.pem"},
               {versions, ['tlsv1.2','tlsv1.3']},
               {session_tickets, stateless}].
      {ok, LSock} = ssl:listen(8001, LOpts).
      {ok, CSock} = ssl:transport_accept(LSock).

Step 2 (client): Start the client and connect to server:

      {ok, _} = application:ensure_all_started(ssl).
      COpts = [{cacertfile, "cert.pem"},
               {versions, ['tlsv1.2','tlsv1.3']},
               {log_level, debug},
               {session_tickets, auto}].
      ssl:connect("localhost", 8001, COpts).

Step 3 (server): Start the TLS handshake:

      ssl:handshake(CSock).

A connection is established using a full handshake. Below is a summary of the exchanged messages:

      >>> TLS 1.3 Handshake, ClientHello ...
      <<< TLS 1.3 Handshake, ServerHello ...
      <<< Handshake, EncryptedExtensions ...
      <<< Handshake, Certificate ...
      <<< Handshake, CertificateVerify ...
      <<< Handshake, Finished ...
      >>> Handshake, Finished ...
      <<< Post-Handshake, NewSessionTicket ...

At this point the client has stored the received session tickets and ready to use them when establishing new connections to the same server.

Step 4 (server): Accept a new connection on the server:

      {ok, CSock2} = ssl:transport_accept(LSock).

Step 5 (client): Make a new connection:

      ssl:connect("localhost", 8001, COpts).

Step 6 (server): Start the handshake:

      ssl:handshake(CSock2).

The second connection is a session resumption using keying material from the previous handshake:

      >>> TLS 1.3 Handshake, ClientHello ...
      <<< TLS 1.3 Handshake, ServerHello ...
      <<< Handshake, EncryptedExtensions ...
      <<< Handshake, Finished ...
      >>> Handshake, Finished ...
      <<< Post-Handshake, NewSessionTicket ...

Manual handling of session tickets is also supported. In manual mode, it is the responsibility of the client to handle received session tickets.

Step 7 (server): Accept a new connection on the server:

      {ok, CSock3} = ssl:transport_accept(LSock).

Step 8 (client): Make a new connection to server:

      {ok, _} = application:ensure_all_started(ssl).
      COpts2 = [{cacertfile, "cert.pem"},
                {versions, ['tlsv1.2','tlsv1.3']},
                {log_level, debug},
                {session_tickets, manual}].
      ssl:connect("localhost", 8001, COpts).

Step 9 (server): Start the handshake:

      ssl:handshake(CSock3).

After the handshake is performed, the user process receives messages with the tickets sent by the server.

Step 10 (client): Receive a new session ticket:

      Ticket = receive {ssl, session_ticket, {_, TicketData}} -> TicketData end.

Step 11 (server): Accept a new connection on the server:

      {ok, CSock4} = ssl:transport_accept(LSock).

Step 12 (client): Initiate a new connection to the server with the session ticket received in Step 10:

      {ok, _} = application:ensure_all_started(ssl).
      COpts2 = [{cacertfile, "cert.pem"},
                {versions, ['tlsv1.2','tlsv1.3']},
                {log_level, debug},
                {session_tickets, manual},
                {use_ticket, [Ticket]}].
      ssl:connect("localhost", 8001, COpts).

Step 13 (server): Start the handshake:

      ssl:handshake(CSock3).

3.5  Anti-Replay Protection in TLS 1.3

The TLS 1.3 protocol does not provide inherent protection for replay of 0-RTT data but describes mechanisms that SHOULD be implemented by compliant server implementations. The implementation of TLS 1.3 in the SSL application employs all standard methods to prevent potential threats.

Single-use tickets

This mechanism is available with stateful session tickets. Session tickets can only be used once, subsequent use of the same ticket results in a full handshake. Stateful servers enforce this rule by maintaining a database of outstanding valid tickets.

Client Hello Recording

This mechanism is available with stateless session tickets. The server records a unique value derived from the ClientHello (PSK binder) in a given time window. The ticket's age is verified by using both the "obsfuscated_ticket_age" and an additional timestamp encrypted in the ticket data. As the used datastore allows false positives, apparent replays will be answered by doing a full 1-RTT handshake.

Freshness Checks

This mechanism is available with the stateless session tickets. As the ticket data has an embedded timestamp, the server can determine if a ClientHello was sent reasonably recently and accept the 0-RTT handshake, otherwise if falls back to a full 1-RTT handshake. This mechanism is tightly coupled with the previous one, it prevents storing an unlimited number of ClientHellos.

The current implementation uses a pair of Bloom filters to implement the last two mechanisms. Bloom filters are fast, memory-efficient, probabilistic data structures that can tell if an element may be in a set or if it is definitely not in the set.

If the option anti_replay is defined in the server, a pair of Bloom filters (current and old) are used to record incoming ClientHello messages (it is the unique binder value that is actually stored). The current Bloom filter is used for WindowSize seconds to store new elements. At the end of the time window the Bloom filters are rotated (the current Bloom filter becomes the old and an empty Bloom filter is set as current.

The Anti-Replay protection feature in statless servers executes in the following steps when a new ClientHello is received:

  • Reported ticket age (obfuscated ticket age) shall be less than ticket lifetime.

  • Actual ticket age shall be less than the ticket lifetime (statless session tickets contain the servers timestamp when the ticket was issued).

  • Ticket shall be used within specified time window (freshness checks).

  • If all above checks passed both current and old Bloom filters are checked to detect if binder was already seen. Being a probabilistic data structure, false positives can occur and they trigger a full handshake.

  • If the binder is not seen, the binder is validated. If the binder is valid, the server proceeds with the 0-RTT handshake.