1 /*
2  * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License").
5  * You may not use this file except in compliance with the License.
6  * A copy of the License is located at
7  *
8  *  http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */
15 
16 #pragma once
17 
18 #include <errno.h>
19 #include <s2n.h>
20 #include <signal.h>
21 #include <stdint.h>
22 
23 #include "stuffer/s2n_stuffer.h"
24 
25 #include "tls/s2n_client_hello.h"
26 #include "tls/s2n_config.h"
27 #include "tls/s2n_crypto.h"
28 #include "tls/s2n_early_data.h"
29 #include "tls/s2n_handshake.h"
30 #include "tls/s2n_prf.h"
31 #include "tls/s2n_quic_support.h"
32 #include "tls/s2n_tls_parameters.h"
33 #include "tls/s2n_x509_validator.h"
34 #include "tls/s2n_key_update.h"
35 #include "tls/s2n_kem_preferences.h"
36 #include "tls/s2n_ecc_preferences.h"
37 #include "tls/s2n_security_policies.h"
38 #include "tls/s2n_record.h"
39 
40 #include "crypto/s2n_hash.h"
41 #include "crypto/s2n_hmac.h"
42 
43 #include "utils/s2n_mem.h"
44 #include "utils/s2n_timer.h"
45 
46 #define S2N_TLS_PROTOCOL_VERSION_LEN    2
47 
48 #define S2N_PEER_MODE(our_mode) ((our_mode + 1) % 2)
49 
50 #define is_handshake_complete(conn) (APPLICATION_DATA == s2n_conn_get_current_message_type(conn))
51 
52 typedef enum {
53     S2N_NO_TICKET = 0,
54     S2N_DECRYPT_TICKET,
55     S2N_NEW_TICKET
56 } s2n_session_ticket_status;
57 
58 struct s2n_connection {
59     /* The following bitfield flags are used in SAW proofs. The positions of
60      * these flags are important, as SAW looks up each flag by their index
61      * in the struct starting from 0. See the comments surrounding
62      * conn_bitfield in tests/saw/spec/handshake/handshake_io_lowlevel.saw for
63      * more details. Make sure that any new flags are added after these ones
64      * so that the indices in the SAW proofs do not need to be changed each time.
65      *
66      * START OF SAW-TRACKED BITFIELD FLAGS */
67 
68     /* Is this connection using CORK/SO_RCVLOWAT optimizations? Only valid when the connection is using
69      * managed_send_io
70      */
71     unsigned corked_io:1;
72 
73     /* Session resumption indicator on client side */
74     unsigned client_session_resumed:1;
75 
76     /* Connection can be used by a QUIC implementation */
77     unsigned quic_enabled:1;
78 
79     /* END OF SAW-TRACKED BITFIELD FLAGS */
80 
81     /* Determines if we're currently sending or receiving in s2n_shutdown */
82     unsigned close_notify_queued:1;
83 
84     /* s2n does not support renegotiation.
85      * RFC5746 Section 4.3 suggests servers implement a minimal version of the
86      * renegotiation_info extension even if renegotiation is not supported.
87      * Some clients may fail the handshake if a corresponding renegotiation_info
88      * extension is not sent back by the server.
89      */
90     unsigned secure_renegotiation:1;
91     /* Was the EC point formats sent by the client */
92     unsigned ec_point_formats:1;
93 
94     /* whether the connection address is ipv6 or not */
95     unsigned ipv6:1;
96 
97     /* Whether server_name extension was used to make a decision on cert selection.
98      * RFC6066 Section 3 states that server which used server_name to make a decision
99      * on certificate or security settings has to send an empty server_name.
100      */
101     unsigned server_name_used:1;
102 
103     /* If write fd is broken */
104     unsigned write_fd_broken:1;
105 
106     /* Has the user set their own I/O callbacks or is this connection using the
107      * default socket-based I/O set by s2n */
108     unsigned managed_send_io:1;
109     unsigned managed_recv_io:1;
110 
111     /* Key update data */
112     unsigned key_update_pending:1;
113 
114     /* Early data supported by caller.
115      * If a caller does not use any APIs that support early data,
116      * do not negotiate early data.
117      */
118     unsigned early_data_expected:1;
119 
120     /* Connection overrides server_max_early_data_size */
121     unsigned server_max_early_data_size_overridden:1;
122 
123     /* Connection overrides psk_mode.
124      * This means that the connection will keep the existing value of psk_params->type,
125      * even when setting a new config. */
126     unsigned psk_mode_overridden:1;
127 
128     /* Have we received a close notify alert from the peer. */
129     unsigned close_notify_received:1;
130 
131     /* Connection negotiated an EMS */
132     unsigned ems_negotiated:1;
133 
134     /* The configuration (cert, key .. etc ) */
135     struct s2n_config *config;
136 
137     /* Overrides Security Policy in config if non-null */
138     const struct s2n_security_policy *security_policy_override;
139 
140     /* The user defined context associated with connection */
141     void *context;
142 
143     /* The user defined secret callback and context */
144     s2n_secret_cb secret_cb;
145     void *secret_cb_context;
146 
147     /* The send and receive callbacks don't have to be the same (e.g. two pipes) */
148     s2n_send_fn *send;
149     s2n_recv_fn *recv;
150 
151     /* The context passed to the I/O callbacks */
152     void *send_io_context;
153     void *recv_io_context;
154 
155     /* Track request extensions to ensure correct response extension behavior.
156      *
157      * We need to track client and server extensions separately because some
158      * extensions (like request_status and other Certificate extensions) can
159      * be requested by the client, the server, or both.
160      */
161     s2n_extension_bitfield extension_requests_sent;
162     s2n_extension_bitfield extension_requests_received;
163 
164     /* Is this connection a client or a server connection */
165     s2n_mode mode;
166 
167     /* Does s2n handle the blinding, or does the application */
168     s2n_blinding blinding;
169 
170     /* A timer to measure the time between record writes */
171     struct s2n_timer write_timer;
172 
173     /* last written time */
174     uint64_t last_write_elapsed;
175 
176     /* When fatal errors occurs, s2n imposes a pause before
177      * the connection is closed. If non-zero, this value tracks
178      * how many nanoseconds to pause - which will be relative to
179      * the write_timer value. */
180     uint64_t delay;
181 
182     /* The session id */
183     uint8_t session_id[S2N_TLS_SESSION_ID_MAX_LEN];
184     uint8_t session_id_len;
185 
186     /* The version advertised by the client, by the
187      * server, and the actual version we are currently
188      * speaking. */
189     uint8_t client_hello_version;
190     uint8_t client_protocol_version;
191     uint8_t server_protocol_version;
192     uint8_t actual_protocol_version;
193 
194     /* Flag indicating whether a protocol version has been
195      * negotiated yet. */
196     uint8_t actual_protocol_version_established;
197 
198     /* Our crypto parameters */
199     struct s2n_crypto_parameters initial;
200     struct s2n_crypto_parameters secure;
201     struct s2n_secrets secrets;
202 
203     /* Which set is the client/server actually using? */
204     struct s2n_crypto_parameters *client;
205     struct s2n_crypto_parameters *server;
206 
207     /* Contains parameters needed to negotiate a shared secret */
208     struct s2n_kex_parameters kex_params;
209 
210     /* Contains parameters needed during the handshake phase */
211     struct s2n_handshake_parameters handshake_params;
212 
213     /* Our PSK parameters */
214     struct s2n_psk_parameters psk_params;
215 
216     /* The PRF needs some storage elements to work with */
217     struct s2n_prf_working_space *prf_space;
218 
219     /* Whether to use client_cert_auth_type stored in s2n_config or in this s2n_connection.
220      *
221      * By default the s2n_connection will defer to s2n_config->client_cert_auth_type on whether or not to use Client Auth.
222      * But users can override Client Auth at the connection level using s2n_connection_set_client_auth_type() without mutating
223      * s2n_config since s2n_config can be shared between multiple s2n_connections. */
224     uint8_t client_cert_auth_type_overridden;
225 
226     /* Whether or not the s2n_connection should require the Client to authenticate itself to the server. Only used if
227      * client_cert_auth_type_overridden is non-zero. */
228     s2n_cert_auth_type client_cert_auth_type;
229 
230     /* Our workhorse stuffers, used for buffering the plaintext
231      * and encrypted data in both directions.
232      */
233     uint8_t header_in_data[S2N_TLS_RECORD_HEADER_LENGTH];
234     struct s2n_stuffer header_in;
235     struct s2n_stuffer in;
236     struct s2n_stuffer out;
237     enum { ENCRYPTED, PLAINTEXT } in_status;
238 
239     /* How much of the current user buffer have we already
240      * encrypted and sent or have pending for the wire but have
241      * not acknowledged to the user.
242      */
243     ssize_t current_user_data_consumed;
244 
245     /* An alert may be fragmented across multiple records,
246      * this stuffer is used to re-assemble.
247      */
248     uint8_t alert_in_data[S2N_ALERT_LENGTH];
249     struct s2n_stuffer alert_in;
250 
251     /* An alert may be partially written in the outbound
252      * direction, so we keep this as a small 2 byte queue.
253      *
254      * We keep separate queues for alerts generated by
255      * readers (a response to an alert from a peer) and writers (an
256      * intentional shutdown) so that the s2n reader and writer
257      * can be separate duplex I/O threads.
258      */
259     uint8_t reader_alert_out_data[S2N_ALERT_LENGTH];
260     uint8_t writer_alert_out_data[S2N_ALERT_LENGTH];
261     struct s2n_stuffer reader_alert_out;
262     struct s2n_stuffer writer_alert_out;
263 
264     /* Our handshake state machine */
265     struct s2n_handshake handshake;
266 
267     /* Maximum outgoing fragment size for this connection. Does not limit
268      * incoming record size.
269      *
270      * This value is updated when:
271      *   1. s2n_connection_prefer_low_latency is set
272      *   2. s2n_connection_prefer_throughput is set
273      *   3. TLS Maximum Fragment Length extension is negotiated
274      *
275      * Default value: S2N_DEFAULT_FRAGMENT_LENGTH
276      */
277     uint16_t max_outgoing_fragment_length;
278 
279     /* The number of bytes to send before changing the record size.
280      * If this value > 0 then dynamic TLS record size is enabled. Otherwise, the feature is disabled (default).
281      */
282     uint32_t dynamic_record_resize_threshold;
283 
284     /* Reset record size back to a single segment after threshold seconds of inactivity */
285     uint16_t dynamic_record_timeout_threshold;
286 
287     /* number of bytes consumed during application activity */
288     uint64_t active_application_bytes_consumed;
289 
290     /* Negotiated TLS extension Maximum Fragment Length code.
291      * If set, the client and server have both agreed to fragment their records to the given length. */
292     uint8_t negotiated_mfl_code;
293 
294     /* Keep some accounting on each connection */
295     uint64_t wire_bytes_in;
296     uint64_t wire_bytes_out;
297     uint64_t early_data_bytes;
298 
299     /* Is the connection open or closed ? We use C's only
300      * atomic type as both the reader and the writer threads
301      * may declare a connection closed.
302      *
303      * A connection can be gracefully closed or hard-closed.
304      * When gracefully closed the reader or the writer mark
305      * the connection as closing, and then the writer will
306      * send an alert message before closing the connection
307      * and marking it as closed.
308      *
309      * A hard-close goes straight to closed with no alert
310      * message being sent.
311      */
312     sig_atomic_t closing;
313     sig_atomic_t closed;
314 
315     /* TLS extension data */
316     char server_name[S2N_MAX_SERVER_NAME + 1];
317 
318     /* The application protocol decided upon during the client hello.
319      * If ALPN is being used, then:
320      * In server mode, this will be set by the time client_hello_cb is invoked.
321      * In client mode, this will be set after is_handshake_complete(connection) is true.
322      */
323     char application_protocol[256];
324 
325     /* OCSP stapling response data */
326     s2n_status_request_type status_type;
327     struct s2n_blob status_response;
328 
329     /* Certificate Transparency response data */
330     s2n_ct_support_level ct_level_requested;
331     struct s2n_blob ct_response;
332 
333     /* QUIC transport parameters data: https://tools.ietf.org/html/draft-ietf-quic-tls-29#section-8.2 */
334     struct s2n_blob our_quic_transport_parameters;
335     struct s2n_blob peer_quic_transport_parameters;
336 
337     struct s2n_client_hello client_hello;
338 
339     struct s2n_x509_validator x509_validator;
340 
341     /* After a connection is created this is the verification function that should always be used. At init time,
342      * the config should be checked for a verify callback and each connection should default to that. However,
343      * from the user's perspective, it's sometimes simpler to manage state by attaching each validation function/data
344      * to the connection, instead of globally to a single config.*/
345     s2n_verify_host_fn verify_host_fn;
346     void *data_for_verify_host;
347     uint8_t verify_host_fn_overridden;
348 
349     /* Session ticket data */
350     s2n_session_ticket_status session_ticket_status;
351     struct s2n_blob client_ticket;
352     uint32_t ticket_lifetime_hint;
353     struct s2n_ticket_fields tls13_ticket_fields;
354 
355     /* Session ticket extension from client to attempt to decrypt as the server. */
356     uint8_t ticket_ext_data[S2N_TLS12_TICKET_SIZE_IN_BYTES];
357     struct s2n_stuffer client_ticket_to_decrypt;
358 
359     uint8_t resumption_master_secret[S2N_TLS13_SECRET_MAX_LEN];
360 
361     /* application protocols overridden */
362     struct s2n_blob application_protocols_overridden;
363 
364     /* Cookie extension data */
365     struct s2n_stuffer cookie_stuffer;
366 
367     /* Flags to prevent users from calling methods recursively.
368      * This can be an easy mistake to make when implementing send/receive callbacks.
369      */
370     bool send_in_use;
371     bool recv_in_use;
372 
373     uint16_t tickets_to_send;
374     uint16_t tickets_sent;
375 
376     s2n_early_data_state early_data_state;
377     uint32_t server_max_early_data_size;
378     struct s2n_blob server_early_data_context;
379     uint32_t server_keying_material_lifetime;
380 };
381 
382 int s2n_connection_is_managed_corked(const struct s2n_connection *s2n_connection);
383 int s2n_connection_is_client_auth_enabled(struct s2n_connection *s2n_connection);
384 
385 /* Kill a bad connection */
386 int s2n_connection_kill(struct s2n_connection *conn);
387 
388 /* Send/recv a stuffer to/from a connection */
389 int s2n_connection_send_stuffer(struct s2n_stuffer *stuffer, struct s2n_connection *conn, uint32_t len);
390 int s2n_connection_recv_stuffer(struct s2n_stuffer *stuffer, struct s2n_connection *conn, uint32_t len);
391 
392 S2N_RESULT s2n_connection_wipe_all_keyshares(struct s2n_connection *conn);
393 
394 int s2n_connection_get_cipher_preferences(struct s2n_connection *conn, const struct s2n_cipher_preferences **cipher_preferences);
395 int s2n_connection_get_security_policy(struct s2n_connection *conn, const struct s2n_security_policy **security_policy);
396 int s2n_connection_get_kem_preferences(struct s2n_connection *conn, const struct s2n_kem_preferences **kem_preferences);
397 int s2n_connection_get_signature_preferences(struct s2n_connection *conn, const struct s2n_signature_preferences **signature_preferences);
398 int s2n_connection_get_ecc_preferences(struct s2n_connection *conn, const struct s2n_ecc_preferences **ecc_preferences);
399 int s2n_connection_get_protocol_preferences(struct s2n_connection *conn, struct s2n_blob **protocol_preferences);
400 int s2n_connection_set_client_auth_type(struct s2n_connection *conn, s2n_cert_auth_type cert_auth_type);
401 int s2n_connection_get_client_auth_type(struct s2n_connection *conn, s2n_cert_auth_type *client_cert_auth_type);
402 int s2n_connection_get_client_cert_chain(struct s2n_connection *conn, uint8_t **der_cert_chain_out, uint32_t *cert_chain_len);
403 int s2n_connection_get_peer_cert_chain(const struct s2n_connection *conn, struct s2n_cert_chain_and_key *cert_chain_and_key);
404 uint8_t s2n_connection_get_protocol_version(const struct s2n_connection *conn);
405 S2N_RESULT s2n_connection_set_max_fragment_length(struct s2n_connection *conn, uint16_t length);
406