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