ssl(3)

๐Ÿ“ฆ
version 29.0.6 ยท 3 versions
, in ubuntu stonking

๐Ÿ‘‘ ssl ๐Ÿ’… โ€” the Erlang Module Definition page (yes bestie, it's ssl(3))

๐ŸŽ€ NAME

  • ssl โ€” interface functions for TLS (Transport Layer Security) and DTLS (Datagram Transport Layer Security).

๐ŸŒธ DESCRIPTION

Note ๐Ÿ“Œ The application's name is still SSL because the very first versions of the TLS protocol were literally named SSL (Secure Socket Layer). BUT โ€” and this is the important part, bestie โ€” no version of the old SSL protocol is supported by this application. Like, none. Zero. It's giving "we kept the name, we ditched the vibe." ๐Ÿ’€

Example, because we love a lil demo:

1> ssl:start(), ssl:connect("google.com", 443, [{verify, verify_peer},
    {cacerts, public_key:cacerts_get()}]).
{ok,{sslsocket, [...]}}

See Examples for detailed usage and more examples of this API. ๐Ÿฆ‹

Special Erlang node configuration for the application can be found in SSL Application. โœจ


๐Ÿ’– DATA TYPES

๐Ÿซถ active_msgs()

active_msgs() ::
          {ssl, sslsocket(), Data :: binary() | list()} |
          {ssl_closed, sslsocket()} |
          {ssl_error,
           sslsocket(),
           Alert :: error_alert() | (Reason :: any())} |
          {ssl_passive, sslsocket()}.

The type for the messages that get delivered to the owner of a TLS/DTLS socket when it's in active mode. ๐Ÿ‘‘

The ssl_error reason may convey a TLS protocol alert if such an event occurs after the connection has been established. The most common case when this will happen is on the client side when a TLS-1.3 server requests a client certificate and the provided certificate is not accepted by the server โ€” because it will be verified after the server has sent its last handshake message. Awkward timing, ik. ๐Ÿ˜ญ

The ssl_passive message is sent only when the socket is in {active, N} mode and the counter has dropped to 0. It indicates that the socket has transitioned to passive ({active, false}) mode. Not me just chillin' in passive mode now.

๐Ÿ› anchor_fun()

anchor_fun() :: fun().

Claim an intermediate CA in the chain as trusted. Bold move. Slay.

fun(Chain::[public_key:der_encoded()]) ->
      {trusted_ca, DerCert::public_key:der_encoded()} | unknown_ca.

TLS then uses public_key:pkix_path_validation/3 with the selected CA as the trusted anchor and verifies the rest of the chain. ๐ŸŽ€

๐Ÿ“ cert_key_conf()

cert_key_conf() ::
          #{cert =>
                public_key:der_encoded() | [public_key:der_encoded()],
            key => key(),
            certfile => file:filename(),
            keyfile => file:filename(),
            password => iodata() | fun(() -> iodata())}.

Configuration of the entity certificate and its corresponding key. โœจ

A certificate (or possibly a list including the certificate and its chain certificates, where the entity certificate must be the first element in the list or the first entry in the file) and its associated key. For the PEM file format, there can also be a password associated with the file containing the key. ๐Ÿ”

For maximum interoperability, the certificates in the chain should be in the correct order, as the chain will be sent as-is to the peer. If chain certificates are not provided, certificates from the configured trusted CA certificates will be used to construct the chain. See client_option_cert() and server_option_cert() for more information. ๐Ÿ’…

๐ŸŒˆ cipher()

cipher() ::
          aes_256_gcm | aes_128_gcm | aes_256_ccm | aes_128_ccm |
          chacha20_poly1305 | aes_256_ccm_8 | aes_128_ccm_8 |
          aes_128_cbc | aes_256_cbc |
          legacy_cipher().

Cipher algorithms that can be used for payload encryption. ๐Ÿ”ฅ Lock it down, bestie.

๐Ÿงš cipher_filters()

cipher_filters() ::
          [{key_exchange | cipher | mac | prf,
            fun((kex_algo() | cipher() | hash() | aead | default_prf) ->
                    true | false)}].

Filter that lets you customize the cipher suite list. It's giving โœจcuratedโœจ.

๐Ÿ‘‘ cipher_suites()

cipher_suites() :: ciphers().

A list of cipher suites that should be supported. ๐Ÿ’–

Function ssl:cipher_suites/2 can be used to find all cipher suites that are supported by default and all cipher suites that can be configured. Very handy fr fr.

If you compose your own cipher_suites/0 make sure they are filtered for crypto library support using ssl:filter_cipher_suites/2. Do NOT skip that step.

The following function can help creating customized cipher suite lists: ๐ŸŒธ

  • ssl:append_cipher_suites/2
  • ssl:prepend_cipher_suites/2
  • ssl:suite_to_str/1
  • ssl:str_to_suite/1
  • ssl:suite_to_openssl_str/1
Note ๐Ÿšจ Note that TLS-1.3 and TLS-1.2 use different sets of cipher suites. To support both versions, cipher suites from both sets need to be included. If the supplied list does not comply with the configured versions or crypto library, that is, resulting in an empty list, the option will fall back to its appropriate default value for the configured versions. So like, it'll catch you, but don't make it have to. ๐Ÿ’€

Non-default cipher suites, including anonymous cipher suites (prior to TLS 1.3), are supported for interoperability and testing purposes. These can be used by adding them to your cipher suite list. Note that they also need to be supported and enabled by the peer to be actually used, and they may require additional configuration; see srp_param_type(). ๐Ÿ™ˆ

๐Ÿฆ‹ ciphers()

ciphers() :: [erl_cipher_suite()] | string().

Cipher suite formats. โœจ

For backwards compatibility, cipher suites can be configured as a colon-separated string of cipher suite RFC names (or even old OpenSSL names). However, a more flexible approach is to use utility functions together with cipher_filters() if a customized cipher suite option is needed. Glow up your config, bestie. ๐Ÿ’…

๐ŸŽ€ client_option()

client_option() ::
          client_option_cert() |
          common_option_cert() |
          {psk_groups, [group()]} |
          {alpn_advertised_protocols,
           AppProtocols :: [AppProto :: binary()]} |
          {max_fragment_length,
           MaxLen :: undefined | 512 | 1024 | 2048 | 4096} |
          client_option_tls13() |
          common_option_tls13() |
          client_option_pre_tls13() |
          common_option_pre_tls13() |
          common_option_dtls() |
          client_option_legacy() |
          common_option_legacy().

The following options are specific to the client side, or have different semantics for the client and server: ๐ŸŒˆ

  • {psk_groups, Groups} โ€” key exchange groups that the client will send pre shared keys for, defaults to the first group in supported_groups. Must be a subset of supported_groups and will be sent in the same order as they appear in supported_groups. No chaotic reordering, periodt.
  • {alpn_advertised_protocols, AppProtocols} โ€” Application layer protocol. The list of protocols supported by the client to be sent to the server to be used for an Application-Layer Protocol Negotiation (ALPN). If the server supports ALPN, it will choose a protocol from this list; otherwise it will fail the connection with a no_application_protocol alert. A server that does not support ALPN will ignore this value. The list of protocols must not contain an empty binary. ๐Ÿšซ
  • {max_fragment_length, MaxLen} โ€” Max fragment length extension. Specifies the maximum fragment length the client is prepared to accept from the server. See RFC 6066. ๐Ÿ“œ

๐Ÿ’œ client_option_cert()

client_option_cert() ::
          {cacerts,
           CACerts ::
               [public_key:der_encoded()] |
[public_key:combined_cert()]} |
          {cacertfile, CACertFile :: file:filename()} |
          {server_name_indication, SNI :: inet:hostname() | disable} |
          {customize_hostname_check, HostNameCheckOpts :: list()} |
          {certificate_authorities, boolean()} |
          {stapling, Stapling :: staple | no_staple | map()}.

Certificate-related options specific to the client side, or with different semantics for the client and server. ๐Ÿ”โœจ

  • {cacerts, CACerts} โ€” Trusted certificates. The DER-encoded trusted certificates. If this option is supplied it overrides option cacertfile. ๐Ÿ’–

Function public_key:cacerts_get/0 can be used to retrieve to the trusted CA certificates provided by the operating system. (Yes, the OS ones, free of charge, iconic.)

  • {cacertfile, CertFile} โ€” End entity certificate. Path to a file containing PEM-encoded CA certificates. The CA certificates are used during server authentication and when building the client certificate chain.
NOTE ๐Ÿ“Œ When PEM caching is enabled, files provided with this option will be checked for updates at fixed time intervals specified by the ssl_pem_cache_clean environment parameter. So it's keeping an eye on your files, bestie.
  • {server_name_indication, SNI} โ€” Server Name Indication extension. Specify the hostname to be used in TLS Server Name Indication extension. If not specified it will default to the Host argument of connect/3,4 unless it is of type inet:ip_address(). The hostname will also be used in the hostname verification of the peer certificate using public_key:pkix_verify_hostname/2. The special value disable prevents the Server Name Indication extension from being sent and disables the hostname verification check. ๐ŸŒธ
  • {customize_hostname_check, HostNameCheckOpts} โ€” Customization option. Customizes the hostname verification of the peer certificate, as various protocols that use TLS, such as HTTP or LDAP, may require different approaches. For example, here is how to use standard hostname checking for HTTPS implemented in Public_Key:
{customize_hostname_check, [{match_fun, public_key:pkix_verify_hostname_match_fun(https)}]}

For futher description of the customize options, see public_key:pkix_verify_hostname/3. ๐Ÿฆ‹

  • {client_certificate_authorities, UseCertAuth} โ€” Inter-op hint option. If UseCertAuth is set to true, sends the certificate authorities extension in the TLS-1.3 client hello. The default is false. Note that setting UseCertAuth to true can result in a significant overhead if there exists many trusted CA certificates. (Since Erlang/OTP 24.3.) ๐Ÿ˜ญ
  • {stapling, Stapling} โ€” Certificate revocation check option. If Stapling is atom staple or a map, OCSP stapling will be enabled, meaning that an extension of type "status_request" will be included in the client hello to indicate the desire to receive certificate status information. ๐Ÿ’…

If Stapling is set to no_staple (the default), OCSP stapling will be disabled. Periodt.

NOTE: Even if requested by the client, the OCSP response might not be provided by the server. In such event, the certificate validation will fail with reason missing_ocsp_staple. Capturing this failure with a custom verify_fun enables the user to implement their own fallback validation, for example by performing a direct OCSP query or a CRL check. Note however that accepting {bad_cert, missing_ocsp_staple} without performing alternative revocation checking is insecure, as it allows a MITM attacker to suppress revocation information by omitting the OCSP staple. iykyk
                       {verify_fun, {fun(_, _, {bad_cert, missing_ocsp_staple} = R, _St) ->
                                             %% Implement fallback revocation check here,
                                             %% e.g. a direct OCSP query or CRL check.
                                             %% Simply returning {valid, St} skips
                                             %% revocation checking entirely.
                                             {fail, R};
                                        (_, _, {bad_cert, _} = R, _) ->
                                             {fail, R};
                                        (_, _, {extension, _}, St) ->
                                             {unknown, St};
                                        (_, _, valid, St) ->
                                             {valid, St};
                                        (_, _, valid_peer, St) ->
                                             {valid, St}
                                     end, []}}

When Stapling is given as a map, boolean ocsp_nonce key can indicate whether an OCSP nonce should be requested by the client (default is false).

NOTE: The OCSP response can be provided without a nonce value โ€” even if it was requested by the client. In such cases SSL will proceed with the handshake and generate a {missing, ocsp_nonce} logger event.

client_option_legacy() ::

       client_option_legacy() ::
                 {verify, Verify :: verify_peer | verify_none} |
                 {client_preferred_next_protocols,
                  NextAppProtocols ::
                      {Precedence :: server | client,
                       ClientPrefs :: [AppProto :: binary()]} |
                      {Precedence :: server | client,
                       ClientPrefs :: [AppProto :: binary()],
                       Default :: (AppProto :: binary())}}.

Legacy client options. Okay bestie, these are the old-school ones, but they still matter.

  • {verify, Verify} โ€” Verification of certificates.

Clients should always verify the servers certificate, this legacy option should only be used for test or debug purposes.

This option specifies whether certificates are to be verified.

If Verify is verify_peer, which is the default, it is required to also provide one of the options cacerts or cacertfile in order for the certificate verification to succeed. For example, an HTTPS client can use option {cacerts, public_key:cacerts_get()} to use the trusted CA certificates provided by the operating system.

If Verify is verify_none, all X.509-certificate path validation errors will be ignored.

CHANGE: The default for Verify was changed to verify_peer in Erlang/OTP 26.0.

  • {client_preferred_next_protocols, NextAppProtocols} โ€” Next Protocol Negotiation.

ALPN (Application-Layer Protocol Negotiation) deprecates NPN (Next Protocol Negotiation) and this option.

Indicates that the client wants to perform Next Protocol Negotiation.

If Precedence is server, the negotiated protocol is the first protocol to be shown on the server advertised list that is also on the client preference list.

If Precedence is client, the negotiated protocol is the first protocol to be shown on the client preference list that is also on the server advertised list.

If the client does not support any of the server advertised protocols or the server does not advertise any protocols, the client falls back to the first protocol in its list or to the default protocol (if a default is supplied). If the server does not support Next Protocol Negotiation, the connection terminates if no default protocol is supplied.


client_option_pre_tls13() ::

       client_option_pre_tls13() ::
                 {reuse_session,
                  SessionRef ::
                      session_id() | {session_id(), SessionData :: binary()}} |
                 {reuse_sessions, Reuse :: boolean() | save} |
                 {psk_identity, PskID :: string()} |
                 {srp_identity,
                  SrpID :: {Username :: string(), Password :: string()}} |
                 {fallback, LegacyFallback :: boolean()}.

Options only relevant to TLS versions prior to TLS-1.3. So retro.

  • {reuse_session, SessionRef} โ€” Explicit session reuse. Reuses a specific session.

Since Erlang/OTP 21.3, if the session was saved earlier using option {reuse_sessions, save}, the session can be referred by its session ID.

Since Erlang/OTP 22.3, the session can be explicitly specified by its session ID and associated data.

See also SSL User's Guide, Session Reuse pre TLS 1.3.

  • {reuse_sessions, Reuse} โ€” Enables later session reuse.

When Reuse is set to save, a new connection will be negotiated and saved for later reuse. The session ID can be fetched with connection_information/2 and used with the client option reuse_session.

When Reuse is set to true, automated session reuse will be performed, if possible. If a new session is created, and is unique in regard to previous stored sessions, it will be saved for possible later reuse.

Since: OTP 21.3.

  • {psk_identity, PskID} โ€” Option for use with PSK cipher suites.

Specifies the identity the client presents to the server. The matching secret is found by the fun given in the user_lookup_fun option.

  • {srp_identity, SrpID} โ€” Option for use SRP cipher suites.

Specifies the username and password to use to authenticate to the server.

  • {fallback, LegacyFallback} โ€” Inter-op legacy client option.

Send special cipher suite TLS_FALLBACK_SCSV to avoid an undesired TLS version downgrade. Defaults to false.

WARNING: This option is not needed in normal TLS usage and must not be used to implement new clients. However, legacy clients that retries connections in the following manner:
ssl:connect(Host, Port, [...{versions, ['tlsv2', 'tlsv1.1', 'tlsv1']}])
ssl:connect(Host, Port, [...{versions, [tlsv1.1', 'tlsv1']}, {fallback, true}])
ssl:connect(Host, Port, [...{versions, ['tlsv1']}, {fallback, true}])

can use it to avoid undesired TLS version downgrade. Note that TLS_FALLBACK_SCSV must also be supported by the server for the prevention to work.


client_option_tls13() ::

       client_option_tls13() ::
                 {session_tickets, SessionTickets :: disabled | manual | auto}
       |
                 {use_ticket, Tickets :: [session_ticket()]} |
                 {early_data, binary()} |
                 {middlebox_comp_mode, MiddleBoxMode :: boolean()}.

Options only relevant for TLS-1.3. Slay, modern TLS!

  • {session_tickets, SessionTickets} โ€” Use of session tickets.

Configures the session ticket functionality. Allowed values are disabled, manual, and auto. If it is set to manual the client will send the ticket information to user process in a 3-tuple:

{ssl, session_ticket, `Ticket::`(`t:session_ticket/0`)}

where Ticket is a map with information about the created TLS-1.3 session ticket. The only key that the user needs to consider is sni key to be able to provide it as a value in the use_ticket option list of possible tickets to use it to attempt session resumption to a server identified by the server name indication in manual session ticket mode.

If it is set to auto, the client automatically handles received tickets and tries to use them when making new TLS connections (session resumption with pre-shared keys).

Ticket lifetime, the number of tickets sent by the server, and the maximum number of tickets stored by the server in stateful mode are configured by application variables.

See also SSL User's Guide, Session Tickets and Session Resumption in TLS 1.3.

  • {use_ticket, Tickets} โ€” Configures the session tickets to be used for session resumption. It is a mandatory option in manual mode ({session_tickets, manual}).
NOTE: Session tickets are only sent to the user if option session_tickets is set to manual This option is supported by TLS-1.3. See also SSL User's Guide, Session Tickets and Session Resumption in TLS 1.3.
  • {early_data, EarlyData} โ€” Configures the early data to be sent by the client.

To verify that the server has the intention to process the early data, the following tuple is sent to the user process:

{ssl, SslSocket, {early_data, Result}}

where Result is either accepted or rejected.

WARNING: It is the responsibility of the user to handle rejected EarlyData and to resend when appropriate.
  • {middlebox_comp_mode, MiddleBoxMode} โ€” Configures the middlebox compatibility mode for a TLS-1.3 connection.

A significant number of middleboxes misbehave when a TLS-1.3 connection is negotiated. Implementations can increase the chance of making connections through those middleboxes by adapting the TLS-1.3 handshake to resemble that of a TLS-1.2 handshake.

The middlebox compatibility mode is enabled (true) by default.



okay so these are the options that both sides get โ€” client AND server, no favorites, equal treatment, we love to see it ๐Ÿ’–

common_option() ::
          {protocol, tls | dtls} |
          {handshake, hello | full} |
          {ciphers, cipher_suites()} |
          {signature_algs, signature_algs()} |
          {signature_algs_cert, [sign_scheme()]} |
          {keep_secrets,
           KeepSecrets ::
               boolean() |
               {keylog_hs, fun((Info :: keylog_info()) -> any())} |
               {keylog, fun((Info :: keylog_info()) -> any())}} |
          {max_handshake_size, HandshakeSize :: pos_integer()} |
          {versions, [protocol_version()]} |
          {log_level, Level :: logger:level() | none | all} |
          {hibernate_after, HibernateTimeout :: timeout()} |
          {receiver_spawn_opts,
           SpawnOpts :: [erlang:spawn_opt_option()]} |
          {sender_spawn_opts,
           SpawnOpts :: [erlang:spawn_opt_option()]}.
  • {protocol, Protocol} โ€” pick your transport layer security flavor, bestie: TLS or DTLS. Defaults to tls โœจ
  • {handshake, Completion} โ€” lets you pause the handshake at the hello stage, like hitting the brakes to peek at the vibe. Defaults to full. If you say hello, the handshake pauses right after the hello message so you can make decisions based on hello extensions before moving on โ€” or you just abort the whole thing by calling handshake_continue/3 or handshake_cancel/1. Main character energy, literally ๐ŸŽ€
  • {keep_secrets, KeepSecrets} โ€” sets up a TLS connection for keylogging ๐Ÿ”‘

fr fr, if you want to retrieve all the keylog info on a TLS connection, you have to configure it in advance. You can't just show up late, bestie.

WARNING: The keylog information defeats the purpose of the protocol and enabling it makes the user responsible for the information not ending up compromising security, it is intended for debugging. ๐Ÿ’€

The keep_secrets functionality is disabled (false) by default. If you set it to the legacy value true, keylog information can be retrieved from the connection using connection_information/2.

Added in OTP 23.2.

NOTE: asking the connection has some drawbacks โ€” for instance you can not get keylog information for failed connections, and other keylog items have to be retrieved in a polling manner and are not correctly formatted for key_updates. not me finding out the hard way ๐Ÿ™ˆ

Since OTP 27.3.1 you may instead of true provide a callback fun, giving keylog information for either just failing handshakes or for entire connections โ€” by setting keep_secrets to {keylog_hs, fun()} or {keylog, fun()}. The fun is of arity one and will be called with keylog information keylog_info() as an argument. The keylog_hs fun will only be called if the handshake fails, and is only relevant for TLS-1.3, that has encrypted messages before the first handshake is complete. The keylog fun will be called every time some secrets are updated, and provides keylog for that update โ€” that is during the connection establishment and after that at renegotiation or key update (depending on TLS protocol version). When a fun is used, the connection_information/2 can not be used to retrieve key log information. For more information see NSS keylog. ๐Ÿ’…

  • {max_handshake_size, HandshakeSize} โ€” limit the acceptable handshake packet size. This exists to cap the size of valid TLS handshake packets so nobody hits you with a DoS attack ๐Ÿ›ก๏ธ. It's an integer (24 bits, unsigned). Defaults to 262144 since OTP 29.0.
  • {hibernate_after, HibernateTimeout} โ€” hibernates inactive connection processes ๐Ÿ˜ด. Give it an integer-value and the TLS/DTLS connection goes into hibernation after that many milliseconds of inactivity, which shrinks its memory footprint. If you don't specify it, the process never goes into hibernation. sleepy time stays optional, periodt.
  • {log_level, Level} โ€” sets the log level for a TLS/DTLS connection ๐Ÿ“œ. Alerts get logged on notice level, which is the default. The level debug triggers verbose logging of TLS/DTLS protocol messages. See also SSL Application.
  • {receiver|sender_spawn_opts, SpawnOpts} โ€” configure erlang spawn opts. This configures the spawn options of the TLS sender and receiver processes โœจ. Setting up garbage collection options can be helpful for trade-offs between CPU usage and memory usage. See erlang:spawn_opt/2.

For connections using Erlang distribution, the default sender option is [...{priority, max}] โ€” and heads up, this priority option cannot be changed. For all connections, ...link is added to receiver and cannot be changed either. rules are rules ๐Ÿซถ


and now the certificate-related common options, also for both client and server, because sharing is caring ๐ŸŽ€

common_option_cert() ::
          {certs_keys, CertsKeys :: [cert_key_conf()]} |
          {depth, AllowedCertChainLen :: pos_integer()} |
          {verify_fun,
           Verify :: {Verifyfun :: fun(), InitialUserState :: any()}} |
          {cert_policy_opts,
           PolicyOpts ::
               [{policy_set, [public_key:oid()]} |
                {explicit_policy, boolean()} |
                {inhibit_policy_mapping, boolean()} |
                {inhibit_any_policy, boolean()}]} |
          {allow_any_ca_purpose, Allow :: boolean()} |
          {crl_check, Check :: boolean() | peer | best_effort} |
          {crl_cache, crl_cache_opts()} |
          {partial_chain, anchor_fun()}.
  • {certs_keys, CertsKeys} โ€” at least one certificate and key pair ๐Ÿ”‘. It's a list of a certificate (or possibly a certificate and its chain) plus the associated key of the certificate that can be used to authenticate the client or the server. The certificate key pair that is considered best and matches the negotiated parameters for the connection gets selected. slay.

The different signature algorithms are prioritized in this order: mldsa, slhdsa, eddsa, ecdsa, rsa_pss_pss, rsa, and dsa. If more than one key is supplied for the same signature algorithm, they will be prioritized by strength (except for engine keys โ€” more on that in the next paragraph). This offers flexibility to, for instance, configure a newer certificate that is expected to be used in most cases, and an older but acceptable certificate that will only be used to talk to legacy systems. Note that there is a trade off between the induced overhead and the flexibility, so alternatives should be chosen for good reasons โ€” not just vibes.

Engine keys will be favored over other keys. And since engine keys cannot be inspected, supplying more than one engine key makes no sense. ๐Ÿ™ˆ

When this option is specified it overrides all single certificate and key options. For examples, see the User's Guide.

NOTE: mldsa, slhdsa, eddsa certificates are only supported by TLS-1.3 implementations that do not support dsa certificates. rsa_pss_pss (RSA certificates using Probabilistic Signature Scheme) are supported in TLS-1.2 and TLS-1.3, but some TLS-1.2 implementations do not support rsa_pss_pss. iykyk ๐Ÿ’…

  • {depth, AllowedCertChainLen} โ€” limits the accepted number of certificates in the certificate chain ๐Ÿ”—. It's the maximum number of non-self-issued intermediate certificates that can follow the peer certificate in a valid certification path. So: if depth is 0 the PEER must be signed by the trusted ROOT-CA directly; if 1 the path can be PEER, CA, ROOT-CA; if 2 the path can be PEER, CA, CA, ROOT-CA, and so on. The default value is 10. Used to mitigate DoS attack possibilities ๐Ÿ›ก๏ธ.
  • {verify_fun, Verify} โ€” customize certificate path validation โœจ. The verification fun is to be defined like this:
fun(OtpCert :: #'OTPCertificate'{},
    Event, InitialUserState :: term()) ->
     {valid, UserState :: term()} |
     {fail, Reason :: term()} | {unknown, UserState :: term()}.

fun(OtpCert :: #'OTPCertificate'{}, DerCert :: public_key:der_encoded(),
    Event, InitialUserState :: term()) ->
     {valid, UserState :: term()} |
     {fail, Reason :: term()} | {unknown, UserState :: term()}.

Types:
      Event = {bad_cert, Reason :: atom() |
              {revoked, atom()}} |
          {extension, #'Extension'{}} |
              valid |
              valid_peer

The verification fun is called during the X.509-path validation when an error occurs, or when an extension unknown to the SSL application is encountered. It is also called when a certificate is considered valid by the path validation, so the user application can get access to each certificate in the path. It differentiates between the peer certificate and the CA certificates by using valid_peer or valid as the Event argument to the verification fun. See the Public_Key User's Guide for definition of #'OTPCertificate'{} and #'Extension'{}.

  • If the verify callback fun returns {fail, Reason}, the verification process is immediately stopped, an alert is sent to the peer, and the TLS/DTLS handshake terminates ๐Ÿ’€.
  • If the verify callback fun returns {valid, UserState}, the verification process continues โœ….
  • If the verify callback fun always returns {valid, UserState}, the TLS/DTLS handshake does not terminate regardless of verification failures, and the connection is established. (yes this is as unhinged as it sounds, be careful bestie ๐Ÿ™ˆ)
  • If called with an extension unknown to the user application, the fun is to return {unknown, UserState}.

Note that if the fun returns unknown for an extension marked as critical, validation will fail. no mercy, periodt.

Default option verify_fun in verify_peer mode:

                     {fun(_, _, {bad_cert, _} = Reason, _) ->
                           {fail, Reason};
                         (_, _, {extension, _}, UserState) ->
                           {unknown, UserState};
                         (_, _, valid, UserState) ->
                           {valid, UserState};
                         (_, _, valid_peer, UserState) ->
                            {valid, UserState}
                      end, []}

And bestie, the default option verify_fun in mode verify_none is this lil guy right here ๐Ÿ’–

        {fun(_, _, {bad_cert, _}, UserState) ->
             {valid, UserState};
           (_, _, {extension, #'Extension'{critical = true}}, UserState) ->
             {valid, UserState};
           (_, _, {extension, _}, UserState) ->
             {unknown, UserState};
           (_, _, valid, UserState) ->
             {valid, UserState};
           (_, _, valid_peer, UserState) ->
             {valid, UserState}
        end, []}

The possible path validation errors come at you in the form {bad_cert, Reason}, where Reason is one of these ๐Ÿ‘‡

  • unknown_ca โ€” no trusted CA was found in the trusted store. The trusted CA is normally a so-called ROOT CA, which is a self-signed certificate. Trust can be claimed for an intermediate CA (the trusted anchor does not have to be self-signed according to X-509) by using option partial_chain.
  • selfsigned_peer โ€” the chain consisted only of one self-signed certificate.
  • {invalid_ext_keyusage, [public_key:oid()]} โ€” if the peer certificate specifies the extended keyusage extension and does not include the purpose for either being a TLS server (id-kp-ServerAuth) or TLS client (id-kp-ClientAuth) depending on the peers role.
  • {ca_invalid_ext_keyusage, [public_key:oid()]} โ€” if a CA certificate specifies the extended keyusage extension and does not include the purpose for either being a TLS server (id-kp-ServerAuth) or TLS client (id-kp-ClientAuth) depending on the role of the peer chained with this CA, or the option allow_any_ca_purpose is set to true but the special any-value (anyExtendedKeyUsage) is not included in the CA cert purposes.
  • PKIX X-509-path validation error โ€” for possible reasons, see public_key:pkix_path_validation/3.

๐Ÿ’– {cert_policy_opts, PolicyOpts} โ€” handle certificate policies

Configure X.509 certificate policy handling for the certificate path validation process; see public_key:pkix_path_validation/3 for more details. It's giving very "deep in the weeds and thriving" energy ๐Ÿงš

๐Ÿ’– {allow_any_ca_purpose, boolean()} โ€” handle certificate extended key usages extension

Okay so if a CA certificate has an extended key usage extension but it does not want to restrict the usages of the key, it can include a special anyExtendedKeyUsage purpose. If this option is set to true, all key usage purposes are automatically accepted for a CA that includes that purpose. The option defaults to false.


  • {crl_check, Check} โ€” handle certificate revocation lists.

Perform CRL (Certificate Revocation List) verification (public_key:pkix_crls_validate/3) on all the certificates during the path validation (public_key:pkix_path_validation/3) of the certificate chain. Check defaults to false.

The meaning of Check is as follows, bestie:

  • false โ€” no checks are performed.
  • peer โ€” the check is only performed on the peer certificate.
  • best_effort โ€” the best_effort check is a legacy behavior and must be considered insecure! ๐Ÿ˜ญ

If certificate revocation status cannot be determined it will be accepted as valid.

The CA certificates specified for the connection will be used to construct the certificate chain validating the CRLs.

The CRLs will be fetched from a local or external cache. See ssl_crl_cache_api.


๐Ÿงฉ common_option_dtls()

common_option_dtls() ::
          {use_srtp,
           UseSrtp ::
               #{protection_profiles := [binary()], mki => binary()}}.

Common options to client and server only valid for DTLS โœจ

{use_srtp, UseSrtp} โ€” configures the use_srtp DTLS hello extension

In order to negotiate the use of SRTP data protection, clients include an extension of type "use_srtp" in the DTLS extended client hello. This extension MUST only be used when the data being transported is RTP or RTCP.

The value is a map with a mandatory protection_profiles parameter and an optional mki parameter.

protection_profiles configures the list of the client's acceptable SRTP Protection Profiles. Each profile is a 2-byte binary. Example: #{protection_profiles => [<<0,2>>, <<0,5>>]}

mki configures the SRTP Master Key Identifier chosen by the client.

The srtp_mki field contains the value of the SRTP MKI which is associated with the SRTP master keys derived from this handshake. Each SRTP session MUST have exactly one master key that is used to protect packets at any given time. The client MUST choose the MKI value so that it is distinct from the last MKI value that was used, and it SHOULD make these values unique for the duration of the TLS session.

NOTE: OTP does not handle SRTP, so an external implementations of SRTP encoder/decoder and a packet demultiplexer are needed to make use of the use_srtp extension. See also option transport_option.

Servers that receive an extended hello containing a "use_srtp" extension can agree to use SRTP by including an extension of type "use_srtp", with the chosen protection profile in the extended server hello. This extension MUST only be used when the data being transported is RTP or RTCP. ๐Ÿซถ


๐Ÿงฉ common_option_legacy()

common_option_legacy() ::
          {cert,
           Cert :: public_key:der_encoded() |
[public_key:der_encoded()]} |
          {certfile, CertPem :: file:filename()} |
          {key, Key :: key()} |
          {keyfile, KeyPem :: file:filename()} |
          {password, KeyPemPasswd :: iodata() | fun(() -> iodata())} |
          {log_alert, LogAlert :: boolean()} |
          {padding_check, PaddingCheck :: boolean()} |
          {beast_mitigation, one_n_minus_one | zero_n | disabled} |
          {ssl_imp, Imp :: new | old}.

Legacy options considered deprecated in favor of other options, insecure to use, or plainly not relevant anymore. It's giving "we keep these around for the nostalgia" ๐Ÿ’€

  • {cert, Certs} โ€” use option certs_keys instead.
  • {certfile, CertPem} โ€” use option certs_keys instead.
  • {keyfile, KeyPem} โ€” use option certs_keys instead.
  • {password, KeyPemPasswd} โ€” use option certs_keys instead.
  • {log_alert, LogAlert} โ€” if LogAlert is false, TLS/DTLS Alert reports are not displayed. Deprecated in OTP 22; use {log_level, Level} instead.

{padding_check, PaddingCheck} โ€” inter-op trade-off option

Affects TLS-1.0 connections only. If set to false, it disables the block cipher padding check to be able to interoperate with legacy software.

WARNING: Using {padding_check, false} makes TLS vulnerable to the Poodle attack. ๐Ÿ˜ญ
  • {beast_mitigation, BeastMitigation} โ€” inter-op trade-off option.

Affects TLS-1.0 connections only. Used to change the BEAST mitigation strategy to interoperate with legacy software. Defaults to one_n_minus_one.

  • one_n_minus_one โ€” perform 1/n-1 BEAST mitigation.
  • zero_n โ€” perform 0/n BEAST mitigation.
  • disabled โ€” disable BEAST mitigation.
WARNING: Using {beast_mitigation, disabled} makes TLS-1.0 vulnerable to the BEAST attack. ๐Ÿ”ฅ
  • {ssl_imp, Imp} โ€” deprecated since OTP 17; has no effect.

๐Ÿงฉ common_option_pre_tls13()

common_option_pre_tls13() ::
          {eccs, NamedCurves :: [named_curve()]} |
          {secure_renegotiate, SecureRenegotiate :: true} |
          {user_lookup_fun, {Lookupfun :: fun(), UserState :: any()}}.

Options common to client and server side prior to TLS-1.3. Vintage era stuff, bestie ๐ŸŒธ

{eccs, NamedCurves} โ€” Named Elliptic Curves

Elliptic curves that can be used in pre TLS-1.3 key exchange.

{secure_renegotiate, SecureRenegotiate} โ€” previous interoperability option

Since OTP 29.0 setting this option to false will fail, that is accepting possible fallback to insecure behavior preceding implementation of RFC 5746 is no longer supported. Setting it to true will continue to work but is not necessary, as the default of true will now always be enforced. The way they just... locked it in ๐Ÿ”’ periodt.

{user_lookup_fun, {LookupFun, UserState}} โ€” PSK/SRP cipher suite option

The lookup fun is to be defined as follows:

       fun(psk, PSKIdentity :: binary(), UserState :: term()) ->
            {ok, SharedSecret :: binary()} | error;
       fun(srp, Username :: binary(), UserState :: term()) ->
            {ok, {SRPParams :: srp_param_type(), Salt :: binary(),
                  DerivedKey :: binary()}} | error.

For Pre-Shared Key (PSK) cipher suites, the lookup fun is called by the client and server to determine the shared secret. When called by the client, PSKIdentity is the hint presented by the server or undefined. When called by the server, PSKIdentity is the identity presented by the client.

For Secure Remote Password (SRP), the fun is only used by the server to obtain parameters that it uses to generate its session keys. DerivedKey is to be derived according to RFC 2945 and RFC 5054: crypto:sha([Salt, crypto:sha([Username, <<$:>>, Password])])


๐Ÿงฉ common_option_tls13()

common_option_tls13() ::
          {supported_groups, [group()]} |
          {key_update_at, KeyUpdateAt :: pos_integer()}.

๐Ÿ’– Common options to both client and server for TLS-1.3 ๐Ÿ’–

  • {supported_groups, Groups} โ€” bestie, this is the key exchange option โœจ

TLS 1.3 pulled up with the "supported_groups" extension, and it's the thing that negotiates the key-exchange parameters during a TLS 1.3 handshake. Both the client and the server get to drop a list of which parameters they're willing to use ๐Ÿซถ

If you don't specify it, it falls back to a default list โ€” and you can peep that list yourself by calling ssl:groups(default). Heads up though: that default list is filtered based on the installed crypto library version ๐Ÿ‘€

  • {key_update_at, KeyUpdateAt} โ€” session key renewal, aka the glow-up refresh ๐Ÿ’…

This one configures the maximum amount of bytes that can be sent over a TLS 1.3 connection before an automatic key update gets performed. Think of it as a hard cap so your keys never overstay their welcome ๐ŸŒธ

There are legit cryptographic limits on how much plaintext you can safely encrypt under one set of keys. The current default makes sure data integrity won't be broken with a probability greater than 1/2^57. For the whole deep dive, see Limits on Authenticated Encryption Use in TLS ๐Ÿ“š


connection_info()

connection_info() ::
          [{protocol, protocol_version()} |
           {session_resumption, boolean()} |
           {selected_cipher_suite, erl_cipher_suite()} |
           {sni_hostname, term()} |
           {ciphers, [erl_cipher_suite()]}] |
          connection_info_pre_tls13() |
          security_info().

A key-value list that spills some tea about the established connection ๐Ÿต


connection_info_keys()

connection_info_keys() ::
          [protocol | selected_cipher_suite | sni_hostname |
           session_resumption | ciphers | client_random |
           server_random | master_secret | keylog | session_id |
           session_data | ecc | srp_username].

These are the TLS connection keys you can actually pull info out of ๐Ÿ”‘


connection_info_pre_tls13()

connection_info_pre_tls13() ::
          [{session_id, session_id()} |
           {session_data, binary()} |
           {ecc, {named_curve, term()}} |
           {srp_username, term()}].

TLS connection info that's relevant prior to TLS-1.3 โ€” the old-version lore ๐Ÿ“œ


crl_cache_opts()

crl_cache_opts() ::
          {Module :: atom(),
           {DbHandle :: internal | term(), Args :: list()}}.

Options for using the built-in CRL cache support โœจ

This is where you say how to perform lookup and caching of certificate revocation lists (CRLs). Module defaults to ssl_crl_cache, with DbHandle being internal, and Args being [].

There are two implementations available, and we're covering both, no skips ๐Ÿซถ

ssl_crl_cache โ€” Implementation 1

This module keeps a cache of CRLs. You can add CRLs to the cache using ssl_crl_cache:insert/1, and it can optionally auto-fetch them through HTTP if you specify the following argument:

  • {http, timeout()} โ€” Enables fetching of CRLs specified as http URIs in X.509 certificate extensions. Requires the Inets application ๐ŸŒ
  • {allowed_hosts, [string()]} โ€” If http fetching is allowed, you can specify a list of allowed hosts as a hardening option. The entries should be "Host:Port". If ":Port" is left out the default port is 80. If allowed_hosts is not specified, only external hosts using port 80 or 8080 will be allowed ๐Ÿ‘‘
Note ๐ŸŽ€ Putting the local host on the allow list will of course make the local host allowed.

ssl_crl_hash_dir โ€” Implementation 2

This module makes use of a directory where CRLs are stored in files named by the hash of the issuer name ๐Ÿ“

The file names consist of eight hexadecimal digits followed by .rN, where N is an integer, for example 1a2b3c4d.r0. For the first version of the CRL, N starts at zero, and for each new version, N is incremented by one. The OpenSSL utility c_rehash creates symlinks according to this pattern ๐Ÿ”—

For a given hash value, this module finds all consecutive .r* files starting from zero, and those files taken together make up the revocation list. CRL files with nextUpdate fields in the past โ€” or issued by a different CA that happens to have the same name hash โ€” are excluded ๐Ÿšซ

The following argument is required:

  • {dir, string()} โ€” Specifies the directory in which the CRLs can be found.

dtls_legacy_version()

dtls_legacy_version() :: dtlsv1.

A DTLS protocol version that is no longer supported by default for security reasons and scheduled for removal in OTP 30 ๐Ÿ˜ญ It's giving sunset era.


dtls_version()

dtls_version() :: 'dtlsv1.2' | dtls_legacy_version().

DTLS protocol version. Simple as that ๐Ÿ’…


erl_cipher_suite()

erl_cipher_suite() ::
          #{key_exchange := kex_algo(),
            cipher := cipher(),
            mac := hash() | aead,
            prf := hash() | default_prf}.

The Erlang cipher suite representation โœจ

Warning ๐Ÿšจ Enabling cipher suites using RSA as a key exchange algorithm is strongly discouraged (only available prior to TLS-1.3). For some configurations software preventions may exist, and can make them usable if they work, but relying on them to work is risky. There exist more reliable cipher suites that can be used instead. Bestie, just don't ๐Ÿซ 

error_alert()

error_alert() ::
          {tls_alert, {tls_alert(), Description :: string()}}.

If a TLS connection fails, a TLS protocol ALERT will be sent/received ๐Ÿšจ

You'll get back an atom reflecting the raised alert (according to the TLS protocol), plus a description string with some further details. So like, you will know what went wrong ๐Ÿ’€


group()

group() ::
          x25519mlkem768 | secp384r1mlkem1024 | secp256r1mlkem768 |
          mlkem1024 | mlkem768 | mlkem512 | x25519 | x448 | secp256r1 |
          secp384r1 | secp521r1 | brainpoolP512r1tls13 |
          brainpoolP384r1tls13 | brainpoolP256r1tls13 | ffdhe2048 |
          ffdhe3072 | ffdhe4096 | ffdhe6144 | ffdhe8192.

TLS-1.3 key exchange configuration ๐Ÿ”


hash()

hash() :: sha2() | legacy_hash().

Hash algorithms used together with signing and encryption functions ๐Ÿงฎ


host()

host() :: inet:hostname() | inet:ip_address().

A name or address to a host ๐Ÿ 


kex_algo()

kex_algo() ::
          ecdhe_ecdsa | ecdh_ecdsa | ecdh_rsa | any | legacy_kex().

Cipher Suite Key Exchange Algorithm โ€” and it will be any in TLS-1.3, because key exchange is no longer part of cipher suite configuration in TLS-1.3. Periodt ๐Ÿ’…


key()

key() ::
          {'RSAPrivateKey' | 'DSAPrivateKey' | 'ECPrivateKey' |
           'PrivateKeyInfo',
           public_key:der_encoded()} |
          #{algorithm := sign_algo(),
            engine := crypto:engine_ref(),
            key_id := crypto:key_id(),
            password => crypto:password()} |
          #{algorithm := sign_algo(),
            sign_fun := fun(),
            sign_opts => list(),
            encrypt_fun => fun(),
            encrypt_opts => list()}.

The user's private key ๐Ÿ”‘

You've got options, bestie โ€” the key can be provided either directly as a DER-encoded entity, indirectly using a crypto engine/provider (with key reference information), or as an Erlang fun (with possible custom options). Those last two can be used for customized signing with hardware security modules (HSM) or trusted platform modules (TPM) ๐Ÿ‘‘

  • DER encoded key will need to specify the ASN-1 type used to create the encoding.
  • An engine/provider needs to specify specific information to support this concept and can optionally be password protected; see also crypto:engine_load/3 and Crypto User's Guide.
  • fun option should include a fun that mimics public_key:sign/4 and possibly public_key:private_encrypt/4 if legacy versions TLS-1.0 and TLS-1.1 must be supported.

keylog_info()

keylog_info() ::
          #{items => [keylog_item()], client_random => binary()}.

keylog_item()

keylog_item() :: unicode:chardata().

legacy_cipher()

legacy_cipher() :: '3des_ede_cbc' | des_cbc | rc4_128.

Cipher algorithms that are no longer supported by default for security reasons ๐ŸŒธ They're the y2k of ciphers, we love them in a museum but not in prod.


legacy_hash()

legacy_hash() :: sha224 | sha | md5.

Hash algorithms that are no longer supported by default for security reasons ๐Ÿšซ


legacy_kex()

legacy_kex() ::
          rsa | rsa_psk | dhe_rsa | dhe_dss | srp_rsa | srp_dss |
          dhe_psk | psk | ecdh_anon | dh_anon | srp_anon.

Backwards compatibility and legacy interoperability โ€” not recommended ๐Ÿ™ˆ


legacy_named_curve()

legacy_named_curve() ::
          sect571r1 | sect571k1 | sect409k1 | sect409r1 | sect283k1 |
          sect283r1 | secp256k1 | sect239k1 | sect233k1 | sect233r1 |
          secp224k1 | secp224r1 | sect193r1 | sect193r2 | secp192k1 |
          secp192r1 | sect163k1 | sect163r1 | sect163r2 | secp160k1 |
          secp160r1 | secp160r2.

Key exchange configuration prior to TLS-1.3. These curves have been deprecated by RFC 8422 ๐Ÿ˜ญ rip.


legacy_sign_algo()

legacy_sign_algo() :: dsa.

Signature algorithms that are no longer supported by default for security reasons ๐Ÿ’€


legacy_sign_scheme()

legacy_sign_scheme() ::
          rsa_pkcs1_sha512 | rsa_pkcs1_sha384 | rsa_pkcs1_sha256 |
          ecdsa_sha1 | rsa_pkcs1_sha1.

Fyi this is only used for certificate signatures if TLS-1.2 is negotiated โ€” meaning the peer only supports TLS-1.2, but we also support TLS-1.3 ๐Ÿซถ


named_curve()

named_curve() ::
          x25519 | x448 | secp521r1 | brainpoolP512r1 |
          brainpoolP384r1 | secp384r1 | brainpoolP256r1 | secp256r1 |
          legacy_named_curve().

Key exchange configuration prior to TLS-1.3 โœจ


old_cipher_suite()

old_cipher_suite() ::
          {kex_algo(), cipher(), hash()} |
          {kex_algo(), cipher(), hash() | aead, hash()}.

For backwards compatibility only; do not use. Like, seriously, don't ๐Ÿ™…โ€โ™€๏ธ


post_quantum_schemes()

post_quantum_schemes() :: crypto:mldsa() | crypto:slh_dsa().

Supported in TLS-1.3 only ๐Ÿ” ML-DSA since 28.1, SLH-DSA since 28.3. Future-proof queen behavior ๐Ÿ‘‘


prf_random()

prf_random() :: client_random | server_random.

Deprecated: the type ssl:prf_random() is deprecated; Only used in deprecated function prf/5 and will no longer be needed. It's giving "we don't talk about her anymore" ๐Ÿ’…


protocol_extensions()

protocol_extensions() ::
          #{renegotiation_info => binary(),
            signature_algs => signature_algs(),
            alpn => binary(),
            srp => binary(),
            next_protocol => binary(),
            max_frag_enum => 1..4,
            ec_point_formats => [0..2],
            elliptic_curves => [public_key:oid()],
            sni => inet:hostname()}.

Client hello extensions ๐ŸŒˆ

protocol_version()

protocol_version() :: tls_version() | dtls_version().

Which protocol version we're talking about, bestie โ€” TLS or DTLS. That's the whole tea. ๐Ÿซ–


reason()

reason() :: term().

The error reason, for debug purposes. And listen, listen: not to be matched. Do not pattern-match on this one. It's for humans reading logs, not for your case clauses. ๐Ÿ™ˆ


rsassa_pss_scheme()

rsassa_pss_scheme() ::
          rsa_pss_rsae_sha512 | rsa_pss_rsae_sha384 |
          rsa_pss_rsae_sha256 | rsa_pss_pss_sha512 |
          rsa_pss_pss_sha384 | rsa_pss_pss_sha256.

Supported in TLS-1.3 and TLS-1.2. Yeah those six are the whole roster. ๐Ÿ’…


security_info()

security_info() ::
          [{client_random, binary()} |
           {server_random, binary()} |
           {master_secret, binary()} |
           {keylog, [keylog_item()]}].

TLS connection info you can hand to NSS key logging ๐Ÿ”‘ โ€” yes bestie, the "save the secrets now, decrypt the traffic later in Wireshark" situation. Iconic behavior honestly.


server_option()

server_option() ::
          server_option_cert() |
          common_option_cert() |
          {honor_cipher_order, HonorServerCipherOrder :: boolean()} |
          {alpn_preferred_protocols, AppProtocols :: [binary()]} |
          {sni_hosts,
           SNIHosts ::
               [{inet:hostname(), [server_option() | common_option()]}]} |
          {sni_fun,
           SNIFun ::
               fun((string()) ->
                       [server_option() | common_option()] |
                       unrecognized | undefined)} |
          server_option_pre_tls13() |
          common_option_pre_tls13() |
          server_option_tls13() |
          common_option_tls13() |
          common_option_dtls() |
          server_option_legacy() |
          common_option_legacy().

Options that are specific to the server side, or that act differently depending on whether you're the client or the server. Same flag, different personality, iykyk. โœจ

  • {alpn_preferred_protocols, AppProtocols} โ€” Application Layer Protocol Negotiation

Says the server is gonna try to do Application-Layer Protocol Negotiation (ALPN). ๐ŸŒˆ

The list is in order of preference โ€” the protocol that gets negotiated is the first one in the list that also matches something the client advertised. If literally nothing matches, the server fails the connection with a no_application_protocol alert. ๐Ÿ’€

You can grab the negotiated protocol with the negotiated_protocol/1 function.

  • {honor_cipher_order, HonorServerCipherOrder} โ€” Trade-off option that alters protocol defined behavior

If true, use the server's preference for cipher suite selection. If false (the default), use the client's preference. Pick your fighter. ๐ŸฅŠ

  • {sni_fun, SNIFun}

If the server receives an SNI (Server Name Indication) from the client, the fun you gave as SNIFun gets called to fetch server_option() for the indicated server. Those returned options override any server options you specified earlier.

The sni_fun can say "idk her" by returning unrecognized โ€” and in that case the connection gets closed with an unrecognized_name alert. If your sni_fun returns undefined instead, the connection is attempted with the default options supplied to listen/2 or handshake/2,3.

Note ๐Ÿ“Œ The options sni_fun and sni_hosts are mutually exclusive. You cannot serve both looks at the same time.
  • {sni_hosts, SNIHosts}

If the server receives an SNI from the client that matches a host listed in sni_hosts, the specific options for that host override previously specified options. If no match is found, it behaves exactly like an sni_fun that returns undefined.

Note ๐Ÿ“Œ Yep, saying it again because it matters: sni_fun and sni_hosts are mutually exclusive.

server_option_cert()

server_option_cert() ::
          {cacerts,
           CACerts ::
               [public_key:der_encoded()] |
               [public_key:combined_cert()]} |
          {cacertfile, CACertFile :: file:filename()} |
          {verify, Verify :: verify_none | verify_peer} |
          {certificate_authorities, ServerCertAuth :: boolean()}.

Certificate-adjacent options for a server. The certificate glow-up section. ๐ŸŽ€

  • {cacerts, CACerts} โ€” Trusted certificates

The DER-encoded trusted certificates. If you supply this option, it overrides the cacertfile option. ๐Ÿ’…

  • {cacertfile, CACertFile :: file:filename()} โ€” the file-path version of the same energy.
  • {verify, Verify} โ€” Verify certificates

Client certificates are an optional part of the TLS protocol. A server only performs X.509 certificate path validation in verify_peer mode. By default the server sits in verify_none mode, which means it will not send a certificate request to the client. When you use verify_peer, you might also want to specify the options fail_if_no_peer_cert and certificate_authorities.

  • {certificate_authorities, ServerCertAuth} โ€” Inter-operate hint option

Decides whether a TLS-1.3 server should include the authorities extension in its certificate request message โ€” the one sent when the verify option is set to verify_peer. Defaults to true. โœจ

If you set it to false for older TLS versions, the corresponding certificate authorities definition in its certificate request will be set to the empty list instead of including the appropriate certificate authorities. This has the same effect as just excluding the TLS-1.3 extension altogether.

One reason you'd want to exclude the extension: the server wants to talk to clients that are incapable of sending complete certificate chains that adhere to the extension, but the server still has the capability to recreate a chain that it can verify. Clever girl behavior. ๐Ÿง 


server_option_legacy()

server_option_legacy() ::
          {fail_if_no_peer_cert, FailNoPeerCert :: boolean()} |
          {next_protocols_advertised, NextAppProtocols :: [binary()]}.

Legacy server options. Vintage, but still here. ๐Ÿ•ฐ๏ธ

  • {next_protocols_advertised, NextAppProtocols}

Heads up: ALPN (Application-Layer Protocol Negotiation) deprecates NPN (Next Protocol Negotiation), which is the thing described right here.

It's the list of protocols to send to the client if the client indicates it supports the Next Protocol extension. Note that the client can select a protocol that is not on this list. The list of protocols must not contain an empty binary. If the server negotiates a Next Protocol, you can access it with the negotiated_protocol/1 method.

  • {fail_if_no_peer_cert, FailNoPeerCert} โ€” Legacy trade-off option

Used together with {verify, verify_peer} by a TLS/DTLS server. If set to true, the server fails if the client has no certificate to send, that is, it sends an empty certificate. If set to false, it fails only if the client sends an invalid certificate (an empty certificate counts as valid). Defaults to true โ€” and heads up, the default value was changed in OTP 26.0. ๐Ÿšจ


server_option_pre_tls13()

server_option_pre_tls13() ::
          {client_renegotiation, ClientRengotiation :: boolean()} |
          {reuse_sessions, ReuseSessions :: boolean()} |
          {reuse_session, ReuseSession :: fun()} |
          {honor_ecc_order, HonorServerECCOrder :: boolean()} |
          {dh, DHDer :: public_key:der_encoded()} |
          {dhfile, DhFile :: file:filename()} |
          {psk_identity, PSKHint :: string()}.

Options that are only relevant to TLS versions before TLS-1.3. Throwbacks only. ๐Ÿ“ผ

  • {client_renegotiation, ClientRengotiation} โ€” DoS attack avoidance option

In protocols that support client-initiated renegotiation, the resource cost of that operation is higher for the server than for the client. Which means it can act as a vector for denial-of-service (DoS) attacks. ๐Ÿ˜ญ The SSL application already takes measures to counteract such attempts, but you can completely disable client-initiated renegotiation by setting this option to false. The default value is true.

Careful bestie: note that disabling renegotiation can result in long-lived connections becoming unusable, because of limits on the number of messages the underlying cipher suite can encipher. Not a fun surprise.
  • {reuse_sessions, ReuseSessions} โ€” Enable session reuse

The boolean value true specifies that the server will agree to reuse sessions. Setting it to false results in an empty session table, meaning no sessions will be reused. Nothing. Zero. Nada. ๐Ÿ™ˆ

  • {reuse_session, ReuseSession} โ€” Local server reuse policy

Lets the TLS/DTLS server have a local policy for deciding whether a session is to be reused. Only meaningful if reuse_sessions is set to true.

ReuseSession should be a fun:

fun(SuggestedSessionId, PeerCert, Compression, CipherSuite)

SuggestedSessionId is a binary(), PeerCert is a DER-encoded certificate, Compression is an enumeration integer, and CipherSuite is of type erl_cipher_suite().

  • {psk_identity, PSKHint} โ€” Inter-operate hint option

Specifies the server identity hint that the server presents to the client. ๐Ÿซถ

  • {honor_ecc_order, HonorServerECCOrder} โ€” Trade-off option that alters protocol defined behavior

If true, use the server's preference for ECC curve selection. If false (the default), use the client's preference.

  • {dh, DHder} โ€” Affects DH key exchange cipher suites

The DER-encoded Diffie-Hellman parameters. If specified, it overrides the dhfile option.

  • {dh_file, DHfile} โ€” Affects DH key exchange cipher suites

Path to a file containing PEM-encoded Diffie Hellman parameters to be used by the server if a cipher suite using Diffie Hellman key exchange gets negotiated. If not specified, default parameters are used.

yes, the type up top says dhfile and this description says dh_file โ€” that's literally how it's written, so we're copying it faithful, no fixing on our watch ๐Ÿ’…

server_option_tls13()

server_option_tls13() ::
          {session_tickets,
           SessionTickets ::
               disabled | stateful | stateless | stateful_with_cert |
               stateless_with_cert} |
          {stateless_tickets_seed, TicketSeed :: binary()} |
          {anti_replay,
           '10k' | '100k' |
           {BloomFilterWindowSize :: pos_integer(),
            BloomFilterHashFunctions :: pos_integer(),
            BloomFilterBits :: pos_integer()}} |
          {cookie, Cookie :: boolean()} |
          {early_data, EarlyData :: enabled | disabled}.

Options that are only relevant for TLS-1.3. The modern era. โœจ

  • {session_tickets, SessionTickets}

Configures the session ticket functionality. Allowed values for SessionTickets are:

  • disabled
  • <hotpink>stateful</hotpink>
  • <hotpink>stateless</hotpink>
  • <hotpink>stateful_with_cert</hotpink>
  • <hotpink>stateless_with_cert</hotpink>

okay so as long as SessionTickets isn't set to disabled, session resumption with pre-shared keys is on, and the server will send stateful or stateless session tickets to the client after successful connections. ๐Ÿ’–

Note โœจ In pre-shared key session ticket resumption there is no certificate exchange involved. So ssl:peercert/1 will not return the peer certificate โ€” because the cert is only ever communicated during the initial handshake. If you wanna associate the client certificate from the original handshake with the tickets the server issues, use the server options stateful_with_cert or stateless_with_cert. ๐Ÿซถ

A stateful session ticket is literally just a database reference to internal state information. A stateless session ticket is a self-encrypted binary that holds both cryptographic keying material and state data. two different vibes, both valid. ๐Ÿ’…

Warning ๐Ÿšจ When SessionTickets is set to stateful_with_cert, the client certificate gets stored along with the internal state information โ€” which means increased memory consumption. Conversely, when it's set to stateless_with_cert, the client certificate is encoded into the self-encrypted binary that gets sent to the client, which means an increase in payload size. pick your poison bestie ๐Ÿ˜ญ

See also SSL User's Guide, Session Tickets and Session Resumption in TLS 1.3. ๐Ÿ“š


  • {stateless_tickets_seed, TicketSeed} โ€” the option for stateless tickets ๐ŸŒธ Configures the seed used for the encryption of stateless session tickets. Allowed values are any randomly generated binary/0. If this option isn't configured, an encryption seed will be randomly generated for you. โœจ
WARNING: Reusing the ticket encryption seed between multiple server instances enables stateless session tickets to work across multiple server instances, but it breaks anti-replay protection across instances. Inaccurate time synchronization between server instances can also affect session ticket freshness checks, potentially causing false negatives as well as false positives. so likeโ€ฆ be careful, fr fr. ๐Ÿ’€
  • {anti_replay, AntiReplay} โ€” the option for stateless tickets ๐Ÿ›ก๏ธ Configures the server's built-in anti replay feature, which is based on Bloom filters. Allowed values for AntiReplay are the pre-defined '10k', '100k', or a custom 3-tuple that defines the properties of the bloom filters: {WindowSize, HashFunctions, Bits}. WindowSize is the number of seconds after the current Bloom filter is rotated, and it's also the window size used for freshness checks of ClientHello. HashFunctions is the number hash functions and Bits is the number of bits in the bit vector. '10k' and '100k' are simple defaults with the following properties:
    • '10k': Bloom filters can hold 10000 elements with 3% probability of false positives. WindowSize: 10, HashFunctions: 5, Bits: 72985 (8.91 KiB).
    • '100k': Bloom filters can hold 100000 elements with 3% probability of false positives. WindowSize: 10, HashFunctions: 5, Bits: 729845 (89.09 KiB). See also SSL User's Guide, Anti-Replay Protection in TLS 1.3. ๐Ÿ’œ
  • {cookie, Cookie} โ€” the option for HelloRetryRequest behavior ๐Ÿช If Cookie is true, which is the default, the server sends a cookie extension in its HelloRetryRequest messages. The cookie extension has two main purposes. It allows the server to force the client to demonstrate reachability at their apparent network address โ€” thus providing a measure of DoS protection. This is primarily useful for non-connection-oriented transports. It also allows offloading the server's state to the client. The cookie extension is enabled by default because it is a mandatory extension in RFC8446. โญ
  • {early_data, EarlyData} โ€” the option for accepting or rejecting Early Data โฐ Configures if the server accepts (enabled) or rejects (disabled) early data sent by a client. The default value is disabled.
WARNING: 0-RTT data is inherently replay-vulnerable by TLS 1.3 design. The mitigation is application-level idempotency or server-side anti-replay. The server side mechanisms for anti-replay are stateful tickets or stateless tickets with a configured Bloom filter. no shortcuts here, bestie ๐Ÿ˜ค

session_id() :: binary().

Identifies a TLS session prior to TLS-1.3. ๐Ÿ•ฐ๏ธ

session_ticket()

(yeah that's the whole entry, that's how it's listed ๐Ÿ‘‘)

sha2() :: sha512 | sha384 | sha256.

SHA2 hash algorithms. hash girlies stay winning โœจ

sign_algo() :: eddsa | ecdsa | rsa | legacy_sign_algo().

Signature algorithms. ๐Ÿ’ซ

sign_scheme() ::
      eddsa_ed25519 | eddsa_ed448 | ecdsa_secp521r1_sha512 |
      ecdsa_secp384r1_sha384 | ecdsa_secp256r1_sha256 |
      ecdsa_brainpoolP512r1tls13_sha512 |
      ecdsa_brainpoolP384r1tls13_sha384 |
      ecdsa_brainpoolP256r1tls13_sha256 |
      post_quantum_schemes() |
      rsassa_pss_scheme() |
      legacy_sign_scheme().

Signature schemes, defined by TLS-1.3, and replacing signature algorithms from TLS-1.2. ๐Ÿฆ‹

Explicitly list acceptable signature schemes in the preferred order.

Overrides the algorithms supplied in signature_algs option for certificates. In addition to the signature_algorithms extension from TLS 1.2, TLS 1.3 (RFC 5246 Section 4.2.3) adds the signature_algorithms_cert extension which enables having special requirements on the signatures used in the certificates that differs from the requirements on digital signatures as a whole. If this is not required this extension is not needed.

The client will send a signature_algorithms_cert extension (in the client hello message), if TLS version 1.2 (back-ported to TLS 1.2 in 24.1) or later is used, and the signature_algs_cert option is explicitly specified. By default, only the signature_algs extension is sent with the exception of when signature_algs option is not explicitly specified, in which case it will append the rsa_pkcs1_sha1 algorithm to the default value of signature_algs and use it as value for signature_algs_cert to allow certificates to have this signature but still disallow sha1 use in the TLS protocol, since 27.0.1 and 26.2.5.2.

NOTE: Note that supported signature schemes for TLS-1.2 are
legacy_sign_scheme()
and rsassa_pss_scheme().
signature_algs() :: [{hash(), sign_algo()} | sign_scheme()].

Explicitly list acceptable signature algorithms for certificates and handshake messages in the preferred order.

The client will send its list as the client hello signature_algorithm extension introduced in TLS-1.2; see Section 7.4.1.4.1 in RFC 5246. Before TLS-1.2, these algorithms where implicitly chosen and partly derived from the cipher suite.

In TLS-1.2 a somewhat more explicit negotiation is made possible using a list of {HashAlgo, SignAlgo} tuples.

In TLS-1.3, these algorithm pairs are replaced by signature schemes that are completely decoupled from the cipher suite.

Signature algorithms used for certificates can be overridden by the signature schemes supplied by the signature_algs_cert option.

The TLS-1.2 default is Default_TLS_12_Alg_Pairs interleaved with rsa_pss_schemes since ssl-11.0 (Erlang/OTP 25). pss_pss is preferred over pss_rsae, which in turn is preferred over rsa.

The list for Default_TLS_12_Alg_Pairs is defined as follows:

[
{sha512, ecdsa},
{sha512, rsa},
{sha384, ecdsa},
{sha384, rsa},
{sha256, ecdsa},
{sha256, rsa}
]
Change ๐Ÿ’… - Support for {md5, rsa} was removed from the TLS-1.2 default in ssl-8.0 (Erlang/OTP 22). - Support for {sha, _} (SHA1) and {sha224, _} was removed from the TLS-1.2 default in ssl-11.0 (Erlang/OTP 26).

The list for rsa_pss_schemes is defined as follows:

[rsa_pss_pss_sha512,
rsa_pss_pss_sha384,
rsa_pss_pss_sha256,
rsa_pss_rsae_sha512,
rsa_pss_rsae_sha384,
rsa_pss_rsae_sha256]

The list of TLS_13_Legacy_Schemes is defined as follows:

[
%% Legacy algorithms only applicable to certificate signatures
rsa_pkcs1_sha512, %% Corresponds to {sha512, rsa}
rsa_pkcs1_sha384, %% Corresponds to {sha384, rsa}
rsa_pkcs1_sha256, %% Corresponds to {sha256, rsa}
]

The list of Default_TLS_13_Schemes is defined as follows:

[
%% EDDSA
eddsa_ed25519,
eddsa_ed448

%% ECDSA
ecdsa_secp521r1_sha512,
ecdsa_secp384r1_sha384,
ecdsa_secp256r1_sha256] ++

%% RSASSA-PSS
rsa_pss_schemes()

CHANGE: EDDSA was made highest priority in ssl-10.8 (Erlang/OTP 25). ๐Ÿ‘‘

The TLS-1.3 default is Default_TLS_13_Schemes.

If both TLS-1.3 and TLS-1.2 are supported the default is:

Default_TLS_13_Schemes ++ TLS_13_Legacy_Schemes ++
Default_TLS_12_Alg_Pairs %% not represented in TLS_13_Legacy_Schemes

to ensure that appropriate algorithms can be chosen for the negotiated version. ๐Ÿ˜Œ

Note ๐ŸŽ€ TLS-1.2 algorithms will not be negotiated for TLS-1.3, but the TLS-1.3 RSASSA-PSS (rsassa_pss_scheme()) signature schemes can be negotiated also for TLS-1.2 from Erlang/OTP 24.1 (fully working from Erlang/OTP 24.1.3). However, if both TLS 1.3 and TLS 1.2 are supported using defaults, and TLS 1.3 is negotiated, the corresponding TLS 1.2 algorithms for TLS 1.3 legacy signature schemes will be treated as legacy schemes and applied only to certificate signatures.
socket() :: gen_tcp:socket() | socket:socket().
  • socket_option() :: gen_tcp:connect_option() | gen_tcp:listen_option() | gen_udp:option()

Literally just the options you hand to the transport socket, bestie. ๐Ÿ’…

The default socket options are [{mode, list}, {packet, 0}, {header, 0}, {active, true}].

For the valid ones, go look at inet, gen_tcp, and gen_udp in Kernel. Heads up though: stream-oriented options like packet are only relevant for TLS, not for DTLS. So don't come for DTLS with your stream ideas, it will not slay. ๐Ÿฆ‹

  • srp_param_type() :: srp_8192 | srp_6144 | srp_4096 | srp_3072 | srp_2048

Your SRP cipher suite configuration, from before TLS-1.3 existed. Vintage behavior, iykyk. โœจ

  • sslsocket() :: any()

An opaque reference to the TLS/DTLS connection. Very "mystery main character", very mysterious. ๐ŸŽ€

But wait โ€” plot twist โ€” despite being opaque, matching sslsocket() instances is allowed. The way that's a thing you can just do. ๐Ÿ˜ญ

  • tls_alert() ::
close_notify | unexpected_message | bad_record_mac |
record_overflow | handshake_failure | bad_certificate |
unsupported_certificate | certificate_revoked |
certificate_expired | certificate_unknown |
illegal_parameter | unknown_ca | access_denied |
decode_error | decrypt_error | export_restriction |
protocol_version | insufficient_security | internal_error |
inappropriate_fallback | user_canceled | no_renegotiation |
unsupported_extension | certificate_unobtainable |
unrecognized_name | bad_certificate_status_response |
bad_certificate_hash_value | unknown_psk_identity |
no_application_protocol.

All the reasons the TLS Alert Protocol has to be upset with you. The full mood board. ๐Ÿ’€

  • tls_client_option() :: client_option() | common_option() | socket_option() | transport_option()

An option you can supply to a TLS client. That's it, that's the whole vibe check. ๐Ÿซถ

  • tls_legacy_version() :: tlsv1 | 'tlsv1.1'

A TLS protocol version that is no longer supported by default โ€” for security reasons, bestie, they're retired โ€” and it's scheduled for removal in OTP 30. So enjoy it while it lasts, but don't get attached. ๐ŸŒธ

  • tls_option() :: tls_client_option() | tls_server_option()

An option related to the TLS/DTLS protocol. Generic queen behavior. ๐Ÿ‘‘

  • tls_server_option() :: server_option() | common_option() | socket_option() | transport_option()

An option that can be supplied to a TLS server. The server side's little menu. โœจ

  • tls_version() :: 'tlsv1.2' | 'tlsv1.3' | tls_legacy_version()

TLS protocol version. The current lineup plus the legacy guests. ๐ŸŒˆ

  • transport_option() ::
{cb_info,
 {CallbackModule :: atom(),
  DataTag :: atom(),
  ClosedTag :: atom(),
  ErrTag :: atom()}} |
{cb_info,
 {CallbackModule :: atom(),
  DataTag :: atom(),
  ClosedTag :: atom(),
  ErrTag :: atom(),
  PassiveTag :: atom()}}.

Transport option that defines a callback module plus the message tags you use to handle the underlying transport socket. ๐Ÿ”ฅ

You can use it to customize the transport layer. Those tag values should be the values your underlying transport actually uses in its active mode messages.

Defaults to {gen_tcp, tcp, tcp_closed, tcp_error, tcp_passive} for TLS.

Note ๐ŸŽ€ For backward compatibility, a tuple of size four gets converted into a tuple of size five, where PassiveTag is the DataTag element with _passive appended to it. Cute little glow-up, no cap.

For TLS, the callback module has to implement a reliable transport protocol, behave as gen_tcp, and have functions corresponding to inet:setopts/2, inet:getopts/2, inet:peername/1, inet:sockname/1, and inet:port/1. That's the whole checklist, bestie. The callback gen_tcp is treated specially and calls inet directly. For DTLS, this feature is considered experimental โ€” proceed with caution, it's giving beta energy. ๐Ÿ™ˆ


โœจ FUNCTIONS โœจ

๐ŸŒธ append_cipher_suites(Deferred, Suites) -> ciphers()

append_cipher_suites(Deferred, Suites) -> ciphers()
                                    when
                                        Deferred ::
                                            ciphers() | cipher_filters(),
                                        Suites :: ciphers().

Makes the Deferred suites become the least preferred suites. Like, they still get invited to the party, they just arrive last. ๐Ÿฅฒ

The Deferred suites get put at the end of the cipher suite list Suites, after removing them from Suites if they were in there. Deferred can be a list of cipher suites, or a list of filters โ€” in which case the filters are used on Suites to extract the deferred cipher list. Two ways to flex, same result. ๐Ÿ’…


๐Ÿฆ‹ cipher_suites(Description, Version) -> ciphers()

cipher_suites(Description, Version) -> ciphers()
                        when
                            Description ::
                                default | all | exclusive | anonymous |
                                exclusive_anonymous,
                            Version :: protocol_version().

Lists all the available cipher suites corresponding to Description. Straightforward, iconic. โœจ

The exclusive and exclusive_anonymous options will exclusively list cipher suites first supported in Version, whereas the other options are inclusive from the lowest possible version all the way up to Version. The all option includes all suites except anonymous suites. No anonymous suites are supported by default. Periodt.

NOTE: ๐Ÿ“ข TLS-1.3 has no overlapping cipher suites with previous TLS versions โ€” meaning the result of cipher_suites(all, 'tlsv1.3') contains a separate set of suites that can be used with TLS-1.3, and another set that can be used if a lower version is negotiated. They do not mix, bestie, they're different friend groups. The so-called PSK and SRP suites (prior to TLS-1.3) need extra configuration to work; namely the option user_lookup_function. So don't just assume they'll show up and slay on their own. No anonymous suites are supported by TLS-1.3. Also note that the cipher suites returned by this function are the cipher suites that the OTP SSL application can support, provided that they are supported by the crypto library linked with the OTP Crypto application. Use ssl:filter_cipher_suites(Suites, []) to filter the list for the current crypto library. And note that cipher suites may be filtered out because they are too old or too new depending on the crypto library. Aging is real. ๐Ÿ˜ญ

๐ŸŒˆ cipher_suites(Description, Version, StringType) -> [string()]

cipher_suites(Description, Version, StringType) -> [string()]
                        when
                            Description ::
                                default | all | exclusive | anonymous,
                            Version :: protocol_version(),
                            StringType :: rfc | openssl.

Equivalent to cipher_suites/2, but it lists RFC or OpenSSL string names instead of erl_cipher_suite(). Same energy, different outfit. ๐Ÿ’–


๐ŸŽ€ clear_pem_cache() -> ok

clear_pem_cache() -> ok.

Clears the PEM cache. The big reset. ๐Ÿงนโœจ

PEM files, used by SSL API-functions, are cached for performance reasons. The cache is automatically checked at regular intervals to determine whether any cache entries should be invalidated โ€” so it does self-care on its own, but sometimes you just gotta step in.

This function gives you a way to unconditionally clear the entire cache, which forces a reload of previously cached PEM files. No questions asked, everything goes. ๐Ÿ’…


๐Ÿ‘‘ close(SslSocket) -> ok | {error, Reason}

close(SslSocket) -> ok | {error, Reason}
                when SslSocket :: sslsocket(), Reason :: any().

Closes a TLS/DTLS connection. Bye bestie, it's been real. ๐Ÿซถ


๐Ÿ’œ close(SslSocket, How) -> ok | {ok, port()} | {ok, port(), Data} | {error, Reason}

close(SslSocket, How) ->
                ok | {ok, port()} | {ok, port(), Data} | {error, Reason}
                when
                    SslSocket :: sslsocket(),
                    How ::
                        timeout() | {NewController :: pid(), timeout()},
                    Data :: binary(),
                    Reason :: any().

Closes or downgrades a TLS connection. Two paths, one function, very versatile of it. ๐ŸŒธ

In the downgrade case, the transport connection gets handed over to the NewController process after receiving the TLS close alert from the peer. The returned transport socket will have the following options set: [{active, false}, {packet, 0}, {mode, binary}]. Fresh new settings, fresh new start.

In the case of a downgrade, the close function might return some binary data that you should treat as the first bytes received on the downgraded connection. So don't just yeet it, bestie, that's real data. ๐Ÿ˜ญ


๐Ÿ”ฅ connect(TCPSocketOrHost, TLSOptionsOrPort, TimeoutOrTLSOptions)

connect(TCPSocketOrHost, TLSOptionsOrPort, TimeoutOrTLSOptions) ->
                    {ok, sslsocket()} |
                    {ok, sslsocket(), Ext :: protocol_extensions()} |
                    {error, Reason}
                    when
                        TCPSocketOrHost :: socket() | host(),
                        TLSOptionsOrPort ::
                            [tls_client_option()] | inet:port_number(),
                        TimeoutOrTLSOptions ::
                            [tls_client_option()] | timeout(),
                        Reason ::
                            closed | timeout |
                            {options, any()} |
                            error_alert() |
                            reason().

Opens a TLS/DTLS connection. ๐ŸŒˆ

This one function has two whole personalities:

connect(TCPSocket, TLSOptions, Timeout).

Upgrades a gen_tcp (or equivalent) connected socket to a TLS socket by performing the client-side TLS handshake. Glow-up arc, activated. โœจ

connect(Host, Port, TLSOptions).

Opens a TLS/DTLS connection to Host, Port. This call is equivalent to:

connect(Host, Port, TLSOptions, infinity).

See? Same thing, just with infinity patience. ๐Ÿ’…


โญ connect(Host, Port, TLSOptions, Timeout)

connect(Host, Port, TLSOptions, Timeout) ->
                    {ok, sslsocket()} |
                    {ok, sslsocket(), Ext :: protocol_extensions()} |
                    {error, Reason}
                    when
                        Host :: host(),
                        Port :: inet:port_number(),
                        TLSOptions :: [tls_client_option()],
                        Timeout :: timeout(),
                        Reason ::
                            closed | timeout |
                            {options, any()} |
                            error_alert() |
                            reason().

Opens a TLS/DTLS connection to Host, Port. That's the whole thing. Iconic, no notes. ๐ŸŽ€

The verify option, when you set it to verify_peer, makes us run the public_key:pkix_verify_hostname/2 check on top of the normal X.509-path validation checks. If that check flops, the error {bad_cert, hostname_check_failed} gets propagated to the path validation fun, where you can do all your customized checks with the full power of the public_key:pkix_verify_hostname/3 API. Now if the server_name_indication option is handed to us, its value (the DNS name, bestie) gets used as the ReferenceID for public_key:pkix_verify_hostname/2. If there's no server_name_indication option at all, then the Host argument gets used as the Server Name Indication extension. And that same Host argument also gets used for the public_key:pkix_verify_hostname/2 check. If Host happens to be an inet:ip_address(), the ReferenceID for the check will be {ip, Host}; otherwise dns_id is assumed, with a fallback to ip if that fails. ๐Ÿ’…

NOTE: per good practices, certificates should not use IP addresses as "server names" โ€” especially outside a closed network. Not the vibe, ok?

If the {handshake, hello} option is used, the handshake gets paused right after receiving the server hello message, and the success response is {ok, SslSocket, Ext} instead of just {ok, SslSocket}. After that you continue or cancel the handshake by calling handshake_continue/3 or handshake_cancel/1. ๐Ÿฆ‹

And if the active option is set to once, true, or an integer value, the process owning the SSL socket will receive messages of type active_msgs().


connection_information(SslSocket)

connection_information(SslSocket) ->
                                {ok, Result} | {error, reason()}
                                when
                                    SslSocket :: sslsocket(),
                                    Result :: connection_info().

Returns the most relevant info about the connection. โœจ

Some items that are undefined get filtered out. And no values that affect the security of the connection will be returned โ€” we're keeping that locked down. ๐Ÿ”’

NOTE: the legacy cipher_suite item was removed in OTP 23. Back in the day it returned the cipher suite in its (undocumented) legacy format. It is replaced by selected_cipher_suite.

connection_information(SslSocket, Items)

connection_information(SslSocket, Items) ->
                                {ok, Result} | {error, reason()}
                                when
                                    SslSocket :: sslsocket(),
                                    Items :: connection_info_keys(),
                                    Result :: connection_info().

Returns the requested info items about the connection, but only if they're defined. ๐Ÿ’–

Heads up that the values for client_random, server_random, master_secret, and keylog affect the security of connection.

And in order to retrieve keylog information from a TLS connection, the keep_secrets option must be configured in advance. Set it up early, bestie.

NOTE: if only undefined options are requested, the resulting list can be empty. Yes, empty. That's not a bug, that's just how it is. ๐Ÿ™ˆ

controlling_process(SslSocket, NewController)

controlling_process(SslSocket, NewController) ->
                                ok | {error, Reason}
                                when
                                    SslSocket :: sslsocket(),
                                    NewController :: pid(),
                                    Reason :: any().

Assigns a new controlling process to the SSL socket.

Iconic behavior: a controlling process is the owner of an SSL socket and receives all messages from the socket. So you're handing over the keys to the whole vibe. ๐Ÿ‘‘

eccs()

eccs() -> NamedCurves when NamedCurves :: [named_curve()].

Returns a list of all supported elliptic curves, including legacy curves, for all TLS/DTLS versions prior to TLS-1.3.

eccs(Version)

eccs(Version) -> NamedCurves
             when
                 Version ::
                     'tlsv1.2' | 'tlsv1.1' | tlsv1 | 'dtlsv1.2' |
                     dtlsv1,
                 NamedCurves :: [named_curve()].

Returns the elliptic curves supported by default for Version.

This is a subset of what eccs/0 returns. The way that it's just a lil slice of the full menu. ๐Ÿ“

export_key_materials(SslSocket, Labels, Contexts, WantedLengths, ConsumeSecret)

export_key_materials(SslSocket, Labels, Contexts, WantedLengths,
                          ConsumeSecret) ->
                             {ok, ExportKeyMaterials} |
                             {error,
                              exporter_master_secret_already_consumed |
                              bad_input}
                             when
                                 SslSocket :: sslsocket(),
                                 Labels :: [binary()],
                                 Contexts :: [binary() | no_context],
                                 WantedLengths :: [non_neg_integer()],
                                 ConsumeSecret :: boolean(),
                                 ExportKeyMaterials :: [binary()].

Uses a Pseudo-Random Function (PRF prior to TLS-1.3) or a Key Derivation Function (HKDF in TLS-1.3) for a TLS connection to generate and export keying materials. Cryptographic craft time. ๐Ÿ”ฅ

In TLS-1.3, using no_context is equivalent to specifying an empty context (an empty binary). Prior to TLS-1.3, no_context and an empty context will produce different results. Don't mix those up, fr fr.

The ConsumeSecret argument is relevant only in TLS-1.3 โ€” it causes the TLS-1.3 exporter_master_secret to be consumed, thereby making it unavailable and increasing security. Further attempts to call this function will fail. One and done, periodt.

filter_cipher_suites(Suites, Filters)

filter_cipher_suites(Suites, Filters) -> Ciphers
                             when
                                 Suites :: ciphers(),
                                 Filters :: cipher_filters(),
                                 Ciphers :: ciphers().

Removes cipher suites if any of the filter functions returns false for any part of the cipher suite.

If no filter function is supplied for some part, the default behavior treats it as a filter function that returns true. For examples, see Customizing cipher suites . Additionally, this function also filters the cipher suites to exclude cipher suites not supported by the crypto library used by the OTP Crypto application โ€” meaning that ssl:filter_cipher_suites(Suites, []) is equivalent to applying only the filters for crypto library support. ๐Ÿ’…

format_error(Error)

format_error(Error) -> ReasonStr
                     when
                         Error :: {error, reason()} | reason(),
                         ReasonStr :: string().

Presents the error returned by an SSL function as a printable string. Puts the error into words for you. ๐ŸŽ€

getopts(SslSocket, OptionNames)

getopts(SslSocket, OptionNames) ->
                {ok, [gen_tcp:option()]} | {error, reason()}
                when
                    SslSocket :: sslsocket(),
                    OptionNames :: [gen_tcp:option_name()].

Gets the values of the specified socket options.

getstat(SslSocket)

getstat(SslSocket) -> {ok, OptionValues} | {error, inet:posix()}
                when
                    SslSocket :: sslsocket(),
                    OptionValues :: [{inet:stat_option(), integer()}].

Get statistics for the underlying socket. Numbers go brrr. โญ

getstat(SslSocket, Options)

getstat(SslSocket, Options) ->
                {ok, OptionValues} | {error, inet:posix()}
                when
                    SslSocket :: sslsocket(),
                    Options :: [inet:stat_option()],
                    OptionValues :: [{inet:stat_option(), integer()}].

Get one or more statistic values for the underlying socket.

See inet:getstat/2 for further details.

groups()

groups() -> [group()].

Returns all supported groups in TLS 1.3.

Existed since OTP 22.0; documented as of OTP 27.0. She was underground for a while, and now she's public. ๐ŸŒธ

groups(Description)

groups(Description) -> [group()] when Description :: default.

Returns default supported groups in TLS 1.3.

Existed since OTP 22.0; documented as of OTP 27.0.

handshake(HsSocket, OptionsOrTimeout)

handshake(HsSocket, OptionsOrTimeout) ->
                  {ok, SslSocket} |
                  {ok, SslSocket, Ext} |
                  {error, Reason}
                  when
                      HsSocket :: sslsocket(),
                      OptionsOrTimeout :: timeout() |
[server_option()],
                      SslSocket :: sslsocket(),
                      Ext :: protocol_extensions(),
                      Reason :: closed | timeout | error_alert().

Performs the TLS/DTLS server-side handshake. ๐Ÿค

If the second argument is a timeout value:

handshake(HsSocket, Timeout).

this call is equivalent to:

handshake(HsSocket, [], Timeout).

Otherwise, if the second argument is a list of options:

handshake(HsSocket, Options).

this call is equivalent to:

handshake(HsSocket, Options, infinity).

handshake(Socket, Options, Timeout)

handshake(Socket, Options, Timeout) ->
                  {ok, SslSocket} |
                  {ok, SslSocket, Ext} |
                  {error, Reason}
                  when
                      Socket :: socket() | sslsocket(),
                      SslSocket :: sslsocket(),
                      Options :: [server_option() | common_option()],
                      Timeout :: timeout(),
                      Ext :: protocol_extensions(),
                      Reason ::
                          closed | timeout |
                          {options, any()} |
                          error_alert().

Performs the TLS/DTLS server-side handshake.

Returns a new TLS/DTLS socket if the handshake is successful. Slay. โœจ

If Socket is a ordinary socket(), it upgrades a gen_tcp or equivalent socket to an SSL socket by performing the TLS server-side handshake and returning a TLS socket.

Note: the ordinary Socket must be in passive mode ({active, false}) before calling this function and before the client tries to connect with TLS โ€” otherwise, the behavior of this function is undefined. ๐Ÿ˜ญ The best way to ensure this is to create the ordinary listen socket in passive mode.

If Socket is an sslsocket(), it provides extra TLS/DTLS options to those specified in listen/2 and then performs the TLS/DTLS handshake. Returns a new TLS/DTLS socket if the handshake is successful.

Warning: not setting the timeout makes the server more vulnerable to Denial of Service (DoS) attacks. Set your timeout, bestie. This is not the moment to be chill. ๐Ÿ’€

If option {handshake, hello} is specified the handshake is paused right after receiving the client hello message, and the success response is {ok, SslSocket, Ext} instead of just {ok, SslSocket}. After that you continue or cancel the handshake by calling handshake_continue/3 or handshake_cancel/1. โœจ

If option active is set to once, true, or an integer value, the process owning the sslsocket() will receive messages of type active_msgs(). ๐Ÿ’Œ (yes bestie, you get pinged, it's giving notifications on your phone but it's your socket)


๐Ÿ’… handshake_cancel(#sslsocket{}) -> any().

Cancel the handshake with a fatal USER_CANCELED alert. ๐Ÿ›‘

๐Ÿซถ handshake_continue(HsSocket, Options, Timeout) -> {ok, SslSocket} | {error, Reason}

when
    HsSocket :: sslsocket(),
    Options ::
        [client_option() |
         server_option() |
         common_option()],
    Timeout :: timeout(),
    SslSocket :: sslsocket(),
    Reason ::
        closed | timeout | error_alert().

Continue the TLS handshake โ€” possibly with new, additional, or changed options. glow up your options mid-handshake, why not ๐Ÿ’โ€โ™€๏ธ

๐ŸŒธ listen(Port, Options) -> {ok, ListenSocket} | {error, Reason}

when
    Port :: inet:port_number(),
    Options :: [tls_server_option()],
    ListenSocket :: sslsocket(),
    Reason :: {options, any()} | reason().

Creates an SSL listen socket. ๐Ÿ‘‘ classic, iconic, does what it says.

๐Ÿฆ‹ negotiated_protocol(SslSocket) -> {ok, Protocol} | {error, Reason}

when
    SslSocket :: sslsocket(),
    Protocol :: binary(),
    Reason ::
        protocol_not_negotiated | closed.

Returns the protocol negotiated through ALPN or NPN extensions. fr fr, this is how you find out which protocol you two agreed on.

๐ŸŽ€ peercert(SslSocket) -> {ok, Cert} | {error, reason()}

when
    SslSocket :: sslsocket(),
    Cert :: public_key:der_encoded().

The peer certificate is returned as a DER-encoded binary. ๐Ÿ’œ

The certificate can be decoded with public_key:pkix_decode_cert/2. Suggested further reading about certificates is Public_Key User's Guide and SSL User's Guide. ๐Ÿ“š (iykyk, go read the guides)

๐ŸŒˆ peername(SslSocket) -> {ok, {Address, Port}} | {error, reason()}

when
    SslSocket :: sslsocket(),
    Address :: inet:ip_address(),
    Port :: inet:port_number().

Returns the address and port number of the peer. who dis โ€” but like, politely, with data ๐Ÿ—บ๏ธ

โœจ prepend_cipher_suites(Preferred, Suites) -> ciphers()

when
    Preferred ::
        ciphers() | cipher_filters(),
    Suites :: ciphers().

Make Preferred suites become the most preferred suites. ๐Ÿ’…

The Preferred suites will be put at the head of the cipher suite list Suites after removing them from Suites if present. Preferred can be a list of cipher suites or a list of filters โ€” in which case the filters are used on Suites to extract the preferred cipher list.

๐Ÿ’€ prf(SslSocket, Secret, Label, Seed, WantedLength) -> {ok, binary()} | {error, reason()}

when
    SslSocket :: sslsocket(),
    Secret :: binary() | master_secret,
    Label :: binary(),
    Seed :: [binary() | prf_random()],
    WantedLength :: non_neg_integer().
Deprecated: ssl:prf/5 is deprecated; use export_key_materials/4 instead. Note that in OTP 28 the 'testing' way of calling this function will no longer be supported. ๐Ÿ˜ญ

Uses the Pseudo-Random Function (PRF) of a TLS session to generate extra key material. ๐Ÿ”‘

It either takes user-generated values for Secret and Seed, or atoms directing it to use a specific value from the session security parameters.

Note ๐Ÿ™ˆ This function is replaced by export_key_materials/4, the officially documented API function since OTP 27, which is equivalent to prf(TLSSocket, master_secret, Label, [client_random, server_random, Context], WantedLength)](prf/5). Other ways of calling this function were for testing purposes only and has no use case. When called in a TLS-1.3 context it will now behave as [export_key_materials(TLSSocket, [Label], [Context], [WantedLength]).

๐Ÿ“ recv(SslSocket, Length, Timeout) -> {ok, Data} | {error, reason()}

when
    SslSocket :: sslsocket(),
    Length :: non_neg_integer(),
    Data :: binary() | list() | HttpPacket,
    Timeout :: timeout(),
    HttpPacket :: any().

Receives a packet from a socket in passive mode.

A closed socket is indicated by return value {error, closed}. Argument Length is meaningful only when the socket is in mode raw and denotes the number of bytes to read. If Length is zero, all available bytes are returned. If Length is greater than zero, exactly Length bytes are returned, or an error; possibly discarding less than Length bytes of data when the socket gets closed from the other side. ๐Ÿ’”

Optional argument Timeout specifies a time-out in milliseconds. The default value is infinity.

๐Ÿงš renegotiate(SslSocket) -> ok | {error, reason()}

when SslSocket :: sslsocket().

Initiates a new handshake. ๐Ÿ”„

A notable return value is {error, renegotiation_rejected}, indicating that the peer refused to go through with the renegotiation โ€” but the connection is still active using the previously negotiated session. (they said no but we're still talking, ok)

TLS-1.3 has removed the renegotiation feature from earlier TLS versions and instead adds a new feature called key update, which replaces the most important part of renegotiation: the refreshing of session keys. This is triggered automatically after reaching a plaintext limit and can be configured using the key_update_at option in common_option_tls13/0. โœจ

๐Ÿ’– send(SslSocket, Data) -> ok | {error, reason()}

when SslSocket :: sslsocket(), Data :: iodata().

Writes Data to SslSocket. ๐Ÿ’Œ

A notable return value is {error, closed}, indicating that the socket is closed. ๐Ÿ™ˆ

๐Ÿ‘‘ setopts(SslSocket, Options) -> ok | {error, reason()}

when
    SslSocket :: sslsocket(),
    Options :: [gen_tcp:option()].

Sets options according to Options for socket SslSocket.

Note โš ๏ธ Note that setting low level transport protocol specific options may or may not work in a TLS-environment. And even if they work, it may make your code platform specific, or stop working in later version of this application. Such options could make sense for some special corner cases although it is not a general viable option. Such trade-offs must be carefully considered by the user that need to fully understand the consequences of setting such options. ๐Ÿ˜ฌ (read this twice bestie, this is a "know what you're doing" situation)

๐Ÿฆ‹ shutdown(SslSocket, How) -> ok | {error, reason()}

when
    SslSocket :: sslsocket(),
    How :: read | write | read_write.

Immediately closes a socket in one or two directions. โœ‚๏ธ

How == write means closing the socket for writing, but reading from it is still possible.

To handle siutations where the peer has performed a shutdown on the write side, option {exit_on_close, false} is useful. (yes, the original says "siutations", we leave that exactly as it is, no cap ๐Ÿ’€)

๐ŸŒŸ signature_algs(Description, Version) -> signature_algs()

when
    Description :: default | all | exclusive,
    Version :: protocol_version().

Lists all available signature algorithms corresponding to Description.

The exclusive option will exclusively list algorithms or algorithm schemes for that protocol version, whereas the default and all options lists the combined list to support the range of protocols from (D)TLS-1.2, the first version to support configuration of the signature algorithms, to Version.

Example:

1> ssl:signature_algs(default, 'tlsv1.3').
[mldsa87,mldsa65,mldsa44,slh_dsa_shake_256f,slh_dsa_shake_256s,
 slh_dsa_sha2_256f,slh_dsa_sha2_256s,slh_dsa_shake_192f,slh_dsa_shake_192s,
 slh_dsa_sha2_192f,slh_dsa_sha2_192s,slh_dsa_shake_128f,slh_dsa_shake_128s,
 slh_dsa_sha2_128f,slh_dsa_sha2_128s,eddsa_ed25519,eddsa_ed448,
 ecdsa_secp521r1_sha512,ecdsa_secp384r1_sha384,ecdsa_secp256r1_sha256,
 ecdsa_brainpoolP512r1tls13_sha512,ecdsa_brainpoolP384r1tls13_sha384,
 ecdsa_brainpoolP256r1tls13_sha256,rsa_pss_pss_sha512,rsa_pss_pss_sha384,
 rsa_pss_pss_sha256,rsa_pss_rsae_sha512,rsa_pss_rsae_sha384,
 rsa_pss_rsae_sha256,rsa_pkcs1_sha512,rsa_pkcs1_sha384,rsa_pkcs1_sha256,
 {sha512,ecdsa},
 {sha384,ecdsa},
 {sha256,ecdsa}].

ate, no crumbs. ๐Ÿฝ๏ธโœจ

2> ssl:signature_algs(all, 'tlsv1.3').
[mldsa87,mldsa65,mldsa44,slh_dsa_shake_256f,slh_dsa_shake_256s,
 slh_dsa_sha2_256f,slh_dsa_sha2_256s,slh_dsa_shake_192f,slh_dsa_shake_192s,
 slh_dsa_sha2_192f,slh_dsa_sha2_192s,slh_dsa_shake_128f,slh_dsa_shake_128s,
 slh_dsa_sha2_128f,slh_dsa_sha2_128s,eddsa_ed25519,eddsa_ed448,
 ecdsa_secp521r1_sha512,ecdsa_secp384r1_sha384,ecdsa_secp256r1_sha256,
 ecdsa_brainpoolP512r1tls13_sha512,ecdsa_brainpoolP384r1tls13_sha384,
 ecdsa_brainpoolP256r1tls13_sha256,rsa_pss_pss_sha512,rsa_pss_pss_sha384,
 rsa_pss_pss_sha256,rsa_pss_rsae_sha512,rsa_pss_rsae_sha384,
 rsa_pss_rsae_sha256,rsa_pkcs1_sha512,rsa_pkcs1_sha384,rsa_pkcs1_sha256,
 {sha512,ecdsa},
 {sha384,ecdsa},
 {sha256,ecdsa},
 slh_dsa_shake_256f,slh_dsa_shake_256s,slh_dsa_sha2_256f,slh_dsa_sha2_256s,
 slh_dsa_shake_192f,slh_dsa_shake_192s,slh_dsa_sha2_192f,slh_dsa_sha2_192s,
 slh_dsa_shake_128f,slh_dsa_shake_128s,slh_dsa_sha2_128f,slh_dsa_sha2_128s,
 ecdsa_sha1,rsa_pkcs1_sha1,
 {sha224,ecdsa},
 {sha224,rsa},
 {sha,dsa}]

3> [ssl:signature_algs(exclusive, 'tlsv1.3').
[mldsa87,mldsa65,mldsa44,slh_dsa_shake_256f,slh_dsa_shake_256s,
 slh_dsa_sha2_256f,slh_dsa_sha2_256s,slh_dsa_shake_192f,slh_dsa_shake_192s,
 slh_dsa_sha2_192f,slh_dsa_sha2_192s,slh_dsa_shake_128f,slh_dsa_shake_128s,
 slh_dsa_sha2_128f,slh_dsa_sha2_128s,eddsa_ed25519,eddsa_ed448,
 ecdsa_secp521r1_sha512,ecdsa_secp384r1_sha384,ecdsa_secp256r1_sha256,
 ecdsa_brainpoolP512r1tls13_sha512,ecdsa_brainpoolP384r1tls13_sha384,
 ecdsa_brainpoolP256r1tls13_sha256,rsa_pss_pss_sha512,rsa_pss_pss_sha384,
 rsa_pss_pss_sha256,rsa_pss_rsae_sha512,rsa_pss_rsae_sha384,
 rsa_pss_rsae_sha256,rsa_pkcs1_sha512,rsa_pkcs1_sha384,rsa_pkcs1_sha256]
NOTE: some TLS-1.3 scheme names overlap with TLS-1.2 algorithm-tuple-pair-names, and when that happens the TLS-1.3 names win โ€” like rsa_pkcs1_sha256 instead of {sha256, rsa}. Those are legacy algorithms in TLS-1.3 and in this version of the protocol they only apply to certificate signatures. iykyk ๐Ÿ’…

sockname

sockname(SslSocket) -> {ok, {Address, Port}} | {error, reason()}
                  when
                      SslSocket :: sslsocket(),
                      Address :: inet:ip_address(),
                      Port :: inet:port_number().

Gives you the local address and port number of socket SslSocket. That's your side of the convo bestie, the address you're sitting at ๐Ÿช‘


start

start(permanent | transient | temporary) -> ok | {error, reason()}.

Starts the SSL application. boot her up โœจ


stop

stop() -> ok.

Stops the SSL application. That's it, that's the whole thing ๐Ÿซถ


str_to_suite

str_to_suite(CipherSuiteName) ->
                      erl_cipher_suite() |
                      {error, {not_recognized, CipherSuiteName}}
                      when CipherSuiteName :: string().

Converts an RFC or OpenSSL name string into an erl_cipher_suite/0 ๐ŸŒธ

Returns an error if the cipher suite isn't supported, or if the name isn't a valid cipher suite name. No guesses, no vibes-based parsing, it just tells you {not_recognized, CipherSuiteName} ๐Ÿ’€


suite_to_openssl_str

suite_to_openssl_str(CipherSuite) -> string()
                              when CipherSuite :: erl_cipher_suite().

Converts an erl_cipher_suite() value into an OpenSSL name string.

PRE TLS-1.3 these names differ from the RFC names. So don't be out here matching them up expecting them to be twins, they are not ๐Ÿ™ˆ

suite_to_str

suite_to_str(CipherSuite) -> string()
                      when CipherSuite :: erl_cipher_suite().

Converts an erl_cipher_suite() value into an RFC name string. This one's the RFC-flavoured twin ๐Ÿงš


transport_accept

transport_accept(ListenSocket, Timeout) ->
                            {ok, SslSocket} | {error, Reason}
                            when
                                ListenSocket :: sslsocket(),
                                Timeout :: timeout(),
                                SslSocket :: sslsocket(),
                                Reason :: reason().

Accepts an incoming connection request on a listen socket ๐ŸŽ€

ListenSocket must be a socket that came back from listen/2. The socket you get back is the one you hand over to handshake/1,2,3 to finish the handshake and actually establish the TLS/DTLS connection. like, the accept is the "hey bestie ๐Ÿ‘‹" and the handshake is the "omg hi let's lock in ๐Ÿ”"

WARNING: most API functions need the TLS/DTLS connection to actually be established for them to work as expected. no shortcuts ๐Ÿ‘‘

The accepted socket inherits the options that were set for ListenSocket in listen/2. Family traits, literally ๐Ÿ’–

The default value for Timeout is infinity. If you do specify a Timeout and nothing gets accepted within that time, you get {error, timeout} back. clock's ticking โฐ


update_keys

update_keys(SslSocket, Type) -> ok | {error, reason()}
                     when
                         SslSocket :: sslsocket(),
                         Type :: write | read_write.

Creates new session keys ๐Ÿ”‘

So here's the tea: there are cryptographic limits on how much plaintext can be safely encrypted under one given set of keys. If the amount of data surpasses those limits, a key update gets triggered and a brand new set of keys is installed. (Also peep the key_update_at option in common_option_tls13/0 if you wanna be proactive ๐Ÿ‘€)

This function lets you explicitly start a key update on a TLS-1.3 connection. There are two types:

  • if Type is write, only the writing key gets updated
  • if Type is read_write, both the reading and writing keys get updated

versions

versions() -> [VersionInfo]
                    when
                        VersionInfo ::
                            {ssl_app, string()} |
                            {supported | available | implemented,
                             [tls_version()]} |
                            {supported_dtls | available_dtls |
                             implemented_dtls,
                             [dtls_version()]}.

Lists info โ€” mostly about TLS/DTLS versions โ€” at runtime, for debugging and testing purposes ๐Ÿ”

Here's the breakdown bestie:

app_vsn

  • The application version of the SSL application.

supported

  • TLS versions supported with the current application environment and crypto library configuration. Overridden by a version option on connect/2,3,4, listen/2, and handshake/2,3. For the negotiated TLS version, see connection_information/1.

supported_dtls

  • DTLS versions supported with the current application environment and crypto library configuration. Overridden by a version option on connect/2,3,4, listen/2, and handshake/2,3. For the negotiated DTLS version, see connection_information/1.

available

  • All TLS versions supported with the linked crypto library.

available_dtls

  • All DTLS versions supported with the linked crypto library.

implemented

  • All TLS versions supported by the SSL application if linked with a crypto library with the necessary support.

implemented_dtls

  • All DTLS versions supported by the SSL application if linked with a crypto library with the necessary support.

okay and that's a wrap on ssl(3) ๐ŸŽฌ ate and left no crumbs, periodt ๐Ÿ’…โœจ

Huge thanks to Ericsson AB for shipping all of this โ€” this page is from ssl 11.7.5 and it lives in the section-3 manuals as ssl(3) ๐Ÿฆ‹ go forth and encrypt responsibly, bestie, you've got this ๐ŸŒธ๐ŸŽ€๐Ÿ‘‘

๐Ÿ“ฆ where this page comes from