1# Using s2n-tls 2 3s2n-tls is a C library, and is built using Make. To clone the latest 4copy of s2n-tls from git use: 5 6```shell 7git clone https://github.com/aws/s2n-tls.git 8cd s2n-tls 9``` 10 11## Building s2n-tls with existing libcrypto 12### make Instructions 13To build s2n-tls with an existing libcrypto installation, store its root folder in the 14`LIBCRYPTO_ROOT` environment variable. 15```shell 16# /usr/local/ssl/lib should contain libcrypto.a 17LIBCRYPTO_ROOT=/usr/local/ssl make 18``` 19### CMake Instructions 20 21Throughout this document, there are instructions for setting a `LIBCRYPTO_ROOT` environment variable, or setting install prefixes to `s2n/lib-crypto-root`. If you 22are using CMake that step is unnecessary. Just follow the instructions here to use any build of libcrypto. 23 24(Required): You need at least CMake version 3.0 to fully benefit from Modern CMake. See [this](https://www.youtube.com/watch?v=bsXLMQ6WgIk) for more information. 25 26(Optional): Set the CMake variable `CMAKE_INSTALL_PREFIX` to the location libcrypto is installed to. If you do not, 27the default installation on your machine will be used. 28 29(Optional): Set the CMake variable `BUILD_SHARED_LIBS=ON` to build shared libraries. The default is static. 30 31We recommend an out-of-source build. Suppose you have a directory `s2n` which contains the s2n-tls source code. At the same level 32we can create a directory called `s2n-build` 33 34For example, we can build and install shared libs using ninja as our build system, and the system libcrypto implementation. 35 36````shell 37mkdir s2n-build 38cd s2n-build 39cmake ../s2n-tls -DBUILD_SHARED_LIBS=ON -GNinja 40ninja 41ninja test 42sudo ninja install 43```` 44 45For another example, we can prepare an Xcode project using static libs using a libcrypto implementation in the directory `$HOME/s2n-user/builds/libcrypto-impl`. 46 47````shell 48mkdir s2n-build 49cd s2n-build 50cmake ../s2n-tls -DCMAKE_INSTALL_PREFIX=$HOME/s2n-user/builds/libcrypto-impl -G "Xcode" 51# now open the project in Xcode and build from there, or use the Xcode CLI 52```` 53 54Or, for unix style vanilla builds: 55 56````shell 57mkdir s2n-build 58cd s2n-build 59cmake ../s2n-build 60make 61make test 62sudo make install 63```` 64 65### Consuming s2n-tls via. CMake 66s2n-tls ships with modern CMake finder scripts if CMake is used for the build. To take advantage of this from your CMake script, all you need to do to compile and link against s2n-tls in your project is: 67 68````shell 69find_package(s2n-tls) 70 71.... 72 73target_link_libraries(yourExecutableOrLibrary AWS::s2n-tls) 74```` 75 76And when invoking CMake for your project, do one of two things: 77 1. Set the `CMAKE_INSTALL_PREFIX` variable with the path to your s2n-tls build. 78 2. If you have globally installed s2n-tls, do nothing, it will automatically be found. 79 80## Building s2n-tls with OpenSSL-1.1.1 81 82To build s2n-tls with OpenSSL-1.1.1, do the following: 83 84```shell 85# We keep the build artifacts in the -build directory 86cd libcrypto-build 87 88# Download the latest version of OpenSSL 89curl -LO https://www.openssl.org/source/openssl-1.1.1-latest.tar.gz 90tar -xzvf openssl-1.1.1-latest.tar.gz 91 92# Build openssl libcrypto 93cd `tar ztf openssl-1.1.1-latest.tar.gz | head -n1 | cut -f1 -d/` 94./config -fPIC no-shared \ 95 no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-zlib \ 96 no-hw no-mdc2 no-seed no-idea enable-ec_nistp_64_gcc_128 no-camellia\ 97 no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng \ 98 -DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS \ 99 --prefix=`pwd`/../../libcrypto-root/ 100make 101make install 102 103# Build s2n-tls 104cd ../../ 105make 106``` 107# Note for 32-bit builds. 108The previous instructions work fine with only a few tweaks to your config command. Example: 109```shell 110setarch i386 ./config -fPIC no-shared \ 111 -m32 no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-zlib \ 112 no-hw no-mdc2 no-seed no-idea no-camellia\ 113 no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng \ 114 -DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS \ 115 --prefix=`pwd`/../../libcrypto-root/ 116``` 117 118## Building s2n-tls with OpenSSL-1.0.2 119 120To build s2n-tls with OpenSSL-1.0.2, do the following: 121 122```shell 123# We keep the build artifacts in the -build directory 124cd libcrypto-build 125 126# Download the latest version of OpenSSL 127curl -LO https://www.openssl.org/source/openssl-1.0.2-latest.tar.gz 128tar -xzvf openssl-1.0.2-latest.tar.gz 129 130# Build openssl libcrypto 131cd `tar ztf openssl-1.0.2-latest.tar.gz | head -n1 | cut -f1 -d/` 132./config -fPIC no-shared no-libunbound no-gmp no-jpake no-krb5 \ 133 no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-store no-zlib \ 134 no-hw no-mdc2 no-seed no-idea enable-ec-nistp_64_gcc_128 no-camellia\ 135 no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng \ 136 -DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS \ 137 --prefix=`pwd`/../../libcrypto-root/ 138make depend 139make 140make install 141 142# Build s2n-tls 143cd ../../ 144make 145``` 146 147**Mac Users:** please replace "./config" with "./Configure darwin64-x86_64-cc". 148 149## Building s2n-tls with LibreSSL 150 151To build s2n-tls with LibreSSL, do the following: 152 153```shell 154# We keep the build artifacts in the -build directory 155cd libcrypto-build 156 157# Download the latest version of LibreSSL 158curl -O http://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-x.y.z.tar.gz 159tar -xzvf libressl-x.y.z.tar.gz 160 161# Build LibreSSL's libcrypto 162cd libressl-x.y.z 163./configure --prefix=`pwd`/../../libcrypto-root/ 164make CFLAGS=-fPIC install 165 166# Build s2n-tls 167cd ../../ 168make 169``` 170 171once built, static and dynamic libraries for s2n-tls will be available in the lib/ 172directory. 173 174## Building s2n-tls with BoringSSL 175 176To build s2n-tls with BoringSSL, you must check out a copy of the BoringSSL 177directly via git. This procedure has been tested with 178fb68d6c901b98ffe15b8890d00bc819bf44c5f01 of BoringSSL. 179 180```shell 181# We keep the build artifacts in the -build directory 182cd libcrypto-build 183 184# Clone BoringSSL 185git clone https://boringssl.googlesource.com/boringssl 186 187# Build BoringSSL 188cd boringssl 189mkdir build 190cd build 191cmake -DCMAKE_C_FLAGS="-fPIC" ../ 192make 193 194# Copy the built library and includes 195mkdir ../../../libcrypto-root/lib/ 196cp crypto/libcrypto.a ../../../libcrypto-root/lib/ 197cp -r ../include/ ../../../libcrypto-root/include 198 199# Build s2n-tls 200cd ../../../ 201make 202``` 203 204once built, static and dynamic libraries for s2n-tls will be available in the lib/ 205directory. 206 207## mlock() and system limits 208 209Internally s2n-tls uses mlock() to prevent memory from being swapped to disk. The 210s2n-tls build tests may fail in some environments where the default limit on locked 211memory is too low. To check this limit, run: 212 213```shell 214ulimit -l 215``` 216 217to raise the limit, consult the documentation for your platform. 218 219### Disabling mlock() 220To disable s2n-tls's mlock behavior, run your application with the `S2N_DONT_MLOCK` environment variable set. 221s2n-tls also reads this for unit tests. Try `S2N_DONT_MLOCK=1 make` if you're having mlock failures during unit tests. 222 223# s2n-tls API 224 225The API exposed by s2n-tls is the set of functions and declarations that 226are in the "s2n.h" header file. Any functions and declarations that are in the "s2n.h" file 227are intended to be stable (API and ABI) within major version numbers of s2n-tls releases. Other functions 228and structures used in s2n-tls internally can not be considered stable and their parameters, names, and 229sizes may change. 230 231The VERSIONING.rst document contains more details about s2n's approach to versions and API changes. 232 233## Preprocessor macros 234 235s2n-tls defines five preprocessor macros that are used to determine what 236version of SSL/TLS is in use on a connection. 237 238```c 239#define S2N_SSLv2 20 240#define S2N_SSLv3 30 241#define S2N_TLS10 31 242#define S2N_TLS11 32 243#define S2N_TLS12 33 244#define S2N_TLS13 34 245``` 246 247These correspond to SSL2.0, SSL3.0, TLS1.0, TLS1.1, TLS1.2 and TLS1.3 respectively. 248Note that s2n-tls does not support SSL2.0 for sending and receiving encrypted data, 249but does accept SSL2.0 hello messages. 250 251## Enums 252 253s2n-tls defines the following enum types: 254 255### s2n_error_type 256 257```c 258typedef enum { 259 S2N_ERR_T_OK=0, 260 S2N_ERR_T_IO, 261 S2N_ERR_T_CLOSED, 262 S2N_ERR_T_BLOCKED, 263 S2N_ERR_T_ALERT, 264 S2N_ERR_T_PROTO, 265 S2N_ERR_T_INTERNAL, 266 S2N_ERR_T_USAGE 267} s2n_error_type; 268``` 269 270***s2n_error_type*** is used to help applications determine why an s2n-tls function failed. 271This enum is optimized for use in C switch statements. Each value in the enum represents 272an error "category". See [Error Handling](#error-handling) for more detail. 273 274### s2n_mode 275 276```c 277typedef enum { 278 S2N_SERVER, 279 S2N_CLIENT 280} s2n_mode; 281``` 282 283**s2n_mode** is used to declare connections as server or client type, respectively. 284 285### s2n_blocked_status 286 287```c 288typedef enum { 289 S2N_NOT_BLOCKED = 0, 290 S2N_BLOCKED_ON_READ, 291 S2N_BLOCKED_ON_WRITE, 292 S2N_BLOCKED_ON_APPLICATION_INPUT, 293 S2N_BLOCKED_ON_EARLY_DATA, 294} s2n_blocked_status; 295``` 296 297**s2n_blocked_status** is used in non-blocking mode to indicate in which 298direction s2n-tls became blocked on I/O before it returned control to the caller. 299This allows an application to avoid retrying s2n-tls operations until I/O is 300possible in that direction. 301 302### s2n_blinding 303 304```c 305typedef enum { S2N_BUILT_IN_BLINDING, S2N_SELF_SERVICE_BLINDING } s2n_blinding; 306``` 307 308**s2n_blinding** is used to opt-out of s2n-tls's built-in blinding. Blinding is a 309mitigation against timing side-channels which in some cases can leak information 310about encrypted data. By default s2n-tls will cause a thread to sleep between 10 and 31130 seconds whenever tampering is detected. 312 313Setting the **S2N_SELF_SERVICE_BLINDING** option with **s2n_connection_set_blinding** 314turns off this behavior. This is useful for applications that are handling many connections 315in a single thread. In that case, if s2n_recv() or s2n_negotiate() return an error, 316self-service applications should call **s2n_connection_get_delay** and pause 317activity on the connection for the specified number of nanoseconds before calling 318close() or shutdown(). 319 320### s2n_status_request_type 321 322```c 323typedef enum { S2N_STATUS_REQUEST_NONE, S2N_STATUS_REQUEST_OCSP } s2n_status_request_type; 324``` 325 326**s2n_status_request_type** is used to define the type, if any, of certificate 327status request an S2N_CLIENT should make during the handshake. The only 328supported status request type is OCSP, **S2N_STATUS_REQUEST_OCSP**. 329 330### s2n_cert_auth_type 331 332```c 333typedef enum { S2N_CERT_AUTH_NONE, S2N_CERT_AUTH_REQUIRED, S2N_CERT_AUTH_OPTIONAL } s2n_cert_auth_type; 334``` 335**s2n_cert_auth_type** is used to declare what type of client certificate authentication to use. 336Currently the default for s2n-tls is for neither the server side or the client side to use Client (aka Mutual) authentication. 337 338## Opaque structures 339 340s2n-tls defines several opaque structures that are used for managed objects. Because 341these structures are opaque, they can only be safely referenced indirectly through 342pointers and their sizes may change with future versions of s2n-tls. 343 344```c 345struct s2n_config; 346struct s2n_connection; 347``` 348 349**s2n_config** structures are a configuration object, used by servers for 350holding cryptographic certificates, keys and preferences. **s2n_connection** 351structures are used to track each connection. 352 353 354```c 355struct s2n_rsa_public_key; 356struct s2n_cert_public_key; 357``` 358 359**s2n_rsa_public_key** and **s2n_cert_public_key** can be used by consumers of s2n-tls to get and set public keys through other API calls. 360 361 362## Error handling 363 364``` 365const char *s2n_strerror(int error, const char *lang); 366const char *s2n_strerror_debug(int error, const char *lang); 367const char *s2n_strerror_name(int error); 368```` 369 370s2n-tls functions that return 'int' return 0 to indicate success and -1 to indicate 371failure. s2n-tls functions that return pointer types return NULL in the case of 372failure. When an s2n-tls function returns a failure, s2n_errno will be set to a value 373corresponding to the error. This error value can be translated into a string 374explaining the error in English by calling s2n_strerror(s2n_errno, "EN"). 375A string containing human readable error name, can be generated with `s2n_strerror_name`. 376A string containing internal debug information, including filename and line number, can be generated with `s2n_strerror_debug`. 377This string is useful to include when reporting issues to the s2n-tls development team. 378 379Example: 380 381``` 382if (s2n_config_set_cipher_preferences(config, prefs) < 0) { 383 printf("Setting cipher prefs failed! %s : %s", s2n_strerror(s2n_errno, "EN"), s2n_strerror_debug(s2n_errno, "EN")); 384 return -1; 385} 386``` 387 388**NOTE**: To avoid possible confusion, s2n_errno should be cleared after processing an error: `s2n_errno = S2N_ERR_T_OK` 389 390When using s2n-tls outside of `C`, the address of the thread-local `s2n_errno` may be obtained by calling the `int *s2n_errno_location()` function. 391This will ensure that the same TLS mechanisms are used with which s2n-tls was compiled. 392 393### Stacktraces 394s2n-tls has an mechanism to capture stacktraces when errors occur. 395This mechanism is off by default, but can be enabled in code by calling `s2n_stack_traces_enabled_set()`. 396It can be enabled globally by setting the environment variable `S2N_PRINT_STACKTRACE=1`. 397Note that enabling stacktraces this can significantly slow down unit tests, and can cause failures on unit-tests (such as `s2n_cbc_verify`) that measure the timing of events. 398 399``` 400bool s2n_stack_traces_enabled(); 401int s2n_stack_traces_enabled_set(bool newval); 402 403int s2n_calculate_stacktrace(void); 404int s2n_print_stacktrace(FILE *fptr); 405int s2n_free_stacktrace(void); 406int s2n_get_stacktrace(char*** trace, int* trace_size); 407``` 408 409### Error categories 410 411s2n-tls organizes errors into different "types" to allow applications to do logic on error values without catching all possibilities. 412Applications using non-blocking I/O should check error type to determine if the I/O operation failed because it would block or for some other error. To retrieve the type for a given error use `s2n_error_get_type()`. 413Applications should perform any error handling logic using these high level types: 414 415``` 416S2N_ERR_T_OK=0, /* No error */ 417S2N_ERR_T_IO, /* Underlying I/O operation failed, check system errno */ 418S2N_ERR_T_CLOSED, /* EOF */ 419S2N_ERR_T_BLOCKED, /* Underlying I/O operation would block */ 420S2N_ERR_T_ALERT, /* Incoming Alert */ 421S2N_ERR_T_PROTO, /* Failure in some part of the TLS protocol. Ex: CBC verification failure */ 422S2N_ERR_T_INTERNAL, /* Error internal to s2n-tls. A precondition could have failed. */ 423S2N_ERR_T_USAGE /* User input error. Ex: Providing an invalid cipher preference version */ 424``` 425 426Here's an example that handles errors based on type: 427 428``` 429s2n_errno = S2N_ERR_T_OK; 430if (s2n_recv(conn, &blocked) < 0) { 431 switch(s2n_error_get_type(s2n_errno)) { 432 case S2N_ERR_T_BLOCKED: 433 /* Blocked, come back later */ 434 return -1; 435 case S2N_ERR_T_CLOSED: 436 return 0; 437 case S2N_ERR_T_IO: 438 handle_io_err(); 439 return -1; 440 case S2N_ERR_T_PROTO: 441 handle_proto_err(); 442 return -1; 443 case S2N_ERR_T_ALERT: 444 log_alert(s2n_connection_get_alert(conn)); 445 return -1; 446 /* Everything else */ 447 default: 448 log_other_error(); 449 return -1; 450 } 451} 452``` 453 454 455## Initialization and teardown 456 457### s2n\_get\_openssl\_version 458 459```c 460unsigned long s2n_get_openssl_version(); 461``` 462 463**s2n_get_openssl_version** returns the version number of OpenSSL that s2n-tls was compiled with. It can be used by 464applications to validate at runtime that the versions of s2n-tls and Openssl that they have loaded are correct. 465 466 467### s2n\_init 468 469```c 470int s2n_init(); 471``` 472 473**s2n_init** initializes the s2n-tls library and should be called once in your application, 474before any other s2n-tls functions are called. Failure to call s2n_init() will result 475in errors from other s2n-tls functions. 476 477### s2n\_crypto\_disable\_init 478 479```c 480int s2n_crypto_disable_init(); 481``` 482 483**s2n_crypto_disable_init** prevents s2n-tls from initializing or tearing down the crypto 484library. This is most useful when s2n-tls is embedded in an application or environment that 485shares usage of the OpenSSL or libcrypto library. Note that if you disable this and are 486using a version of OpenSSL/libcrypto < 1.1.x, you will be responsible for library init 487and cleanup (specifically OPENSSL_add_all_algorithms() or OPENSSL_crypto_init), and 488`EVP_*` APIs will not be usable unless the library is initialized. 489 490This function must be called BEFORE `s2n_init()` to have any effect. It will return an error 491if s2n is already initialized. 492 493### s2n\_disable\_atexit 494 495```c 496int s2n_disable_atexit(); 497``` 498 499**s2n_disable_atexit** prevents s2n-tls from installing an atexit() handler to clean itself 500up. This is most useful when s2n-tls is embedded in an application or environment that 501shares usage of the OpenSSL or libcrypto library. Note that this will cause `s2n_cleanup` to 502do complete cleanup of s2n-tls when called from the main thread (the thread `s2n_init` was 503called from). 504 505This function must be called BEFORE `s2n_init()` to have any effect. It will return an error 506if s2n is already initialized. 507 508### s2n\_cleanup 509 510```c 511int s2n_cleanup(); 512``` 513 514**s2n_cleanup** cleans up any internal resources used by s2n-tls. This function should be 515called from each thread or process that is created subsequent to calling **s2n_init** 516when that thread or process is done calling other s2n-tls functions. 517 518## Configuration-oriented functions 519 520### s2n\_config\_new 521 522```c 523struct s2n_config * s2n_config_new(); 524``` 525 526**s2n_config_new** returns a new configuration object suitable for associating certs and keys. 527This object can (and should) be associated with many connection objects. 528 529### s2n\_config\_free 530 531```c 532int s2n_config_free(struct s2n_config *config); 533``` 534 535**s2n_config_free** frees the memory associated with an **s2n_config** object. 536 537### s2n\_config\_set\_cipher\_preferences 538 539```c 540int s2n_config_set_cipher_preferences(struct s2n_config *config, 541 const char *version); 542``` 543 544**s2n_config_set_cipher_preferences** sets the security policy that includes the cipher/kem/signature/ecc preferences and protocol version. 545 546The following chart maps the security policy version to protocol version and ciphersuites supported: 547 548| version | SSLv3 | TLS1.0 | TLS1.1 | TLS1.2 | TLS1.3 | AES-CBC | ChaCha20-Poly1305 | ECDSA | AES-GCM | 3DES | RC4 | DHE | ECDHE | 549|----------------|-------|--------|--------|--------|---------|---------|-------------------|-------|---------|------|-----|-----|-------| 550| "default" | | X | X | X | | X | X | | X | | | | X | 551| "20190214" | | X | X | X | | X | | X | X | X | | X | X | 552| "20170718" | | X | X | X | | X | | | X | | | | X | 553| "20170405" | | X | X | X | | X | | | X | X | | | X | 554| "20170328" | | X | X | X | | X | | | X | X | | X | X | 555| "20170210" | | X | X | X | | X | X | | X | | | | X | 556| "20160824" | | X | X | X | | X | | | X | | | | X | 557| "20160804" | | X | X | X | | X | | | X | X | | | X | 558| "20160411" | | X | X | X | | X | | | X | X | | | X | 559| "20150306" | | X | X | X | | X | | | X | X | | | X | 560| "20150214" | | X | X | X | | X | | | X | X | | X | | 561| "20150202" | | X | X | X | | X | | | | X | | X | | 562| "20141001" | | X | X | X | | X | | | | X | X | X | | 563| "20140601" | X | X | X | X | | X | | | | X | X | X | | 564| "20190120" | | X | X | X | | X | | | X | X | | | X | 565| "20190121" | | X | X | X | | X | | | X | X | | | X | 566| "20190122" | | X | X | X | | X | | X | X | X | | X | X | 567| "default_tls13"| | X | X | X | X | X | X | X | X | | | | X | 568| "20190801" | | X | X | X | X | X | X | | X | | | | X | 569| "20190802" | | X | X | X | X | X | X | | X | | | | X | 570| "20200207" | | X | X | X | X | X | X | | X | | | | | 571 572The "default" and "default_tls13" version is special in that it will be updated with future s2n-tls changes and ciphersuites and protocol versions may be added and removed, or their internal order of preference might change. Numbered versions are fixed and will never change. 573 574"20160411" follows the same general preference order as "default". The main difference is it has a CBC cipher suite at the top. This is to accommodate certain Java clients that have poor GCM implementations. Users of s2n-tls who have found GCM to be hurting performance for their clients should consider this version. 575 576"20170405" is a FIPS compliant cipher suite preference list based on approved algorithms in the [FIPS 140-2 Annex A](http://csrc.nist.gov/publications/fips/fips140-2/fips1402annexa.pdf). Similarly to "20160411", this preference list has CBC cipher suites at the top to accommodate certain Java clients. Users of s2n-tls who plan to enable FIPS mode should consider this version. 577 578s2n-tls does not expose an API to control the order of preference for each ciphersuite or protocol version. s2n-tls follows the following order: 579 580*NOTE*: All ChaCha20-Poly1305 cipher suites will not be available if s2n-tls is not built with an Openssl 1.1.1 libcrypto. The 581underlying encrypt/decrypt functions are not available in older versions. 582 5831. Always prefer the highest protocol version supported 5842. Always use forward secrecy where possible. Prefer ECDHE over DHE. 5853. Prefer encryption ciphers in the following order: AES128, AES256, ChaCha20, 3DES, RC4. 5864. Prefer record authentication modes in the following order: GCM, Poly1305, SHA256, SHA1, MD5. 587 588The following chart maps the security policy version to the signature scheme supported: 589 590| version | RSA PKCS1 | ECDSA | SHA-1 Legacy | RSA PSS | 591|----------------|--------------|----------|---------------|----------| 592| "default" | X | X | X | | 593| "20190214" | X | X | X | | 594| "20170718" | X | X | X | | 595| "20170405" | X | X | X | | 596| "20170328" | X | X | X | | 597| "20170210" | X | X | X | | 598| "20160824" | X | X | X | | 599| "20160804" | X | X | X | | 600| "20160411" | X | X | X | | 601| "20150306" | X | X | X | | 602| "20150214" | X | X | X | | 603| "20150202" | X | X | X | | 604| "20141001" | X | X | X | | 605| "20140601" | X | X | X | | 606| "20190120" | X | X | X | | 607| "20190121" | X | X | X | | 608| "20190122" | X | X | X | | 609| "default_tls13"| X | X | X | X | 610| "20190801" | X | X | X | X | 611| "20190802" | X | X | X | X | 612| "20200207" | X | X | X | X | 613 614Note that the default_tls13 security policy will never support legacy SHA-1 algorithms in TLS1.3, but will support 615legacy SHA-1 algorithms in CertificateVerify messages if TLS1.2 has been negotiated. 616 617The following chart maps the security policy version to the supported curves/groups: 618 619| version | secp256r1 | secp384r1 | x25519 | 620|----------------|--------------|------------|--------| 621| "default" | X | X | | 622| "20190214" | X | X | | 623| "20170718" | X | X | | 624| "20170405" | X | X | | 625| "20170328" | X | X | | 626| "20170210" | X | X | | 627| "20160824" | X | X | | 628| "20160804" | X | X | | 629| "20160411" | X | X | | 630| "20150306" | X | X | | 631| "20150214" | X | X | | 632| "20150202" | X | X | | 633| "20141001" | X | X | | 634| "20140601" | X | X | | 635| "20190120" | X | X | | 636| "20190121" | X | X | | 637| "20190122" | X | X | | 638| "default_tls13"| X | X | X | 639| "20190801" | X | X | X | 640| "20190802" | X | X | | 641| "20200207" | X | X | X | 642 643### s2n\_config\_add\_cert\_chain\_and\_key 644 645```c 646int s2n_config_add_cert_chain_and_key(struct s2n_config *config, 647 const char *cert_chain_pem, 648 const char *private_key_pem); 649``` 650 651**s2n_config_add_cert_chain_and_key** associates a certificate chain and a 652private key, with an **s2n_config** object. At present, only one 653certificate-chain/key pair may be associated with a config. 654 655**cert_chain_pem** should be a PEM encoded certificate chain, with the first 656certificate in the chain being your servers certificate. **private_key_pem** 657should be a PEM encoded private key corresponding to the server certificate. 658 659### s2n\_config\_add\_cert\_chain\_and\_key\_to\_store 660 661```c 662int s2n_config_add_cert_chain_and_key_to_store(struct s2n_config *config, 663 struct s2n_cert_chain_and_key *cert_key_pair); 664``` 665 666**s2n_config_add_cert_chain_and_key_to_store** is the preferred method of associating a certificate chain and private key pair with an **s2n_config** object. It is not recommended to free or modify the **cert_key_pair** as any subsequent changes will be reflected in the config. 667 668**s2n_config_add_cert_chain_and_key_to_store** may be called multiple times to support multiple key types(RSA, ECDSA) and multiple domains. On the server side, the certificate selected will be based on the incoming SNI value and the client's capabilities(supported ciphers). In the case of no certificate matching the client's SNI extension or if no SNI extension was sent by the client, the certificate from the **first** call to **s2n_config_add_cert_chain_and_key_to_store** will be selected. 669 670### s2n\_config\_set\_cert\_chain\_and\_key\_defaults 671 672```c 673int s2n_config_set_cert_chain_and_key_defaults(struct s2n_config *config, 674 struct s2n_cert_chain_and_key **cert_key_pairs, 675 uint32_t num_cert_key_pairs); 676``` 677 678**s2n_config_set_cert_chain_and_key_defaults** explicitly sets certificate chain and private key pairs to be used as defaults for each auth method (key type). A "default" certificate is used when there is not an SNI match with any other configured certificate. Only one certificate can be set as the default per auth method (one RSA default, one ECDSA default, etc.). All previous default certificates will be cleared and re-set when this API is called. This API is called for a specific **s2n_config** object. 679 680s2n-tls will attempt to automatically choose default certificates for each auth method (key type) based on the order that **s2n_cert_chain_and_key** are added to the **s2n_config** using one of the APIs listed above. **s2n_config_set_cert_chain_and_key_defaults** can be called at any time; s2n-tls will clear defaults and no longer attempt to automatically choose any default certificates. 681 682### s2n\_cert\_tiebreak\_callback 683```c 684typedef struct s2n_cert_chain_and_key* (*s2n_cert_tiebreak_callback) (struct s2n_cert_chain_and_key *cert1, struct s2n_cert_chain_and_key *cert2, uint8_t *name, uint32_t name_len); 685``` 686 687**s2n_cert_tiebreak_callback** is invoked if s2n-tls cannot resolve a conflict between two certificates with the same domain name. This function is invoked while certificates are added to an **s2n_config**. 688Currently, the only builtin resolution for domain name conflicts is certificate type(RSA, ECDSA, etc). 689The callback should return a pointer to the **s2n_cert_chain_and_key** that should be used for dns name **name**. If NULL is returned, the first certificate will be used. 690Typically an application will use properties like trust and expiry to implement tiebreaking. 691 692### s2n\_config\_set\_cert\_tiebreak\_callback 693```c 694int s2n_config_set_cert_tiebreak_callback(struct s2n_config *config, s2n_cert_tiebreak_callback tiebreak_fn); 695``` 696 697**s2n_config_set_cert_tiebreak_callback** sets the **s2n_cert_tiebreak_callback** for resolving domain name conflicts. If no callback is set, the first certificate added for a domain name will always be preferred. 698 699### s2n\_config\_add\_dhparams 700 701```c 702int s2n_config_add_dhparams(struct s2n_config *config, 703 char *dhparams_pem); 704``` 705 706**s2n_config_add_dhparams** associates a set of Diffie-Hellman parameters with 707an **s2n_config** object. **dhparams_pem** should be PEM encoded DH parameters. 708 709### s2n\_config\_set\_protocol\_preferences 710 711```c 712int s2n_config_set_protocol_preferences(struct s2n_config *config, 713 const char **protocols, 714 int protocol_count); 715``` 716 717**s2n_config_set_protocol_preferences** sets the application protocol 718preferences on an **s2n_config** object. **protocols** is a list in order of 719preference, with most preferred protocol first, and of length 720**protocol_count**. When acting as an **S2N_CLIENT** the protocol list is 721included in the Client Hello message as the ALPN extension. As an 722**S2N_SERVER**, the list is used to negotiate a mutual application protocol 723with the client. After the negotiation for the connection has completed, the 724agreed upon protocol can be retrieved with [s2n_get_application_protocol](#s2n_get_application_protocol) 725 726### s2n\_config\_set\_status\_request\_type 727 728```c 729int s2n_config_set_status_request_type(struct s2n_config *config, s2n_status_request_type type); 730``` 731 732**s2n_config_set_status_request_type** Sets up an S2N_CLIENT to request the 733server certificate status during an SSL handshake. If set to 734S2N_STATUS_REQUEST_NONE, no status request is made. 735 736### s2n\_config\_set\_extension\_data 737 738```c 739int s2n_config_set_extension_data(struct s2n_config *config, s2n_tls_extension_type type, const uint8_t *data, uint32_t length); 740``` 741 742**s2n_config_set_extension_data** Sets the extension data in the **s2n_config** 743object for the specified extension. This method will clear any existing data 744that is set. If the data and length parameters are set to NULL, no new data 745is set in the **s2n_config** object, effectively clearing existing data. 746 747`s2n_tls_extension_type` is defined as: 748 749```c 750 typedef enum { 751 S2N_EXTENSION_SERVER_NAME = 0, 752 S2N_EXTENSION_MAX_FRAG_LEN = 1, 753 S2N_EXTENSION_OCSP_STAPLING = 5, 754 S2N_EXTENSION_SUPPORTED_GROUPS = 10, 755 S2N_EXTENSION_EC_POINT_FORMATS = 11, 756 S2N_EXTENSION_SIGNATURE_ALGORITHMS = 13, 757 S2N_EXTENSION_ALPN = 16, 758 S2N_EXTENSION_CERTIFICATE_TRANSPARENCY = 18, 759 S2N_EXTENSION_RENEGOTIATION_INFO = 65281, 760 } s2n_tls_extension_type; 761``` 762 763At this time the following extensions are supported: 764 765`S2N_EXTENSION_OCSP_STAPLING` - If a client requests the OCSP status of the server 766certificate, this is the response used in the CertificateStatus handshake 767message. 768 769`S2N_EXTENSION_CERTIFICATE_TRANSPARENCY` - If a client supports receiving SCTs 770via the TLS extension (section 3.3.1 of RFC6962) this data is returned within 771the extension response during the handshake. The format of this data is the 772SignedCertificateTimestampList structure defined in that document. See 773http://www.certificate-transparency.org/ for more information about Certificate 774Transparency. 775 776### s2n\_config\_set\_wall\_clock 777 778```c 779int s2n_config_set_wall_clock(struct s2n_config *config, s2n_clock_time_nanoseconds clock_fn, void *data); 780``` 781 782**s2n_config_set_wall_clock** allows the caller to set a 783callback function that will be used to get the system time. The callback function 784takes two arguments; a pointer to arbitrary data for use within the callback, 785and a pointer to a 64 bit unsigned integer. The first pointer will be set to 786the value of **data** which supplied by the caller when setting the callback. 787The integer pointed to by the second pointer should be set to the number of 788nanoseconds since the Unix epoch (Midnight, January 1st, 1970). The function 789should return 0 on success and -1 on error. The default implementation, which uses the REALTIME clock, 790will be used if this callback is not manually set. 791 792### s2n\_config\_set\_monotonic\_clock 793 794```c 795int s2n_config_set_monotonic_clock(struct s2n_config *config, s2n_clock_time_nanoseconds clock_fn, void *data); 796``` 797 798**s2n_config_set_monotonic_clock** allows the caller to set a 799callback function that will be used to get monotonic time. The callback function 800takes two arguments; a pointer to arbitrary data for use within the callback, 801and a pointer to a 64 bit unsigned integer. The first pointer will be set to 802the value of **data** which supplied by the caller when setting the callback. 803The integer pointed to by the second pointer should be an always increasing value. The function 804should return 0 on success and -1 on error. The default implementation, which uses the MONOTONIC clock, 805will be used if this callback is not manually set. 806 807### s2n\_config\_set\_verification\_ca\_location 808```c 809int s2n_config_set_verification_ca_location(struct s2n_config *config, const char *ca_pem_filename, const char *ca_dir); 810``` 811 812**s2n_config_set_verification_ca_location** adds to the trust store from a CA file or directory 813containing trusted certificates. Note that the trust store will be initialized with the common locations 814for the host operating system by default. To completely override those locations, call 815[s2n_config_wipe_trust_store](#s2n_config_wipe_trust_store) before calling this function. 816Returns 0 on success and -1 on failure. 817 818### s2n\_config\_add\_pem\_to\_trust\_store 819```c 820int s2n_config_add_pem_to_trust_store(struct s2n_config *config, const char *pem); 821``` 822 823**s2n_config_add_pem_to_trust_store** adds a PEM to the trust store. This will allocate memory, and load PEM into the Trust Store. 824Note that the trust store will be initialized with the common locations for the host operating system by default. 825To completely override those locations, call [s2n_config_wipe_trust_store](#s2n_config_wipe_trust_store) 826before calling this function. 827This function returns 0 on success and -1 on error. 828 829 830### s2n\_config\_wipe\_trust\_store 831```c 832int s2n_config_wipe_trust_store(struct s2n_config *config); 833``` 834 835***s2n_config_wipe_trust_store*** clears the trust store. 836Note that the trust store will be initialized with the common locations for the host operating system by default. 837To completely override those locations, call this before functions like 838[s2n_config_set_verification_ca_location](#s2n_config_set_verification_ca_location) 839or [s2n_config_add_pem_to_trust_store](#s2n_config_add_pem_to_trust_store). 840This function returns 0 on success and -1 on error. 841 842### s2n\_verify\_host\_fn 843```c 844typedef uint8_t (*s2n_verify_host_fn) (const char *host_name, size_t host_name_len, void *ctx); 845``` 846 847**s2n_verify_host_fn** is invoked (usually multiple times) during X.509 validation for each name encountered in the leaf certificate. 848Return 1 to trust that hostname or 0 to not trust the hostname. If this function returns 1, then the certificate is considered trusted and that portion 849of the X.509 validation will succeed. If no hostname results in a 1 being returned, 850the certificate will be untrusted and the validation will terminate immediately. The default behavior is to reject all host names found in a certificate 851if client mode or client authentication is being used.. 852 853### s2n\_config\_set\_verify\_host\_callback 854```c 855int s2n_config_set_verify_host_callback(struct s2n_config *config, s2n_verify_host_fn, void *ctx); 856``` 857 858**s2n_config_set_verify_host_callback** sets the callback to use for verifying that a hostname from an X.509 certificate 859is trusted. By default, no certificate will be trusted. To override this behavior, set this callback. 860See [s2n_verify_host_fn](#s2n_verify_host_fn) for details. This configuration will be inherited by default to new instances of **s2n_connection**. 861If a separate callback for different connections using the same config is desired, see 862[s2n_connection_set_verify_host_callback](#s2n_connection_set_verify_host_callback). 863 864### s2n\_config\_set\_check\_stapled\_ocsp\_response 865 866```c 867int s2n_config_set_check_stapled_ocsp_response(struct s2n_config *config, uint8_t check_ocsp); 868``` 869 870**s2n_config_set_check_stapled_ocsp_response** toggles whether or not to validate stapled OCSP responses. 1 means OCSP responses 871will be validated when they are encountered, while 0 means this step will be skipped. The default value is 1 if the underlying 872libCrypto implementation supports OCSP. Returns 0 on success and -1 on failure. 873 874### s2n\_config\_disable\_x509\_verification 875 876```c 877int s2n_config_disable_x509_verification(struct s2n_config *config); 878``` 879 880**s2n_config_disable_x509_verification** turns off all X.509 validation during the negotiation phase of the connection. This should only be used 881for testing or debugging purposes. 882 883```c 884int s2n_config_set_max_cert_chain_depth(struct s2n_config *config, uint16_t max_depth); 885``` 886 887**s2n_config_set_max_cert_chain_depth** sets the maximum allowed depth of a cert chain used for X509 validation. The default value is 7. If this limit 888is exceeded, validation will fail if s2n_config_disable_x509_verification() has not been called. 0 is an illegal value and will return an error. 8891 means only a root certificate will be used. 890 891### s2n\_config\_set\_client\_hello\_cb 892 893```c 894int s2n_config_set_client_hello_cb(struct s2n_config *config, s2n_client_hello_fn client_hello_callback, void *ctx); 895``` 896 897**s2n_config_set_client_hello_cb** allows the caller to set a callback function 898that will be called after ClientHello was parsed. 899 900```c 901typedef int s2n_client_hello_fn(struct s2n_connection *conn, void *ctx); 902``` 903 904The callback function takes a s2n-tls connection as input, which receives the 905ClientHello and the context previously provided in **s2n_config_set_client_hello_cb**. 906The callback can access any ClientHello information from the connection and use 907the **s2n_connection_set_config** call to change the config of the connection. 908 909```c 910int s2n_config_set_client_hello_cb_mode(struct s2n_config *config, s2n_client_hello_cb_mode cb_mode); 911``` 912Sets the callback execution mode. 913 914The callback can be be invoked in two modes 915- **S2N_CLIENT_HELLO_CB_BLOCKING** (default): 916 917 In this mode s2n-tls expects the callback to complete its work 918 and return the appropriate response code before the handshake continues. 919 If any of the connection properties were changed based on the server_name 920 extension the callback must either return a value greater than 0 or invoke **s2n_connection_server_name_extension_used**, 921 otherwise the callback returns 0 to continue the handshake. 922 923- **S2N_CLIENT_HELLO_CB_NONBLOCKING**: 924 925 In non-blocking mode, s2n-tls expects the callback to not complete its work. If the callback 926 returns a response code of 0 s2n-tls will return **S2N_FAILURE** with **S2N_ERR_T_BLOCKED** 927 error type and **s2n_blocked_status** set to **S2N_BLOCKED_ON_APPLICATION_INPUT**. 928 The handshake is paused and further calls to **s2n_negotiate** will continue to return the 929 same error until **s2n_client_hello_cb_done** is invoked for the **s2n_connection** to resume 930 the handshake. This allows s2n-tls clients to process client_hello without 931 blocking and then resume the handshake at a later time. 932 If any of the connection properties were changed on the basis of the server_name extension then 933 **s2n_connection_server_name_extension_used** must be invoked before marking the callback done. 934 935The callback can return a negative value to make s2n-tls terminate the 936handshake early with a fatal handshake failure alert. 937 938```c 939int s2n_client_hello_cb_done(struct s2n_connection *conn) 940``` 941Marks the non-blocking callback as complete. 942Can be invoked from within the callback when operating in non-blocking mode 943to continue the handshake. 944 945```c 946int s2n_client_server_name_used(struct s2n_connection *conn) 947``` 948Indicates that connection properties were changed on the basis of server_name. 949Triggers a s2n-tls server to send the server_name extension. Must be called 950before s2n-tls finishes processing the ClientHello. 951 952### s2n\_config\_set\_alert\_behavior 953```c 954int s2n_config_set_alert_behavior(struct s2n_config *config, s2n_alert_behavior alert_behavior); 955``` 956Sets whether or not a connection should terminate on receiving a WARNING alert from its peer. `alert_behavior` can take the following values: 957- `S2N_ALERT_FAIL_ON_WARNINGS` - default behavior: s2n-tls will terminate the connection if its peer sends a WARNING alert. 958- `S2N_ALERT_IGNORE_WARNINGS` - with the exception of `close_notify` s2n-tls will ignore all WARNING alerts and keep communicating with its peer. 959 960This setting is ignored in TLS1.3. TLS1.3 terminates a connection for all alerts except user_canceled. 961 962### s2n\_config\_set\_async\_pkey\_validation\_mode 963```c 964int s2n_config_set_async_pkey_validation_mode(struct s2n_config *config, s2n_async_pkey_validation_mode mode); 965``` 966Sets whether or not a connection should enforce strict signature validation during the `s2n_async_pkey_op_apply` call. 967`mode` can take the following values: 968- `S2N_ASYNC_PKEY_VALIDATION_FAST` - default behavior: s2n-tls will perform only the minimum validation required for safe use of the asyn pkey operation. 969- `S2N_ASYNC_PKEY_VALIDATION_STRICT` - in addition to the previous checks, s2n-tls will also ensure that the signature created as a result of the async private key sign operation matches the public key on the connection. 970 971## Certificate-related functions 972 973### s2n\_cert\_chain\_and\_key\_new 974 975```c 976struct s2n_cert_chain_and_key *s2n_cert_chain_and_key_new(void); 977``` 978**s2n_cert_chain_and_key_new** returns a new object used to represent a certificate-chain/key pair. This object can be associated with many config objects. 979 980### s2n\_cert\_chain\_and\_key\_free 981 982```c 983int s2n_cert_chain_and_key_free(struct s2n_cert_chain_and_key *cert_and_key); 984``` 985**s2n_cert_chain_and_key_free** frees the memory associated with an **s2n_cert_chain_and_key** object. 986 987### s2n\_cert\_chain\_and\_key\_load\_pem 988 989```c 990int s2n_cert_chain_and_key_load_pem(struct s2n_cert_chain_and_key *chain_and_key, const char *chain_pem, const char *private_key_pem); 991``` 992 993**s2n_cert_chain_and_key_load_pem** associates a certificate chain and private key with an **s2n_cert_chain_and_key** object. 994 995**cert_chain_pem** should be a PEM encoded certificate chain, with the first 996certificate in the chain being your leaf certificate. **private_key_pem** 997should be a PEM encoded private key corresponding to the leaf certificate. 998 999### s2n\_cert\_chain\_and\_key\_load\_pem\_bytes 1000 1001```c 1002int s2n_cert_chain_and_key_load_pem_bytes(struct s2n_cert_chain_and_key *chain_and_key, uint8_t *chain_pem, uint32_t chain_pem_len, uint8_t *private_key_pem, uint32_t private_key_pem_len); 1003``` 1004 1005**s2n_cert_chain_and_key_load_pem_bytes** associates a certificate chain and private key with an **s2n_cert_chain_and_key** object. 1006 1007**chain_pem** should be a PEM encoded certificate chain, with the first certificate in the chain being your leaf certificate. 1008**chain_pem_len** is the length of the certificate chain. 1009**private_key_pem** should be a PEM encoded private key corresponding to the leaf certificate. 1010**private_key_pem_len** is the length of the private key. 1011 1012### s2n\_cert\_chain\_and\_key\_load\_public\_pem\_bytes 1013 1014```c 1015int s2n_cert_chain_and_key_load_public_pem_bytes(struct s2n_cert_chain_and_key *chain_and_key, uint8_t *chain_pem, uint32_t chain_pem_len); 1016``` 1017 1018**s2n_cert_chain_and_key_load_public_pem_bytes** associates a public certificate chain with a **s2n_cert_chain_and_key** object. It does NOT set a private key, so the connection will need to be configured to [offload private key operations](#offloading-asynchronous-private-key-operations). 1019 1020**chain_pem** should be a PEM encoded certificate chain, with the first certificate in the chain being your leaf certificate. 1021**chain_pem_len** is the length in bytes of the PEM encoded certificate chain. 1022 1023### s2n\_cert\_chain\_and\_key\_set\_ctx 1024 1025```c 1026int s2n_cert_chain_and_key_set_ctx(struct s2n_cert_chain_and_key *chain_and_key, void *ctx); 1027``` 1028 1029**s2n_cert_chain_and_key_set_ctx** associates an application defined context with a **s2n_cert_chain_and_key** object. 1030This is useful when multiple s2n_cert_chain_and_key objects are used and the application would like to associate unique data 1031with each certificate. 1032 1033### s2n\_cert\_chain\_and\_key\_get\_ctx 1034 1035```c 1036int s2n_cert_chain_and_key_get_ctx(struct s2n_cert_chain_and_key *chain_and_key); 1037``` 1038 1039**s2n_cert_chain_and_key_set_ctx** returns a previously set context pointer or NULL if no context was set. 1040 1041### s2n\_cert\_chain\_and\_key\_get\_key 1042 1043```c 1044extern s2n_cert_private_key *s2n_cert_chain_and_key_get_private_key(struct s2n_cert_chain_and_key *cert_and_key); 1045``` 1046 1047**s2n_cert_chain_and_key_get_private_key** returns a private key from 1048**s2n_cert_chain_and_key** object. 1049 1050## Client Auth Related calls 1051Client Auth Related API's are not recommended for normal users. Use of these API's is discouraged. 1052 10531. Using these API's requires users to: Complete full x509 parsing and hostname validation in the application layer 10542. Application knowledge of TLS code points for certificate types 10553. Application dependency on libcrypto to give a libcrypto RSA struct back to s2n-tls 1056 1057### s2n\_config\_set\_client\_auth\_type and s2n\_connection\_set\_client\_auth\_type 1058```c 1059int s2n_config_set_client_auth_type(struct s2n_config *config, s2n_cert_auth_type cert_auth_type); 1060int s2n_connection_set_client_auth_type(struct s2n_connection *conn, s2n_cert_auth_type cert_auth_type); 1061``` 1062Sets whether or not a Client Certificate should be required to complete the TLS Connection. If this is set to 1063**S2N_CERT_AUTH_OPTIONAL** the server will request a client certificate but allow the client to not provide one. 1064Rejecting a client certificate when using **S2N_CERT_AUTH_OPTIONAL** will terminate the handshake. 1065 1066### Public Key API's 1067```c 1068int s2n_rsa_public_key_set_from_openssl(struct s2n_rsa_public_key *s2n_rsa, RSA *openssl_rsa); 1069int s2n_cert_public_key_set_cert_type(struct s2n_cert_public_key *cert_pub_key, s2n_cert_type cert_type); 1070int s2n_cert_public_key_get_rsa(struct s2n_cert_public_key *cert_pub_key, struct s2n_rsa_public_key **rsa); 1071int s2n_cert_public_key_set_rsa(struct s2n_cert_public_key *cert_pub_key, struct s2n_rsa_public_key rsa); 1072``` 1073**s2n_rsa_public_key** and **s2n_cert_public_key** are opaque structs. These API's are intended to be used by Implementations of **verify_cert_trust_chain_fn** to 1074set the public keys found in the Certificate into **public_key_out**. 1075 1076## Session Caching related calls 1077 1078s2n-tls includes support for resuming from cached SSL/TLS session, provided 1079the caller sets (and implements) three callback functions. 1080 1081### s2n\_config\_set\_cache\_store\_callback 1082 1083```c 1084int s2n_config_set_cache_store_callback(struct s2n_config *config, int 1085 (*cache_store_callback)(struct s2n_connection *conn, void *, uint64_t ttl_in_seconds, const void *key, uint64_t key_size, const void *value, uint64_t value_size), void *data); 1086``` 1087 1088**s2n_config_set_cache_store_callback** allows the caller to set a callback 1089function that will be used to store SSL session data in a cache. The callback 1090function takes seven arguments: a pointer to the s2n_connection object, 1091a pointer to abitrary data for use within the callback, a 64-bit unsigned integer 1092specifying the number of seconds the session data may be stored for, a pointer 1093to a key which can be used to retrieve the cached entry, a 64 bit unsigned 1094integer specifying the size of this key, a pointer to a value which should be stored, 1095and a 64 bit unsigned integer specified the size of this value. 1096 1097### s2n\_config\_set\_cache\_retrieve\_callback 1098 1099```c 1100int s2n_config_set_cache_retrieve_callback(struct s2n_config *config, int 1101 (*cache_retrieve_callback)(struct s2n_connection *conn, void *, const void *key, uint64_t key_size, void *value, uint64_t *value_size), void *data) 1102``` 1103 1104**s2n_config_set_cache_retrieve_callback** allows the caller to set a callback 1105function that will be used to retrieve SSL session data from a cache. The 1106callback function takes six arguments: a pointer to the s2n_connection object, 1107a pointer to abitrary data for use within the callback, a pointer to a key which 1108can be used to retrieve the cached entry, a 64 bit unsigned integer specifying 1109the size of this key, a pointer to a memory location where the value should be stored, 1110and a pointer to a 64 bit unsigned integer specifing the size of this value. 1111Initially *value_size will be set to the amount of space allocated for 1112the value, the callback should set *value_size to the actual size of the 1113data returned. If there is insufficient space, -1 should be returned. 1114 1115If the cache is not ready to provide data for the request, S2N_CALLBACK_BLOCKED should be returned. 1116This will cause s2n_negotiate() to return S2N_BLOCKED_ON_APPLICATION_INPUT. 1117 1118### s2n\_config\_set\_cache\_delete\_callback 1119 1120```c 1121int s2n_config_set_cache_delete_callback(struct s2n_config *config, int 1122 (*cache_delete_callback))(struct s2n_connection *conn, void *, const void *key, uint64_t key_size), void *data); 1123``` 1124 1125**s2n_config_set_cache_delete_callback** allows the caller to set a callback 1126function that will be used to delete SSL session data from a cache. The 1127callback function takes four arguments: a pointer to s2n_connection object, 1128a pointer to abitrary data for use within the callback, a pointer to a key 1129which can be used to delete the cached entry, and a 64 bit unsigned integer 1130specifying the size of this key. 1131 1132### s2n\_config\_send\_max\_fragment\_length 1133 1134```c 1135int s2n_config_send_max_fragment_length(struct s2n_config *config, uint8_t mfl_code); 1136``` 1137 1138**s2n_config_send_max_fragment_length** allows the caller to set a TLS Maximum 1139Fragment Length extension that will be used to fragment outgoing messages. 1140s2n-tls currently does not reject fragments larger than the configured maximum when 1141in server mode. The TLS negotiated maximum fragment length overrides the preference set 1142by the **s2n_connection_prefer_throughput** and **s2n_connection_prefer_low_latency**. 1143 1144### s2n\_config\_accept\_max\_fragment\_length 1145 1146```c 1147int s2n_config_accept_max_fragment_length(struct s2n_config *config); 1148``` 1149 1150**s2n_config_accept_max_fragment_length** allows the server to opt-in to accept 1151client's TLS maximum fragment length extension requests. 1152If this API is not called, and client requests the extension, server will ignore the 1153request and continue TLS handshake with default maximum fragment length of 8k bytes 1154## Connection-oriented functions 1155 1156### s2n\_connection\_new 1157 1158```c 1159struct s2n_connection * s2n_connection_new(s2n_mode mode); 1160``` 1161 1162**s2n_connection_new** creates a new connection object. Each s2n-tls SSL/TLS 1163connection uses one of these objects. These connection objects can be operated 1164on by up to two threads at a time, one sender and one receiver, but neither 1165sending nor receiving are atomic, so if these objects are being called by 1166multiple sender or receiver threads, you must perform your own locking to 1167ensure that only one sender or receiver is active at a time. The **mode** 1168parameters specifies if the caller is a server, or is a client. 1169 1170Connections objects are re-usable across many connections, and should be 1171re-used (to avoid deallocating and allocating memory). You should wipe 1172connections immediately after use. 1173 1174### s2n\_connection\_set\_config 1175 1176```c 1177int s2n_connection_set_config(struct s2n_connection *conn, 1178 struct s2n_config *config); 1179``` 1180 1181**s2n_connection_set_config** Associates a configuration object with a 1182connection. 1183 1184### s2n\_connection\_set\_ctx 1185 1186```c 1187int s2n_connection_set_ctx(struct s2n_connection *conn, void *ctx); 1188``` 1189 1190**s2n_connection_set_ctx** sets user defined context in **s2n_connection** 1191object. 1192 1193### s2n\_connection\_get\_ctx 1194 1195```c 1196void *s2n_connection_get_ctx(struct s2n_connection *conn); 1197``` 1198 1199**s2n_connection_get_ctx** gets user defined context from **s2n_connection** 1200object. 1201 1202### s2n\_connection\_set\_fd 1203 1204```c 1205int s2n_connection_set_fd(struct s2n_connection *conn, 1206 int readfd); 1207int s2n_connection_set_read_fd(struct s2n_connection *conn, 1208 int readfd); 1209int s2n_connection_set_write_fd(struct s2n_connection *conn, 1210 int writefd); 1211``` 1212 1213**s2n_connection_set_fd** sets the file-descriptor for an s2n-tls connection. This 1214file-descriptor should be active and connected. s2n-tls also supports setting the 1215read and write file-descriptors to different values (for pipes or other unusual 1216types of I/O). 1217 1218**Important Note:** 1219If the read end of the pipe is closed unexpectedly, writing to the pipe will raise 1220a SIGPIPE signal. **s2n-tls does NOT handle SIGPIPE.** A SIGPIPE signal will cause 1221the process to terminate unless it is handled or ignored by the application. 1222 1223### s2n\_connection\_is\_valid\_for\_cipher\_preferences 1224 1225```c 1226int s2n_connection_is_valid_for_cipher_preferences(struct s2n_connection *conn, const char *version); 1227``` 1228 1229**s2n_connection_is_valid_for_cipher_preferences** checks if the cipher used by current connection 1230is supported by a given cipher preferences. It returns 1231- 1 if the connection satisfies the cipher suite 1232- 0 if it does not 1233- -1 on any other errors 1234 1235 1236### s2n\_connection\_set\_cipher\_preferences 1237 1238```c 1239int s2n_connection_set_cipher_preferences(struct s2n_connection *conn, const char *version); 1240``` 1241 1242**s2n_connection_set_cipher_preferences** sets the cipher preference override for the 1243s2n_connection. Calling this function is not necessary unless you want to set the 1244cipher preferences on the connection to something different than what is in the s2n_config. 1245 1246 1247### s2n\_connection\_set\_protocol\_preferences 1248 1249```c 1250int s2n_connection_set_protocol_preferences(struct s2n_connection *conn, const char * const *protocols, int protocol_count); 1251``` 1252 1253**s2n_connection_set_protocol_preferences** sets the protocol preference override for the 1254s2n_connection. Calling this function is not necessary unless you want to set the 1255protocol preferences on the connection to something different than what is in the s2n_config. 1256 1257### s2n\_set\_server\_name 1258 1259```c 1260int s2n_set_server_name(struct s2n_connection *conn, 1261 const char *server_name); 1262``` 1263 1264**s2n_set_server_name** Sets the server name for the connection. In future, 1265this can be used by clients who wish to use the TLS "Server Name indicator" 1266extension. At present, client functionality is disabled. 1267 1268### s2n\_get\_server\_name 1269 1270```c 1271const char *s2n_get_server_name(struct s2n_connection *conn); 1272``` 1273 1274**s2n_get_server_name** returns the server name associated with a connection, 1275or NULL if none is found. This can be used by a server to determine which server 1276name the client is using. This function returns the first ServerName entry in the ServerNameList 1277sent by the client. Subsequent entries are not returned. 1278 1279### s2n\_connection\_set\_blinding 1280 1281```c 1282int s2n_connection_set_blinding(struct s2n_connection *conn, s2n_blinding blinding); 1283``` 1284 1285**s2n_connection_set_blinding** can be used to configure s2n-tls to either use 1286built-in blinding (set blinding to S2N_BUILT_IN_BLINDING) or self-service blinding 1287(set blinding to S2N_SELF_SERVICE_BLINDING). 1288 1289### s2n\_connection\_get\_delay 1290 1291```c 1292uint64_t s2n_connection_get_delay(struct s2n_connection *conn); 1293``` 1294 1295**s2n_connection_get_delay** returns the number of nanoseconds an application 1296using self-service blinding should pause before calling close() or shutdown(). 1297 1298### s2n\_connection\_prefer\_throughput(struct s2n_connection *conn) 1299 1300```c 1301int s2n_connection_prefer_throughput(struct s2n_connection *conn); 1302int s2n_connection_prefer_low_latency(struct s2n_connection *conn); 1303int s2n_connection_set_dynamic_record_threshold(struct s2n_connection *conn, uint32_t resize_threshold, uint16_t timeout_threshold); 1304``` 1305 1306**s2n_connection_prefer_throughput** and **s2n_connection_prefer_low_latency** 1307change the behavior of s2n-tls when sending data to prefer either throughput 1308or low latency. Connections preferring low latency will be encrypted using small 1309record sizes that can be decrypted sooner by the recipient. Connections 1310preferring throughput will use large record sizes that minimize overhead. 1311 1312-Connections default to an 8k outgoing maximum 1313 1314**s2n_connection_set_dynamic_record_threshold** 1315provides a smooth transition from **s2n_connection_prefer_low_latency** to **s2n_connection_prefer_throughput**. 1316**s2n_send** uses small TLS records that fit into a single TCP segment for the resize_threshold bytes (cap to 8M) of data 1317and reset record size back to a single segment after timeout_threshold seconds of inactivity. 1318 1319### s2n\_connection\_get\_wire\_bytes 1320 1321```c 1322uint64_t s2n_connection_get_wire_bytes_in(struct s2n_connection *conn); 1323uint64_t s2n_connection_get_wire_bytes_out(struct s2n_connection *conn); 1324``` 1325 1326**s2n_connection_get_wire_bytes_in** and **s2n_connection_get_wire_bytes_out** 1327return the number of bytes transmitted by s2n-tls "on the wire", in and out 1328respectively. 1329 1330### s2n\_connection\_get\_protocol\_version 1331 1332```c 1333int s2n_connection_get_client_hello_version(struct s2n_connection *conn); 1334int s2n_connection_get_client_protocol_version(struct s2n_connection *conn); 1335int s2n_connection_get_server_protocol_version(struct s2n_connection *conn); 1336int s2n_connection_get_actual_protocol_version(struct s2n_connection *conn); 1337``` 1338 1339**s2n_connection_get_client_protocol_version** returns the protocol version 1340number supported by the client, **s2n_connection_get_server_protocol_version** 1341returns the protocol version number supported by the server and 1342**s2n_connection_get_actual_protocol_version** returns the protocol version 1343number actually used by s2n-tls for the connection. **s2n_connection_get_client_hello_version** 1344returns the protocol version used to send the initial client hello message. 1345 1346Each version number value corresponds to the macros defined as **S2N_SSLv2**, 1347**S2N_SSLv3**, **S2N_TLS10**, **S2N_TLS11**, **S2N_TLS12**, and **S2N_TLS13**. 1348 1349### s2n\_connection\_set\_verify\_host\_callback 1350```c 1351int s2n_connection_set_verify_host_callback(struct s2n_connection *config, s2n_verify_host_fn host_fn, void *data); 1352``` 1353Every connection inherits the value of **s2n_verify_host_fn** from it's instance of **s2n_config**. 1354Since a configuration can (and should) be used for multiple connections, it may be useful to override 1355this value on a per connection basis. For example, this may be based on a host header from an http request. In that case, 1356calling this function will override the value inherited from the configuration. 1357See [s2n_verify_host_fn](#s2n_verify_host_fn) for details. 1358 1359### s2n\_connection\_get\_client\_hello 1360 1361```c 1362struct s2n_client_hello *s2n_connection_get_client_hello(struct s2n_connection *conn); 1363``` 1364For a given s2n_connection, **s2n_connection_get_client_hello** returns a handle 1365to the s2n_client_hello structure holding the client hello message sent by the client during the handshake. 1366NULL is returned if the connection has not yet received and parsed the client hello. 1367Earliest point during the handshake when this structure is available for use is in the client_hello_callback (see **s2n_config_set_client_hello_cb**). 1368 1369### s2n\_client\_hello\_get\_raw\_message 1370 1371```c 1372ssize_t s2n_client_hello_get_raw_message_length(struct s2n_client_hello *ch); 1373ssize_t s2n_client_hello_get_raw_message(struct s2n_client_hello *ch, uint8_t *out, uint32_t max_length); 1374``` 1375 1376- **ch** The s2n_client_hello on the s2n_connection. The handle can be obtained using **s2n_connection_get_client_hello**. 1377- **out** Pointer to a buffer into which the raw client hello bytes should be copied. 1378- **max_length** Max number of bytes to copy into the **out** buffer. 1379 1380**s2n_client_hello_get_raw_message_length** returns the size of the ClientHello message received by the server; it can be used to allocate the **out** buffer. 1381**s2n_client_hello_get_raw_message** copies **max_length** bytes of the ClientHello message into the **out** buffer and returns the number of copied bytes. 1382The ClientHello instrumented using this function will have the Random bytes zero-ed out. 1383 1384For SSLv2 ClientHello messages, the raw message contains only the cipher_specs, session_id and members portions of the hello message 1385(see [RFC5246](https://tools.ietf.org/html/rfc5246#appendix-E.2)). To access other members, you may use the 1386**s2n_connection_get_client_hello_version**, **s2n_connection_get_client_protocol_version** and **s2n_connection_get_session_id_length** accesor functions. 1387 1388### s2n\_client\_hello\_get\_cipher\_suites 1389 1390```c 1391ssize_t s2n_client_hello_get_cipher_suites_length(struct s2n_client_hello *ch); 1392ssize_t s2n_client_hello_get_cipher_suites(struct s2n_client_hello *ch, uint8_t *out, uint32_t max_length); 1393``` 1394 1395- **ch** The s2n_client_hello on the s2n_connection. The handle can be obtained using **s2n_connection_get_client_hello**. 1396- **out** Pointer to a buffer into which the cipher_suites bytes should be copied. 1397- **max_length** Max number of bytes to copy into the **out** buffer. 1398 1399**s2n_client_hello_get_cipher_suites_length** returns the number of bytes the cipher_suites takes on the ClientHello message received by the server; it can be used to allocate the **out** buffer. 1400**s2n_client_hello_get_cipher_suites** copies into the **out** buffer **max_length** bytes of the cipher_suites on the ClientHello and returns the number of copied bytes. 1401 1402### s2n\_client\_hello\_get\_extensions 1403 1404```c 1405ssize_t s2n_client_hello_get_extensions_length(struct s2n_client_hello *ch); 1406ssize_t s2n_client_hello_get_extensions(struct s2n_client_hello *ch, uint8_t *out, uint32_t max_length); 1407``` 1408 1409- **ch** The s2n_client_hello on the s2n_connection. The handle can be obtained using **s2n_connection_get_client_hello**. 1410- **out** Pointer to a buffer into which the cipher_suites bytes should be copied. 1411- **max_length** Max number of bytes to copy into the **out** buffer. 1412 1413**s2n_client_hello_get_extensions_length** returns the number of bytes the extensions take on the ClientHello message received by the server; it can be used to allocate the **out** buffer. 1414**s2n_client_hello_get_extensions** copies into the **out** buffer **max_length** bytes of the extensions on the ClientHello and returns the number of copied bytes. 1415 1416### s2n\_client\_hello\_get\_extension 1417 1418```c 1419ssize_t s2n_client_hello_get_extension_length(struct s2n_client_hello *ch, s2n_tls_extension_type extension_type); 1420ssize_t s2n_client_hello_get_extension_by_id(struct s2n_client_hello *ch, s2n_tls_extension_type extension_type, uint8_t *out, uint32_t max_length); 1421``` 1422 1423- **ch** The s2n_client_hello on the s2n_connection. The handle can be obtained using **s2n_connection_get_client_hello**. 1424- **s2n_tls_extension_type** Enum [s2n_tls_extension_type](#s2n\_config\_set\_extension\_data) lists all supported extension types. 1425- **out** Pointer to a buffer into which the extension bytes should be copied. 1426- **max_length** Max number of bytes to copy into the **out** buffer. 1427 1428**s2n_client_hello_get_extension_length** returns the number of bytes the given extension type takes on the ClientHello message received by the server; it can be used to allocate the **out** buffer. 1429**s2n_client_hello_get_extension_by_id** copies into the **out** buffer **max_length** bytes of a given extension type on the ClientHello and returns the number of copied bytes. 1430 1431### s2n\_client\_hello\_get\_session\_id 1432 1433```c 1434int s2n_client_hello_get_session_id_length(struct s2n_client_hello *ch, uint32_t *out_length); 1435int s2n_client_hello_get_session_id(struct s2n_client_hello *ch, uint8_t *out, uint32_t *out_length, uint32_t max_length); 1436``` 1437 1438These functions retrieve the session id as sent by the client in the ClientHello message. The session id on the **s2n_connection** may change later when the server sends the ServerHello; see **s2n_connection_get_session_id** for how to get the final session id used for future session resumption. 1439 1440**s2n_client_hello_get_session_id_length** stores the ClientHello session id length in bytes in **out_length**. The **ch** is a pointer to **s2n_client_hello** of the **s2n_connection** which can be obtained using **s2n_connection_get_client_hello**. The **out_length** can be used to allocate the **out** buffer for the **s2n_client_hello_get_session_id** call. 1441 1442**s2n_client_hello_get_session_id** copies up to **max_length** bytes of the ClientHello session_id into the **out** buffer and stores the number of copied bytes in **out_length**. 1443 1444### s2n\_connection\_client\_cert\_used 1445 1446```c 1447int s2n_connection_client_cert_used(struct s2n_connection *conn); 1448``` 1449**s2n_connection_client_cert_used** returns 1 if the handshake completed and Client Auth was 1450negotiated during the handshake. 1451 1452### s2n\_get\_application\_protocol 1453 1454```c 1455const char *s2n_get_application_protocol(struct s2n_connection *conn); 1456``` 1457 1458**s2n_get_application_protocol** returns the negotiated application protocol 1459for a **s2n_connection**. In the event of no protocol being negotiated, NULL 1460is returned. 1461 1462### s2n\_connection\_get\_ocsp\_response 1463 1464```c 1465const uint8_t *s2n_connection_get_ocsp_response(struct s2n_connection *conn, uint32_t *length); 1466``` 1467 1468**s2n_connection_get_ocsp_response** returns the OCSP response sent by a server 1469during the handshake. If no status response is received, NULL is returned. 1470 1471### s2n\_connection\_is\_ocsp\_stapled 1472 1473```c 1474int s2n_connection_is_ocsp_stapled(struct s2n_connection *conn); 1475``` 1476 1477**s2n_connection_is_ocsp_stapled** returns 1 if OCSP response was sent (if connection is in S2N_SERVER mode) or received (if connection is in S2N_CLIENT mode) during handshake, otherwise it returns 0. 1478 1479### s2n\_connection\_get\_handshake\_type\_name 1480 1481```c 1482const char *s2n_connection_get_handshake_type_name(struct s2n_connection *conn); 1483``` 1484 1485**s2n_connection_get_handshake_type_name** returns a human-readable handshake type name, e.g. "NEGOTIATED|FULL_HANDSHAKE|PERFECT_FORWARD_SECRECY" 1486 1487### s2n\_connection\_get\_last\_message\_name 1488 1489```c 1490const char *s2n_connection_get_last_message_name(struct s2n_connection *conn); 1491``` 1492 1493**s2n_connection_get_last_message_name** returns the last message name in TLS state machine, e.g. "SERVER_HELLO", "APPLICATION_DATA". 1494 1495### s2n\_connection\_get\_alert 1496 1497```c 1498int s2n_connection_get_alert(struct s2n_connection *conn); 1499``` 1500 1501If a connection was shut down by the peer, **s2n_connection_get_alert** returns 1502the TLS alert code that caused a connection to be shut down. s2n-tls considers all 1503TLS alerts fatal and shuts down a connection whenever one is received. 1504 1505### s2n\_connection\_get\_cipher 1506 1507```c 1508const char * s2n_connection_get_cipher(struct s2n_connection *conn); 1509``` 1510 1511**s2n_connection_get_cipher** returns a string indicating the cipher suite 1512negotiated by s2n-tls for a connection in Openssl format, e.g. "ECDHE-RSA-AES128-GCM-SHA256". 1513 1514### s2n\_connection\_get\_curve 1515 1516```c 1517const char * s2n_connection_get_curve(struct s2n_connection *conn); 1518``` 1519 1520**s2n_connection_get_curve** returns a string indicating the elliptic curve used during ECDHE key exchange. The string "NONE" is returned if no curve was used. 1521 1522### s2n\_connection\_get\_selected\_cert 1523 1524```c 1525struct s2n_cert_chain_and_key s2n_connection_get_selected_cert(struct s2n_connection *conn); 1526``` 1527 1528Return the certificate that was used during the TLS handshake. 1529 1530- If **conn** is a server connection, the certificate selected will depend on the 1531 ServerName sent by the client and supported ciphers. 1532- If **conn** is a client connection, the certificate sent in response to a CertificateRequest 1533 message is returned. Currently s2n-tls supports loading only one certificate in client mode. Note that 1534 not all TLS endpoints will request a certificate. 1535 1536This function returns NULL if the certificate selection phase of the handshake has not completed 1537 or if a certificate was not requested by the peer. 1538 1539### s2n\_cert\_chain\_get\_length 1540 1541```c 1542int s2n_cert_chain_get_length(const struct s2n_cert_chain_and_key *chain_and_key, uint32_t *cert_length); 1543``` 1544 1545**s2n_cert_chain_get_length** gets the length of the certificate chain `chain_and_key`. If the certificate chain `chain_and_key` is NULL an error is thrown. 1546 1547### s2n\_cert\_chain\_get\_cert 1548 1549```c 1550int s2n_cert_chain_get_cert(const struct s2n_cert_chain_and_key *chain_and_key, struct s2n_cert **out_cert, const uint32_t cert_idx); 1551``` 1552 1553**s2n_cert_chain_get_cert** gets the certificate `out_cert` present at the index `cert_idx` of the certificate chain `chain_and_key`. If the certificate chain `chain_and_key` is NULL or the certificate index value is not in the acceptable range for the input certificate chain, an error is thrown. Note that the index of the head_cert is zero. 1554 1555### s2n\_cert\_get\_der 1556 1557```c 1558int s2n_cert_get_der(const struct s2n_cert *cert, const uint8_t **out_cert_der, uint32_t *cert_length); 1559``` 1560 1561**s2n_cert_get_der** gets the certificate `cert` in .der format which is returned in the buffer `out_cert_der`, `cert_len` represents the length of the certificate. 1562 1563### s2n\_connection\_get_peer\_cert\_chain 1564 1565```c 1566int s2n_connection_get_peer_cert_chain(const struct s2n_connection *conn, struct s2n_cert_chain_and_key *s2n_cert_chain_and_key); 1567``` 1568 1569**s2n_connection_get_peer_cert_chain** gets the validated peer certificate chain from the s2n connection object. 1570 1571### s2n\_cert\_get\_x509\_extension\_value\_length 1572 1573```c 1574int s2n_cert_get_x509_extension_value_length(struct s2n_cert *cert, const uint8_t *oid, uint32_t ext_value_len); 1575``` 1576 1577**s2n_cert_get_x509_extension_value_length** gets the length of the DER encoding of an ASN.1 X.509 certificate extension value. 1578 1579 1580### s2n\_cert\_get\_x509\_extension\_value 1581 1582```c 1583int s2n_cert_get_x509_extension_value(struct s2n_cert *cert, const uint8_t *oid, uint8_t *ext_value, uint32_t *ext_value_len, bool *critical); 1584``` 1585 1586**s2n_cert_get_x509_extension_value** gets the DER encoding of an ASN.1 X.509 certificate extension value, it's length and a boolean critical. 1587 1588 1589### s2n\_cert\_get\_utf8\_string\_from\_extension\_data\_length 1590 1591```c 1592int s2n_cert_get_utf8_string_from_extension_data_length(const uint8_t *extension_data, uint32_t extension_len, uint32_t *utf8_str_len); 1593``` 1594 1595**s2n_cert_get_utf8_string_from_extension_data** gets the UTF8 String length of the ASN.1 X.509 certificate extension data. 1596 1597### s2n\_cert\_get\_utf8\_string\_from\_extension\_data 1598 1599```c 1600int s2n_cert_get_utf8_string_from_extension_data(const uint8_t *extension_data, uint32_t extension_len, uint8_t *out_data, uint32_t *out_len); 1601``` 1602 1603**s2n_cert_get_utf8_string_from_extension_data** gets the UTF8 String representation of the DER encoded ASN.1 X.509 certificate extension data. 1604 1605### Session Resumption Related calls 1606 1607```c 1608int s2n_config_set_session_state_lifetime(struct s2n_config *config, uint32_t lifetime_in_secs); 1609 1610int s2n_connection_set_session(struct s2n_connection *conn, const uint8_t *session, size_t length); 1611int s2n_connection_get_session(struct s2n_connection *conn, uint8_t *session, size_t max_length); 1612int s2n_connection_get_session_ticket_lifetime_hint(struct s2n_connection *conn); 1613int s2n_connection_get_session_length(struct s2n_connection *conn); 1614int s2n_connection_get_session_id_length(struct s2n_connection *conn); 1615int s2n_connection_get_session_id(struct s2n_connection *conn, uint8_t *session_id, size_t max_length); 1616int s2n_connection_is_session_resumed(struct s2n_connection *conn); 1617``` 1618 1619- **lifetime_in_secs** lifetime of the cached session state required to resume a 1620handshake. 1621- **session** session will contain serialized session related information needed to resume handshake either using session id or session ticket. 1622- **length** length of the serialized session state. 1623- **max_length** Max number of bytes to copy into the **session** buffer. 1624 1625**s2n_config_set_session_state_lifetime** sets the lifetime of the cached session state. The default value is 15 hours. 1626 1627**s2n_connection_set_session** de-serializes the session state and updates the connection accordingly. Note that s2n-tls session tickets are versioned and this function will error if it receives a ticket version it doesn't understand. Therefore users need to handle errors for this function in case the inputted ticket is an unrecognized version, which could occur during a long deployment. 1628 1629**s2n_connection_get_session** serializes the session state from connection and copies into the **session** buffer and returns the number of copied bytes. The output of this function depends on whether session ids or session tickets are being used for resumption. 1630 1631If the first byte in **session** is 1, then the next 2 bytes will contain the session ticket length, followed by session ticket and session state. In versions TLS1.3 and greater, (which allows multiple session tickets), the most recent session ticket received will be used. Note that the size of the session tickets varies. 1632 1633If the first byte in **session** is 0, then the next byte will contain session id length, followed by session id and session state. 1634 1635**s2n_connection_get_session_ticket_lifetime_hint** returns the session ticket lifetime hint in seconds from the server or -1 when session ticket was not used for resumption. 1636 1637**s2n_connection_get_session_length** returns number of bytes needed to store serialized session state; it can be used to allocate the **session** buffer. 1638 1639**s2n_connection_get_session_id_length** returns the latest session id length from the connection. Session id length will be 0 for TLS versions >= TLS1.3 as stateful session resumption has not yet been implemented in TLS1.3. 1640 1641**s2n_connection_get_session_id** gets the latest session id from the connection, copies it into the **session_id** buffer, and returns the number of copied bytes. The session id may change between s2n receiving the ClientHello and sending the ServerHello, but this function will always describe the latest session id. See **s2n_client_hello_get_session_id** to get the session id as it was sent by the client in the ClientHello message. 1642 1643**s2n_connection_is_session_resumed** returns 1 if the handshake was abbreviated, otherwise returns 0. 1644 1645## TLS1.3 Session Resumption Related Calls 1646 1647Session resumption works differently in versions TLS1.3 and higher. While some of the TLS1.2 session resumption APIs have relevance for TLS1.3 session resumption, you need additional APIs to utilize all the capabilities of TLS1.3 session resumption. Session ticket messages are now sent immediately after the handshake in "post-handshake" messages, although more tickets can be sent and received anytime after the handshake has completed. Additionally, multiple session tickets may be issued for the same connection. 1648 1649Clients need to call s2n_recv after negotiating to receive session ticket messages, as these could arrive anytime post-handshake. 1650 1651```c 1652int s2n_config_set_initial_ticket_count(struct s2n_config *config, uint8_t num); 1653int s2n_connection_add_new_tickets_to_send(struct s2n_connection *conn, uint8_t num); 1654int s2n_connection_set_server_keying_material_lifetime(struct s2n_connection *conn, uint32_t lifetime_in_secs); 1655 1656typedef int (*s2n_session_ticket_fn)(struct s2n_connection *conn, void *ctx, struct s2n_session_ticket *ticket); 1657int s2n_config_set_session_ticket_cb(struct s2n_config *config, s2n_session_ticket_fn callback, void *ctx); 1658int s2n_session_ticket_get_data_len(struct s2n_session_ticket *ticket, size_t *data_len); 1659int s2n_session_ticket_get_data(struct s2n_session_ticket *ticket, size_t max_data_len, uint8_t *data); 1660int s2n_session_ticket_get_lifetime(struct s2n_session_ticket *ticket, uint32_t *session_lifetime); 1661``` 1662 1663**s2n_config_set_initial_ticket_count** sets the initial number of session tickets the server will send. The default value is one ticket. 1664 1665**s2n_connection_add_new_tickets_to_send** increases the number of session tickets to send by **num**. If this function is called after the handshake, a server should call s2n_send to send the additional session tickets, as they do not automatically get sent. 1666 1667**s2n_connection_set_server_keying_material_lifetime** sets the keying material lifetime for session tickets. Use this to ensure session tickets don't get reissued past the lifetime of the certificate used to authenticate the original full handshake. The default lifetime is one week. 1668 1669**s2n_session_ticket_fn** is invoked whenever a client receives a session ticket. Use this callback in conjunction with the **s2n_session_ticket** getters to get the serialized ticket data and related information. A **ctx** pointer is provided to let a user pass state to the callback, if needed. Be careful if the implemented callback is expensive or allocates a lot of memory, as the server can send many session tickets. 1670 1671**s2n_config_set_session_ticket_cb** sets the session ticket callback function to be invoked whenever the client receives 1672a session ticket from the server. 1673 1674**s2n_session_ticket_get_data_len** takes a s2n_session_ticket object and retrieves the number of bytes needed to store the session ticket. Use this to allocate enough memory for the session ticket in **s2n_session_ticket_get_data**. 1675 1676**s2n_session_ticket_get_data** takes a s2n_session_ticket object and copies the serialized session ticket data into the 1677**data** buffer. For this reason **max_data_len** must be set to the maximum amount of bytes that can be copied into 1678the **data** buffer. 1679 1680**s2n_session_ticket_get_lifetime** takes a s2n_session_ticket object and retrieves the lifetime of the ticket in seconds. 1681 1682### Session Ticket Specific calls 1683 1684```c 1685int s2n_config_set_session_tickets_onoff(struct s2n_config *config, uint8_t enabled); 1686int s2n_config_set_ticket_encrypt_decrypt_key_lifetime(struct s2n_config *config, uint64_t lifetime_in_secs); 1687int s2n_config_set_ticket_decrypt_key_lifetime(struct s2n_config *config, uint64_t lifetime_in_secs); 1688int s2n_config_add_ticket_crypto_key(struct s2n_config *config, const uint8_t *name, uint32_t name_len, uint8_t *key, uint32_t key_len, uint64_t intro_time_in_seconds_from_epoch); 1689``` 1690 1691- **enabled** when set to 0 will disable session resumption using session ticket 1692- **name** name of the session ticket key that should be randomly generated to avoid collisions 1693- **name_len** length of session ticket key name 1694- **key** key used to perform encryption/decryption of session ticket 1695- **key_len** length of the session ticket key 1696- **intro_time_in_seconds_from_epoch** time at which the session ticket key is introduced. If this is 0, then intro_time_in_seconds_from_epoch is set to now. 1697 1698**s2n_config_set_session_tickets_onoff** enables and disables session resumption using session ticket 1699 1700**s2n_config_set_ticket_encrypt_decrypt_key_lifetime** sets how long a session ticket key will be in a state where it can be used for both encryption and decryption of tickets on the server side. The default value is 2 hours. 1701 1702**s2n_config_set_ticket_decrypt_key_lifetime** sets how long a session ticket key will be in a state where it can used just for decryption of already assigned tickets on the server side. Once decrypted, the session will resume and the server will issue a new session ticket encrypted using a key in encrypt-decrypt state. The default value is 13 hours. 1703 1704**s2n_config_add_ticket_crypto_key** adds session ticket key on the server side. It would be ideal to add new keys after every (encrypt_decrypt_key_lifetime_in_nanos/2) nanos because 1705this will allow for gradual and linear transition of a key from encrypt-decrypt state to decrypt-only state. 1706 1707### Asynchronous private key operations related calls 1708 1709When s2n-tls is used in non-blocking mode, this set of functions allows user 1710to move execution of CPU-heavy private key operations out of the main 1711event loop, preventing **s2n_negotiate** blocking the loop for a few 1712milliseconds each time the private key operation needs to be performed. 1713 1714To enable asynchronous private key operations user needs to provide a 1715callback function **s2n_async_pkey_fn** to 1716**s2n_config_set_async_pkey_callback** call. This function will be 1717executed during **s2n_negotiate** call every time an operation on private 1718key needs to be performed. The argument **op** represents the operation 1719to perform. From the callback the user can spawn the thread to perform 1720**op** through **s2n_async_pkey_op_perform** call and immediately return 1721**S2N_SUCCESS** from the function without waiting for thread to complete. 1722The **s2n_negotiate** will return **S2N_FAILURE** with **S2N_ERR_T_BLOCKED** 1723error type and **s2n_blocked_status** **S2N_BLOCKED_ON_APPLICATION_INPUT**, 1724and will keep giving the same error until the **op** is performed and 1725applied to the connection through **s2n_async_pkey_op_apply** call. 1726 1727Note, it is not safe to call multiple functions on the same **conn** or 1728**op** objects from 2 different threads at the same time. Doing so will 1729produce undefined behavior. However it is safe to have a call to 1730function involving only **conn** at the same time with a call to 1731function involving only **op**, as those 2 objects are not coupled with 1732each other. It is also safe to free **conn** or **op** at any moment with 1733respective function calls, with the only exception that **conn** cannot 1734be freed inside the **s2n_async_pkey_fn** callback. 1735 1736```c 1737typedef int (*s2n_async_pkey_fn)(struct s2n_connection *conn, struct s2n_async_pkey_op *op); 1738extern int s2n_config_set_async_pkey_callback(struct s2n_config *config, s2n_async_pkey_fn fn); 1739extern int s2n_async_pkey_op_perform(struct s2n_async_pkey_op *op, s2n_cert_private_key *key); 1740extern int s2n_async_pkey_op_apply(struct s2n_async_pkey_op *op, struct s2n_connection *conn); 1741extern int s2n_async_pkey_op_free(struct s2n_async_pkey_op *op); 1742``` 1743 1744- **op** is an opaque object representing private key operation which 1745needs to be performed. 1746- **key** is a private key used for operation, can be extracted from 1747 **conn** through **s2n_connection_get_selected_cert** and 1748 **s2n_cert_chain_and_key_get_key** calls. 1749 1750**s2n_async_pkey_fn** is invoked every time some action involving 1751private key is required during **s2n_negotiate**. The **conn** provides 1752a pointer to the connection which triggered the callback, the **op** is 1753a pointer to an operation to be performed. The callback takes the 1754ownership of **op** object and is responsible for freeing the memory for 1755it. 1756 1757**s2n_config_set_async_pkey_callback** sets up the callback to invoke 1758for asynchronous private key operations and enables asynchronous mode. 1759 1760**s2n_async_pkey_op_perform** performs the **op** allowing it to be used 1761to resume the handshake through **s2n_async_pkey_op_apply** call. This 1762function can be called only once and any subsequent calls will produce a 1763failure. It is safe to call from a different thread, as long as no other 1764thread is operating on **op**. 1765 1766**s2n_async_pkey_op_apply** applies the performed **op** to **conn** 1767allowing for the next call to **s2n_negotiate** to proceed through 1768handshake. The function will fail if it is called from 1769**s2n_async_pkey_fn** callback, or if **op** was not performed through 1770**s2n_async_pkey_op_perform** call, or if provided **conn** is different 1771from the original **conn** which initiated callback for this **op**. The 1772function will succeed only once and any subsequent call will result in 1773failure for the same **op**. 1774 1775**s2n_async_pkey_op_free** frees the memory for **op**. Should eventually 1776be called for each of the **op** received in **s2n_async_pkey_fn** to 1777avoid any memory leaks. 1778 1779### Offloading asynchronous private key operations 1780 1781The **s2n_async_pkey_op_\*** API can be used to perform a private key operation 1782outside of the S2N context, without copying the private key into S2N memory. 1783 1784The application can query the type of private 1785key operation by calling **s2n_async_pkey_op_get_op_type**. In order to perform 1786an operation, the application must ask S2N to copy the operation's input into an 1787application supplied buffer. The appropriate buffer size can be determined by calling 1788**s2n_async_pkey_op_get_input_size**. Once a buffer of proper size is 1789allocated, the application can request the input data from the **s2n_async_pkey_op** 1790by calling **s2n_async_pkey_op_get_input**. After the operation is completed, the 1791finished output can be copied back to S2N by calling **s2n_async_pkey_op_set_output**. 1792Once the output is set the asynchronous private key operation can be completed by 1793following the steps outlined [above](#Asynchronous-private-key-operations-related-calls) 1794to apply the operation and free the op object. 1795 1796```c 1797typedef enum { S2N_ASYNC_DECRYPT, S2N_ASYNC_SIGN } s2n_async_pkey_op_type; 1798 1799extern int s2n_async_pkey_op_get_op_type(struct s2n_async_pkey_op *op, s2n_async_pkey_op_type *type); 1800extern int s2n_async_pkey_op_get_input_size(struct s2n_async_pkey_op *op, uint32_t *data_len); 1801extern int s2n_async_pkey_op_get_input(struct s2n_async_pkey_op *op, uint8_t *data, uint32_t data_len); 1802extern int s2n_async_pkey_op_set_output(struct s2n_async_pkey_op *op, const uint8_t *data, uint32_t data_len); 1803``` 1804 1805**s2n_async_pkey_op_type** contains the private key operation types. 1806**s2n_async_pkey_op_get_op_type** retrieves the operation type of the **op**. 1807**s2n_async_pkey_op_get_input_size** queries the **op** for the size of the input data. 1808**s2n_async_pkey_op_get_input** retrieves the input data buffer from the **op**. 1809The **op** will copy the data into a buffer passed in through the **data** parameter. 1810This buffer is owned by the application, and it is the responsibility of the 1811application to free it. 1812**s2n_async_pkey_op_set_output** copies the input data buffer and uses it 1813to complete the private key operation. The data buffer is owned by the application. 1814Once **s2n_async_pkey_op_set_output** has returned, the application is free to 1815release the data buffer. 1816 1817### s2n\_connection\_free\_handshake 1818 1819```c 1820int s2n_connection_free_handshake(struct s2n_connection *conn); 1821``` 1822 1823**s2n_connection_free_handshake** wipes and releases buffers and memory 1824allocated during the TLS handshake. This function should be called after the 1825handshake is successfully negotiated and logging or recording of handshake data 1826is complete. 1827 1828### s2n\_connection\_release\_buffers 1829 1830```c 1831int s2n_connection_release_buffers(struct s2n_connection *conn); 1832``` 1833 1834**s2n_connection_release_buffers** wipes and free the `in` and `out` buffers 1835associated with a connection. This function may be called when a connection is 1836in keep-alive or idle state to reduce memory overhead of long lived connections. 1837 1838### s2n\_connection\_wipe 1839 1840```c 1841int s2n_connection_wipe(struct s2n_connection *conn); 1842``` 1843 1844**s2n_connection_wipe** wipes an existing connection and allows it to be reused. It erases all data associated with a connection including 1845pending reads. This function should be called after all I/O is completed and [s2n_shutdown](#s2n\_shutdown) has been called. 1846Reusing the same connection handle(s) is more performant than repeatedly calling [s2n_connection_new](#s2n\_connection\_new) and 1847[s2n_connection_free](#s2n\_connection\_free) 1848 1849### s2n\_connection\_free 1850 1851```c 1852int s2n_connection_free(struct s2n_connection *conn); 1853``` 1854 1855**s2n_connection_free** frees the memory associated with an s2n_connection 1856handle. The handle is considered invalid after **s2n_connection_free** is used. 1857[s2n_connection_wipe](#s2n\_connection\_wipe) does not need to be called prior to this function. **s2n_connection_free** performs its own wipe 1858of sensitive data. 1859 1860## TLS1.3 Pre-Shared Key Related Calls 1861 1862s2n-tls supports pre-shared keys (PSKs) as of TLS1.3. PSKs allow users to establish secrets outside of the handshake, skipping certificate exchange and authentication. 1863 1864### Benefits of Using Pre-Shared Keys 1865 1866Using pre-shared keys can avoid the need for public key operations. This is useful in performance-constrained environments with limited CPU power. PSKs may also be more convenient from a key management point of view: If the system already has a mechanism for sharing secrets, that mechanism can be reused for TLS PSKs. 1867 1868### Security Considerations 1869 1870A PSK must not be shared between more than one server and one client. An entity that acts as both a server and a client should not use the same PSK for both roles. For more information see: [Selfie: reflections on TLS 1.3 with PSK.](https://eprint.iacr.org/2019/347.pdf) 1871 1872 1873### Configuring External Pre-Shared Keys 1874 1875Use the following APIs to configure external pre-shared keys. 1876 1877```c 1878struct s2n_psk* s2n_external_psk_new(); 1879int s2n_psk_free(struct s2n_psk **psk); 1880int s2n_psk_set_identity(struct s2n_psk *psk, const uint8_t *identity, uint16_t identity_size); 1881int s2n_psk_set_secret(struct s2n_psk *psk, const uint8_t *secret, uint16_t secret_size); 1882int s2n_psk_set_hmac(struct s2n_psk *psk, s2n_psk_hmac hmac); 1883int s2n_connection_append_psk(struct s2n_connection *conn, struct s2n_psk *psk); 1884int s2n_config_set_psk_mode(struct s2n_config *config, s2n_psk_mode mode); 1885int s2n_connection_set_psk_mode(struct s2n_connection *conn, s2n_psk_mode mode); 1886``` 1887 1888**s2n_external_psk_new** creates a new external PSK object with **S2N_PSK_HMAC_SHA256** as the default PSK hmac algorithm. Use **s2n_psk_free** to free the memory allocated to the external PSK object. 1889 1890**s2n_psk_set_identity** sets the identity for a given PSK. The identity is a unique identifier for the pre-shared secret. This identity is transmitted over the network unencrypted and is a non-secret value, therefore do not include any confidential information. 1891 1892**s2n_psk_set_secret** sets the secret value for a given PSK. Deriving a shared secret from a password or other low-entropy source is not secure and is subject to dictionary attacks. 1893 1894**s2n_psk_set_hmac** sets the PSK hmac algorithm for a given PSK. The supported PSK hmac algorithms are listed in the **s2n_psk_hmac** enum. This API overrides the default PSK hmac algorithm value of **S2N_PSK_HMAC_SHA256** and may influence the server cipher suite selection. 1895 1896**s2n_connection_append_psk** appends the PSK to the connection. Both server and client should call this API to add PSKs to their connection. The order this API is called matters, as PSKs that are appended first will be more preferred than PSKs appended last. This API must be called prior to the server selecting a PSK for the connection. 1897 1898**s2n_config_set_psk_mode** configures s2n-tls to expect either session resumption PSKs or external PSKs. This API should be called prior to selecting a PSK. 1899 1900**s2n_connection_set_psk_mode** overrides the PSK mode set on the config for this connection. 1901 1902### Selecting a Pre-Shared Key 1903 1904By default, the server chooses the first identity in its PSK list that also appears in the client's PSK list. If you would like to implement your own PSK selection logic, use the **s2n_psk_selection_callback** to select the PSK to be used for the connection, along with the following offered PSK APIs to process the client sent list of PSKs. 1905 1906```c 1907typedef int (*s2n_psk_selection_callback)(struct s2n_connection *conn, void *context, 1908 struct s2n_offered_psk_list *psk_list); 1909int s2n_config_set_psk_selection_callback(struct s2n_config *config, s2n_psk_selection_callback cb, void *context); 1910struct s2n_offered_psk* s2n_offered_psk_new(); 1911int s2n_offered_psk_free(struct s2n_offered_psk **psk); 1912bool s2n_offered_psk_list_has_next(struct s2n_offered_psk_list *psk_list); 1913int s2n_offered_psk_list_next(struct s2n_offered_psk_list *psk_list, struct s2n_offered_psk *psk); 1914int s2n_offered_psk_list_reread(struct s2n_offered_psk_list *psk_list); 1915int s2n_offered_psk_get_identity(struct s2n_offered_psk *psk, uint8_t** identity, uint16_t *size); 1916int s2n_offered_psk_list_choose_psk(struct s2n_offered_psk_list *psk_list, struct s2n_offered_psk *psk); 1917``` 1918 1919**s2n_psk_selection_callback** is a callback function that the server calls to select a PSK from a list of offered PSKs. Implement this callback to use custom PSK selection logic. To examine the list of client PSK identities use the input **psk_list** along with the **s2n_offered_psk_list_next** and **s2n_offered_psk_get_identity** APIs. To choose a client PSK identity, call **s2n_offered_psk_list_choose_psk**. Before a client PSK identity is chosen, the server must have configured its corresponding PSK using **s2n_connection_append_psk**. Currently, this callback is not asynchronous. 1920 1921**s2n_config_set_psk_selection_callback** sets the **s2n_psk_selection_callback**. If it is not set, the s2n-tls server chooses the first identity in its PSK list that also appears in the client's PSK list. 1922 1923**s2n_offered_psk_new** creates a new offered PSK object. Pass this object to **s2n_offered_psk_list_next** to retrieve the next PSK from the list. Use **s2n_offered_psk_list_has_next** prior to this API call to ensure we have not reached the end of the list. **s2n_offered_psk_free** frees the memory associated with the **s2n_offered_psk** object. 1924 1925**s2n_offered_psk_list_reread** returns the offered PSK list to its original read state. After **s2n_offered_psk_list_reread** is called, the next call to **s2n_offered_psk_list_next** will return the first PSK in the offered PSK list. 1926 1927**s2n_offered_psk_get_identity** gets the identity and identity length for a given offered PSK object. 1928 1929**s2n_offered_psk_list_choose_psk** sets the chosen offered PSK to be used for the connection. To disable PSKs for the connection and perform a full handshake instead, set the PSK identity to NULL. 1930 1931In the following example, **s2n_psk_selection_callback** chooses the first client offered PSK identity present in an external store. 1932 1933```c 1934int s2n_psk_selection_callback(struct s2n_connection *conn, void *context, 1935 struct s2n_offered_psk_list *psk_list) 1936{ 1937 struct s2n_offered_psk *offered_psk = s2n_offered_psk_new(); 1938 1939 while (s2n_offered_psk_list_has_next(psk_list)) { 1940 uint8_t *client_psk_id = NULL; 1941 uint16_t client_psk_id_len = 0; 1942 1943 s2n_offered_psk_list_next(psk_list, offered_psk); 1944 s2n_offered_psk_get_identity(offered_psk, &client_psk_id, &client_psk_id_len); 1945 struct s2n_psk *psk = user_lookup_identity_db(client_psk_id, client_psk_id_len); 1946 1947 if (psk) { 1948 s2n_connection_append_psk(conn, psk); 1949 s2n_offered_psk_list_choose_psk(psk_list, offered_psk); 1950 break; 1951 } 1952 } 1953 s2n_offered_psk_free(&offered_psk); 1954 return S2N_SUCCESS; 1955} 1956``` 1957 1958### Retrieve the Negotiated Pre-Shared Key 1959 1960The following APIs enable the caller to retrieve the PSK selected by the server for the connection. 1961 1962```c 1963int s2n_connection_get_negotiated_psk_identity_length(struct s2n_connection *conn, uint16_t *identity_length); 1964int s2n_connection_get_negotiated_psk_identity(struct s2n_connection *conn, uint8_t *identity, uint16_t max_identity_length); 1965``` 1966 1967**s2n_connection_get_negotiated_psk_identity** gets the identity of the PSK used to negotiate the connection. **s2n_connection_get_negotiated_psk_identity_length** gets the length of the identity. If the connection performed a full handshake instead of using PSKs then **s2n_connection_get_negotiated_psk_identity_length** returns 0 and **s2n_connection_get_negotiated_psk_identity** does nothing. 1968 1969## I/O functions 1970 1971s2n-tls supports both blocking and non-blocking I/O. To use s2n-tls in non-blocking 1972mode, set the underlying file descriptors as non-blocking (i.e. with 1973**fcntl**). In blocking mode, each s2n-tls I/O function will not return until it is 1974complete. In non-blocking mode an s2n-tls I/O function may return while there is 1975still I/O pending. In this case the value of the **blocked** parameter will be set 1976to either **S2N_BLOCKED_ON_READ** or **S2N_BLOCKED_ON_WRITE**, depending on the 1977direction in which s2n-tls is blocked. 1978 1979s2n-tls I/O functions should be called repeatedly until the **blocked** parameter is 1980**S2N_NOT_BLOCKED**. 1981 1982If the read end of the pipe is closed unexpectedly, writing to the pipe will raise 1983a SIGPIPE signal. **s2n-tls does NOT handle SIGPIPE.** A SIGPIPE signal will cause 1984the process to terminate unless it is handled or ignored by the application. 1985 1986### s2n\_negotiate 1987 1988```c 1989int s2n_negotiate(struct s2n_connection *conn, s2n_blocked_status *blocked); 1990``` 1991 1992**s2n_negotiate** performs the initial "handshake" phase of a TLS connection and must be called before any **s2n_recv** or **s2n_send** calls. 1993 1994### s2n\_send 1995 1996```c 1997ssize_t s2n_send(struct s2n_connection *conn 1998 void *buf, 1999 ssize_t size, 2000 s2n_blocked_status *blocked); 2001``` 2002 2003**s2n_send** writes and encrypts **size* of **buf** data to the associated connection. **s2n_send** will return the number of bytes written, and may indicate a partial write. Partial writes are possible not just for non-blocking I/O, but also for connections aborted while active. **NOTE:** Unlike OpenSSL, repeated calls to **s2n_send** should not duplicate the original parameters, but should update **buf** and **size** per the indication of size written. For example; 2004 2005```c 2006s2n_blocked_status blocked; 2007int written = 0; 2008char data[10]; /* Some data we want to write */ 2009do { 2010 int w = s2n_send(conn, data + written, 10 - written, &blocked); 2011 if (w < 0) { 2012 /* Some kind of error */ 2013 break; 2014 } 2015 written += w; 2016} while (blocked != S2N_NOT_BLOCKED); 2017``` 2018 2019### s2n\_sendv\_with\_offset 2020 2021```c 2022ssize_t s2n_sendv_with_offset(struct s2n_connection *conn 2023 const struct iovec *bufs, 2024 ssize_t count, 2025 ssize_t offs, 2026 s2n_blocked_status *blocked); 2027``` 2028 2029**s2n_sendv_with_offset** works in the same way as **s2n_send** except that it accepts vectorized buffers. **s2n_sendv_with_offset** will return the number of bytes written, and may indicate a partial write. Partial writes are possible not just for non-blocking I/O, but also for connections aborted while active. **NOTE:** Unlike OpenSSL, repeated calls to **s2n_sendv_with_offset** should not duplicate the original parameters, but should update **bufs** and **count** per the indication of size written. For example; 2030 2031```c 2032s2n_blocked_status blocked; 2033int written = 0; 2034char data[10]; /* Some data we want to write */ 2035struct iovec iov[1]; 2036iov[0].iov_base = data; 2037iov[0].iov_len = 10; 2038do { 2039 int w = s2n_sendv_with_offset(conn, iov, 1, written, &blocked); 2040 if (w < 0) { 2041 /* Some kind of error */ 2042 break; 2043 } 2044 written += w; 2045} while (blocked != S2N_NOT_BLOCKED); 2046``` 2047 2048### s2n\_sendv 2049 2050```c 2051ssize_t s2n_sendv(struct s2n_connection *conn 2052 const struct iovec *bufs, 2053 ssize_t count, 2054 s2n_blocked_status *blocked); 2055``` 2056 2057**s2n_sendv** works in the same way as **s2n_sendv_with_offset** except that the latter's **offs** parameter is implicitly assumed to be 0. Therefore in the partial write case, the caller would have to make sure that **bufs** and **count** fields are modified in a way that takes the partial writes into account. 2058 2059### s2n\_recv 2060 2061```c 2062ssize_t s2n_recv(struct s2n_connection *conn, 2063 void *buf, 2064 ssize_t size, 2065 s2n_blocked_status *blocked); 2066``` 2067 2068**s2n_recv** decrypts and reads **size* to **buf** data from the associated 2069connection. **s2n_recv** will return the number of bytes read and also return 2070"0" on connection shutdown by the peer. 2071 2072**NOTE:** Unlike OpenSSL, repeated calls to **s2n_recv** should not duplicate the original parameters, but should update **buf** and **size** per the indication of size read. For example; 2073 2074```c 2075s2n_blocked_status blocked; 2076int bytes_read = 0; 2077char data[10]; 2078do { 2079 int r = s2n_recv(conn, data + bytes_read, 10 - bytes_read, &blocked); 2080 if (r < 0) { 2081 /* Some kind of error */ 2082 break; 2083 } 2084 bytes_read += r; 2085} while (blocked != S2N_NOT_BLOCKED); 2086``` 2087 2088### s2n\_peek 2089 2090```c 2091uint32_t s2n_peek(struct s2n_connection *conn); 2092``` 2093 2094**s2n_peek** allows users of s2n-tls to peek inside the data buffer of an s2n-tls connection to see if there more data to be read without actually reading it. This is useful when using select() on the underlying s2n-tls file descriptor with a message based application layer protocol. As a single call to s2n_recv may read all data off the underlying file descriptor, select() will be unable to tell you there if there is more application data ready for processing already loaded into the s2n-tls buffer. s2n_peek can then be used to determine if s2n_recv needs to be called before more data comes in on the raw fd. 2095 2096 2097 2098### s2n\_connection\_set\_send\_cb 2099 2100```c 2101int s2n_connection_set_recv_cb(struct s2n_connection *conn, s2n_connection_recv recv); 2102int s2n_connection_set_send_cb(struct s2n_connection *conn, s2n_connection_send send); 2103int s2n_connection_set_recv_ctx(struct s2n_connection *conn, void *ctx); 2104int s2n_connection_set_send_ctx(struct s2n_connection *conn, void *ctx); 2105``` 2106 2107s2n-tls also provides an I/O abstraction layer in the event the application would 2108like to keep control over I/O operations. **s2n_connection_set_recv_cb** and 2109**s2n_connection_set_send_cb** may be used to send or receive data with callbacks 2110defined by the user. These may be blocking or nonblocking. 2111 2112```c 2113typedef int s2n_connection_send(void *io_context, const uint8_t *buf, uint32_t len); 2114typedef int s2n_connection_recv(void *io_context, uint8_t *buf, uint32_t len); 2115``` 2116 2117These callbacks take as input a context containing anything needed in the 2118function (for example, a file descriptor), the buffer holding data to be sent 2119or received, and the length of the buffer. The **io_context** passed to the 2120callbacks may be set separately using **s2n_connection_set_recv_ctx** and 2121**s2n_connection_set_send_ctx**. 2122 2123The callback may send or receive less than the requested length. The function 2124should return the number of bytes sent/received, or set errno and return an error code < 0. 2125 2126### s2n_shutdown 2127 2128```c 2129int s2n_shutdown(struct s2n_connection *conn, 2130 s2n_blocked_status *blocked); 2131``` 2132 2133**s2n_shutdown** attempts a closure at the TLS layer. It does not close the underlying transport. The call may block in either direction. 2134Unlike other TLS implementations, **s2n_shutdown** attempts a graceful shutdown by default. It will not return with success unless a close_notify alert is successfully 2135sent and received. As a result, **s2n_shutdown** may fail when interacting with a non-conformant TLS implementation. 2136Once **s2n_shutdown** is complete: 2137* The s2n_connection handle cannot be used for reading for writing. 2138* The underlying transport can be closed. Most likely via `close()`. 2139* The s2n_connection handle can be freed via [s2n_connection_free](#s2n\_connection\_free) or reused via [s2n_connection_wipe](#s2n\_connection\_wipe) 2140 2141 2142### s2n_mem_set_callbacks 2143 2144```c 2145typedef int (*s2n_mem_init_callback)(void); 2146typedef int (*s2n_mem_cleanup_callback)(void); 2147typedef int (*s2n_mem_malloc_callback)(void **ptr, uint32_t requested, uint32_t *allocated); 2148typedef int (*s2n_mem_free_callback)(void *ptr, uint32_t size); 2149 2150extern int s2n_mem_set_callbacks(s2n_mem_init_callback mem_init_callback, s2n_mem_cleanup_callback mem_cleanup_callback, s2n_mem_malloc_callback mem_malloc_callback, s2n_mem_free_callback mem_free_callback); 2151``` 2152 2153 2154**s2n_mem_set_callbacks** allows the caller to over-ride s2n-tls's internal memory 2155handling functions. To work correctly, **s2n_mem_set_callbacks** must be called 2156before **s2n_init**. **s2n_mem_init_callback** should be a function that will 2157be called when s2n-tls is initialized. **s2n_mem_cleanup_callback** will be called 2158when **s2n_cleanup** is executed. **s2n_mem_malloc_callback** should be a 2159function that can allocate at least **requested** bytes of memory and store the 2160location of that memory in **\*ptr**, and the size of the allocated data in 2161**\*allocated**. The function may choose to allocate more memory than was requested. 2162s2n-tls will consider all allocated memory available for use, and will attempt to 2163free all allocated memory when able. **s2n_mem_free_callback** should be a 2164function that can free memory. 2165 2166 2167## Using Early Data / 0RTT 2168 2169TLS1.3 introduced the ability for clients to send data before completing the handshake when using external pre-shared keys or session resumption. 2170 2171**WARNING:** Early data does not have the same security properties as regular data sent after a successful handshake. 2172* It is not forward secret. If the PSK or session resumption secret is compromised, then the early data is also compromised. 2173* It is susceptible to replay attacks unless proper precautions are taken. Early data can be captured and successfully resent by an attacker. See https://tools.ietf.org/rfc/rfc8446#appendix-E.5 for more details, and ["Adding anti-replay protection"](#adding-anti-replay-protection) for how to implement counter measures. 2174 2175_**Do not enable early data for your application unless you have understood and mitigated the risks.**_ 2176 2177### Configuring session resumption for early data 2178 2179To use early data with session tickets, early data must be enabled on a server by setting the maximum early data allowed to a non-zero value with **s2n_config_set_server_max_early_data_size** or **s2n_connection_set_server_max_early_data_size**. The server then begins issuing tickets that support early data, and clients can use early data when they use those tickets. 2180 2181### Configuring external pre-shared keys for early data 2182 2183To use early data with pre-shared keys, individual pre-shared keys must support early data. In addition to configuring the maximum early data allowed, each pre-shared key needs an associated cipher suite and if applicable, application protocol. The server only accepts early data if the pre-shared key's associated cipher suite and application protocol match the cipher suite and the application protocol negotiated during the handshake. 2184 2185The maximum early data allowed and cipher suite can be set with **s2n_psk_configure_early_data**. If the connection will negotiate an application protocol then the expected application protocol can be set with **s2n_psk_set_application_protocol**. 2186 2187### Sending early data 2188 2189To send early data, your application should call **s2n_send_early_data** before it calls **s2n_negotiate**. 2190 2191**s2n_connection_get_remaining_early_data_size** can be called to check how much more early data the client is allowed to send. If **s2n_send_early_data** exceeds the allowed maximum, s2n-tls returns a usage error. 2192 2193Like other IO functions, **s2n_send_early_data** can potentially fail repeatedly with a blocking error before it eventually succeeds: see [I/O Functions](#io-functions) for more information. An application can stop calling **s2n_send_early_data** at any time, even if the function has not returned success yet. If **s2n_send_early_data** does return success, the connection is ready to complete the handshake and begin sending normal data. However, **s2n_send_early_data** can continue to be called to send more early data if desired. 2194 2195Once a client finishes sending early data, you should call **s2n_negotiate** to complete the handshake just as you would for a handshake that did not include early data. 2196 2197For example: 2198``` 2199uint8_t early_data[] = "early data to send"; 2200ssize_t total_data_sent = 0, len = sizeof(early_data); 2201while (total_data_sent < len) { 2202 ssize_t data_sent = 0; 2203 int r = s2n_send_early_data(client_conn, early_data + total_data_sent, 2204 len - total_data_sent, &data_sent, &blocked); 2205 total_data_sent += data_sent; 2206 if (r == S2N_SUCCESS) { 2207 break; 2208 } else if (s2n_error_get_type(s2n_errno) != S2N_ERR_T_BLOCKED) { 2209 exit(1); 2210 } 2211} 2212while (s2n_negotiate(client_conn, &blocked) != S2N_SUCCESS) { 2213 if (s2n_error_get_type(s2n_errno) != S2N_ERR_T_BLOCKED) { 2214 exit(1); 2215 } 2216} 2217``` 2218 2219### Receiving early data 2220 2221To receive early data, your application should call **s2n_recv_early_data** before it calls **s2n_negotiate**. 2222 2223Like other S2N IO functions, **s2n_recv_early_data** can potentially fail repeatedly with a blocking error before it eventually succeeds: see [I/O Functions](#io-functions) for more information. Once **s2n_recv_early_data** has been called, it must be called until it returns success. If an application stops calling **s2n_recv_early_data** early, some early data may be left unread and cause later calls to **s2n_negotiate** to return fatal errors. Calling **s2n_recv_early_data** again after it returns success is possible but has no effect on the connection. 2224 2225Once a server has read all early data, you should call **s2n_negotiate** to complete the handshake just as you would for a handshake that did not include early data. 2226 2227For example: 2228``` 2229uint8_t early_data[MAX_EARLY_DATA] = { 0 }; 2230ssize_t total_data_recv = 0, data_recv = 0; 2231while (s2n_recv_early_data(conn, early_data + total_data_recv, MAX_EARLY_DATA - total_data_recv, 2232 &data_recv, &blocked) != S2N_SUCCESS) { 2233 total_data_recv += data_recv; 2234 if (s2n_error_get_type(s2n_errno) != S2N_ERR_T_BLOCKED) { 2235 exit(1); 2236 } 2237} 2238while (s2n_negotiate(conn, &blocked) != S2N_SUCCESS) { 2239 if (s2n_error_get_type(s2n_errno) != S2N_ERR_T_BLOCKED) { 2240 exit(1); 2241 } 2242} 2243``` 2244 2245### Adding anti-replay protection 2246**s2n-tls does not include anti-replay protection automatically.** Effective anti-replay protection for a multi-server application requires an external state shared by all servers. Without shared state, an attacker can capture early data originally sent to server A and successfully replay it against server B. 2247 2248The TLS1.3 specification suggests two possible anti-replay solutions that a user can implement: 22491. Single-Use Tickets (https://tools.ietf.org/rfc/rfc8446#section-8.1): Valid tickets are stored in a shared database and deleted after use. **s2n_connection_get_negotiated_psk_identity_length** and **s2n_connection_get_negotiated_psk_identity** can be used to get the ticket identifer, or "pre-shared key identity", associated with offered early data. 22502. Client Hello Recording (https://tools.ietf.org/rfc/rfc8446#section-8.2): Instead of recording outstanding valid tickets, unique values from recent ClientHellos can be stored. The client hello message can be retrieved with **s2n_connection_get_client_hello** and the pre-shared key identity can be retrieved with **s2n_connection_get_negotiated_psk_identity_length** and **s2n_connection_get_negotiated_psk_identity**, but s2n-tls does not currently provide methods to retrieve the validated binders or the ClientHello.random. 2251 2252The **s2n_early_data_cb** can be used to hook an anti-replay solution into s2n-tls. The callback can be configured by using **s2n_config_set_early_data_cb**. Using the **s2n_offered_early_data** pointer offered by the callback, **s2n_offered_early_data_reject** or **s2n_offered_early_data_accept** can accept or reject the client request to use early data. 2253 2254An example implementation: 2255``` 2256int s2n_early_data_cb_impl(struct s2n_connection *conn, struct s2n_offered_early_data *early_data) 2257{ 2258 uint16_t identity_size = 0; 2259 s2n_connection_get_negotiated_psk_identity_length(conn, &identity_size); 2260 uint8_t *identity = malloc(identity_size); 2261 s2n_connection_get_negotiated_psk_identity(conn, identity, identity_size); 2262 2263 if (user_verify_single_use_ticket(identity)) { 2264 s2n_offered_early_data_accept(early_data); 2265 } else { 2266 s2n_offered_early_data_reject(early_data); 2267 } 2268 2269 free(identity); 2270 return S2N_SUCCESS; 2271} 2272``` 2273 2274The callback can also be implemented asynchronously by returning **S2N_SUCCESS** without either accepting or rejecting the early data. The handshake will then fail with an **S2N_ERR_T_BLOCKED** error type and **s2n_blocked_status** set to **S2N_BLOCKED_ON_APPLICATION_INPUT** until **s2n_offered_early_data_reject** or **s2n_offered_early_data_accept** is called asynchronously. 2275 2276An example asynchronous implementation: 2277``` 2278void *user_accept_or_reject_early_data(void *arg) 2279{ 2280 struct s2n_offered_early_data *early_data = (struct s2n_offered_early_data *) arg; 2281 if (user_slowly_verify_early_data(early_data)) { 2282 s2n_offered_early_data_accept(early_data); 2283 } else { 2284 s2n_offered_early_data_reject(early_data); 2285 } 2286 return NULL; 2287} 2288 2289int s2n_early_data_cb_async_impl(struct s2n_connection *conn, struct s2n_offered_early_data *early_data) 2290{ 2291 pthread_t thread_id; 2292 pthread_create(&thread_id, NULL, user_accept_or_reject_early_data, (void *) early_data); 2293 return S2N_SUCCESS; 2294} 2295``` 2296 2297**s2n_offered_early_data_get_context_length** and **s2n_offered_early_data_get_context** can be called to examine the optional user context associated with the early data. Unlike most s2n-tls callbacks, the context is not configured when the callback is set. Instead, the context is associated with the specific pre-shared key or session ticket used for early data. The context can be set for external pre-shared keys by calling **s2n_psk_set_early_data_context**. For session tickets, **s2n_connection_set_server_early_data_context** can be used to set the context the server includes on its new session tickets. Because the server needs to serialize the context when creating a new session ticket, the context is a byte buffer instead of the usual void pointer. 2298 2299 2300# Examples 2301 2302To understand the API it may be easiest to see examples in action. s2n-tls's [bin/](https://github.com/aws/s2n-tls/blob/main/bin/) directory 2303includes an example client (s2nc) and server (s2nd). 2304