1 /*
2  * Copyright (C) 2000-2016 Free Software Foundation, Inc.
3  * Copyright (C) 2015-2018 Red Hat, Inc.
4  *
5  * Author: Nikos Mavrogiannopoulos
6  *
7  * This file is part of GnuTLS.
8  *
9  * The GnuTLS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1 of
12  * the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program.  If not, see <https://www.gnu.org/licenses/>
21  *
22  */
23 
24 #ifndef GNUTLS_LIB_GNUTLS_INT_H
25 #define GNUTLS_LIB_GNUTLS_INT_H
26 
27 #ifdef HAVE_CONFIG_H
28 #include <config.h>
29 #endif
30 
31 #include <stddef.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <ctype.h>
36 #include <limits.h>
37 #include <stdint.h>
38 #include <stdbool.h>
39 #include <assert.h>
40 
41 #ifdef NO_SSIZE_T
42 #define HAVE_SSIZE_T
43 typedef int ssize_t;
44 #endif
45 
46 #include <sys/types.h>
47 #include <unistd.h>
48 #include <sys/stat.h>
49 #if HAVE_SYS_SOCKET_H
50 #include <sys/socket.h>
51 #elif HAVE_WS2TCPIP_H
52 #include <ws2tcpip.h>
53 #endif
54 #include <time.h>
55 
56 #include <nettle/memxor.h>
57 
58 #include "attribute.h"
59 
60 #define ENABLE_ALIGN16
61 
62 #ifdef __clang_major
63 # define _GNUTLS_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
64 #else
65 # define _GNUTLS_CLANG_VERSION 0
66 #endif
67 
68 /* clang also defines __GNUC__. It promotes a GCC version of 4.2.1. */
69 #ifdef __GNUC__
70 # define _GNUTLS_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
71 #endif
72 
73 #if _GNUTLS_GCC_VERSION >= 30100
74 # define likely(x)      __builtin_expect((x), 1)
75 # define unlikely(x)    __builtin_expect((x), 0)
76 #else
77 # define likely
78 # define unlikely
79 #endif
80 
81 #include <gnutls/gnutls.h>
82 #include <gnutls/dtls.h>
83 #include <gnutls/abstract.h>
84 #include <gnutls/socket.h>
85 #include <system.h>
86 
87 /* in case we compile with system headers taking priority, we
88  * make sure that some new attributes are still available.
89  */
90 #ifndef __GNUTLS_CONST__
91 # define __GNUTLS_CONST__
92 #endif
93 
94 /* The size of a handshake message should not
95  * be larger than this value.
96  */
97 #define MAX_HANDSHAKE_PACKET_SIZE 128*1024
98 
99 #define GNUTLS_DEF_SESSION_ID_SIZE 32
100 
101 /* The maximum digest size of hash algorithms.
102  */
103 #define MAX_FILENAME 512
104 #define MAX_HASH_SIZE 64
105 
106 #define MAX_MAC_KEY_SIZE 64
107 
108 #define MAX_CIPHER_BLOCK_SIZE 64 /* CHACHA20 */
109 #define MAX_CIPHER_KEY_SIZE 32
110 
111 #define MAX_CIPHER_IV_SIZE 16
112 
113 #define MAX_USERNAME_SIZE 128
114 #define MAX_SERVER_NAME_SIZE 256
115 
116 #define AEAD_EXPLICIT_DATA_SIZE 8
117 #define AEAD_IMPLICIT_DATA_SIZE 4
118 
119 #define GNUTLS_MASTER_SIZE 48
120 #define GNUTLS_RANDOM_SIZE 32
121 
122 /* Under TLS1.3 a hello retry request is sent as server hello */
123 #define REAL_HSK_TYPE(t) ((t)==GNUTLS_HANDSHAKE_HELLO_RETRY_REQUEST?GNUTLS_HANDSHAKE_SERVER_HELLO:t)
124 
125 /* DTLS */
126 #define DTLS_RETRANS_TIMEOUT 1000
127 
128 /* TLS Extensions */
129 /* we can receive up to MAX_EXT_TYPES extensions.
130  */
131 #define MAX_EXT_TYPES 64
132 
133 /* TLS-internal extension (will be parsed after a ciphersuite is selected).
134  * This amends the gnutls_ext_parse_type_t. Not exported yet to allow more refining
135  * prior to finalizing an API. */
136 #define _GNUTLS_EXT_TLS_POST_CS 177
137 
138 /* expire time for resuming sessions */
139 #define DEFAULT_EXPIRE_TIME 21600
140 #define STEK_ROTATION_PERIOD_PRODUCT 3
141 #define DEFAULT_HANDSHAKE_TIMEOUT_MS 40*1000
142 
143 /* The EC group to be used when the extension
144  * supported groups/curves is not present */
145 #define DEFAULT_EC_GROUP GNUTLS_GROUP_SECP256R1
146 
147 typedef enum transport_t {
148 	GNUTLS_STREAM,
149 	GNUTLS_DGRAM
150 } transport_t;
151 
152 /* The TLS 1.3 stage of handshake */
153 typedef enum hs_stage_t {
154 	STAGE_HS,
155 	STAGE_APP,
156 	STAGE_UPD_OURS,
157 	STAGE_UPD_PEERS,
158 	STAGE_EARLY
159 } hs_stage_t;
160 
161 typedef enum record_send_state_t {
162 	RECORD_SEND_NORMAL = 0,
163 	RECORD_SEND_CORKED, /* corked and transition to NORMAL afterwards */
164 	RECORD_SEND_CORKED_TO_KU, /* corked but must transition to RECORD_SEND_KEY_UPDATE_1 */
165 	RECORD_SEND_KEY_UPDATE_1,
166 	RECORD_SEND_KEY_UPDATE_2,
167 	RECORD_SEND_KEY_UPDATE_3
168 } record_send_state_t;
169 
170 /* The mode check occurs a lot throughout GnuTLS and can be replaced by
171  * the following shorter macro. Also easier to update one macro
172  * in the future when the internal structure changes than all the conditionals
173  * itself.
174  */
175 #define IS_SERVER(session) (session->security_parameters.entity == GNUTLS_SERVER)
176 
177 /* To check whether we have a DTLS session */
178 #define IS_DTLS(session) (session->internals.transport == GNUTLS_DGRAM)
179 
180 /* the maximum size of encrypted packets */
181 #define DEFAULT_MAX_RECORD_SIZE 16384
182 #define DEFAULT_MAX_EARLY_DATA_SIZE 16384
183 #define TLS_RECORD_HEADER_SIZE 5
184 #define DTLS_RECORD_HEADER_SIZE (TLS_RECORD_HEADER_SIZE+8)
185 #define RECORD_HEADER_SIZE(session) (IS_DTLS(session) ? DTLS_RECORD_HEADER_SIZE : TLS_RECORD_HEADER_SIZE)
186 #define MAX_RECORD_HEADER_SIZE DTLS_RECORD_HEADER_SIZE
187 
188 #define MIN_RECORD_SIZE 512
189 #define MIN_RECORD_SIZE_SMALL 64
190 
191 /* The following macro is used to calculate the overhead when sending.
192  * when receiving we use a different way as there are implementations that
193  * store more data than allowed.
194  */
195 #define MAX_RECORD_SEND_OVERHEAD(session) (MAX_CIPHER_BLOCK_SIZE/*iv*/+MAX_PAD_SIZE+MAX_HASH_SIZE/*MAC*/)
196 #define MAX_RECORD_SEND_SIZE(session) (IS_DTLS(session)? \
197 	(MIN((size_t)gnutls_dtls_get_mtu(session), (size_t)session->security_parameters.max_record_send_size+MAX_RECORD_SEND_OVERHEAD(session))): \
198 	((size_t)session->security_parameters.max_record_send_size+MAX_RECORD_SEND_OVERHEAD(session)))
199 #define MAX_PAD_SIZE 255
200 #define EXTRA_COMP_SIZE 2048
201 
202 #define TLS_HANDSHAKE_HEADER_SIZE 4
203 #define DTLS_HANDSHAKE_HEADER_SIZE (TLS_HANDSHAKE_HEADER_SIZE+8)
204 #define HANDSHAKE_HEADER_SIZE(session) (IS_DTLS(session) ? DTLS_HANDSHAKE_HEADER_SIZE : TLS_HANDSHAKE_HEADER_SIZE)
205 #define MAX_HANDSHAKE_HEADER_SIZE DTLS_HANDSHAKE_HEADER_SIZE
206 
207 /* Maximum seed size for provable parameters */
208 #define MAX_PVP_SEED_SIZE 256
209 
210 /* This is the maximum handshake message size we send without
211    fragmentation. This currently ignores record layer overhead. */
212 #define DTLS_DEFAULT_MTU 1200
213 
214 /* the maximum size of the DTLS cookie */
215 #define DTLS_MAX_COOKIE_SIZE 32
216 
217 /* The maximum number of HELLO_VERIFY_REQUEST messages the client
218    processes before aborting. */
219 #define MAX_HANDSHAKE_HELLO_VERIFY_REQUESTS 5
220 
221 #define MAX_PK_PARAM_SIZE 2048
222 
223 /* defaults for verification functions
224  */
225 #define DEFAULT_MAX_VERIFY_DEPTH 16
226 #define DEFAULT_MAX_VERIFY_BITS (MAX_PK_PARAM_SIZE*8)
227 #define MAX_VERIFY_DEPTH 4096
228 
229 #include <mem.h>
230 
231 #define MEMSUB(x,y) ((ssize_t)((ptrdiff_t)x-(ptrdiff_t)y))
232 
233 #define DECR_LEN(len, x) DECR_LENGTH_RET(len, x, GNUTLS_E_UNEXPECTED_PACKET_LENGTH)
234 #define DECR_LEN_FINAL(len, x) do { \
235 	if (len != x) \
236 		return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH); \
237 	else \
238 		len = 0; \
239 	} while (0)
240 #define DECR_LENGTH_RET(len, x, RET) DECR_LENGTH_COM(len, x, return RET)
241 #define DECR_LENGTH_COM(len, x, COM) do { if (len<x) {gnutls_assert(); COM;} else len-=x; } while (0)
242 
243 #define GNUTLS_POINTER_TO_INT(_) ((int) GNUTLS_POINTER_TO_INT_CAST (_))
244 #define GNUTLS_INT_TO_POINTER(_) ((void*) GNUTLS_POINTER_TO_INT_CAST (_))
245 
246 #define GNUTLS_KX_INVALID (-1)
247 
248 #include <mpi.h>
249 
250 typedef enum handshake_state_t { STATE0 = 0, STATE1, STATE2,
251 	STATE3, STATE4, STATE5, STATE6, STATE7, STATE8,
252 	STATE9, STATE10, STATE11, STATE12, STATE13, STATE14,
253 	STATE15, STATE16, STATE17, STATE18, STATE19,
254 	STATE20 = 20, STATE21, STATE22,
255 	STATE30 = 30, STATE31, STATE40 = 40, STATE41, STATE50 = 50,
256 	STATE90=90, STATE91, STATE92, STATE93, STATE94, STATE99=99,
257 	STATE100=100, STATE101, STATE102, STATE103, STATE104,
258 	STATE105, STATE106, STATE107, STATE108, STATE109, STATE110,
259 	STATE111, STATE112, STATE113, STATE114, STATE115,
260 	STATE150 /* key update */
261 } handshake_state_t;
262 
263 typedef enum bye_state_t {
264 	BYE_STATE0 = 0, BYE_STATE1, BYE_STATE2
265 } bye_state_t;
266 
267 typedef enum send_ticket_state_t {
268 	TICKET_STATE0 = 0, TICKET_STATE1
269 } send_ticket_state_t;
270 
271 typedef enum reauth_state_t {
272 	REAUTH_STATE0 = 0, REAUTH_STATE1, REAUTH_STATE2, REAUTH_STATE3,
273 	REAUTH_STATE4, REAUTH_STATE5
274 } reauth_state_t;
275 
276 #define TICKET_STATE session->internals.ticket_state
277 #define BYE_STATE session->internals.bye_state
278 #define REAUTH_STATE session->internals.reauth_state
279 
280 typedef enum heartbeat_state_t {
281 	SHB_SEND1 = 0,
282 	SHB_SEND2,
283 	SHB_RECV
284 } heartbeat_state_t;
285 
286 typedef enum recv_state_t {
287 	RECV_STATE_0 = 0,
288 	RECV_STATE_DTLS_RETRANSMIT,
289 	/* client-side false start state */
290 	RECV_STATE_FALSE_START_HANDLING, /* we are calling gnutls_handshake() within record_recv() */
291 	RECV_STATE_FALSE_START, /* gnutls_record_recv() should complete the handshake */
292 	/* async handshake msg state */
293 	RECV_STATE_ASYNC_HANDSHAKE, /* an incomplete async handshake message was seen */
294 	/* server-side early start under TLS1.3; enabled when no client cert is received */
295 	RECV_STATE_EARLY_START_HANDLING, /* we are calling gnutls_handshake() within record_recv() */
296 	RECV_STATE_EARLY_START, /* gnutls_record_recv() should complete the handshake */
297 	RECV_STATE_REHANDSHAKE, /* gnutls_record_recv() should complete any incoming re-handshake requests */
298 	RECV_STATE_REAUTH /* gnutls_record_recv() should complete any incoming reauthentication requests */
299 } recv_state_t;
300 
301 #include "str.h"
302 
303 /* This is the maximum number of algorithms (ciphers or macs etc).
304  * keep it synced with GNUTLS_MAX_ALGORITHM_NUM in gnutls.h
305  */
306 #define MAX_ALGOS GNUTLS_MAX_ALGORITHM_NUM
307 
308 /* IDs are allocated in a way that all values fit in 64-bit integer as (1<<val) */
309 typedef enum extensions_t {
310 	GNUTLS_EXTENSION_INVALID = 0xffff,
311 	GNUTLS_EXTENSION_STATUS_REQUEST = 0,
312 	GNUTLS_EXTENSION_CERT_TYPE,
313 	GNUTLS_EXTENSION_CLIENT_CERT_TYPE,
314 	GNUTLS_EXTENSION_SERVER_CERT_TYPE,
315 	GNUTLS_EXTENSION_SUPPORTED_GROUPS,
316 	GNUTLS_EXTENSION_SUPPORTED_EC_POINT_FORMATS,
317 	GNUTLS_EXTENSION_SRP,
318 	GNUTLS_EXTENSION_SIGNATURE_ALGORITHMS,
319 	GNUTLS_EXTENSION_SRTP,
320 	GNUTLS_EXTENSION_HEARTBEAT,
321 	GNUTLS_EXTENSION_ALPN,
322 	GNUTLS_EXTENSION_ETM,
323 	GNUTLS_EXTENSION_EXT_MASTER_SECRET,
324 	GNUTLS_EXTENSION_SESSION_TICKET,
325 	GNUTLS_EXTENSION_KEY_SHARE,
326 	GNUTLS_EXTENSION_SUPPORTED_VERSIONS,
327 	GNUTLS_EXTENSION_POST_HANDSHAKE,
328 	GNUTLS_EXTENSION_SAFE_RENEGOTIATION,
329 	GNUTLS_EXTENSION_SERVER_NAME,
330 	GNUTLS_EXTENSION_COOKIE,
331 	GNUTLS_EXTENSION_EARLY_DATA,
332 	GNUTLS_EXTENSION_PSK_KE_MODES,
333 	GNUTLS_EXTENSION_RECORD_SIZE_LIMIT,
334 	GNUTLS_EXTENSION_MAX_RECORD_SIZE,
335 	/*
336 	 * pre_shared_key and dumbfw must always be the last extensions,
337 	 * in that order */
338 	GNUTLS_EXTENSION_DUMBFW,
339 	GNUTLS_EXTENSION_PRE_SHARED_KEY,
340 	GNUTLS_EXTENSION_MAX /* not real extension - used for iterators */
341 } extensions_t;
342 
343 #define GNUTLS_EXTENSION_MAX_VALUE 63
344 #define ext_track_t uint64_t
345 
346 #include <verify.h>
347 
348 verify(GNUTLS_EXTENSION_MAX < GNUTLS_EXTENSION_MAX_VALUE);
349 verify(GNUTLS_EXTENSION_MAX < MAX_EXT_TYPES);
350 
351 /* we must provide at least 16 extensions for users to register;
352  * increase GNUTLS_EXTENSION_MAX_VALUE, MAX_EXT_TYPES and used_exts
353  * type if this fails
354  */
355 verify(GNUTLS_EXTENSION_MAX_VALUE - GNUTLS_EXTENSION_MAX >= 16);
356 
357 /* The 'verify' symbol from <verify.h> is used extensively in the
358  * code; undef it to avoid clash
359  */
360 #undef verify
361 
362 typedef enum { CIPHER_STREAM, CIPHER_BLOCK, CIPHER_AEAD } cipher_type_t;
363 
364 #define RESUME_TRUE 1
365 #define RESUME_FALSE 0
366 
367 /* Record Protocol */
368 typedef enum content_type_t {
369 	GNUTLS_CHANGE_CIPHER_SPEC = 20, GNUTLS_ALERT,
370 	GNUTLS_HANDSHAKE, GNUTLS_APPLICATION_DATA,
371 	GNUTLS_HEARTBEAT
372 } content_type_t;
373 
374 
375 #define GNUTLS_PK_ANY (gnutls_pk_algorithm_t)-1
376 #define GNUTLS_PK_NONE (gnutls_pk_algorithm_t)-2
377 
378 #define GNUTLS_PK_IS_RSA(pk) ((pk) == GNUTLS_PK_RSA || (pk) == GNUTLS_PK_RSA_PSS)
379 
380 /* Message buffers (mbuffers) structures */
381 
382 /* this is actually the maximum number of distinct handshake
383  * messages that can arrive in a single flight
384  */
385 #define MAX_HANDSHAKE_MSGS 6
386 typedef struct {
387 	/* Handshake layer type and sequence of message */
388 	gnutls_handshake_description_t htype;
389 
390 	/* The "real" type received; that is, it does not distinguish
391 	 * HRR from server hello, while htype does */
392 	gnutls_handshake_description_t rtype;
393 	uint32_t length;
394 
395 	/* valid in DTLS */
396 	uint16_t sequence;
397 
398 	/* indicate whether that message is complete.
399 	 * complete means start_offset == 0 and end_offset == length
400 	 */
401 	uint32_t start_offset;
402 	uint32_t end_offset;
403 
404 	uint8_t header[MAX_HANDSHAKE_HEADER_SIZE];
405 	int header_size;
406 
407 	gnutls_buffer_st data;
408 } handshake_buffer_st;
409 
410 typedef struct mbuffer_st {
411 	/* when used in mbuffer_head_st */
412 	struct mbuffer_st *next;
413 	struct mbuffer_st *prev;
414 
415 	/* msg->size - mark = number of bytes left to process in this
416 	   message. Mark should only be non-zero when this buffer is the
417 	   head of the queue. */
418 	size_t mark;
419 
420 
421 	/* the data */
422 	gnutls_datum_t msg;
423 	size_t maximum_size;
424 
425 	/* used during fill in, to separate header from data
426 	 * body. */
427 	unsigned int uhead_mark;
428 
429 	/* Filled in by record layer on recv:
430 	 * type, record_sequence
431 	 */
432 
433 	/* record layer content type */
434 	content_type_t type;
435 
436 	/* record layer sequence */
437 	uint64_t record_sequence;
438 
439 	/* Filled in by handshake layer on send:
440 	 * type, epoch, htype, handshake_sequence
441 	 */
442 
443 	/* Record layer epoch of message */
444 	uint16_t epoch;
445 
446 	/* Handshake layer type and sequence of message */
447 	gnutls_handshake_description_t htype;
448 	uint16_t handshake_sequence;
449 } mbuffer_st;
450 
451 typedef struct mbuffer_head_st {
452 	mbuffer_st *head;
453 	mbuffer_st *tail;
454 
455 	unsigned int length;
456 	size_t byte_length;
457 } mbuffer_head_st;
458 
459 /* Store & Retrieve functions defines:
460  */
461 
462 typedef struct auth_cred_st {
463 	gnutls_credentials_type_t algorithm;
464 
465 	/* the type of credentials depends on algorithm
466 	 */
467 	void *credentials;
468 	struct auth_cred_st *next;
469 } auth_cred_st;
470 
471 /* session ticket definitions */
472 #define TICKET_MASTER_KEY_SIZE (TICKET_KEY_NAME_SIZE+TICKET_CIPHER_KEY_SIZE+TICKET_MAC_SECRET_SIZE)
473 #define TICKET_KEY_NAME_SIZE 16
474 #define TICKET_CIPHER_KEY_SIZE 32
475 #define TICKET_MAC_SECRET_SIZE 16
476 
477 /* These are restricted by TICKET_CIPHER_KEY_SIZE and TICKET_MAC_SECRET_SIZE */
478 #define TICKET_CIPHER GNUTLS_CIPHER_AES_256_CBC
479 #define TICKET_IV_SIZE 16
480 #define TICKET_BLOCK_SIZE 16
481 
482 #define TICKET_MAC_ALGO GNUTLS_MAC_SHA1
483 #define TICKET_MAC_SIZE 20 /* HMAC-SHA1 */
484 
485 struct ticket_st {
486 	uint8_t key_name[TICKET_KEY_NAME_SIZE];
487 	uint8_t IV[TICKET_IV_SIZE];
488 	uint8_t *encrypted_state;
489 	uint16_t encrypted_state_len;
490 	uint8_t mac[TICKET_MAC_SIZE];
491 };
492 
493 struct binder_data_st {
494 	const struct mac_entry_st *prf; /* non-null if this struct is set */
495 	gnutls_datum_t psk;
496 
497 	/* 0-based index of the selected PSK.
498 	 * This only applies if the HSK_PSK_SELECTED flag is set in internals.hsk_flags,
499 	 * which signals a PSK has indeed been selected. */
500 	uint8_t idx;
501 	uint8_t resumption; /* whether it is a resumption binder */
502 };
503 
504 typedef void (* gnutls_stek_rotation_callback_t) (const gnutls_datum_t *prev_key,
505 						const gnutls_datum_t *new_key,
506 						uint64_t t);
507 
508 struct gnutls_key_st {
509 	struct { /* These are kept outside the TLS1.3 union as they are
510 	          * negotiated via extension, even before protocol is negotiated */
511 		gnutls_pk_params_st ecdh_params;
512 		gnutls_pk_params_st ecdhx_params;
513 		gnutls_pk_params_st dh_params;
514 	} kshare;
515 
516 	/* The union contents depend on the negotiated protocol.
517 	 * It should not contain any values which are allocated
518 	 * prior to protocol negotiation, as it would be impossible
519 	 * to deinitialize.
520 	 */
521 	union {
522 		struct {
523 			/* the current (depending on state) secret, can be
524 			 * early_secret, client_early_traffic_secret, ... */
525 			uint8_t temp_secret[MAX_HASH_SIZE];
526 			unsigned temp_secret_size; /* depends on negotiated PRF size */
527 			uint8_t e_ckey[MAX_HASH_SIZE]; /* client_early_traffic_secret */
528 			uint8_t hs_ckey[MAX_HASH_SIZE]; /* client_hs_traffic_secret */
529 			uint8_t hs_skey[MAX_HASH_SIZE]; /* server_hs_traffic_secret */
530 			uint8_t ap_ckey[MAX_HASH_SIZE]; /* client_ap_traffic_secret */
531 			uint8_t ap_skey[MAX_HASH_SIZE]; /* server_ap_traffic_secret */
532 			uint8_t ap_expkey[MAX_HASH_SIZE]; /* {early_,}exporter_master_secret */
533 			uint8_t ap_rms[MAX_HASH_SIZE]; /* resumption_master_secret */
534 		} tls13; /* tls1.3 */
535 
536 		/* Follow the SSL3.0 and TLS1.2 key exchanges */
537 		struct {
538 			/* For ECDH KX */
539 			struct {
540 				gnutls_pk_params_st params; /* private part */
541 				/* public part */
542 				bigint_t x;
543 				bigint_t y;
544 				gnutls_datum_t raw; /* public key used in ECDHX (point) */
545 			} ecdh;
546 
547 			/* For DH KX */
548 			struct {
549 				gnutls_pk_params_st params;
550 				bigint_t client_Y;
551 			} dh;
552 
553 			/* for SRP KX */
554 			struct {
555 				bigint_t srp_key;
556 				bigint_t srp_g;
557 				bigint_t srp_p;
558 				bigint_t A;
559 				bigint_t B;
560 				bigint_t u;
561 				bigint_t b;
562 				bigint_t a;
563 				bigint_t x;
564 			} srp;
565 		} tls12; /* from ssl3.0 to tls12 */
566 	} proto;
567 
568 	/* binders / pre-shared keys in use; temporary storage.
569 	 * On client side it will hold data for the resumption and external
570 	 * PSKs After server hello is received the selected binder is set on 0 position
571 	 * and HSK_PSK_SELECTED is set.
572 	 *
573 	 * On server side the first value is populated with
574 	 * the selected PSK data if HSK_PSK_SELECTED flag is set. */
575 	struct binder_data_st binders[2];
576 
577 	/* TLS pre-master key; applies to 1.2 and 1.3 */
578 	gnutls_datum_t key;
579 
580 	uint8_t
581 		/* The key to encrypt and decrypt session tickets */
582 		session_ticket_key[TICKET_MASTER_KEY_SIZE],
583 		/* Static buffer for the previous key, whenever we need it */
584 		previous_ticket_key[TICKET_MASTER_KEY_SIZE],
585 		/* Initial key supplied by the caller */
586 		initial_stek[TICKET_MASTER_KEY_SIZE];
587 
588 	/* this is used to hold the peers authentication data
589 	 */
590 	/* auth_info_t structures SHOULD NOT contain malloced
591 	 * elements. Check gnutls_session_pack.c, and gnutls_auth.c.
592 	 * Remember that this should be calloced!
593 	 */
594 	void *auth_info;
595 	gnutls_credentials_type_t auth_info_type;
596 	int auth_info_size;	/* needed in order to store to db for restoring
597 				 */
598 	auth_cred_st *cred;	/* used to specify keys/certificates etc */
599 
600 	struct {
601 		uint64_t last_result;
602 		uint8_t was_rotated;
603 		gnutls_stek_rotation_callback_t cb;
604 	} totp;
605 };
606 
607 typedef struct gnutls_key_st gnutls_key_st;
608 
609 struct pin_info_st {
610 	gnutls_pin_callback_t cb;
611 	void *data;
612 };
613 
614 struct record_state_st;
615 typedef struct record_state_st record_state_st;
616 
617 struct record_parameters_st;
618 typedef struct record_parameters_st record_parameters_st;
619 
620 #define GNUTLS_CIPHER_FLAG_ONLY_AEAD	(1 << 0) /* When set, this cipher is only available through the new AEAD API */
621 #define GNUTLS_CIPHER_FLAG_XOR_NONCE	(1 << 1) /* In this TLS AEAD cipher xor the implicit_iv with the nonce */
622 #define GNUTLS_CIPHER_FLAG_NO_REKEY	(1 << 2) /* whether this tls1.3 cipher doesn't need to rekey after 2^24 messages */
623 
624 /* cipher and mac parameters */
625 typedef struct cipher_entry_st {
626 	const char *name;
627 	gnutls_cipher_algorithm_t id;
628 	uint16_t blocksize;
629 	uint16_t keysize;
630 	cipher_type_t type;
631 	uint16_t implicit_iv;	/* the size of implicit IV - the IV generated but not sent */
632 	uint16_t explicit_iv;	/* the size of explicit IV - the IV stored in record */
633 	uint16_t cipher_iv;	/* the size of IV needed by the cipher */
634 	uint16_t tagsize;
635 	unsigned flags;
636 } cipher_entry_st;
637 
638 typedef struct gnutls_cipher_suite_entry_st {
639 	const char *name;
640 	const uint8_t id[2];
641 	gnutls_cipher_algorithm_t block_algorithm;
642 	gnutls_kx_algorithm_t kx_algorithm;
643 	gnutls_mac_algorithm_t mac_algorithm;
644 	gnutls_protocol_t min_version;	/* this cipher suite is supported
645 					 * from 'version' and above;
646 					 */
647 	gnutls_protocol_t max_version;	/* this cipher suite is not supported
648 					 * after 'version' and above;
649 					 */
650 	gnutls_protocol_t min_dtls_version;	/* DTLS min version */
651 	gnutls_protocol_t max_dtls_version;	/* DTLS max version */
652 	gnutls_mac_algorithm_t prf;
653 } gnutls_cipher_suite_entry_st;
654 
655 
656 typedef struct gnutls_group_entry_st {
657 	const char *name;
658 	gnutls_group_t id;
659 	const gnutls_datum_t *prime;
660 	const gnutls_datum_t *q;
661 	const gnutls_datum_t *generator;
662 	const unsigned *q_bits;
663 	gnutls_ecc_curve_t curve;
664 	gnutls_pk_algorithm_t pk;
665 	unsigned tls_id;		/* The RFC4492 namedCurve ID or TLS 1.3 group ID */
666 } gnutls_group_entry_st;
667 
668 #define GNUTLS_MAC_FLAG_PREIMAGE_INSECURE	1  /* if this algorithm should not be trusted for pre-image attacks */
669 #define GNUTLS_MAC_FLAG_CONTINUOUS_MAC		(1 << 1) /* if this MAC should be used in a 'continuous' way in TLS */
670 /* This structure is used both for MACs and digests
671  */
672 typedef struct mac_entry_st {
673 	const char *name;
674 	const char *oid;	/* OID of the hash - if it is a hash */
675 	const char *mac_oid;    /* OID of the MAC algorithm - if it is a MAC */
676 	gnutls_mac_algorithm_t id;
677 	unsigned output_size;
678 	unsigned key_size;
679 	unsigned nonce_size;
680 	unsigned placeholder;	/* if set, then not a real MAC */
681 	unsigned block_size;	/* internal block size for HMAC */
682 	unsigned flags;
683 } mac_entry_st;
684 
685 typedef struct {
686 	const char *name;
687 	gnutls_protocol_t id;	/* gnutls internal version number */
688 	unsigned age;		/* internal ordering by protocol age */
689 	uint8_t major;		/* defined by the protocol */
690 	uint8_t minor;		/* defined by the protocol */
691 	transport_t transport;	/* Type of transport, stream or datagram */
692 	bool supported;	/* 0 not supported, > 0 is supported */
693 	bool explicit_iv;
694 	bool extensions;	/* whether it supports extensions */
695 	bool selectable_sighash;	/* whether signatures can be selected */
696 	bool selectable_prf;	/* whether the PRF is ciphersuite-defined */
697 
698 	/* if SSL3 is disabled this flag indicates that this protocol is a placeholder,
699 	 * otherwise it prevents this protocol from being set as record version */
700 	bool obsolete;
701 	bool tls13_sem;		/* The TLS 1.3 handshake semantics */
702 	bool false_start;	/* That version can be used with false start */
703 	bool only_extension;	/* negotiated only with an extension */
704 	bool post_handshake_auth;	/* Supports the TLS 1.3 post handshake auth */
705 	bool key_shares;	/* TLS 1.3 key share key exchange */
706 	bool multi_ocsp;	/* TLS 1.3 multiple OCSP responses */
707 	/*
708 	 * TLS versions modify the semantics of signature algorithms. This number
709 	 * is there to distinguish signature algorithms semantics between versions
710 	 * (maps to sign_algorithm_st->tls_sem)
711 	 */
712 	uint8_t tls_sig_sem;
713 } version_entry_st;
714 
715 
716 /* STATE (cont) */
717 
718 #include <hash_int.h>
719 #include <cipher_int.h>
720 
721 typedef struct {
722 	uint8_t id[2]; /* used to be (in TLS 1.2) hash algorithm , PK algorithm */
723 	uint8_t tls_sem; /* should match the protocol version's tls_sig_sem. */
724 } sign_algorithm_st;
725 
726 /* This structure holds parameters got from TLS extension
727  * mechanism. (some extensions may hold parameters in auth_info_t
728  * structures also - see SRP).
729  */
730 
731 #define MAX_VERIFY_DATA_SIZE 36	/* in SSL 3.0, 12 in TLS 1.0 */
732 
733 /* auth_info_t structures now MAY contain malloced
734  * elements.
735  */
736 
737 /* This structure and auth_info_t, are stored in the resume database,
738  * and are restored, in case of resume.
739  * Holds all the required parameters to resume the current
740  * session.
741  */
742 
743 /* Note that the security parameters structure is set up after the
744  * handshake has finished. The only value you may depend on while
745  * the handshake is in progress is the cipher suite value.
746  */
747 typedef struct {
748 	unsigned int entity;	/* GNUTLS_SERVER or GNUTLS_CLIENT */
749 
750 	/* The epoch used to read and write */
751 	uint16_t epoch_read;
752 	uint16_t epoch_write;
753 
754 	/* The epoch that the next handshake will initialize. */
755 	uint16_t epoch_next;
756 
757 	/* The epoch at index 0 of record_parameters. */
758 	uint16_t epoch_min;
759 
760 	/* this is the ciphersuite we are going to use
761 	 * moved here from internals in order to be restored
762 	 * on resume;
763 	 */
764 	const struct gnutls_cipher_suite_entry_st *cs;
765 
766 	/* This is kept outside the ciphersuite entry as on certain
767 	 * TLS versions we need a separate PRF MAC, i.e., MD5_SHA1. */
768 	const mac_entry_st *prf;
769 
770 	uint8_t master_secret[GNUTLS_MASTER_SIZE];
771 	uint8_t client_random[GNUTLS_RANDOM_SIZE];
772 	uint8_t server_random[GNUTLS_RANDOM_SIZE];
773 	uint8_t session_id[GNUTLS_MAX_SESSION_ID_SIZE];
774 	uint8_t session_id_size;
775 	time_t timestamp;
776 
777 	/* whether client has agreed in post handshake auth - only set on server side */
778 	uint8_t post_handshake_auth;
779 
780 	/* The maximum amount of plaintext sent in a record,
781 	 * negotiated with the peer.
782 	 */
783 	uint16_t max_record_send_size;
784 	uint16_t max_record_recv_size;
785 
786 	/* The maximum amount of plaintext sent in a record, set by
787 	 * the programmer.
788 	 */
789 	uint16_t max_user_record_send_size;
790 	uint16_t max_user_record_recv_size;
791 
792 	/* The maximum amount of early data */
793 	uint32_t max_early_data_size;
794 
795 	/* holds the negotiated certificate types */
796 	gnutls_certificate_type_t client_ctype;
797 	gnutls_certificate_type_t server_ctype;
798 
799 	/* The selected (after server hello EC or DH group */
800 	const gnutls_group_entry_st *grp;
801 
802 	/* Holds the signature algorithm that will be used in this session,
803 	 * selected by the server at the time of Ciphersuite/certificate
804 	 * selection - see select_sign_algorithm() */
805 	gnutls_sign_algorithm_t server_sign_algo;
806 
807 	/* Holds the signature algorithm used in this session - If any */
808 	gnutls_sign_algorithm_t client_sign_algo;
809 
810 	/* Whether the master secret negotiation will be according to
811 	 * draft-ietf-tls-session-hash-01
812 	 */
813 	uint8_t ext_master_secret;
814 	/* encrypt-then-mac -> rfc7366 */
815 	uint8_t etm;
816 
817 	uint8_t client_auth_type; /* gnutls_credentials_type_t */
818 	uint8_t server_auth_type;
819 
820 	/* Note: if you add anything in Security_Parameters struct, then
821 	 * also modify CPY_COMMON in constate.c, and session_pack.c,
822 	 * in order to save it in the session storage.
823 	 */
824 
825 	/* Used by extensions that enable supplemental data: Which ones
826 	 * do that? Do they belong in security parameters?
827 	 */
828 	int do_recv_supplemental, do_send_supplemental;
829 	const version_entry_st *pversion;
830 } security_parameters_st;
831 
832 typedef struct api_aead_cipher_hd_st {
833 	cipher_hd_st ctx_enc;
834 } api_aead_cipher_hd_st;
835 
836 struct record_state_st {
837 	/* mac keys can be as long as the hash size */
838 	uint8_t mac_key[MAX_HASH_SIZE];
839 	unsigned mac_key_size;
840 
841 	uint8_t iv[MAX_CIPHER_IV_SIZE];
842 	unsigned iv_size;
843 
844 	uint8_t key[MAX_CIPHER_KEY_SIZE];
845 	unsigned key_size;
846 
847 	union {
848 		auth_cipher_hd_st tls12;
849 		api_aead_cipher_hd_st aead;
850 	} ctx;
851 	unsigned aead_tag_size;
852 	unsigned is_aead;
853 	uint64_t sequence_number;
854 };
855 
856 
857 /* These are used to resolve relative epochs. These values are just
858    outside the 16 bit range to prevent off-by-one errors. An absolute
859    epoch may be referred to by its numeric id in the range
860    0x0000-0xffff. */
861 #define EPOCH_READ_CURRENT  70000
862 #define EPOCH_WRITE_CURRENT 70001
863 #define EPOCH_NEXT	  70002
864 
865 struct record_parameters_st {
866 	uint16_t epoch;
867 	int initialized;
868 
869 	const cipher_entry_st *cipher;
870 	bool etm;
871 	const mac_entry_st *mac;
872 
873 	/* for DTLS sliding window */
874 	uint64_t dtls_sw_next; /* The end point (next expected packet) of the sliding window without epoch */
875 	uint64_t dtls_sw_bits;
876 	unsigned dtls_sw_have_recv; /* whether at least a packet has been received */
877 
878 	record_state_st read;
879 	record_state_st write;
880 
881 	/* Whether this state is in use, i.e., if there is
882 	   a pending handshake message waiting to be encrypted
883 	   under this epoch's parameters.
884 	 */
885 	int usage_cnt;
886 };
887 
888 typedef struct {
889 	unsigned int priorities[MAX_ALGOS];
890 	unsigned int num_priorities;
891 } priority_st;
892 
893 typedef enum {
894 	SR_DISABLED,
895 	SR_UNSAFE,
896 	SR_PARTIAL,
897 	SR_SAFE
898 } safe_renegotiation_t;
899 
900 #define MAX_CIPHERSUITE_SIZE 256
901 
902 typedef struct ciphersuite_list_st {
903 	const gnutls_cipher_suite_entry_st *entry[MAX_CIPHERSUITE_SIZE];
904 	unsigned int size;
905 } ciphersuite_list_st;
906 
907 typedef struct group_list_st {
908 	const gnutls_group_entry_st *entry[MAX_ALGOS];
909 	unsigned int size;
910 	bool have_ffdhe;
911 } group_list_st;
912 
913 typedef struct sign_algo_list_st {
914 	const struct gnutls_sign_entry_st *entry[MAX_ALGOS];
915 	unsigned int size;
916 } sign_algo_list_st;
917 
918 #include "atomic.h"
919 
920 /* For the external api */
921 struct gnutls_priority_st {
922 	priority_st protocol;
923 	priority_st client_ctype;
924 	priority_st server_ctype;
925 
926 	/* The following are not necessary to be stored in
927 	 * the structure; however they are required by the
928 	 * external APIs: gnutls_priority_*_list() */
929 	priority_st _cipher;
930 	priority_st _mac;
931 	priority_st _kx;
932 	priority_st _sign_algo;
933 	priority_st _supported_ecc;
934 
935 	/* the supported groups */
936 	group_list_st groups;
937 
938 	/* the supported signature algorithms */
939 	sign_algo_list_st sigalg;
940 
941 	/* the supported ciphersuites */
942 	ciphersuite_list_st cs;
943 
944 	/* to disable record padding */
945 	bool no_extensions;
946 
947 
948 	safe_renegotiation_t sr;
949 	bool min_record_version;
950 	bool server_precedence;
951 	bool allow_server_key_usage_violation; /* for test suite purposes only */
952 	bool no_tickets;
953 	bool have_cbc;
954 	bool have_psk;
955 	bool force_etm;
956 	unsigned int additional_verify_flags;
957 
958 	/* TLS_FALLBACK_SCSV */
959 	bool fallback;
960 
961 	/* The session's expected security level.
962 	 * Will be used to determine the minimum DH bits,
963 	 * (or the acceptable certificate security level).
964 	 */
965 	gnutls_sec_param_t level;
966 
967 	/* these should be accessed from
968 	 * session->internals.VAR names */
969 	bool _allow_large_records;
970 	bool _allow_small_records;
971 	bool _no_etm;
972 	bool _no_ext_master_secret;
973 	bool _allow_key_usage_violation;
974 	bool _allow_wrong_pms;
975 	bool _dumbfw;
976 	unsigned int _dh_prime_bits;	/* old (deprecated) variable */
977 
978 	DEF_ATOMIC_INT(usage_cnt);
979 };
980 
981 /* Allow around 50KB of length-hiding padding
982  * when using legacy padding,
983  * or around 3.2MB when using new padding. */
984 #define DEFAULT_MAX_EMPTY_RECORDS 200
985 
986 #define ENABLE_COMPAT(x) \
987 	      (x)->allow_large_records = 1; \
988 	      (x)->allow_small_records = 1; \
989 	      (x)->no_etm = 1; \
990 	      (x)->no_ext_master_secret = 1; \
991 	      (x)->allow_key_usage_violation = 1; \
992 	      (x)->allow_wrong_pms = 1; \
993 	      (x)->dumbfw = 1
994 
995 #define ENABLE_PRIO_COMPAT(x) \
996 	      (x)->_allow_large_records = 1; \
997 	      (x)->_allow_small_records = 1; \
998 	      (x)->_no_etm = 1; \
999 	      (x)->_no_ext_master_secret = 1; \
1000 	      (x)->_allow_key_usage_violation = 1; \
1001 	      (x)->_allow_wrong_pms = 1; \
1002 	      (x)->_dumbfw = 1
1003 
1004 /* DH and RSA parameters types.
1005  */
1006 typedef struct gnutls_dh_params_int {
1007 	/* [0] is the prime, [1] is the generator, [2] is Q if available.
1008 	 */
1009 	bigint_t params[3];
1010 	int q_bits;		/* length of q in bits. If zero then length is unknown.
1011 				 */
1012 } dh_params_st;
1013 
1014 /* TLS 1.3 session ticket
1015  */
1016 typedef struct {
1017 	struct timespec arrival_time;
1018 	struct timespec creation_time;
1019 	uint32_t lifetime;
1020 	uint32_t age_add;
1021 	uint8_t nonce[255];
1022 	size_t nonce_size;
1023 	const mac_entry_st *prf;
1024 	uint8_t resumption_master_secret[MAX_HASH_SIZE];
1025 	gnutls_datum_t ticket;
1026 } tls13_ticket_st;
1027 
1028 /* DTLS session state
1029  */
1030 typedef struct {
1031 	/* HelloVerifyRequest DOS prevention cookie */
1032 	gnutls_datum_t dcookie;
1033 
1034 	/* For DTLS handshake fragmentation and reassembly. */
1035 	uint16_t hsk_write_seq;
1036 	/* the sequence number of the expected packet */
1037 	unsigned int hsk_read_seq;
1038 	uint16_t mtu;
1039 
1040 	/* a flight transmission is in process */
1041 	bool flight_init;
1042 	/* whether this is the last flight in the protocol  */
1043 	bool last_flight;
1044 
1045 	/* the retransmission timeout in milliseconds */
1046 	unsigned int retrans_timeout_ms;
1047 
1048 	unsigned int hsk_hello_verify_requests;
1049 
1050 	/* The actual retrans_timeout for the next message (e.g. doubled or so)
1051 	 */
1052 	unsigned int actual_retrans_timeout_ms;
1053 
1054 	/* timers to handle async handshake after gnutls_handshake()
1055 	 * has terminated. Required to handle retransmissions.
1056 	 */
1057 	time_t async_term;
1058 
1059 	/* last retransmission triggered by record layer */
1060 	struct timespec last_retransmit;
1061 	unsigned int packets_dropped;
1062 } dtls_st;
1063 
1064 typedef struct tfo_st {
1065 	int fd;
1066 	int flags;
1067 	bool connect_only; /* a previous sendmsg() failed, attempting connect() */
1068 	struct sockaddr_storage connect_addr;
1069 	socklen_t connect_addrlen;
1070 } tfo_st;
1071 
1072 typedef struct {
1073 	/* holds all the parsed data received by the record layer */
1074 	mbuffer_head_st record_buffer;
1075 
1076 	int handshake_hash_buffer_prev_len;	/* keeps the length of handshake_hash_buffer, excluding
1077 						 * the last received message */
1078 	unsigned handshake_hash_buffer_client_hello_len; /* if non-zero it is the length of data until the client hello message */
1079 	unsigned handshake_hash_buffer_client_kx_len;/* if non-zero it is the length of data until the
1080 						 * the client key exchange message */
1081 	unsigned handshake_hash_buffer_server_finished_len;/* if non-zero it is the length of data until the
1082 						 * the server finished message */
1083 	unsigned handshake_hash_buffer_client_finished_len;/* if non-zero it is the length of data until the
1084 						 * the client finished message */
1085 	gnutls_buffer_st handshake_hash_buffer;	/* used to keep the last received handshake
1086 						 * message */
1087 
1088 	bool resumable;	/* TRUE or FALSE - if we can resume that session */
1089 
1090 	send_ticket_state_t ticket_state; /* used by gnutls_session_ticket_send() */
1091 	bye_state_t bye_state; /* used by gnutls_bye() */
1092 	reauth_state_t reauth_state; /* used by gnutls_reauth() */
1093 
1094 	handshake_state_t handshake_final_state;
1095 	handshake_state_t handshake_state;	/* holds
1096 						 * a number which indicates where
1097 						 * the handshake procedure has been
1098 						 * interrupted. If it is 0 then
1099 						 * no interruption has happened.
1100 						 */
1101 
1102 	bool invalid_connection;	/* true or FALSE - if this session is valid */
1103 
1104 	bool may_not_read;	/* if it's 0 then we can read/write, otherwise it's forbidden to read/write
1105 				 */
1106 	bool may_not_write;
1107 	bool read_eof;		/* non-zero if we have received a closure alert. */
1108 
1109 	int last_alert;		/* last alert received */
1110 
1111 	/* The last handshake messages sent or received.
1112 	 */
1113 	int last_handshake_in;
1114 	int last_handshake_out;
1115 
1116 	/* priorities */
1117 	struct gnutls_priority_st *priorities;
1118 
1119 	/* variables directly set when setting the priorities above, or
1120 	 * when overriding them */
1121 	bool allow_large_records;
1122 	bool allow_small_records;
1123 	bool no_etm;
1124 	bool no_ext_master_secret;
1125 	bool allow_key_usage_violation;
1126 	bool allow_wrong_pms;
1127 	bool dumbfw;
1128 
1129 	/* old (deprecated) variable. This is used for both srp_prime_bits
1130 	 * and dh_prime_bits as they don't overlap */
1131 	/* For SRP: minimum bits to allow for SRP
1132 	 * use gnutls_srp_set_prime_bits() to adjust it.
1133 	 */
1134 	uint16_t dh_prime_bits; /* srp_prime_bits */
1135 
1136 	/* resumed session */
1137 	bool resumed;	/* RESUME_TRUE or FALSE - if we are resuming a session */
1138 
1139 	/* server side: non-zero if resumption was requested by client
1140 	 * client side: non-zero if we set resumption parameters */
1141 	bool resumption_requested;
1142 	security_parameters_st resumed_security_parameters;
1143 	gnutls_datum_t resumption_data; /* copy of input to gnutls_session_set_data() */
1144 
1145 	/* These buffers are used in the handshake
1146 	 * protocol only. freed using _gnutls_handshake_io_buffer_clear();
1147 	 */
1148 	mbuffer_head_st handshake_send_buffer;
1149 	mbuffer_head_st handshake_header_recv_buffer;
1150 	handshake_buffer_st handshake_recv_buffer[MAX_HANDSHAKE_MSGS];
1151 	int handshake_recv_buffer_size;
1152 
1153 	/* this buffer holds a record packet -mostly used for
1154 	 * non blocking IO.
1155 	 */
1156 	mbuffer_head_st record_recv_buffer;	/* buffer holding the unparsed record that is currently
1157 						 * being received */
1158 	mbuffer_head_st record_send_buffer;	/* holds cached data
1159 						 * for the gnutls_io_write_buffered()
1160 						 * function.
1161 						 */
1162 	size_t record_send_buffer_user_size;	/* holds the
1163 						 * size of the user specified data to
1164 						 * send.
1165 						 */
1166 
1167 	mbuffer_head_st early_data_recv_buffer;
1168 	gnutls_buffer_st early_data_presend_buffer;
1169 
1170 	record_send_state_t rsend_state;
1171 	/* buffer used temporarily during key update */
1172 	gnutls_buffer_st record_key_update_buffer;
1173 	gnutls_buffer_st record_presend_buffer;	/* holds cached data
1174 						 * for the gnutls_record_send()
1175 						 * function.
1176 						 */
1177 
1178 	/* buffer used temporarily during TLS1.3 reauthentication */
1179 	gnutls_buffer_st reauth_buffer;
1180 
1181 	time_t expire_time;	/* after expire_time seconds this session will expire */
1182 	const struct mod_auth_st_int *auth_struct;	/* used in handshake packets and KX algorithms */
1183 
1184 	/* this is the highest version available
1185 	 * to the peer. (advertized version).
1186 	 * This is obtained by the Handshake Client Hello
1187 	 * message. (some implementations read the Record version)
1188 	 */
1189 	uint8_t adv_version_major;
1190 	uint8_t adv_version_minor;
1191 
1192 	/* if this is non zero a certificate request message
1193 	 * will be sent to the client. - only if the ciphersuite
1194 	 * supports it. In server side it contains GNUTLS_CERT_REQUIRE
1195 	 * or similar.
1196 	 */
1197 	gnutls_certificate_request_t send_cert_req;
1198 
1199 	size_t max_handshake_data_buffer_size;
1200 
1201 	/* PUSH & PULL functions.
1202 	 */
1203 	gnutls_pull_timeout_func pull_timeout_func;
1204 	gnutls_pull_func pull_func;
1205 	gnutls_push_func push_func;
1206 	gnutls_vec_push_func vec_push_func;
1207 	gnutls_errno_func errno_func;
1208 	/* Holds the first argument of PUSH and PULL
1209 	 * functions;
1210 	 */
1211 	gnutls_transport_ptr_t transport_recv_ptr;
1212 	gnutls_transport_ptr_t transport_send_ptr;
1213 
1214 	/* STORE & RETRIEVE functions. Only used if other
1215 	 * backend than gdbm is used.
1216 	 */
1217 	gnutls_db_store_func db_store_func;
1218 	gnutls_db_retr_func db_retrieve_func;
1219 	gnutls_db_remove_func db_remove_func;
1220 	void *db_ptr;
1221 
1222 	/* post client hello callback (server side only)
1223 	 */
1224 	gnutls_handshake_post_client_hello_func user_hello_func;
1225 	/* handshake hook function */
1226 	gnutls_handshake_hook_func h_hook;
1227 	unsigned int h_type;	/* the hooked type */
1228 	int16_t h_post;		/* whether post-generation/receive */
1229 
1230 	gnutls_keylog_func keylog_func;
1231 
1232 	/* holds the selected certificate and key.
1233 	 * use _gnutls_selected_certs_deinit() and _gnutls_selected_certs_set()
1234 	 * to change them.
1235 	 */
1236 	gnutls_pcert_st *selected_cert_list;
1237 	uint16_t selected_cert_list_length;
1238 	struct gnutls_privkey_st *selected_key;
1239 
1240 	/* new callbacks such as gnutls_certificate_retrieve_function3
1241 	 * set the selected_ocsp datum values. The older OCSP callback-based
1242 	 * functions, set the ocsp_func. The former takes precedence when
1243 	 * set.
1244 	 */
1245 	gnutls_ocsp_data_st *selected_ocsp;
1246 	uint16_t selected_ocsp_length;
1247 	gnutls_status_request_ocsp_func selected_ocsp_func;
1248 	void *selected_ocsp_func_ptr;
1249 	bool selected_need_free;
1250 
1251 
1252 	/* This holds the default version that our first
1253 	 * record packet will have. */
1254 	uint8_t default_record_version[2];
1255 	uint8_t default_hello_version[2];
1256 
1257 	void *user_ptr;
1258 
1259 	/* Holds 0 if the last called function was interrupted while
1260 	 * receiving, and non zero otherwise.
1261 	 */
1262 	bool direction;
1263 
1264 	/* If non zero the server will not advertise the CA's he
1265 	 * trusts (do not send an RDN sequence).
1266 	 */
1267 	bool ignore_rdn_sequence;
1268 
1269 	/* This is used to set an arbitrary version in the RSA
1270 	 * PMS secret. Can be used by clients to test whether the
1271 	 * server checks that version. (** only used in gnutls-cli-debug)
1272 	 */
1273 	uint8_t rsa_pms_version[2];
1274 
1275 	/* To avoid using global variables, and especially on Windows where
1276 	 * the application may use a different errno variable than GnuTLS,
1277 	 * it is possible to use gnutls_transport_set_errno to set a
1278 	 * session-specific errno variable in the user-replaceable push/pull
1279 	 * functions.  This value is used by the send/recv functions.  (The
1280 	 * strange name of this variable is because 'errno' is typically
1281 	 * #define'd.)
1282 	 */
1283 	int errnum;
1284 
1285 	/* A handshake process has been completed */
1286 	bool initial_negotiation_completed;
1287 	void *post_negotiation_lock; /* protects access to the variable above
1288 				      * in the cases where negotiation is incomplete
1289 				      * after gnutls_handshake() - early/false start */
1290 
1291 	/* The type of transport protocol; stream or datagram */
1292 	transport_t transport;
1293 
1294 	/* DTLS session state */
1295 	dtls_st dtls;
1296 	/* Protect from infinite loops due to GNUTLS_E_LARGE_PACKET non-handling
1297 	 * or due to multiple alerts being received. */
1298 	unsigned handshake_suspicious_loops;
1299 	/* should be non-zero when a handshake is in progress */
1300 	bool handshake_in_progress;
1301 
1302 	/* if set it means that the master key was set using
1303 	 * gnutls_session_set_master() rather than being negotiated. */
1304 	bool premaster_set;
1305 
1306 	unsigned int cb_tls_unique_len;
1307 	unsigned char cb_tls_unique[MAX_VERIFY_DATA_SIZE];
1308 
1309 	/* starting time of current handshake */
1310 	struct timespec handshake_start_time;
1311 
1312 	/* expected end time of current handshake (start+timeout);
1313 	 * this is only filled if a handshake_time_ms is set. */
1314 	struct timespec handshake_abs_timeout;
1315 
1316 	/* An estimation of round-trip time under TLS1.3; populated in client side only */
1317 	unsigned ertt;
1318 
1319 	unsigned int handshake_timeout_ms;	/* timeout in milliseconds */
1320 	unsigned int record_timeout_ms;	/* timeout in milliseconds */
1321 
1322 	/* saved context of post handshake certificate request. In
1323 	 * client side is what we received in server's certificate request;
1324 	 * in server side is what we sent to client. */
1325 	gnutls_datum_t post_handshake_cr_context;
1326 	/* it is a copy of the handshake hash buffer if post handshake is used */
1327 	gnutls_buffer_st post_handshake_hash_buffer;
1328 
1329 /* When either of PSK or DHE-PSK is received */
1330 #define HSK_PSK_KE_MODES_RECEIVED (HSK_PSK_KE_MODE_PSK|HSK_PSK_KE_MODE_DHE_PSK|HSK_PSK_KE_MODE_INVALID)
1331 
1332 #define HSK_CRT_VRFY_EXPECTED 1
1333 #define HSK_CRT_ASKED (1<<2)
1334 #define HSK_HRR_SENT (1<<3)
1335 #define HSK_HRR_RECEIVED (1<<4)
1336 #define HSK_CRT_REQ_SENT (1<<5)
1337 #define HSK_KEY_UPDATE_ASKED (1<<7) /* flag is not used during handshake */
1338 #define HSK_FALSE_START_USED (1<<8) /* TLS1.2 only */
1339 #define HSK_HAVE_FFDHE (1<<9) /* whether the peer has advertized at least an FFDHE group */
1340 #define HSK_USED_FFDHE (1<<10) /* whether ffdhe was actually negotiated and used */
1341 #define HSK_PSK_KE_MODES_SENT (1<<11)
1342 #define HSK_PSK_KE_MODE_PSK (1<<12) /* client: whether PSK without DH is allowed,
1343 				     * server: whether PSK without DH is selected. */
1344 #define HSK_PSK_KE_MODE_INVALID (1<<13) /* server: no compatible PSK modes were seen */
1345 #define HSK_PSK_KE_MODE_DHE_PSK (1<<14) /* server: whether PSK with DH is selected
1346 					 * client: whether PSK with DH is allowed
1347 					 */
1348 #define HSK_PSK_SELECTED (1<<15) /* server: whether PSK was selected, either for resumption or not;
1349 				  *	    on resumption session->internals.resumed will be set as well.
1350 				  * client: the same */
1351 #define HSK_KEY_SHARE_SENT (1<<16) /* server: key share was sent to client */
1352 #define HSK_KEY_SHARE_RECEIVED (1<<17) /* client: key share was received
1353 					* server: key share was received and accepted */
1354 #define HSK_TLS13_TICKET_SENT (1<<18) /* client: sent a ticket under TLS1.3;
1355 					 * server: a ticket was sent to client.
1356 					 */
1357 #define HSK_TLS12_TICKET_SENT (1<<19) /* client: sent a ticket under TLS1.2;
1358 				       * server: a ticket was sent to client.
1359 				       */
1360 #define HSK_TICKET_RECEIVED (1<<20) /* client: a session ticket was received */
1361 #define HSK_EARLY_START_USED (1<<21)
1362 #define HSK_EARLY_DATA_IN_FLIGHT (1<<22) /* client: sent early_data extension in ClientHello
1363 					  * server: early_data extension was seen in ClientHello
1364 					  */
1365 #define HSK_EARLY_DATA_ACCEPTED (1<<23) /* client: early_data extension was seen in EncryptedExtensions
1366 					 * server: intend to process early data
1367 					 */
1368 #define HSK_RECORD_SIZE_LIMIT_NEGOTIATED (1<<24)
1369 #define HSK_RECORD_SIZE_LIMIT_SENT (1<<25) /* record_size_limit extension was sent */
1370 #define HSK_RECORD_SIZE_LIMIT_RECEIVED (1<<26) /* server: record_size_limit extension was seen but not accepted yet */
1371 #define HSK_OCSP_REQUESTED (1<<27) /* server: client requested OCSP stapling */
1372 #define HSK_CLIENT_OCSP_REQUESTED (1<<28) /* client: server requested OCSP stapling */
1373 #define HSK_SERVER_HELLO_RECEIVED (1<<29) /* client: Server Hello message has been received */
1374 
1375 	/* The hsk_flags are for use within the ongoing handshake;
1376 	 * they are reset to zero prior to handshake start by gnutls_handshake. */
1377 	unsigned hsk_flags;
1378 	struct timespec last_key_update;
1379 	unsigned key_update_count;
1380 	/* Read-only pointer to the full ClientHello message */
1381 	gnutls_buffer_st full_client_hello;
1382 	/* The offset at which extensions start in the ClientHello buffer */
1383 	int extensions_offset;
1384 
1385 	gnutls_buffer_st hb_local_data;
1386 	gnutls_buffer_st hb_remote_data;
1387 	struct timespec hb_ping_start;	/* timestamp: when first HeartBeat ping was sent */
1388 	struct timespec hb_ping_sent;	/* timestamp: when last HeartBeat ping was sent */
1389 	unsigned int hb_actual_retrans_timeout_ms;	/* current timeout, in milliseconds */
1390 	unsigned int hb_retrans_timeout_ms;	/* the default timeout, in milliseconds */
1391 	unsigned int hb_total_timeout_ms;	/* the total timeout, in milliseconds */
1392 
1393 	bool ocsp_check_ok;	/* will be zero if the OCSP response TLS extension
1394 					 * check failed (OCSP was old/unrelated or so). */
1395 
1396 	heartbeat_state_t hb_state;	/* for ping */
1397 
1398 	recv_state_t recv_state;	/* state of the receive function */
1399 
1400 	/* if set, server and client random were set by the application */
1401 	bool sc_random_set;
1402 
1403 #define INT_FLAG_NO_TLS13 (1LL<<60)
1404 	uint64_t flags; /* the flags in gnutls_init() and GNUTLS_INT_FLAGS */
1405 
1406 	/* a verify callback to override the verify callback from the credentials
1407 	 * structure */
1408 	gnutls_certificate_verify_function *verify_callback;
1409 	gnutls_typed_vdata_st *vc_data;
1410 	gnutls_typed_vdata_st vc_sdata;
1411 	unsigned vc_elements;
1412 	unsigned vc_status;
1413 	unsigned int additional_verify_flags; /* may be set by priorities or the vc functions */
1414 
1415 	/* we append the verify flags because these can be set,
1416 	 * either by this function or by gnutls_session_set_verify_cert().
1417 	 * However, we ensure that a single profile is set. */
1418 #define ADD_PROFILE_VFLAGS(session, vflags) do { \
1419 	if ((session->internals.additional_verify_flags & GNUTLS_VFLAGS_PROFILE_MASK) && \
1420 	    (vflags & GNUTLS_VFLAGS_PROFILE_MASK)) \
1421 		session->internals.additional_verify_flags &= ~GNUTLS_VFLAGS_PROFILE_MASK; \
1422 	session->internals.additional_verify_flags |= vflags; \
1423 	} while(0)
1424 
1425 	/* the SHA256 hash of the peer's certificate */
1426 	uint8_t cert_hash[32];
1427 	bool cert_hash_set;
1428 
1429 	/* The saved username from PSK or SRP auth */
1430 	char saved_username[MAX_USERNAME_SIZE+1];
1431 	int saved_username_size;
1432 
1433 	/* Needed for TCP Fast Open (TFO), set by gnutls_transport_set_fastopen() */
1434 	tfo_st tfo;
1435 
1436 	struct gnutls_supplemental_entry_st *rsup;
1437 	unsigned rsup_size;
1438 
1439 	struct hello_ext_entry_st *rexts;
1440 	unsigned rexts_size;
1441 
1442 	struct { /* ext_data[id] contains data for extension_t id */
1443 		gnutls_ext_priv_data_t priv;
1444 		gnutls_ext_priv_data_t resumed_priv;
1445 		uint8_t set;
1446 		uint8_t resumed_set;
1447 	} ext_data[MAX_EXT_TYPES];
1448 
1449 	/* In case of a client holds the extensions we sent to the peer;
1450 	 * otherwise the extensions we received from the client. This is
1451 	 * an OR of (1<<extensions_t values).
1452 	 */
1453 	ext_track_t used_exts;
1454 
1455 	gnutls_ext_flags_t ext_msg; /* accessed through _gnutls_ext_get/set_msg() */
1456 
1457 	/* this is not the negotiated max_record_recv_size, but the actual maximum
1458 	 * receive size */
1459 	unsigned max_recv_size;
1460 
1461 	/* candidate groups to be selected for security params groups, they are
1462 	 * prioritized in isolation under TLS1.2 */
1463 	const gnutls_group_entry_st *cand_ec_group;
1464 	const gnutls_group_entry_st *cand_dh_group;
1465 	/* used under TLS1.3+ */
1466 	const gnutls_group_entry_st *cand_group;
1467 
1468 	/* the ciphersuite received in HRR */
1469 	uint8_t hrr_cs[2];
1470 
1471 	/* this is only used under TLS1.2 or earlier */
1472 	int session_ticket_renew;
1473 
1474 	tls13_ticket_st tls13_ticket;
1475 
1476 	/* the amount of early data received so far */
1477 	uint32_t early_data_received;
1478 
1479 	/* anti-replay measure for 0-RTT mode */
1480 	gnutls_anti_replay_t anti_replay;
1481 
1482 	/* Protects _gnutls_epoch_gc() from _gnutls_epoch_get(); these may be
1483 	 * called in parallel when false start is used and false start is used. */
1484 	void *epoch_lock;
1485 
1486 	/* If you add anything here, check _gnutls_handshake_internal_state_clear().
1487 	 */
1488 } internals_st;
1489 
1490 /* Maximum number of epochs we keep around. */
1491 #define MAX_EPOCH_INDEX 4
1492 
1493 #define reset_cand_groups(session) \
1494 	session->internals.cand_ec_group = session->internals.cand_dh_group = \
1495 		session->internals.cand_group = NULL
1496 
1497 struct gnutls_session_int {
1498 	security_parameters_st security_parameters;
1499 	record_parameters_st *record_parameters[MAX_EPOCH_INDEX];
1500 	internals_st internals;
1501 	gnutls_key_st key;
1502 };
1503 
1504 
1505 /* functions
1506  */
1507 void _gnutls_free_auth_info(gnutls_session_t session);
1508 
1509 /* These two macros return the advertised TLS version of
1510  * the peer.
1511  */
1512 #define _gnutls_get_adv_version_major(session) \
1513 	session->internals.adv_version_major
1514 
1515 #define _gnutls_get_adv_version_minor(session) \
1516 	session->internals.adv_version_minor
1517 
1518 #define set_adv_version(session, major, minor) \
1519 	session->internals.adv_version_major = major; \
1520 	session->internals.adv_version_minor = minor
1521 
1522 int _gnutls_is_secure_mem_null(const void *);
1523 
get_version(gnutls_session_t session)1524 inline static const version_entry_st *get_version(gnutls_session_t session)
1525 {
1526 	return session->security_parameters.pversion;
1527 }
1528 
get_num_version(gnutls_session_t session)1529 inline static unsigned get_num_version(gnutls_session_t session)
1530 {
1531 	if (likely(session->security_parameters.pversion != NULL))
1532 		return session->security_parameters.pversion->id;
1533 	else
1534 		return GNUTLS_VERSION_UNKNOWN;
1535 }
1536 
1537 void _gnutls_priority_update_fips(void);
1538 void _gnutls_priority_update_non_aesni(void);
1539 extern unsigned _gnutls_disable_tls13;
1540 
1541 #define timespec_sub_ms _gnutls_timespec_sub_ms
1542 unsigned int
1543 /* returns a-b in ms */
1544  timespec_sub_ms(struct timespec *a, struct timespec *b);
1545 
_gnutls_timespec_cmp(struct timespec * a,struct timespec * b)1546 inline static int _gnutls_timespec_cmp(struct timespec *a, struct timespec *b) {
1547 	if (a->tv_sec < b->tv_sec)
1548 		return -1;
1549 	if (a->tv_sec > b->tv_sec)
1550 		return 1;
1551 	if (a->tv_nsec < b->tv_nsec)
1552 		return -1;
1553 	if (a->tv_nsec > b->tv_nsec)
1554 		return 1;
1555 	return 0;
1556 }
1557 
1558 #include <algorithms.h>
_gnutls_set_current_version(gnutls_session_t s,unsigned v)1559 inline static int _gnutls_set_current_version(gnutls_session_t s, unsigned v)
1560 {
1561 	s->security_parameters.pversion = version_to_entry(v);
1562 	if (s->security_parameters.pversion == NULL) {
1563 		return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
1564 	}
1565 	return 0;
1566 }
1567 
1568 /* Returns the maximum amount of the plaintext to be sent, considering
1569  * both user-specified/negotiated maximum values.
1570  */
max_record_send_size(gnutls_session_t session,record_parameters_st * record_params)1571 inline static size_t max_record_send_size(gnutls_session_t session,
1572 					  record_parameters_st *
1573 					  record_params)
1574 {
1575 	size_t max;
1576 
1577 	max = MIN(session->security_parameters.max_record_send_size,
1578 		  session->security_parameters.max_user_record_send_size);
1579 
1580 	if (IS_DTLS(session))
1581 		max = MIN(gnutls_dtls_get_data_mtu(session), max);
1582 
1583 	return max;
1584 }
1585 
1586 /* Returns the during the handshake negotiated certificate type(s).
1587  * See state.c for the full function documentation.
1588  *
1589  * This function is made static inline for optimization reasons.
1590  */
1591 inline static gnutls_certificate_type_t
get_certificate_type(gnutls_session_t session,gnutls_ctype_target_t target)1592 get_certificate_type(gnutls_session_t session,
1593 		     gnutls_ctype_target_t target)
1594 {
1595 	switch (target) {
1596 		case GNUTLS_CTYPE_CLIENT:
1597 			return session->security_parameters.client_ctype;
1598 			break;
1599 		case GNUTLS_CTYPE_SERVER:
1600 			return session->security_parameters.server_ctype;
1601 			break;
1602 		case GNUTLS_CTYPE_OURS:
1603 			if (IS_SERVER(session)) {
1604 				return session->security_parameters.server_ctype;
1605 			} else {
1606 				return session->security_parameters.client_ctype;
1607 			}
1608 			break;
1609 		case GNUTLS_CTYPE_PEERS:
1610 			if (IS_SERVER(session)) {
1611 				return session->security_parameters.client_ctype;
1612 			} else {
1613 				return session->security_parameters.server_ctype;
1614 			}
1615 			break;
1616 		default:	// Illegal parameter passed
1617 			return GNUTLS_CRT_UNKNOWN;
1618 	}
1619 }
1620 
1621 /* Macros to aide constant time/mem checks */
1622 #define CONSTCHECK_NOT_EQUAL(a, b) ((-((uint32_t)(a) ^ (uint32_t)(b))) >> 31)
1623 #define CONSTCHECK_EQUAL(a, b) (1U - CONSTCHECK_NOT_EQUAL(a, b))
1624 
1625 extern unsigned int _gnutls_global_version;
1626 
1627 #endif /* GNUTLS_LIB_GNUTLS_INT_H */
1628