Debian Codegraph @

crt/s2n/docs/DEVELOPMENT-GUIDE.md

raw symbols SCIP
1 # Development guide for s2n-tls
2
3 If you are curious about the internals of s2n-tls, or interested in contributing to
4 s2n-tls, this document is for you. If instead you are interested in using s2n-tls in an application
5 that you are developing, please see the accompanying [Usage Guide](usage-guide).
6
7 ## s2n-tls's development principles
8
9 Before getting into the detail of how s2n-tls works internally, it's worth covering
10 s2n-tls's development principles. These principles guide and inform many of the design
11 decisions we'll go through. We're always open to new principles, if you can think of
12 better ones and make a case for them.
13
14 #### Development principles
15 * **Maintain an excellent TLS/SSL implementation**<br/>Although it's hidden "*under the hood*", TLS/SSL is the direct interface with customers and end-users. Good performance and security are critical to a positive experience.
16 * **Protect user data and keys**<br/>Above all else, s2n-tls must ensure that user data and private keys are being handled correctly and carefully. Security is often a matter of trade-offs and costs; we should always strive to increase the costs for attackers whenever the tradeoffs are acceptable to users.
17 * **Stay simple**<br/>Write as little code as necessary, omit rarely used optional features and support as few modes of operation as possible. We will also promote and encourage changes that reduce the size of our code base.
18 * **Write clear readable code with a light cognitive load**<br/>s2n-tls's code must be concise, easy to follow and legible to a proficient C programmer. Our code should be organized in a way that divides the implementation up into small units of work, with the entire context necessary at hand. We should also minimize the number of branches in our code, the depth of our call stacks, and the number of members in our structures.
19 * **Defend in depth and systematically**<br/>Great care and attention to detail is required to write good code, but we also use automation and mechanistic processes to protect against human error.
20 * **Be easy to use and maintain sane defaults**<br/>It should be low effort, even for a novice developer, to use s2n-tls in a safe way. We also shouldn't "*pass the buck*" and place the burden of subtle or complicated TLS-specific decision making upon application authors and system administrators.
21 * **Provide great performance and responsiveness**<br/>TLS/SSL is rapidly becoming ubiquitous. Even small inefficiencies and overhead can become significant when multiplied by billions of users and quintillions of sessions.
22 * **Stay paranoid**<br/>s2n-tls operates in a security critical space. Even with the most precautionary development methods it is impossible to guarantee the absence of defects. A subtle one-byte error on a single line may still cause problems.
23 * **Make data-driven decisions**<br/>Opinions can differ on security best practices, sometimes in contradictory ways. Where possible, we are guided by facts and measurable data.
24
25 #### Priorities
26
27 When weighing up difficult implementation trade-offs our ordered set of priorities are:
28
29 1. Security
30 2. Readability
31 3. Ease of use
32 4. Performance.
33
34 #### Commit and code-review policy
35
36 s2n-tls is review-then-commit for code changes, and commit-then-review for
37 documentation changes. Code additions are made by pull requests, no author may
38 merge their own pull request on code. Changes to documentation, including code
39 comments, may be made more freely.
40
41 ## Coding style and conventions
42
43 Per our development principles, an important goal is to reduce the cognitive load required to
44 read, review and extend s2n-tls . Although s2n-tls is written in C, s2n-tls adopts several
45 patterns more common to functional programming. Though they are used in a way
46 that is idiomatic and shouldn't feel completely alien in C.
47
48 ### High level function design
49 The first convention is that's s2n-tls's functions are generally quite small, no
50 more than a page or two at most and commonly just a few lines. Functions
51 have a clear input and output and are in that sense "pure" functions; for
52 example handling a particular TLS handshake message type takes the message
53 as input, and the output is connection state.
54
55 ```c
56 /* An idiomatic s2n-tls function generally has:
57 *
58 * An s2n_result return value. This is used to signal success or error.
59 * An input, often a struct.
60 * An output, often a struct.
61 */
62 S2N_RESULT s2n_do_something(struct *some_input, struct *some_output);
63 ```
64
65 s2n-tls functions also operate in a message passing style. For example,
66 a simplified version of the flow when handling a TLS client finished message
67 might looks like this:
68
69 ![s2n-tls message passing](images/s2n_lambda.png "s2n-tls message passing")
70
71 each function handles a clear, well-defined piece of work, before passing on
72 responsibility to the next function.
73
74 The second convention of s2n-tls's functions is that functions are
75 split into two kinds: those that handle control flow and coordinate
76 other functions, and those that parse messages. For example, in the above
77 diagram, it might appear that the functions are calling each other directly
78 but we try to avoid that. Instead there is a coordinating outer function
79 responsible for the flow control.
80
81 A simplified version of the coordinating function would resemble:
82
83 ```c
84 GUARD(s2n_stuffer_read(connection, input_stuffer));
85 GUARD(s2n_cbc_aes_decrypt(input_stuffer, output_stuffer));
86 GUARD(s2n_cbc_verify(output_stuffer));
87 ```
88
89 Splitting things up this way leads to a shallower call stack, but the main
90 benefit is that functions can read quite declaratively. In the case of message
91 parsers, the function contents can read almost like schemas of the message
92 being parsed.
93
94 A good example file for message parsing to look at is [tls/s2n_server_finished.c](https://github.com/aws/s2n-tls/blob/main/tls/s2n_server_finished.c).
95 From reading the file it should be reasonably clear that a server
96 finished message consists just of S2N_TLS_FINISHED_LEN number of bytes, what
97 the next state is and so on.
98
99 As you may also see in that file, the functions for reading and writing a
100 particular message type are in the same file. That way all of context and
101 logic needed to handle that message type can be reviewed and thought about in
102 one place.
103
104 ### Error handling and Macros
105
106 As may also be clear from the above examples, s2n-tls has some conventions for how errors are handled. Firstly, s2n-tls functions should always return `S2N_RESULT_ERROR` or `NULL` on error, and `S2N_RESULT_OK` or a valid pointer on success. s2n-tls also includes a thread local variable: s2n_errno, for indicating the cause of the error. This follows the convention set by libc (with errno), getaddrinfo (gai_errno), net-snmp (snmp_errno), and countless other libraries.
107
108 In s2n-tls, we **always** check return values. Because of that, the coding pattern:
109
110 ```c
111 if (s2n_result_is_error(s2n_do_something(with_something_else))) {
112 return S2N_RESULT_ERROR;
113 }
114 ```
115
116 is so common that [utils/s2n_safety.h](https://github.com/aws/s2n-tls/blob/main/utils/s2n_safety.h) provides several macros for working with fallible functions. Notable macros include;
117
118 ```c
119 /**
120 * Ensures `x` is not an error, otherwise the function will return a `S2N_RESULT_ERROR`
121 */
122 #define GUARD( x ) ...
123
124 /**
125 * Ensures `x` is not an error, otherwise the function will return `NULL`
126 */
127 #define GUARD_PTR( x ) ...
128 ```
129
130 These macros should be used when calling functions you expect to succeed. Primarily these macros help save two lines that repeatedly clutter files, and secondarily they are very useful when developing and debugging code as it is easy to redefine the macro to implement a simple backtrace (even a simple printf will suffice, but a breakpoint is more usual).
131
132 If a function does fail, it should use the `BAIL(errno)` macro provided for surfacing the error to an application.
133 New error translations, and their human-readable translations can be defined in [error/s2n_errno.h](https://github.com/aws/s2n-tls/blob/main/error/s2n_errno.h) and [error/s2n_errno.c](https://github.com/aws/s2n-tls/blob/main/error/s2n_errno.c). When called, e.g.:
134
135 ```c
136 BAIL(S2N_ERR_BAD_MESSAGE);
137 ```
138
139 the macro will set s2n_errno correctly, as well as some useful debug strings, and return `S2N_RESULT_ERROR`.
140
141 ### Safety checking
142
143 [utils/s2n_safety.h](https://github.com/aws/s2n-tls/blob/main/utils/s2n_safety.h) provides several more convenience macros intended to make safety and bounds checking easier. There are checked versions of memcpy (`CHECKED_MEMCPY`) and memset (`CHECKED_MEMSET`), as well as predicate testers like `ENSURE`, `ENSURE_GTE`, `ENSURE_INCLUSIVE_RANGE`, `ENSURE_EXCLUSIVE_RANGE` for performing simple comparisons in a systematic, error-handled, way.
144
145 *Note*: In general, C preprocessor Macros with embedded control flow are a bad idea, but `GUARD`, `ENSURE`, and `BAIL` are so thoroughly used throughout s2n-tls that it should be a clear and idiomatic pattern, almost forming a small domain specific language.
146
147 ### Cleanup on Error
148 As discussed below, s2n-tls rarely allocates resources, and so has nothing to clean up on error. For cases where functions do allocate resources which must be cleaned up, s2n-tls offers a macro:
149
150 ```c
151 /**
152 * Runs _thecleanup function on _thealloc once _thealloc went out of scope
153 */
154 #define DEFER_CLEANUP(_thealloc, _thecleanup) ...
155 ```
156
157 `DEFER_CLEANUP(_thealloc, _thecleanup)` is a failsafe way of ensuring that resources are cleaned up, using the ` __attribute__((cleanup())` destructor mechanism available in modern C compilers. When the variable declared in `_thealloc` goes out of scope, the cleanup function `_thecleanup` is automatically called. This guarantees that resources will be cleaned up, no matter how the function exits.
158
159 ### Lifecycle of s2n memory
160 `s2n_init()` resources have to be explicitly cleaned up by users by calling `s2n_cleanup_final()`. Previously we had an atexit handler that cleaned up s2n resources automatically, but it was disabled in our library. The only place it is still on is our unit tests.
161
162 `s2n_cleanup()` is a legacy API that previously cleaned up per-thread random state. Since s2n-tls no longer maintains thread-local random state, `s2n_cleanup()` is now a no-op. Use `s2n_cleanup_final()` for full library cleanup.
163
164 ### Control flow and the state machine
165
166 Branches can be a source of cognitive load, as they ask the reader to follow a path of thinking, while also remembering that there is another path to be explored. When branches are nested, they can often lead to impossible to grasp combinatorial explosions. s2n-tls tries to systematically reduce the number of branches used in the code in several ways.
167
168 Firstly, there are almost no ifdef calls in s2n-tls . Ifdefs can be a particularly penalizing source of cognitive load. In addition to being a branch, they also ask the reader to mix state from two different languages (C, and the C preprocessor) and they tend to be associated with ugly rendering in IDEs and code formatters. In the few places where ifdef's are necessary, we use them in a careful way without compromising the integrity of the function. [tls/s2n_config.c](https://github.com/aws/s2n-tls/blob/main/tls/s2n_config.c) is a good example. Rather than mixing the Apple and non-Apple implementations and cluttering one function with several ifdefs, there is a complete implementation of the timer functionality for each platform. Within the POSIX implementation, an ifdef and define are used to use the most precise clock type, but in a way that does not compromise readability.
169
170 Secondly, s2n-tls generally branches in the case of failure, rather than success. So instead of creating a nest of if's:
171
172 ```c
173 if (s2n_foo() == 0) {
174 if (s2n_bar() == 0) {
175 if (s2n_baz() == 0) {
176 ```
177
178 we do:
179
180 ```c
181 GUARD(s2n_foo());
182 GUARD(s2n_bar());
183 GUARD(s2n_baz());
184 ```
185
186 This pattern leads to a linear control flow, where the main body of a function describes everything that happens in a regular, "*happy*" case. Any deviation is usually a fatal error and we exit the function. This is safe because s2n-tls rarely allocates resources, and so has nothing to clean up on error.
187
188 This pattern also leads to extremely few "else" clauses in the s2n-tls code base. Within s2n-tls, else clauses should be treated with suspicion and examined for potential eradication. Where an else clause is necessary, we try to ensure that the first if block is the most likely case. This aids readability, and also results in a more efficient compiled instruction pipeline (although good CPU branch prediction will rapidly correct any misordering).
189
190 For branches on small enumerated types, s2n-tls generally favors switch statements: though switch statements taking up more than about 25 lines of code are discouraged, and a "default:" block is mandatory.
191
192 Another technique for complexity avoidance is that the core TLS state machine within s2n-tls does not use branches and instead uses a table of function pointers (another technique borrowed from functional programming) to dispatch data to the correct handler. This is covered in more detail later in this document.
193
194 Lastly, s2n-tls studiously avoids locks. s2n-tls is designed to be thread-safe, but does so by using atomic data types in the small number of well-isolated variables that may be accessed by multiple threads.
195
196 ### Code formatting and commenting
197
198 s2n-tls is written in C99. The code formatting and indentation should be relatively clear from reading some s2n-tls source files, but we also have a .clang-format file which we are adopting. The code format is checked by a CI job, and if clang-format finds any unformatted code the check will fail. For convenience, there is a utility script at `./codebuild/bin/clang_format_changed_files.sh` which will format all of the source files changed on a git branch.
199
200 There should be no need for comments to explain *what* s2n-tls code is doing; variables and functions should be given clear and human-readable names that make their purpose and intent intuitive. Comments explaining *why* we are doing something are encouraged. Often some context setting is necessary; a reference to an RFC, or a reminder of some critical state that is hard to work directly into the immediate code in a natural way. All comments should be written using C syntax `/* */` and **avoid** C++ comments `//` even though C99 compilers allow `//`.
201
202 Every source code file must include a copy of the Apache Software License 2.0, as well as a correct copyright notification. The year of copyright should be the year in which the file was first created.
203
204 There is also a brief set of other coding conventions:
205
206 * s2n-tls uses explicitly sized primitives where possible. E.g. uint8_t, uint32_t.
207 * In general, s2n-tls uses unsigned ints for sizes, as TLS/SSL do the same.
208 * Any structures exposed to application authors must be opaque: s2n-tls manages the memory allocation and de-allocation.
209 * Variables are declared closest to their first point of use, to maximize context around the typing.
210 * Duplication of logic is discouraged
211 * 4 spaces, no tabs
212 * Assuming a terminal that is 120 characters wide is ok
213 * Control structures should always include curly braces (even if only one line)
214
215 ## Tests
216
217 s2n-tls is written in C99, a language which lacks a "standard" testing framework. Although there are some more well used C++ testing frameworks, s2n-tls also targets some embedded platforms on which a C++ compiler is unavailable.
218
219 Since testing and test-cases are absolutely mandatory for all s2n-tls functionality, s2n-tls includes its own small testing framework, defined in [tests/s2n_test.h](https://github.com/aws/s2n-tls/blob/main/tests/s2n_test.h). The framework consists of 15 macros that allow you to start a test suite, which is a normal C application with a main() function, and to validate various expectations.
220
221 Unit tests are added as .c files in [tests/unit/](https://github.com/aws/s2n-tls/blob/main/tests/unit/). A simple example to look at is [tests/unit/s2n_stuffer_base64_test.c](https://github.com/aws/s2n-tls/blob/main/tests/unit/s2n_stuffer_base64_test.c). The tests are started with BEGIN_TEST(), and expectations are tested with EXPECT_SUCCESS and EXPECT_EQUAL before exiting with an END_TEST call.
222
223 The test framework will take care of compiling and executing the tests and indicates success or failure with green or red text in the console.
224
225 In addition to fully covering functionality in the correct cases, s2n-tls tests are also expected to include adversarial or "negative" test cases. For example, the tests performed on record encryption validate that s2n-tls is tamper resistant by attempting to actually tamper with records. Similarly, we validate that our memory handling routines cannot be over-filled by attempting to over-fill them.
226
227 To avoid adding unneeded code to the production build of s2n-tls, there is also a small test library defined at [tests/testlib/](https://github.com/aws/s2n-tls/blob/main/tests/testlib/) which includes routines useful for test cases. For example, there is a hex parser and emitter, which is useful for defining network data in test cases, but not needed in production.
228
229 Unit tests are run automatically with `make`. To run a subset of the unit tests, set the `UNIT_TESTS` environment variable with the unit test name(s). For example:
230 ```
231 UNIT_TESTS=s2n_hash_test make
232 ```
233
234 ### Debugging With GDB
235 When trying to debug a failing test case, it is often useful to use a debugger like `gdb`. First make sure that the tests and s2n are compiled with debug information. This can be done by setting the `CMAKE_BUILD_TYPE` to `DEBUG`. Alternatively, you can set the build type to `RelWithDebInfo` to get a release build with debug info included.
236 ```
237 # generate the build configuration with debug symbols enabled
238 cmake . \
239 -Bbuild \
240 -DCMAKE_BUILD_TYPE=DEBUG
241 ```
242
243 Our unit tests rely on relative paths for certificates, so the test executable must be invoked from the folder that holds the test source file, or you can `cd` into the unit test folder once gdb is running.
244
245 To run the `s2n_x509_validator_test` with `gdb`
246 ```
247 pwd
248 # .../s2n-tls/tests/unit/
249 gdb ../../build/bin/s2n_x509_validator_test
250 ```
251
252 ## A tour of s2n-tls memory handling: blobs and stuffers
253
254 C has a history of issues around memory and buffer handling. To avoid problems in this area, s2n-tls does not use C string functions or standard buffer manipulation patterns. Instead memory regions are tracked explicitly, with `s2n_blob` structures, and buffers are re-oriented as streams with `s2n_stuffer` structures.
255
256 ### s2n_blob: keeping track of memory ranges
257
258 `s2n_blob` is a data structure representing either allocated, "owned" memory or a reference to some other non-owned slice of memory.
259
260 ```c
261 struct s2n_blob {
262 uint8_t *data;
263 uint32_t size;
264 uint32_t allocated;
265 unsigned growable: 1;
266 };
267 ```
268
269 Functions that handle memory ranges are expected to at least use blobs (stuffers are better though, as we'll see). A blob can be initialized with an existing memory buffer using **s2n_blob_init**, but [utils/s2n_mem.h](https://github.com/aws/s2n-tls/blob/main/utils/s2n_mem.h) also defines routines for dynamically allocated blobs. For handling user data, we prefer the latter, as s2n-tls prevents the memory regions from being swapped to disk and from showing up in core files (where supported).
270
271 ### s2n_stuffer: a streaming buffer
272
273 The stuffer data structure included in s2n-tls is intended to handle all protocol level
274 input and output to memory buffers and is the real work-horse of s2n-tls . At its core
275 a stuffer is a blob and two cursors:
276
277 ```c
278 struct s2n_stuffer {
279 struct s2n_blob blob;
280 uint32_t read_cursor;
281 uint32_t write_cursor;
282 ...
283 };
284 ```
285
286 This layout that makes it possible to implement a stream:
287
288 ![Stuffer layout](images/s2n_stuffer_layout.png "s2n-tls stuffer internal layout")
289
290 All access to/from the stuffer goes "through" s2n_stuffer_ functions. For example, we can write with **s2n_stuffer_write()**, and when we do the write cursor is incremented to the new position. We can read with **s2n_stuffer_read()**, and of course we can only read data as far as the write cursor (which is always at or ahead of the read cursor). To protect user data, when we read data out of the stuffer, we wipe the copy of the data within the local stuffer memory. We also ensure that it's only possible to read as much data as is in the stuffer.
291
292 A stuffer can be initialized directly from a blob, which makes it fixed in size, or it can be allocated dynamically. In the latter case, we can also choose to make the stuffer growable (by using **s2n_stuffer_growable_alloc** instead of **s2n_stuffer_alloc**). If a stuffer is growable then attempting to write past the end of the current blob will result in the blob being extended (by at least 1K at a time) to fit the data.
293
294 To further encourage stream-oriented programming, the stuffer is also the place where all marshaling and de-marshaling happens. For example, you can read and write ints directly to a stuffer:
295
296 ```c
297 /* Read and write integers in network order */
298 int s2n_stuffer_read_uint8(struct s2n_stuffer *stuffer, uint8_t *u);
299 int s2n_stuffer_read_uint16(struct s2n_stuffer *stuffer, uint16_t *u);
300 int s2n_stuffer_read_uint24(struct s2n_stuffer *stuffer, uint32_t *u);
301 int s2n_stuffer_read_uint32(struct s2n_stuffer *stuffer, uint32_t *u);
302 int s2n_stuffer_read_uint64(struct s2n_stuffer *stuffer, uint64_t *u);
303 int s2n_stuffer_write_uint8(struct s2n_stuffer *stuffer, uint8_t u);
304 int s2n_stuffer_write_uint16(struct s2n_stuffer *stuffer, uint16_t u);
305 int s2n_stuffer_write_uint24(struct s2n_stuffer *stuffer, uint32_t u);
306 int s2n_stuffer_write_uint32(struct s2n_stuffer *stuffer, uint32_t u);
307 int s2n_stuffer_write_uint64(struct s2n_stuffer *stuffer, uint64_t u);
308 ```
309
310 and there are other utility functions for handling base64 encoding to and from a stuffer, or text manipulation - like tokenization. The idea is to implement basic serializing just once, rather than spread out and duplicated across the message parsers, and to maximize the declarative nature of the I/O. For example, this code parses a TLS record header:
311
312 ```c
313 GUARD(s2n_stuffer_read_uint8(in, &message_type));
314 GUARD(s2n_stuffer_read_uint8(in, &protocol_major_version));
315 GUARD(s2n_stuffer_read_uint8(in, &protocol_minor_version));
316 GUARD(s2n_stuffer_read_uint16(in, &record_size));
317 ```
318
319 This pattern should make it very clear what the message format is, where the contents are being stored, and that we're handling things in a safe way.
320
321 There are times when we must interact with C functions from other libraries; for example, when handling encryption and decryption. In these cases, it is usually necessary to provide access to "raw" pointers into stuffers. s2n-tls provides two functions for this:
322
323 ```c
324 void *s2n_stuffer_raw_write(struct s2n_stuffer *stuffer, uint32_t data_len);
325 void *s2n_stuffer_raw_read(struct s2n_stuffer *stuffer, uint32_t data_len);
326 ```
327
328 the first function returns a pointer to the existing location of the write cursor, and then increments the write cursor by `data_len`, so an external function is free to write to the pointer, as long as it only writes `data_len` bytes.
329 The second function does the same thing, except that it increments the read cursor.
330 Use of these functions is discouraged and should only be done when necessary for compatibility.
331
332 One problem with returning raw pointers is that a pointer can become stale if the stuffer is later resized. Growable stuffers are resized using realloc(), which is free to copy and re-address memory. This could leave the original pointer location dangling, potentially leading to an invalid access. To prevent this, stuffers have a life-cycle and can be marked as tainted, which prevents them from being resized within their present life-cycle.
333
334 Internally stuffers track 4 pieces of state:
335
336 ```c
337 uint32_t high_water_mark;
338 unsigned int alloced:1;
339 unsigned int growable:1;
340 unsigned int tainted:1;
341 ```
342
343 The `high_water_mark` tracks the furthermost byte which has been written but not yet wiped.
344 Note that this may be past the `write_cursor` if `s2n_stuffer_rewrite()` has been called.
345 Explicitly tracking the `high_water_mark` allows us to track the bytes which need to be wiped, and helps avoids needless zeroing of memory.
346 The next two bits of state track whether a stuffer was dynamically allocated (and so should be free'd later) and whether or not it is growable.
347 `tainted` is set to true whenever `s2n_stuffer_raw_read/write()` are called.
348 If a stuffer is currently tainted then it can not be resized and it becomes ungrowable due to memory safety constraints.
349 This is reset when a stuffer is explicitly wiped, which begins the life-cycle anew.
350 So any pointers returned by `s2n_stuffer_raw_read/write()` are legal only until `s2n_stuffer_wipe()` is called.
351 The end result is that this kind of pattern is legal:
352
353 ```c
354 GUARD(s2n_stuffer_growable_alloc(&in, 1500));
355 GUARD(s2n_stuffer_write(&in, &fifteen_hundred_bytes_blob));
356 uint8_t * ptr = s2n_stuffer_raw_read(&in, 1500);
357 ```
358
359 but attempting to write more data would not be legal:
360
361 ```c
362 GUARD(s2n_stuffer_growable_alloc(&in, 1500));
363 GUARD(s2n_stuffer_write(&in, &fifteen_hundred_bytes_blob));
364 uint8_t * ptr = s2n_stuffer_raw_read(&in, 1500);
365
366 /* This write will fail, the stuffer is no longer growable, as a raw
367 * pointer was taken */
368 GUARD(s2n_stuffer_write(&in, &some_more_data_blob));
369
370 /* Stuffer life cycle is now complete, reset everything and wipe */
371 GUARD(s2n_stuffer_wipe(&in));
372 ```
373
374 Ideally, a `tainted` stuffer should be wiped before further write operations. If that is not an option, you may need to manually reset the `tainted` flag to false. When resetting the `tainted` flag, be very careful that the pointer is really no longer accessible and that a future developer won't unknowingly change the lifetime of the pointer. Include a comment explaining why resetting the `tainted` flag is safe.
375
376 ## s2n_connection and the TLS state machine
377
378 Every connection is associated with an s2n_connection structure. The details of this structure are opaque to applications, but internally it is where all of the TLS state is managed. To make sense of what is going on, it is necessary to understand how the TLS protocol works at the record and handshake layers.
379
380 When a TLS connection is being started, the first communication consists of handshake messages. The client sends the first message (a client hello), and then the server replies (with a server hello), and so on. Because a server must wait for a client and vice versa, this phase of a TLS connection is not full-duplex. To save on memory, s2n-tls uses a single stuffer for both incoming and outgoing handshake messages and it is located as s2n_connection->handshake.io (which is a growable stuffer).
381
382 Borrowing another trick from functional programming, the state machine for handling handshake messages is implemented using a table of function pointers, located in [tls/s2n_handshake_io.c](https://github.com/aws/s2n-tls/blob/main/tls/s2n_handshake_io.c).
383
384 ```c
385 static struct s2n_handshake_action state_machine[] = {
386 /*Message type Handshake type Writer S2N_SERVER S2N_CLIENT handshake.state */
387 {TLS_HANDSHAKE, TLS_CLIENT_HELLO, 'C', {s2n_client_hello_recv, s2n_client_hello_send}}, /* CLIENT_HELLO */
388 {TLS_HANDSHAKE, TLS_SERVER_HELLO, 'S', {s2n_server_hello_send, s2n_server_hello_recv}}, /* SERVER_HELLO */
389 {TLS_HANDSHAKE, TLS_SERVER_CERT, 'S', {s2n_server_cert_send, s2n_server_cert_recv}}, /* SERVER_CERT */
390 {TLS_HANDSHAKE, TLS_SERVER_KEY, 'S', {s2n_server_key_send, s2n_server_key_recv}}, /* SERVER_KEY */
391 {TLS_HANDSHAKE, TLS_SERVER_CERT_REQ, 'S', {NULL, NULL}}, /* SERVER_CERT_REQ */
392 {TLS_HANDSHAKE, TLS_SERVER_HELLO_DONE, 'S', {s2n_server_done_send, s2n_server_done_recv}}, /* SERVER_HELLO_DONE */
393 {TLS_HANDSHAKE, TLS_CLIENT_CERT, 'C', {NULL, NULL}}, /* CLIENT_CERT */
394 {TLS_HANDSHAKE, TLS_CLIENT_KEY, 'C', {s2n_client_key_recv, s2n_client_key_send}}, /* CLIENT_KEY */
395 {TLS_HANDSHAKE, TLS_CLIENT_CERT_VERIFY,'C', {NULL, NULL}}, /* CLIENT_CERT_VERIFY */
396 {TLS_CHANGE_CIPHER_SPEC, 0, 'C', {s2n_client_ccs_recv, s2n_client_ccs_send}}, /* CLIENT_CHANGE_CIPHER_SPEC */
397 {TLS_HANDSHAKE, TLS_CLIENT_FINISHED, 'C', {s2n_client_finished_recv, s2n_client_finished_send}}, /* CLIENT_FINISHED */
398 {TLS_CHANGE_CIPHER_SPEC, 0, 'S', {s2n_server_ccs_send, s2n_server_ccs_recv}}, /* SERVER_CHANGE_CIPHER_SPEC */
399 {TLS_HANDSHAKE, TLS_SERVER_FINISHED, 'S', {s2n_server_finished_send, s2n_server_finished_recv}}, /* SERVER_FINISHED */
400 {TLS_APPLICATION_DATA, 0, 'B', {NULL, NULL}} /* HANDSHAKE_OVER */
401 };
402 ```
403
404 The 'writer' field indicates whether we expect a Client or a Server to write a particular message type (or 'B' for both in the case of an application data message, but we haven't gotten to that yet). If s2n-tls is acting as a server, then it attempts to read client messages, if it's acting as a client it will try to write it. To perform either operation it calls the relevant function pointer. This way the state machine can be very short and simple: write a handshake message out when we have one pending, and in the other direction read in data until we have a fully-buffered handshake message before then calling the relevant message parsing function.
405
406 One detail we've skipped over so far is that handshake messages are encapsulated by an additional record layer within the TLS protocol. As we've already seen, TLS records are fairly simple: just a 5-byte header indicating the message type (Handshake, application data, and alerts), protocol version, and record size. The remainder of the record is data and may or may not be encrypted. What isn't so simple is that TLS allows 'inner' messages, like Handshake message, to be fragmented across several records, and for a single record to contain multiple messages.
407
408 ![TLS layers](images/s2n_tls_layers.png "s2n-tls TLS layers")
409
410 In the outbound direction, s2n-tls never coalesces multiple messages into a single record, so writing a handshake message is a simple matter of fragmenting the handshake message if necessary and writing the records. In the inbound direction, the small state machine in s2n_handshake_io.c takes care of any fragmentation and coalescing. See [tests/unit/s2n_fragmentation_coalescing_test.c](https://github.com/aws/s2n-tls/blob/main/tests/unit/s2n_fragmentation_coalescing_test.c) for our test cases covering the logic too.
411
412 To perform all of this, the s2n_connection structure has a few more internal stuffers:
413
414 ```c
415 struct s2n_stuffer header_in;
416 struct s2n_stuffer in;
417 struct s2n_stuffer out;
418 struct s2n_stuffer alert_in;
419 ```
420
421 'header_in' is a small 5-byte stuffer, which is used to read in a record header. Once that stuffer is full, and the size of the next record is determined (from that header), inward data is directed to the 'in' stuffer. The 'out' stuffer is for data that we are writing out; like an encrypted TLS record. 'alert_in' is for any TLS alert message that s2n-tls receives from its peer. s2n-tls treats all alerts as fatal, but we buffer the full alert message so that reason can be logged.
422
423 When past the handshake phase, s2n-tls supports full-duplex I/O. Separate threads or event handlers are free to call s2n_send and s2n_recv on the same connection. Because either a read or a write may cause a connection to be closed, there are two additional fields for storing outbound alert messages:
424
425 ```c
426 uint8_t reader_alert_out;
427 uint8_t writer_alert_out;
428 ```
429
430 This pattern means that both the reader thread and writer thread can create pending alert messages without needing any locks. If either the reader or writer generates an alert, it also sets the 'closed' states to 1.
431
432 ```c
433 sig_atomic_t read_closed;
434 sig_atomic_t write_closed;
435 ```
436
437 These fields are atomic. However because they are only ever changed from 0 to 1, an over-write would be harmless.
438
439 s2n-tls only sends fatal alerts during `s2n_shutdown()` or `s2n_shutdown_send()`.
440 Only one alert is sent, so writer alerts take priority if both are present.
441 If no alerts are present, then a generic close_notify will be sent instead.
442
443 ## s2n-tls and entropy
444
445 s2n-tls provides two deterministic random number generators to every thread. **s2n_get_public_random_data()** should be used to generate any data that is exposed in a public context including nonces, initialization vectors, and randomized timing values. **s2n_get_private_random_data()** should be used for data which must be kept secret. Additionally s2n-tls over-rides libcrypto's entropy generation with **s2n_get_private_random_data()**.
446
447 ## Contributing to s2n-tls
448
449 We are happy to accept contributions to s2n-tls . We suggest the following general procedure:
450
451 * Please read all of the documentation available in the s2n-tls "docs/" directory. This development guide along with the usage guide should give a good flavor for what the goals of s2n-tls are and whether they line up with your idea for a contribution
452 * If you have an idea for a significant contribution, it is worth first cutting an issue and discussing the change. Get feedback on the API design, or what the feature might require, before writing code.
453 * If you discover a security critical bug, please report it via http://aws.amazon.com/security/vulnerability-reporting/ and **do not** create a public issue.
454 * Create a git fork of the s2n-tls repository and prepare your changes locally within your fork.
455 * When you're ready, and when all tests are passing, create a pull request to the master awslabs s2n-tls repository.
456 * All changes to s2n-tls go through code review and legal review. All submissions and contributions are made under the terms of the Apache Software License 2.0. For larger contributions, we may ask you to sign a contributor license agreement.
457 * s2n-tls undergoes periodic government and commercial security analyses, including code audits and penetration tests. To participate in these analyses, we may ask you to sign a Non-Disclosure Agreement.