Imported Upstream version 3.4.11
[platform/upstream/gnutls.git] / lib / gnutls_int.h
1 /*
2  * Copyright (C) 2000-2015 Free Software Foundation, Inc.
3  * Copyright (C) 2015 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 <http://www.gnu.org/licenses/>
21  *
22  */
23
24 #ifndef GNUTLS_INT_H
25 #define 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
40 /* For some reason gnulib likes to provide alternatives for
41  * functions it doesn't include. Even worse these functions seem
42  * to be available on the target systems.
43  */
44 #undef strdup
45
46 #ifdef NO_SSIZE_T
47 #define HAVE_SSIZE_T
48 typedef int ssize_t;
49 #endif
50
51 #include <sys/types.h>
52 #include <unistd.h>
53 #include <sys/stat.h>
54 #if HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
56 #elif HAVE_WS2TCPIP_H
57 #include <ws2tcpip.h>
58 #endif
59 #include <time.h>
60
61 #ifdef HAVE_LIBNETTLE
62 #include <nettle/memxor.h>
63 #else
64 #include <gl/memxor.h>
65 #define memxor gl_memxor
66 #endif
67
68 #define ENABLE_ALIGN16
69
70 #ifdef __GNUC__
71 #ifndef _GNUTLS_GCC_VERSION
72 #define _GNUTLS_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
73 #endif
74 #if _GNUTLS_GCC_VERSION >= 30100
75 #define likely(x)      __builtin_expect((x), 1)
76 #define unlikely(x)    __builtin_expect((x), 0)
77 #endif
78 #endif
79
80 #ifndef likely
81 #define likely
82 #define unlikely
83 #endif
84
85 /* some systems had problems with long long int, thus,
86  * it is not used.
87  */
88 typedef struct {
89         unsigned char i[8];
90 } uint64;
91
92 #include <gnutls/gnutls.h>
93 #include <gnutls/dtls.h>
94 #include <gnutls/abstract.h>
95 #include <system.h>
96
97 /*
98  * They are not needed any more. You can simply enable
99  * the gnutls_log callback to get error descriptions.
100
101 #define BUFFERS_DEBUG
102 #define WRITE_DEBUG
103 #define READ_DEBUG
104 #define HANDSHAKE_DEBUG // Prints some information on handshake 
105 #define COMPRESSION_DEBUG
106 #define DEBUG
107 */
108
109 /* The size of a handshake message should not
110  * be larger than this value.
111  */
112 #define MAX_HANDSHAKE_PACKET_SIZE 48*1024
113
114 /* The maximum digest size of hash algorithms. 
115  */
116 #define MAX_FILENAME 512
117 #define MAX_HASH_SIZE 64
118 #define MAX_CIPHER_BLOCK_SIZE 16
119 #define MAX_CIPHER_KEY_SIZE 32
120
121 #define MAX_USERNAME_SIZE 128
122 #define MAX_SERVER_NAME_SIZE 128
123
124 #define SESSION_TICKET_KEY_NAME_SIZE 16
125 #define SESSION_TICKET_KEY_SIZE 16
126
127 #define AEAD_EXPLICIT_DATA_SIZE 8
128 #define AEAD_IMPLICIT_DATA_SIZE 4
129
130 #define GNUTLS_MASTER_SIZE 48
131 #define GNUTLS_RANDOM_SIZE 32
132
133 /* DTLS */
134 #define DTLS_RECORD_WINDOW_SIZE 64
135 #define DTLS_RETRANS_TIMEOUT 1000
136
137 /* TLS Extensions */
138 /* we can receive up to MAX_EXT_TYPES extensions.
139  */
140 #define MAX_EXT_TYPES 32
141
142 /* expire time for resuming sessions */
143 #define DEFAULT_EXPIRE_TIME 3600
144 #define DEFAULT_HANDSHAKE_TIMEOUT_MS 40*1000
145
146 typedef enum transport_t {
147         GNUTLS_STREAM,
148         GNUTLS_DGRAM
149 } transport_t;
150
151 typedef enum record_flush_t {
152         RECORD_FLUSH = 0,
153         RECORD_CORKED,
154 } record_flush_t;
155
156 /* the maximum size of encrypted packets */
157 #define IS_DTLS(session) (session->internals.transport == GNUTLS_DGRAM)
158
159 #define DEFAULT_MAX_RECORD_SIZE 16384
160 #define TLS_RECORD_HEADER_SIZE 5
161 #define DTLS_RECORD_HEADER_SIZE (TLS_RECORD_HEADER_SIZE+8)
162 #define RECORD_HEADER_SIZE(session) (IS_DTLS(session) ? DTLS_RECORD_HEADER_SIZE : TLS_RECORD_HEADER_SIZE)
163 #define MAX_RECORD_HEADER_SIZE DTLS_RECORD_HEADER_SIZE
164
165 /* The following macro is used to calculate the overhead when sending.
166  * when receiving we use a different way as there are implementations that
167  * store more data than allowed.
168  */
169 #define MAX_RECORD_SEND_OVERHEAD(session) (MAX_CIPHER_BLOCK_SIZE/*iv*/+MAX_PAD_SIZE+((gnutls_compression_get(session)!=GNUTLS_COMP_NULL)?(EXTRA_COMP_SIZE):(0))+MAX_HASH_SIZE/*MAC*/)
170 #define MAX_RECORD_SEND_SIZE(session) (IS_DTLS(session)? \
171         ((size_t)gnutls_dtls_get_mtu(session)): \
172         ((size_t)session->security_parameters.max_record_send_size+MAX_RECORD_SEND_OVERHEAD(session)))
173 #define MAX_PAD_SIZE 255
174 #define EXTRA_COMP_SIZE 2048
175
176 #define TLS_HANDSHAKE_HEADER_SIZE 4
177 #define DTLS_HANDSHAKE_HEADER_SIZE (TLS_HANDSHAKE_HEADER_SIZE+8)
178 #define HANDSHAKE_HEADER_SIZE(session) (IS_DTLS(session) ? DTLS_HANDSHAKE_HEADER_SIZE : TLS_HANDSHAKE_HEADER_SIZE)
179 #define MAX_HANDSHAKE_HEADER_SIZE DTLS_HANDSHAKE_HEADER_SIZE
180
181 /* This is the maximum handshake message size we send without
182    fragmentation. This currently ignores record layer overhead. */
183 #define DTLS_DEFAULT_MTU 1200
184
185 /* the maximum size of the DTLS cookie */
186 #define DTLS_MAX_COOKIE_SIZE 32
187
188 /* The maximum number of HELLO_VERIFY_REQUEST messages the client
189    processes before aborting. */
190 #define MAX_HANDSHAKE_HELLO_VERIFY_REQUESTS 5
191
192 /* defaults for verification functions
193  */
194 #define DEFAULT_MAX_VERIFY_DEPTH 16
195 #define DEFAULT_MAX_VERIFY_BITS 16*1024
196 #define MAX_VERIFY_DEPTH 4096
197
198 #include <gnutls_mem.h>
199
200 #define MEMSUB(x,y) ((ssize_t)((ptrdiff_t)x-(ptrdiff_t)y))
201
202 #define DECR_LEN(len, x) do { len-=x; if (len<0) {gnutls_assert(); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;} } while (0)
203 #define DECR_LEN_FINAL(len, x) do { \
204         len-=x; \
205         if (len != 0) \
206                 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH); \
207         } while (0)
208 #define DECR_LENGTH_RET(len, x, RET) do { len-=x; if (len<0) {gnutls_assert(); return RET;} } while (0)
209 #define DECR_LENGTH_COM(len, x, COM) do { len-=x; if (len<0) {gnutls_assert(); COM;} } while (0)
210
211 #define GNUTLS_POINTER_TO_INT(_) ((int) GNUTLS_POINTER_TO_INT_CAST (_))
212 #define GNUTLS_INT_TO_POINTER(_) ((void*) GNUTLS_POINTER_TO_INT_CAST (_))
213
214 #define GNUTLS_KX_INVALID (-1)
215
216 typedef struct {
217         uint8_t pint[3];
218 } uint24;
219
220 #include <gnutls_mpi.h>
221
222 typedef enum handshake_state_t { STATE0 = 0, STATE1, STATE2,
223         STATE3, STATE4, STATE5, STATE6, STATE7, STATE8,
224         STATE9, STATE10, STATE11, STATE12, STATE13, STATE14,
225         STATE15, STATE16, STATE17, STATE18,
226         STATE20 = 20, STATE21, STATE22,
227         STATE30 = 30, STATE31, STATE40 = 40, STATE41, STATE50 = 50,
228         STATE60 = 60, STATE61, STATE62, 
229 } handshake_state_t;
230
231 typedef enum heartbeat_state_t {
232         SHB_SEND1 = 0,
233         SHB_SEND2,
234         SHB_RECV,
235 } heartbeat_state_t;
236
237 typedef enum recv_state_t {
238         RECV_STATE_0 = 0,
239         RECV_STATE_DTLS_RETRANSMIT,
240 } recv_state_t;
241
242 #include <gnutls_str.h>
243
244 /* This is the maximum number of algorithms (ciphers or macs etc).
245  * keep it synced with GNUTLS_MAX_ALGORITHM_NUM in gnutls.h
246  */
247 #define MAX_ALGOS GNUTLS_MAX_ALGORITHM_NUM
248
249 /* http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
250  */
251 typedef enum extensions_t {
252         GNUTLS_EXTENSION_SERVER_NAME = 0,
253         GNUTLS_EXTENSION_MAX_RECORD_SIZE = 1,
254         GNUTLS_EXTENSION_STATUS_REQUEST = 5,
255         GNUTLS_EXTENSION_CERT_TYPE = 9,
256         GNUTLS_EXTENSION_SUPPORTED_ECC = 10,
257         GNUTLS_EXTENSION_SUPPORTED_ECC_PF = 11,
258         GNUTLS_EXTENSION_SRP = 12,
259         GNUTLS_EXTENSION_SIGNATURE_ALGORITHMS = 13,
260         GNUTLS_EXTENSION_SRTP = 14,
261         GNUTLS_EXTENSION_HEARTBEAT = 15,
262         GNUTLS_EXTENSION_ALPN = 16,
263         GNUTLS_EXTENSION_DUMBFW = 21,
264         GNUTLS_EXTENSION_ETM = 22,
265         GNUTLS_EXTENSION_EXT_MASTER_SECRET = 23,
266         GNUTLS_EXTENSION_SESSION_TICKET = 35,
267         GNUTLS_EXTENSION_SAFE_RENEGOTIATION = 65281     /* aka: 0xff01 */
268 } extensions_t;
269
270 typedef enum { CIPHER_STREAM, CIPHER_BLOCK, CIPHER_AEAD } cipher_type_t;
271
272 #define RESUME_TRUE 1
273 #define RESUME_FALSE 0
274
275 /* Record Protocol */
276 typedef enum content_type_t {
277         GNUTLS_CHANGE_CIPHER_SPEC = 20, GNUTLS_ALERT,
278         GNUTLS_HANDSHAKE, GNUTLS_APPLICATION_DATA,
279         GNUTLS_HEARTBEAT
280 } content_type_t;
281
282
283 #define GNUTLS_PK_ANY (gnutls_pk_algorithm_t)-1
284 #define GNUTLS_PK_NONE (gnutls_pk_algorithm_t)-2
285
286 /* Message buffers (mbuffers) structures */
287
288 /* this is actually the maximum number of distinct handshake
289  * messages that can arrive in a single flight
290  */
291 #define MAX_HANDSHAKE_MSGS 6
292 typedef struct {
293         /* Handshake layer type and sequence of message */
294         gnutls_handshake_description_t htype;
295         uint32_t length;
296
297         /* valid in DTLS */
298         uint16_t sequence;
299
300         /* indicate whether that message is complete.
301          * complete means start_offset == 0 and end_offset == length
302          */
303         uint32_t start_offset;
304         uint32_t end_offset;
305
306         uint8_t header[MAX_HANDSHAKE_HEADER_SIZE];
307         int header_size;
308
309         gnutls_buffer_st data;
310 } handshake_buffer_st;
311
312 typedef struct mbuffer_st {
313         /* when used in mbuffer_head_st */
314         struct mbuffer_st *next;
315         struct mbuffer_st *prev;
316
317         /* msg->size - mark = number of bytes left to process in this
318            message. Mark should only be non-zero when this buffer is the
319            head of the queue. */
320         size_t mark;
321
322
323         /* the data */
324         gnutls_datum_t msg;
325         size_t maximum_size;
326
327         /* used during fill in, to separate header from data
328          * body. */
329         unsigned int uhead_mark;
330
331         /* Filled in by record layer on recv:
332          * type, record_sequence
333          */
334
335         /* record layer content type */
336         content_type_t type;
337
338         /* record layer sequence */
339         uint64 record_sequence;
340
341         /* Filled in by handshake layer on send:
342          * type, epoch, htype, handshake_sequence
343          */
344
345         /* Record layer epoch of message */
346         uint16_t epoch;
347
348         /* Handshake layer type and sequence of message */
349         gnutls_handshake_description_t htype;
350         uint16_t handshake_sequence;
351 } mbuffer_st;
352
353 typedef struct mbuffer_head_st {
354         mbuffer_st *head;
355         mbuffer_st *tail;
356
357         unsigned int length;
358         size_t byte_length;
359 } mbuffer_head_st;
360
361 /* Store & Retrieve functions defines: 
362  */
363
364 typedef struct auth_cred_st {
365         gnutls_credentials_type_t algorithm;
366
367         /* the type of credentials depends on algorithm 
368          */
369         void *credentials;
370         struct auth_cred_st *next;
371 } auth_cred_st;
372
373 struct gnutls_key_st {
374         /* For ECDH KX */
375         gnutls_pk_params_st ecdh_params;
376         bigint_t ecdh_x;
377         bigint_t ecdh_y;
378
379         /* For DH KX */
380         gnutls_datum_t key;
381         
382         /* For DH KX */
383         gnutls_pk_params_st dh_params;
384         bigint_t client_Y;
385         /* for SRP */
386
387         bigint_t srp_key;
388         bigint_t srp_g;
389         bigint_t srp_p;
390         bigint_t A;
391         bigint_t B;
392         bigint_t u;
393         bigint_t b;
394         bigint_t a;
395         bigint_t x;
396         /* RSA: e, m
397          */
398         bigint_t rsa[2];
399
400         /* this is used to hold the peers authentication data 
401          */
402         /* auth_info_t structures SHOULD NOT contain malloced 
403          * elements. Check gnutls_session_pack.c, and gnutls_auth.c.
404          * Remember that this should be calloced!
405          */
406         void *auth_info;
407         gnutls_credentials_type_t auth_info_type;
408         int auth_info_size;     /* needed in order to store to db for restoring 
409                                  */
410         uint8_t crypt_algo;
411
412         auth_cred_st *cred;     /* used to specify keys/certificates etc */
413
414         int crt_requested;
415         /* some ciphersuites use this
416          * to provide client authentication.
417          * 1 if client auth was requested
418          * by the peer, 0 otherwise
419          *** In case of a server this
420          * holds 1 if we should wait
421          * for a client certificate verify
422          */
423 };
424 typedef struct gnutls_key_st gnutls_key_st;
425
426 struct pin_info_st {
427         gnutls_pin_callback_t cb;
428         void *data;
429 };
430
431 struct record_state_st;
432 typedef struct record_state_st record_state_st;
433
434 struct record_parameters_st;
435 typedef struct record_parameters_st record_parameters_st;
436
437 /* cipher and mac parameters */
438 typedef struct cipher_entry_st {
439         const char *name;
440         gnutls_cipher_algorithm_t id;
441         uint16_t blocksize;
442         uint16_t keysize;
443         cipher_type_t type;
444         uint16_t implicit_iv;   /* the size of implicit IV - the IV generated but not sent */
445         uint16_t explicit_iv;   /* the size of explicit IV - the IV stored in record */
446         uint16_t cipher_iv;     /* the size of IV needed by the cipher */
447         uint16_t tagsize;
448         bool    xor_nonce;      /* In this TLS AEAD cipher xor the implicit_iv with the nonce */
449 } cipher_entry_st;
450
451 typedef struct gnutls_cipher_suite_entry_st {
452         const char *name;
453         const uint8_t id[2];
454         gnutls_cipher_algorithm_t block_algorithm;
455         gnutls_kx_algorithm_t kx_algorithm;
456         gnutls_mac_algorithm_t mac_algorithm;
457         gnutls_protocol_t min_version;  /* this cipher suite is supported
458                                          * from 'version' and above;
459                                          */
460         gnutls_protocol_t min_dtls_version;     /* DTLS min version */
461         gnutls_mac_algorithm_t prf;
462 } gnutls_cipher_suite_entry_st;
463
464 /* This structure is used both for MACs and digests
465  */
466 typedef struct mac_entry_st {
467         const char *name;
468         const char *oid;        /* OID of the hash - if it is a hash */
469         gnutls_mac_algorithm_t id;
470         unsigned output_size;
471         unsigned key_size;
472         unsigned nonce_size;
473         unsigned placeholder;   /* if set, then not a real MAC */
474         unsigned secure;        /* must be set to zero if this hash is known to be broken */
475         unsigned block_size;    /* internal block size for HMAC */
476 } mac_entry_st;
477
478 typedef struct {
479         const char *name;
480         gnutls_protocol_t id;   /* gnutls internal version number */
481         unsigned age;           /* internal ordering by protocol age */
482         uint8_t major;          /* defined by the protocol */
483         uint8_t minor;          /* defined by the protocol */
484         transport_t transport;  /* Type of transport, stream or datagram */
485         bool supported; /* 0 not supported, > 0 is supported */
486         bool explicit_iv;
487         bool extensions;        /* whether it supports extensions */
488         bool selectable_sighash;        /* whether signatures can be selected */
489         bool selectable_prf;    /* whether the PRF is ciphersuite-defined */
490         bool obsolete;          /* Do not use this protocol version as record version */
491 } version_entry_st;
492
493
494 /* STATE (cont) */
495
496 #include <gnutls_hash_int.h>
497 #include <gnutls_cipher_int.h>
498 #include <gnutls_compress.h>
499
500 typedef struct {
501         uint8_t hash_algorithm;
502         uint8_t sign_algorithm; /* pk algorithm actually */
503 } sign_algorithm_st;
504
505 /* This structure holds parameters got from TLS extension
506  * mechanism. (some extensions may hold parameters in auth_info_t
507  * structures also - see SRP).
508  */
509
510 #define MAX_SIGNATURE_ALGORITHMS 16
511 #define MAX_SIGN_ALGO_SIZE (2 + MAX_SIGNATURE_ALGORITHMS * 2)
512
513 #define MAX_VERIFY_DATA_SIZE 36 /* in SSL 3.0, 12 in TLS 1.0 */
514
515 /* auth_info_t structures now MAY contain malloced 
516  * elements.
517  */
518
519 /* This structure and auth_info_t, are stored in the resume database,
520  * and are restored, in case of resume.
521  * Holds all the required parameters to resume the current 
522  * session.
523  */
524
525 /* Note that the security parameters structure is set up after the
526  * handshake has finished. The only value you may depend on while
527  * the handshake is in progress is the cipher suite value.
528  */
529 typedef struct {
530         unsigned int entity;    /* GNUTLS_SERVER or GNUTLS_CLIENT */
531         gnutls_kx_algorithm_t kx_algorithm;
532
533         /* The epoch used to read and write */
534         uint16_t epoch_read;
535         uint16_t epoch_write;
536
537         /* The epoch that the next handshake will initialize. */
538         uint16_t epoch_next;
539
540         /* The epoch at index 0 of record_parameters. */
541         uint16_t epoch_min;
542
543         /* this is the ciphersuite we are going to use 
544          * moved here from internals in order to be restored
545          * on resume;
546          */
547         uint8_t cipher_suite[2];
548         gnutls_compression_method_t compression_method;
549         uint8_t master_secret[GNUTLS_MASTER_SIZE];
550         uint8_t client_random[GNUTLS_RANDOM_SIZE];
551         uint8_t server_random[GNUTLS_RANDOM_SIZE];
552         uint8_t session_id[GNUTLS_MAX_SESSION_ID_SIZE];
553         uint8_t session_id_size;
554         time_t timestamp;
555
556         /* The send size is the one requested by the programmer.
557          * The recv size is the one negotiated with the peer.
558          */
559         uint16_t max_record_send_size;
560         uint16_t max_record_recv_size;
561         /* holds the negotiated certificate type */
562         gnutls_certificate_type_t cert_type;
563         gnutls_ecc_curve_t ecc_curve;   /* holds the first supported ECC curve requested by client */
564
565         /* Holds the signature algorithm used in this session - If any */
566         gnutls_sign_algorithm_t server_sign_algo;
567         gnutls_sign_algorithm_t client_sign_algo;
568
569         /* Whether the master secret negotiation will be according to
570          * draft-ietf-tls-session-hash-01
571          */
572         uint8_t ext_master_secret;
573         /* encrypt-then-mac -> rfc7366 */
574         uint8_t etm;
575
576         /* Note: if you add anything in Security_Parameters struct, then
577          * also modify CPY_COMMON in gnutls_constate.c, and gnutls_session_pack.c,
578          * in order to save it in the session storage.
579          */
580
581         /* Used by extensions that enable supplemental data: Which ones
582          * do that? Do they belong in security parameters?
583          */
584         int do_recv_supplemental, do_send_supplemental;
585         const version_entry_st *pversion;
586 } security_parameters_st;
587
588 struct record_state_st {
589         gnutls_datum_t mac_secret;
590         gnutls_datum_t IV;
591         gnutls_datum_t key;
592         auth_cipher_hd_st cipher_state;
593         comp_hd_st compression_state;
594         uint64 sequence_number;
595 };
596
597
598 /* These are used to resolve relative epochs. These values are just
599    outside the 16 bit range to prevent off-by-one errors. An absolute
600    epoch may be referred to by its numeric id in the range
601    0x0000-0xffff. */
602 #define EPOCH_READ_CURRENT  70000
603 #define EPOCH_WRITE_CURRENT 70001
604 #define EPOCH_NEXT          70002
605
606 struct record_parameters_st {
607         uint16_t epoch;
608         int initialized;
609
610         gnutls_compression_method_t compression_algorithm;
611
612         const cipher_entry_st *cipher;
613         bool etm;
614         const mac_entry_st *mac;
615
616         /* for DTLS */
617         uint64_t record_sw[DTLS_RECORD_WINDOW_SIZE];
618         unsigned int record_sw_head_idx;
619         unsigned int record_sw_size;
620
621         record_state_st read;
622         record_state_st write;
623
624         /* Whether this state is in use, i.e., if there is
625            a pending handshake message waiting to be encrypted
626            under this epoch's parameters.
627          */
628         int usage_cnt;
629 };
630
631 typedef struct {
632         unsigned int priority[MAX_ALGOS];
633         unsigned int algorithms;
634 } priority_st;
635
636 typedef enum {
637         SR_DISABLED,
638         SR_UNSAFE,
639         SR_PARTIAL,
640         SR_SAFE
641 } safe_renegotiation_t;
642
643 /* For the external api */
644 struct gnutls_priority_st {
645         priority_st cipher;
646         priority_st mac;
647         priority_st kx;
648         priority_st compression;
649         priority_st protocol;
650         priority_st cert_type;
651         priority_st sign_algo;
652         priority_st supported_ecc;
653
654         /* to disable record padding */
655         bool no_extensions;
656         bool no_ext_master_secret;
657         bool allow_large_records;
658         unsigned int dumbfw;
659         safe_renegotiation_t sr;
660         bool min_record_version;
661         bool server_precedence;
662         bool allow_wrong_pms;
663         bool no_tickets;
664         bool no_etm;
665         bool have_cbc;
666         /* Whether stateless compression will be used */
667         bool stateless_compression;
668         unsigned int additional_verify_flags;
669
670         /* The session's expected security level.
671          * Will be used to determine the minimum DH bits,
672          * (or the acceptable certificate security level).
673          */
674         gnutls_sec_param_t level;
675         unsigned int dh_prime_bits;     /* old (deprecated) variable */
676
677         /* TLS_FALLBACK_SCSV */
678         bool fallback;
679 };
680
681 /* Allow around 50KB of length-hiding padding
682  * when using legacy padding,
683  * or around 3.2MB when using new padding. */
684 #define DEFAULT_MAX_EMPTY_RECORDS 200
685
686 #define ENABLE_COMPAT(x) \
687               (x)->allow_large_records = 1; \
688               (x)->no_etm = 1; \
689               (x)->no_ext_master_secret = 1; \
690               (x)->allow_wrong_pms = 1; \
691               (x)->dumbfw = 1
692
693 /* DH and RSA parameters types.
694  */
695 typedef struct gnutls_dh_params_int {
696         /* [0] is the prime, [1] is the generator.
697          */
698         bigint_t params[2];
699         int q_bits;             /* length of q in bits. If zero then length is unknown.
700                                  */
701 } dh_params_st;
702
703 typedef struct {
704         gnutls_dh_params_t dh_params;
705         int free_dh_params;
706 } internal_params_st;
707
708 /* DTLS session state
709  */
710 typedef struct {
711         /* HelloVerifyRequest DOS prevention cookie */
712         uint8_t cookie[DTLS_MAX_COOKIE_SIZE];
713         uint8_t cookie_len;
714
715         /* For DTLS handshake fragmentation and reassembly. */
716         uint16_t hsk_write_seq;
717         /* the sequence number of the expected packet */
718         unsigned int hsk_read_seq;
719         uint16_t mtu;
720
721         /* a flight transmission is in process */
722         bool flight_init;
723         /* whether this is the last flight in the protocol  */
724         bool last_flight;
725
726         /* the retransmission timeout in milliseconds */
727         unsigned int retrans_timeout_ms;
728
729         unsigned int hsk_hello_verify_requests;
730
731         /* The actual retrans_timeout for the next message (e.g. doubled or so) 
732          */
733         unsigned int actual_retrans_timeout_ms;
734
735         /* timers to handle async handshake after gnutls_handshake()
736          * has terminated. Required to handle retransmissions.
737          */
738         time_t async_term;
739
740         /* last retransmission triggered by record layer */
741         struct timespec last_retransmit;
742         unsigned int packets_dropped;
743 } dtls_st;
744
745 typedef struct {
746         /* holds all the parsed data received by the record layer */
747         mbuffer_head_st record_buffer;
748
749         int handshake_hash_buffer_prev_len;     /* keeps the length of handshake_hash_buffer, excluding
750                                                  * the last received message */
751         unsigned handshake_hash_buffer_client_kx_len;/* if non-zero it is the length of data until the
752                                                  * the client key exchange message */
753         gnutls_buffer_st handshake_hash_buffer; /* used to keep the last received handshake 
754                                                  * message */
755         bool resumable; /* TRUE or FALSE - if we can resume that session */
756         bool ticket_sent;       /* whether a session ticket was sent */
757         handshake_state_t handshake_final_state;
758         handshake_state_t handshake_state;      /* holds
759                                                  * a number which indicates where
760                                                  * the handshake procedure has been
761                                                  * interrupted. If it is 0 then
762                                                  * no interruption has happened.
763                                                  */
764
765         bool invalid_connection;        /* true or FALSE - if this session is valid */
766
767         bool may_not_read;      /* if it's 0 then we can read/write, otherwise it's forbiden to read/write
768                                  */
769         bool may_not_write;
770         bool read_eof;          /* non-zero if we have received a closure alert. */
771
772         int last_alert;         /* last alert received */
773
774         /* The last handshake messages sent or received.
775          */
776         int last_handshake_in;
777         int last_handshake_out;
778
779         /* priorities */
780         struct gnutls_priority_st priorities;
781
782         /* resumed session */
783         bool resumed;   /* RESUME_TRUE or FALSE - if we are resuming a session */
784         bool resumption_requested;      /* non-zero if resumption was requested by client */
785         security_parameters_st resumed_security_parameters;
786
787         /* These buffers are used in the handshake
788          * protocol only. freed using _gnutls_handshake_io_buffer_clear();
789          */
790         mbuffer_head_st handshake_send_buffer;
791         handshake_buffer_st handshake_recv_buffer[MAX_HANDSHAKE_MSGS];
792         int handshake_recv_buffer_size;
793
794         /* this buffer holds a record packet -mostly used for
795          * non blocking IO.
796          */
797         mbuffer_head_st record_recv_buffer;     /* buffer holding the unparsed record that is currently 
798                                                  * being received */
799         mbuffer_head_st record_send_buffer;     /* holds cached data
800                                                  * for the gnutls_io_write_buffered()
801                                                  * function.
802                                                  */
803         size_t record_send_buffer_user_size;    /* holds the
804                                                  * size of the user specified data to
805                                                  * send.
806                                                  */
807
808         record_flush_t record_flush_mode;       /* GNUTLS_FLUSH or GNUTLS_CORKED */
809         gnutls_buffer_st record_presend_buffer; /* holds cached data
810                                                  * for the gnutls_record_send()
811                                                  * function.
812                                                  */
813
814         unsigned expire_time;   /* after expire_time seconds this session will expire */
815         struct mod_auth_st_int *auth_struct;    /* used in handshake packets and KX algorithms */
816
817         /* this is the highest version available
818          * to the peer. (advertized version).
819          * This is obtained by the Handshake Client Hello 
820          * message. (some implementations read the Record version)
821          */
822         uint8_t adv_version_major;
823         uint8_t adv_version_minor;
824
825         /* if this is non zero a certificate request message
826          * will be sent to the client. - only if the ciphersuite
827          * supports it. In server side it contains GNUTLS_CERT_REQUIRE
828          * or similar.
829          */
830         unsigned send_cert_req;
831
832         size_t max_handshake_data_buffer_size;
833
834         /* PUSH & PULL functions.
835          */
836         gnutls_pull_timeout_func pull_timeout_func;
837         gnutls_pull_func pull_func;
838         gnutls_push_func push_func;
839         gnutls_vec_push_func vec_push_func;
840         gnutls_errno_func errno_func;
841         /* Holds the first argument of PUSH and PULL
842          * functions;
843          */
844         gnutls_transport_ptr_t transport_recv_ptr;
845         gnutls_transport_ptr_t transport_send_ptr;
846
847         /* STORE & RETRIEVE functions. Only used if other
848          * backend than gdbm is used.
849          */
850         gnutls_db_store_func db_store_func;
851         gnutls_db_retr_func db_retrieve_func;
852         gnutls_db_remove_func db_remove_func;
853         void *db_ptr;
854
855         /* post client hello callback (server side only)
856          */
857         gnutls_handshake_post_client_hello_func user_hello_func;
858         /* handshake hook function */
859         gnutls_handshake_hook_func h_hook;
860         unsigned int h_type;    /* the hooked type */
861         int16_t h_post;         /* whether post-generation/receive */
862
863         /* holds the selected certificate and key.
864          * use _gnutls_selected_certs_deinit() and _gnutls_selected_certs_set()
865          * to change them.
866          */
867         gnutls_pcert_st *selected_cert_list;
868         int16_t selected_cert_list_length;
869         struct gnutls_privkey_st *selected_key;
870         bool selected_need_free;
871
872         /* In case of a client holds the extensions we sent to the peer;
873          * otherwise the extensions we received from the client.
874          */
875         uint16_t extensions_sent[MAX_EXT_TYPES];
876         uint16_t extensions_sent_size;
877
878         /* is 0 if we are to send the whole PGP key, or non zero
879          * if the fingerprint is to be sent.
880          */
881         bool pgp_fingerprint;
882
883         /* This holds the default version that our first
884          * record packet will have. */
885         uint8_t default_record_version[2];
886         uint8_t default_hello_version[2];
887
888         void *user_ptr;
889
890         bool enable_private;    /* non zero to
891                                          * enable cipher suites
892                                          * which have 0xFF status.
893                                          */
894
895         /* Holds 0 if the last called function was interrupted while
896          * receiving, and non zero otherwise.
897          */
898         bool direction;
899
900         /* This callback will be used (if set) to receive an
901          * openpgp key. (if the peer sends a fingerprint)
902          */
903         gnutls_openpgp_recv_key_func openpgp_recv_key_func;
904
905         /* If non zero the server will not advertise the CA's he
906          * trusts (do not send an RDN sequence).
907          */
908         bool ignore_rdn_sequence;
909
910         /* This is used to set an arbitary version in the RSA
911          * PMS secret. Can be used by clients to test whether the
912          * server checks that version. (** only used in gnutls-cli-debug)
913          */
914         uint8_t rsa_pms_version[2];
915
916         /* Here we cache the DH or RSA parameters got from the
917          * credentials structure, or from a callback. That is to
918          * minimize external calls.
919          */
920         internal_params_st params;
921
922         /* To avoid using global variables, and especially on Windows where
923          * the application may use a different errno variable than GnuTLS,
924          * it is possible to use gnutls_transport_set_errno to set a
925          * session-specific errno variable in the user-replaceable push/pull
926          * functions.  This value is used by the send/recv functions.  (The
927          * strange name of this variable is because 'errno' is typically
928          * #define'd.)
929          */
930         int errnum;
931
932         /* minimum bits to allow for SRP
933          * use gnutls_srp_set_prime_bits() to adjust it.
934          */
935         uint16_t srp_prime_bits;
936
937         /* A handshake process has been completed */
938         bool initial_negotiation_completed;
939
940         struct {
941                 uint16_t type;
942                 gnutls_ext_priv_data_t priv;
943                 bool set;
944         } extension_int_data[MAX_EXT_TYPES];
945
946         struct {
947                 uint16_t type;
948                 gnutls_ext_priv_data_t priv;
949                 bool set;
950         } resumed_extension_int_data[MAX_EXT_TYPES];
951         /* The type of transport protocol; stream or datagram */
952         transport_t transport;
953
954         /* DTLS session state */
955         dtls_st dtls;
956         /* In case of clients that don't handle GNUTLS_E_LARGE_PACKET, don't
957          * force them into an infinite loop */
958         unsigned handshake_large_loops;
959         /* should be non-zero when a handshake is in progress */
960         bool handshake_in_progress;
961
962         /* if set it means that the master key was set using
963          * gnutls_session_set_master() rather than being negotiated. */
964         bool premaster_set;
965
966         unsigned int cb_tls_unique_len;
967         unsigned char cb_tls_unique[MAX_VERIFY_DATA_SIZE];
968
969         /* starting time of current handshake */
970         struct timespec handshake_start_time;
971
972         time_t handshake_endtime;       /* end time in seconds */
973         unsigned int handshake_timeout_ms;      /* timeout in milliseconds */
974         unsigned int record_timeout_ms; /* timeout in milliseconds */
975
976         gnutls_buffer_st hb_local_data;
977         gnutls_buffer_st hb_remote_data;
978         struct timespec hb_ping_start;  /* timestamp: when first HeartBeat ping was sent */
979         struct timespec hb_ping_sent;   /* timestamp: when last HeartBeat ping was sent */
980         unsigned int hb_actual_retrans_timeout_ms;      /* current timeout, in milliseconds */
981         unsigned int hb_retrans_timeout_ms;     /* the default timeout, in milliseconds */
982         unsigned int hb_total_timeout_ms;       /* the total timeout, in milliseconds */
983
984         bool ocsp_check_ok;     /* will be zero if the OCSP response TLS extension
985                                          * check failed (OCSP was old/unrelated or so). */
986
987         heartbeat_state_t hb_state;     /* for ping */
988
989         recv_state_t recv_state;        /* state of the receive function */
990
991         bool sc_random_set;
992         bool no_replay_protection;      /* DTLS replay protection */
993         bool try_ext_master_secret;     /* whether to try negotiating the ext master secret */
994
995         /* a verify callback to override the verify callback from the credentials
996          * structure */
997         gnutls_certificate_verify_function *verify_callback;
998         gnutls_typed_vdata_st *vc_data;
999         gnutls_typed_vdata_st vc_sdata;
1000         unsigned vc_elements;
1001         unsigned vc_status;
1002         unsigned int additional_verify_flags; /* may be set by priorities or the vc functions */
1003
1004         /* whether this session uses non-blocking sockets */
1005         bool blocking;
1006
1007         /* If you add anything here, check _gnutls_handshake_internal_state_clear().
1008          */
1009 } internals_st;
1010
1011 /* Maximum number of epochs we keep around. */
1012 #define MAX_EPOCH_INDEX 16
1013
1014 struct gnutls_session_int {
1015         security_parameters_st security_parameters;
1016         record_parameters_st *record_parameters[MAX_EPOCH_INDEX];
1017         internals_st internals;
1018         gnutls_key_st key;
1019 };
1020
1021
1022 /* functions 
1023  */
1024 void _gnutls_free_auth_info(gnutls_session_t session);
1025
1026 /* These two macros return the advertised TLS version of
1027  * the peer.
1028  */
1029 #define _gnutls_get_adv_version_major( session) \
1030         session->internals.adv_version_major
1031
1032 #define _gnutls_get_adv_version_minor( session) \
1033         session->internals.adv_version_minor
1034
1035 #define set_adv_version( session, major, minor) \
1036         session->internals.adv_version_major = major; \
1037         session->internals.adv_version_minor = minor
1038
1039 int _gnutls_is_secure_mem_null(const void *);
1040
1041 inline static const version_entry_st *get_version(gnutls_session_t session)
1042 {
1043         return session->security_parameters.pversion;
1044 }
1045
1046 inline static unsigned get_num_version(gnutls_session_t session)
1047 {
1048         if (likely(session->security_parameters.pversion != NULL))
1049                 return session->security_parameters.pversion->id;
1050         else
1051                 return GNUTLS_VERSION_UNKNOWN;
1052 }
1053
1054 void _gnutls_priority_update_fips(void);
1055
1056 #define timespec_sub_ms _gnutls_timespec_sub_ms
1057 unsigned int
1058 /* returns a-b in ms */
1059  timespec_sub_ms(struct timespec *a, struct timespec *b);
1060
1061 #include <algorithms.h>
1062 inline static int _gnutls_set_current_version(gnutls_session_t s, unsigned v)
1063 {
1064         s->security_parameters.pversion = version_to_entry(v);
1065         if (s->security_parameters.pversion == NULL) {
1066                 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
1067         }
1068         return 0;
1069 }
1070
1071 inline static size_t max_user_send_size(gnutls_session_t session,
1072                                         record_parameters_st *
1073                                         record_params)
1074 {
1075         size_t max;
1076
1077         if (IS_DTLS(session))
1078                 max = gnutls_dtls_get_data_mtu(session);
1079         else {
1080                 max = session->security_parameters.max_record_send_size;
1081         }
1082
1083         return max;
1084 }
1085
1086 #endif                          /* GNUTLS_INT_H */