]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/Source/CyaSSL/cyassl/internal.h
Add FreeRTOS-Plus directory with new directory structure so it matches the FreeRTOS...
[freertos] / FreeRTOS-Plus / Source / CyaSSL / cyassl / internal.h
1 /* internal.h
2  *
3  * Copyright (C) 2006-2012 Sawtooth Consulting Ltd.
4  *
5  * This file is part of CyaSSL.
6  *
7  * CyaSSL is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * CyaSSL is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20  */
21
22
23 #ifndef CYASSL_INT_H
24 #define CYASSL_INT_H
25
26
27 #include <cyassl/ssl.h>
28 #include <cyassl/crl.h>
29 #include <cyassl/ctaocrypt/types.h>
30 #include <cyassl/ctaocrypt/random.h>
31 #include <cyassl/ctaocrypt/des3.h>
32 #include <cyassl/ctaocrypt/hc128.h>
33 #include <cyassl/ctaocrypt/rabbit.h>
34 #include <cyassl/ctaocrypt/asn.h>
35 #include <cyassl/ctaocrypt/md5.h>
36 #include <cyassl/ctaocrypt/aes.h>
37 #include <cyassl/ctaocrypt/logging.h>
38 #ifdef HAVE_ECC
39     #include <cyassl/ctaocrypt/ecc.h>
40 #endif
41 #ifndef NO_SHA256
42     #include <cyassl/ctaocrypt/sha256.h>
43 #endif
44 #ifdef HAVE_OCSP
45     #include <cyassl/ocsp.h>
46 #endif
47 #ifdef CYASSL_SHA512
48     #include <cyassl/ctaocrypt/sha512.h>
49 #endif
50
51 #ifdef CYASSL_CALLBACKS
52     #include <cyassl/openssl/cyassl_callbacks.h>
53     #include <signal.h>
54 #endif
55
56 #ifdef USE_WINDOWS_API 
57     #ifdef CYASSL_GAME_BUILD
58         #include "system/xtl.h"
59     #else
60         #if defined(_WIN32_WCE) || defined(WIN32_LEAN_AND_MEAN)
61             /* On WinCE winsock2.h must be included before windows.h */
62             #include <winsock2.h>
63         #endif
64         #include <windows.h>
65     #endif
66 #elif defined(THREADX)
67     #ifndef SINGLE_THREADED
68         #include "tx_api.h"
69     #endif
70 #elif defined(MICRIUM)
71     /* do nothing, just don't pick Unix */
72 #elif defined(FREERTOS)
73     /* do nothing */
74 #else
75     #ifndef SINGLE_THREADED
76         #define CYASSL_PTHREADS
77         #include <pthread.h>
78     #endif
79     #if defined(OPENSSL_EXTRA) || defined(GOAHEAD_WS)
80         #include <unistd.h>      /* for close of BIO */
81     #endif
82 #endif
83
84 #ifdef HAVE_LIBZ
85     #include "zlib.h"
86 #endif
87
88 #ifdef _MSC_VER
89     /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
90     #pragma warning(disable: 4996)
91 #endif
92
93 #ifdef NO_AES
94     #if !defined (ALIGN16)
95         #define ALIGN16
96     #endif
97 #endif
98
99 #ifdef NO_SHA256
100     #define SHA256_DIGEST_SIZE 32 
101 #endif
102
103 #ifdef __cplusplus
104     extern "C" {
105 #endif
106
107
108 #ifdef USE_WINDOWS_API 
109     typedef unsigned int SOCKET_T;
110 #else
111     typedef int SOCKET_T;
112 #endif
113
114
115 typedef byte word24[3];
116
117 /* used by ssl.c and cyassl_int.c */
118 void c32to24(word32 in, word24 out);
119
120 /* Define or comment out the cipher suites you'd like to be compiled in
121    make sure to use at least one BUILD_SSL_xxx or BUILD_TLS_xxx is defined
122
123    When adding cipher suites, add name to cipher_names, idx to cipher_name_idx
124 */
125 #ifndef NO_RC4
126     #define BUILD_SSL_RSA_WITH_RC4_128_SHA
127     #define BUILD_SSL_RSA_WITH_RC4_128_MD5
128     #if !defined(NO_TLS) && defined(HAVE_NTRU)
129         #define BUILD_TLS_NTRU_RSA_WITH_RC4_128_SHA
130     #endif
131 #endif
132
133 #ifndef NO_DES3
134     #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
135     #if !defined(NO_TLS) && defined(HAVE_NTRU)
136         #define BUILD_TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA
137     #endif
138 #endif
139
140 #if !defined(NO_AES) && !defined(NO_TLS)
141     #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
142     #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
143     #if !defined (NO_PSK)
144         #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
145         #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
146     #endif
147     #if defined(HAVE_NTRU)
148         #define BUILD_TLS_NTRU_RSA_WITH_AES_128_CBC_SHA
149         #define BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA
150     #endif
151     #if !defined (NO_SHA256)
152         #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
153         #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
154     #endif
155     #if defined (HAVE_AESGCM)
156         #define BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
157         #define BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
158     #endif
159 #endif
160
161 #if !defined(NO_HC128) && !defined(NO_TLS)
162     #define BUILD_TLS_RSA_WITH_HC_128_CBC_MD5
163     #define BUILD_TLS_RSA_WITH_HC_128_CBC_SHA
164 #endif
165
166 #if !defined(NO_RABBIT) && !defined(NO_TLS)
167     #define BUILD_TLS_RSA_WITH_RABBIT_CBC_SHA
168 #endif
169
170 #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && defined(OPENSSL_EXTRA)
171     #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
172     #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
173     #if !defined (NO_SHA256)
174         #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
175         #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
176         #if defined (HAVE_AESGCM)
177             #define BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
178             #define BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
179         #endif
180     #endif
181 #endif
182
183 #if defined(HAVE_ECC) && !defined(NO_TLS)
184     #if !defined(NO_AES)
185         #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
186         #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
187         #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
188         #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
189
190         #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
191         #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
192         #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
193         #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
194
195         #if defined (HAVE_AESGCM)
196             #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
197             #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
198             #define BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
199             #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
200
201             #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
202             #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
203             #define BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
204             #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
205         #endif
206     #endif
207     #if !defined(NO_RC4)
208         #define BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
209         #define BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
210
211         #define BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
212         #define BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
213     #endif
214     #if !defined(NO_DES3)
215         #define BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
216         #define BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
217
218         #define BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
219         #define BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
220     #endif
221 #endif
222
223
224 #if defined(BUILD_SSL_RSA_WITH_RC4_128_SHA) || \
225     defined(BUILD_SSL_RSA_WITH_RC4_128_MD5)
226     #define BUILD_ARC4
227 #endif
228
229 #if defined(BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA)
230     #define BUILD_DES3
231 #endif
232
233 #if defined(BUILD_TLS_RSA_WITH_AES_128_CBC_SHA) || \
234     defined(BUILD_TLS_RSA_WITH_AES_256_CBC_SHA)
235     #define BUILD_AES
236 #endif
237
238 #if defined(BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256)
239     #define BUILD_AESGCM
240 #endif
241
242 #if defined(BUILD_TLS_RSA_WITH_HC_128_CBC_SHA) || \
243     defined(BUILD_TLS_RSA_WITH_HC_128_CBC_MD5)
244     #define BUILD_HC128
245 #endif
246
247 #if defined(BUILD_TLS_RSA_WITH_RABBIT_CBC_SHA)
248     #define BUILD_RABBIT
249 #endif
250
251 #ifdef NO_DES3
252     #define DES_BLOCK_SIZE 8
253 #endif
254
255 #ifdef NO_AES
256     #define AES_BLOCK_SIZE 16
257 #endif
258
259
260 /* actual cipher values, 2nd byte */
261 enum {
262     TLS_DHE_RSA_WITH_AES_256_CBC_SHA  = 0x39,
263     TLS_DHE_RSA_WITH_AES_128_CBC_SHA  = 0x33,
264     TLS_RSA_WITH_AES_256_CBC_SHA      = 0x35,
265     TLS_RSA_WITH_AES_128_CBC_SHA      = 0x2F,
266     TLS_PSK_WITH_AES_256_CBC_SHA      = 0x8d,
267     TLS_PSK_WITH_AES_128_CBC_SHA      = 0x8c,
268     SSL_RSA_WITH_RC4_128_SHA          = 0x05,
269     SSL_RSA_WITH_RC4_128_MD5          = 0x04,
270     SSL_RSA_WITH_3DES_EDE_CBC_SHA     = 0x0A,
271
272     /* ECC suites, first byte is 0xC0 (ECC_BYTE) */
273     TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA    = 0x14,
274     TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA    = 0x13,
275     TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA  = 0x0A,
276     TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA  = 0x09,
277     TLS_ECDHE_RSA_WITH_RC4_128_SHA        = 0x11,
278     TLS_ECDHE_ECDSA_WITH_RC4_128_SHA      = 0x07,
279     TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA   = 0x12,
280     TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x08,
281
282         /* static ECDH, first byte is 0xC0 (ECC_BYTE) */
283     TLS_ECDH_RSA_WITH_AES_256_CBC_SHA    = 0x0F,
284     TLS_ECDH_RSA_WITH_AES_128_CBC_SHA    = 0x0E,
285     TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA  = 0x05,
286     TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA  = 0x04,
287     TLS_ECDH_RSA_WITH_RC4_128_SHA        = 0x0C,
288     TLS_ECDH_ECDSA_WITH_RC4_128_SHA      = 0x02,
289     TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA   = 0x0D,
290     TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x03,
291
292     /* CyaSSL extension - eSTREAM */
293     TLS_RSA_WITH_HC_128_CBC_MD5       = 0xFB,
294     TLS_RSA_WITH_HC_128_CBC_SHA       = 0xFC,
295     TLS_RSA_WITH_RABBIT_CBC_SHA       = 0xFD,
296
297     /* CyaSSL extension - NTRU */
298     TLS_NTRU_RSA_WITH_RC4_128_SHA      = 0xe5,
299     TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA = 0xe6,
300     TLS_NTRU_RSA_WITH_AES_128_CBC_SHA  = 0xe7,  /* clases w/ official SHA-256 */
301     TLS_NTRU_RSA_WITH_AES_256_CBC_SHA  = 0xe8,
302
303     /* SHA256 */
304     TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x6b,
305     TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x67,
306     TLS_RSA_WITH_AES_256_CBC_SHA256     = 0x3d,
307     TLS_RSA_WITH_AES_128_CBC_SHA256     = 0x3c,
308
309     /* AES-GCM */
310     TLS_RSA_WITH_AES_128_GCM_SHA256          = 0x9c,
311     TLS_RSA_WITH_AES_256_GCM_SHA384          = 0x9d,
312     TLS_DHE_RSA_WITH_AES_128_GCM_SHA256      = 0x9e,
313     TLS_DHE_RSA_WITH_AES_256_GCM_SHA384      = 0x9f,
314
315     /* ECC AES-GCM, first byte is 0xC0 (ECC_BYTE) */
316     TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256  = 0x2b,
317     TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384  = 0x2c,
318     TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256   = 0x2d,
319     TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384   = 0x2e,
320     TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256    = 0x2f,
321     TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384    = 0x30,
322     TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256     = 0x31,
323     TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384     = 0x32
324 };
325
326
327 enum Misc {
328     SERVER_END = 0,
329     CLIENT_END,
330
331     ECC_BYTE =  0xC0,           /* ECC first cipher suite byte */
332
333     SEND_CERT       = 1,
334     SEND_BLANK_CERT = 2,
335
336     DTLS_MAJOR      = 0xfe,     /* DTLS major version number */
337     DTLS_MINOR      = 0xff,     /* DTLS minor version number */
338     SSLv3_MAJOR     = 3,        /* SSLv3 and TLSv1+  major version number */
339     SSLv3_MINOR     = 0,        /* TLSv1   minor version number */
340     TLSv1_MINOR     = 1,        /* TLSv1   minor version number */
341     TLSv1_1_MINOR   = 2,        /* TLSv1_1 minor version number */
342     TLSv1_2_MINOR   = 3,        /* TLSv1_2 minor version number */
343     NO_COMPRESSION  =  0,
344     ZLIB_COMPRESSION = 221,     /* CyaSSL zlib compression */
345     HELLO_EXT_SIG_ALGO = 13,    /* ID for the sig_algo hello extension */
346     SECRET_LEN      = 48,       /* pre RSA and all master */
347     ENCRYPT_LEN     = 512,      /* allow 4096 bit static buffer */
348     SIZEOF_SENDER   =  4,       /* clnt or srvr           */
349     FINISHED_SZ     = MD5_DIGEST_SIZE + SHA_DIGEST_SIZE,
350     MAX_RECORD_SIZE = 16384,    /* 2^14, max size by standard */
351     MAX_MSG_EXTRA   = 70,       /* max added to msg, mac + pad  from */
352                                 /* RECORD_HEADER_SZ + BLOCK_SZ (pad) + SHA_256
353                                    digest sz + BLOC_SZ (iv) + pad byte (1) */
354     MAX_COMP_EXTRA  = 1024,     /* max compression extra */
355     MAX_MTU         = 1500,     /* max expected MTU */
356     MAX_UDP_SIZE    = MAX_MTU - 100,   /* don't exceed MTU w/ 100 byte header */
357     MAX_DH_SZ       = 612,      /* 2240 p, pub, g + 2 byte size for each */
358     MAX_STR_VERSION = 8,        /* string rep of protocol version */
359
360     PAD_MD5        = 48,       /* pad length for finished */
361     PAD_SHA        = 40,       /* pad length for finished */
362     PEM_LINE_LEN   = 80,       /* PEM line max + fudge */
363     LENGTH_SZ      =  2,       /* length field for HMAC, data only */
364     VERSION_SZ     =  2,       /* length of proctocol version */
365     SEQ_SZ         =  8,       /* 64 bit sequence number  */
366     BYTE3_LEN      =  3,       /* up to 24 bit byte lengths */
367     ALERT_SIZE     =  2,       /* level + description     */
368     REQUEST_HEADER =  2,       /* always use 2 bytes      */
369     VERIFY_HEADER  =  2,       /* always use 2 bytes      */
370     MAX_DH_SIZE    = 513,      /* 4096 bit plus possible leading 0 */
371
372     MAX_SUITE_SZ = 200,        /* 100 suites for now! */
373     RAN_LEN      = 32,         /* random length           */
374     SEED_LEN     = RAN_LEN * 2, /* tls prf seed length    */
375     ID_LEN       = 32,         /* session id length       */
376     MAX_COOKIE_LEN = 32,       /* max dtls cookie size    */
377     COOKIE_SZ    = 20,         /* use a 20 byte cookie    */
378     SUITE_LEN    =  2,         /* cipher suite sz length  */
379     ENUM_LEN     =  1,         /* always a byte           */
380     COMP_LEN     =  1,         /* compression length      */
381     CURVE_LEN    =  2,         /* ecc named curve length  */
382     
383     HANDSHAKE_HEADER_SZ = 4,   /* type + length(3)        */
384     RECORD_HEADER_SZ    = 5,   /* type + version + len(2) */
385     CERT_HEADER_SZ      = 3,   /* always 3 bytes          */
386     REQ_HEADER_SZ       = 2,   /* cert request header sz  */
387     HINT_LEN_SZ         = 2,   /* length of hint size field */
388     HELLO_EXT_SZ        = 14,  /* total length of the lazy hello extensions */
389     HELLO_EXT_LEN       = 12,  /* length of the lazy hello extensions */
390     HELLO_EXT_SIGALGO_SZ  = 8, /* length of signature algo extension  */
391     HELLO_EXT_SIGALGO_LEN = 6, /* number of items in the signature algo list */
392
393     DTLS_HANDSHAKE_HEADER_SZ = 12, /* normal + seq(2) + offset(3) + length(3) */
394     DTLS_RECORD_HEADER_SZ    = 13, /* normal + epoch(2) + seq_num(6) */
395     DTLS_HANDSHAKE_EXTRA     = 8,  /* diff from normal */
396     DTLS_RECORD_EXTRA        = 8,  /* diff from normal */
397
398     FINISHED_LABEL_SZ   = 15,  /* TLS finished label size */
399     TLS_FINISHED_SZ     = 12,  /* TLS has a shorter size  */
400     MASTER_LABEL_SZ     = 13,  /* TLS master secret label sz */
401     KEY_LABEL_SZ        = 13,  /* TLS key block expansion sz */
402     MAX_PRF_HALF        = 128, /* Maximum half secret len */
403     MAX_PRF_LABSEED     = 80,  /* Maximum label + seed len */
404     MAX_PRF_DIG         = 224, /* Maximum digest len      */
405     MAX_REQUEST_SZ      = 256, /* Maximum cert req len (no auth yet */
406     SESSION_FLUSH_COUNT = 256, /* Flush session cache unless user turns off */ 
407
408     RC4_KEY_SIZE        = 16,  /* always 128bit           */
409     DES_KEY_SIZE        =  8,  /* des                     */
410     DES3_KEY_SIZE       = 24,  /* 3 des ede               */
411     DES_IV_SIZE         = DES_BLOCK_SIZE,
412     AES_256_KEY_SIZE    = 32,  /* for 256 bit             */
413     AES_192_KEY_SIZE    = 24,  /* for 192 bit             */
414     AES_IV_SIZE         = 16,  /* always block size       */
415     AES_GCM_IMP_IV_SZ   = 4,   /* Implicit part of IV     */
416     AES_GCM_EXP_IV_SZ   = 8,   /* Explicit part of IV     */
417     AES_GCM_CTR_IV_SZ   = 4,   /* Counter part of IV      */
418     AES_128_KEY_SIZE    = 16,  /* for 128 bit             */
419
420     AEAD_SEQ_OFFSET     = 4,        /* Auth Data: Sequence number */
421     AEAD_TYPE_OFFSET    = 8,        /* Auth Data: Type            */
422     AEAD_VMAJ_OFFSET    = 9,        /* Auth Data: Major Version   */
423     AEAD_VMIN_OFFSET    = 10,       /* Auth Data: Minor Version   */
424     AEAD_LEN_OFFSET     = 11,       /* Auth Data: Length          */
425     AEAD_AUTH_TAG_SZ    = 16,       /* Size of the authentication tag   */
426     AEAD_AUTH_DATA_SZ   = 13,       /* Size of the data to authenticate */
427
428     HC_128_KEY_SIZE     = 16,  /* 128 bits                */
429     HC_128_IV_SIZE      = 16,  /* also 128 bits           */
430
431     RABBIT_KEY_SIZE     = 16,  /* 128 bits                */
432     RABBIT_IV_SIZE      =  8,  /* 64 bits for iv          */
433
434     EVP_SALT_SIZE       =  8,  /* evp salt size 64 bits   */
435
436     ECDHE_SIZE          = 32,  /* ECHDE server size defaults to 256 bit */
437     MAX_EXPORT_ECC_SZ   = 256, /* Export ANS X9.62 max future size */
438
439     MAX_HELLO_SZ       = 128,  /* max client or server hello */
440     MAX_CERT_VERIFY_SZ = 1024, /* max   */
441     CLIENT_HELLO_FIRST =  35,  /* Protocol + RAN_LEN + sizeof(id_len) */
442     MAX_SUITE_NAME     =  48,  /* maximum length of cipher suite string */
443     DEFAULT_TIMEOUT    = 500,  /* default resumption timeout in seconds */
444
445     MAX_PSK_ID_LEN     = 128,  /* max psk identity/hint supported */
446     MAX_PSK_KEY_LEN    =  64,  /* max psk key supported */
447
448 #ifdef FORTRESS
449     MAX_EX_DATA        =   3,  /* allow for three items of ex_data */
450     MAX_CHAIN_DEPTH    =   9,  /* max cert chain peer depth, FORTRESS option */
451 #else
452     MAX_CHAIN_DEPTH    =   6,  /* max cert chain peer depth */
453 #endif
454     MAX_X509_SIZE      = 2048, /* max static x509 buffer size */
455     CERT_MIN_SIZE      =  256, /* min PEM cert size with header/footer */
456     MAX_FILENAME_SZ    =  256, /* max file name length */
457     FILE_BUFFER_SIZE   = 1024, /* default static file buffer size for input,
458                                   will use dynamic buffer if not big enough */
459
460     MAX_NTRU_PUB_KEY_SZ = 1027, /* NTRU max for now */
461     MAX_NTRU_ENCRYPT_SZ = 1027, /* NTRU max for now */
462     MAX_NTRU_BITS       =  256, /* max symmetric bit strength */
463     NO_SNIFF           =   0,  /* not sniffing */
464     SNIFF              =   1,  /* currently sniffing */
465
466     HASH_SIG_SIZE      =   2,  /* default SHA1 RSA */
467
468     NO_COPY            =   0,  /* should we copy static buffer for write */
469     COPY               =   1   /* should we copy static buffer for write */
470 };
471
472
473 /* states */
474 enum states {
475     NULL_STATE = 0,
476
477     SERVER_HELLOVERIFYREQUEST_COMPLETE,
478     SERVER_HELLO_COMPLETE,
479     SERVER_CERT_COMPLETE,
480     SERVER_KEYEXCHANGE_COMPLETE,
481     SERVER_HELLODONE_COMPLETE,
482     SERVER_FINISHED_COMPLETE,
483
484     CLIENT_HELLO_COMPLETE,
485     CLIENT_KEYEXCHANGE_COMPLETE,
486     CLIENT_FINISHED_COMPLETE,
487
488     HANDSHAKE_DONE
489 };
490
491
492
493 /* SSL Version */
494 typedef struct ProtocolVersion {
495     byte major;
496     byte minor;
497 } ProtocolVersion;
498
499
500 CYASSL_LOCAL ProtocolVersion MakeSSLv3(void);
501 CYASSL_LOCAL ProtocolVersion MakeTLSv1(void);
502 CYASSL_LOCAL ProtocolVersion MakeTLSv1_1(void);
503 CYASSL_LOCAL ProtocolVersion MakeTLSv1_2(void);
504
505 #ifdef CYASSL_DTLS
506     CYASSL_LOCAL ProtocolVersion MakeDTLSv1(void);
507 #endif
508
509
510 enum BIO_TYPE {
511     BIO_BUFFER = 1,
512     BIO_SOCKET = 2,
513     BIO_SSL    = 3,
514     BIO_MEMORY = 4
515 };
516
517
518 /* CyaSSL BIO_METHOD type */
519 struct CYASSL_BIO_METHOD {
520     byte type;               /* method type */
521 };
522
523
524 /* CyaSSL BIO type */
525 struct CYASSL_BIO {
526     byte        type;          /* method type */
527     byte        close;         /* close flag */
528     byte        eof;           /* eof flag */
529     CYASSL*     ssl;           /* possible associated ssl */
530     byte*       mem;           /* memory buffer */
531     int         memLen;        /* memory buffer length */
532     int         fd;            /* possible file descriptor */
533     CYASSL_BIO* prev;          /* previous in chain */
534     CYASSL_BIO* next;          /* next in chain */
535 };
536
537
538 /* CyaSSL method type */
539 struct CYASSL_METHOD {
540     ProtocolVersion version;
541     byte            side;         /* connection side, server or client */
542     byte            downgrade;    /* whether to downgrade version, default no */
543 };
544
545
546 /* defautls to client */
547 CYASSL_LOCAL void InitSSL_Method(CYASSL_METHOD*, ProtocolVersion);
548
549 /* for sniffer */
550 CYASSL_LOCAL int DoFinished(CYASSL* ssl, const byte* input, word32* inOutIdx,
551                             int sniff);
552 CYASSL_LOCAL int DoApplicationData(CYASSL* ssl, byte* input, word32* inOutIdx);
553
554
555 /* CyaSSL buffer type */
556 typedef struct buffer {
557     word32 length;
558     byte*  buffer;
559 } buffer;
560
561
562 enum {
563     FORCED_FREE = 1,
564     NO_FORCED_FREE = 0
565 };
566
567
568 /* only use compression extra if using compression */
569 #ifdef HAVE_LIBZ
570     #define COMP_EXTRA MAX_COMP_EXTRA
571 #else
572     #define COMP_EXTRA 0
573 #endif
574
575 /* only the sniffer needs space in the buffer for extra MTU record(s) */
576 #ifdef CYASSL_SNIFFER
577     #define MTU_EXTRA MAX_MTU * 3 
578 #else
579     #define MTU_EXTRA 0
580 #endif
581
582 /* give user option to use 16K static buffers, sniffer needs them too */
583 #if defined(LARGE_STATIC_BUFFERS) || defined(CYASSL_SNIFFER)
584     #define RECORD_SIZE MAX_RECORD_SIZE
585 #else
586     #ifdef CYASSL_DTLS
587         #define RECORD_SIZE MAX_MTU 
588     #else
589         #define RECORD_SIZE 128 
590     #endif
591 #endif
592
593
594 /* user option to turn off 16K output option */
595 /* if using small static buffers (default) and SSL_write tries to write data
596    larger than the record we have, dynamically get it, unless user says only
597    write in static buffer chuncks  */
598 #ifndef STATIC_CHUNKS_ONLY
599     #define OUTPUT_RECORD_SIZE MAX_RECORD_SIZE
600 #else
601     #define OUTPUT_RECORD_SIZE RECORD_SIZE
602 #endif
603
604 /* CyaSSL input buffer
605
606    RFC 2246:
607
608    length
609        The length (in bytes) of the following TLSPlaintext.fragment.
610        The length should not exceed 2^14.
611 */
612 #define STATIC_BUFFER_LEN RECORD_HEADER_SZ + RECORD_SIZE + COMP_EXTRA + \
613         MTU_EXTRA + MAX_MSG_EXTRA
614
615 typedef struct {
616     word32 length;       /* total buffer length used */
617     word32 idx;          /* idx to part of length already consumed */
618     byte*  buffer;       /* place holder for static or dynamic buffer */
619     ALIGN16 byte staticBuffer[STATIC_BUFFER_LEN];
620     word32 bufferSize;   /* current buffer size */
621     byte   dynamicFlag;  /* dynamic memory currently in use */
622 } bufferStatic;
623
624 /* Cipher Suites holder */
625 typedef struct Suites {
626     int    setSuites;               /* user set suites from default */
627     byte   suites[MAX_SUITE_SZ];  
628     word16 suiteSz;                 /* suite length in bytes        */
629 } Suites;
630
631
632 CYASSL_LOCAL
633 void InitSuites(Suites*, ProtocolVersion, byte, byte, byte, byte, byte, int);
634 CYASSL_LOCAL
635 int  SetCipherList(Suites*, const char* list);
636
637 #ifndef PSK_TYPES_DEFINED
638     typedef unsigned int (*psk_client_callback)(CYASSL*, const char*, char*,
639                           unsigned int, unsigned char*, unsigned int);
640     typedef unsigned int (*psk_server_callback)(CYASSL*, const char*,
641                           unsigned char*, unsigned int);
642 #endif /* PSK_TYPES_DEFINED */
643
644
645 #ifndef CYASSL_USER_IO
646     /* default IO callbacks */
647     CYASSL_LOCAL
648     int EmbedReceive(char *buf, int sz, void *ctx);
649     CYASSL_LOCAL 
650     int EmbedSend(char *buf, int sz, void *ctx);
651 #endif
652
653 #ifdef CYASSL_DTLS
654     CYASSL_LOCAL
655     int EmbedGenerateCookie(byte *buf, int sz, void *ctx);
656     CYASSL_LOCAL
657     int IsUDP(void*);
658 #endif
659
660
661 /* CyaSSL Cipher type just points back to SSL */
662 struct CYASSL_CIPHER {
663     CYASSL* ssl;
664 };
665
666
667 #ifdef SINGLE_THREADED
668     typedef int CyaSSL_Mutex;
669 #else /* MULTI_THREADED */
670     /* FREERTOS comes first to enable use of FreeRTOS Windows simulator only */
671     #ifdef FREERTOS
672         typedef xSemaphoreHandle CyaSSL_Mutex;
673     #elif defined(USE_WINDOWS_API)
674         typedef CRITICAL_SECTION CyaSSL_Mutex;
675     #elif defined(CYASSL_PTHREADS)
676         typedef pthread_mutex_t CyaSSL_Mutex;
677     #elif defined(THREADX)
678         typedef TX_MUTEX CyaSSL_Mutex;
679     #elif defined(MICRIUM)
680         typedef OS_MUTEX CyaSSL_Mutex;
681     #else
682         #error Need a mutex type in multithreaded mode
683     #endif /* USE_WINDOWS_API */
684 #endif /* SINGLE_THREADED */
685
686 CYASSL_LOCAL int InitMutex(CyaSSL_Mutex*);
687 CYASSL_LOCAL int FreeMutex(CyaSSL_Mutex*);
688 CYASSL_LOCAL int LockMutex(CyaSSL_Mutex*);
689 CYASSL_LOCAL int UnLockMutex(CyaSSL_Mutex*);
690
691
692
693 typedef struct OCSP_Entry OCSP_Entry;
694
695 struct OCSP_Entry {
696     OCSP_Entry* next;                       /* next entry             */
697     byte    issuerHash[SHA_DIGEST_SIZE];    /* issuer hash            */ 
698     byte    issuerKeyHash[SHA_DIGEST_SIZE]; /* issuer public key hash */
699     CertStatus* status;                     /* OCSP response list     */
700     int         totalStatus;                /* number on list         */
701 };
702
703
704 /* CyaSSL OCSP controller */
705 struct CYASSL_OCSP {
706     byte enabled;
707     byte useOverrideUrl;
708     char overrideName[80];
709     char overridePath[80];
710     int  overridePort;
711     OCSP_Entry* ocspList;
712 };
713
714
715 typedef struct CRL_Entry CRL_Entry;
716
717 /* Complete CRL */
718 struct CRL_Entry {
719     CRL_Entry* next;                      /* next entry */
720     byte    issuerHash[SHA_DIGEST_SIZE];  /* issuer hash                 */ 
721     byte    crlHash[MD5_DIGEST_SIZE];     /* raw crl data hash           */ 
722     byte    lastDate[MAX_DATE_SIZE]; /* last date updated  */
723     byte    nextDate[MAX_DATE_SIZE]; /* next update date   */
724     byte    lastDateFormat;          /* last date format */
725     byte    nextDateFormat;          /* next date format */
726     RevokedCert* certs;              /* revoked cert list  */
727     int          totalCerts;         /* number on list     */
728 };
729
730
731 typedef struct CRL_Monitor CRL_Monitor;
732
733 /* CRL directory monitor */
734 struct CRL_Monitor {
735     char* path;      /* full dir path, if valid pointer we're using */
736     int   type;      /* PEM or ASN1 type */
737 };
738
739
740 /* CyaSSL CRL controller */
741 struct CYASSL_CRL {
742     CYASSL_CERT_MANAGER* cm;            /* pointer back to cert manager */
743     CRL_Entry*           crlList;       /* our CRL list */
744     CyaSSL_Mutex         crlLock;       /* CRL list lock */
745     CRL_Monitor          monitors[2];   /* PEM and DER possible */
746 #ifdef HAVE_CRL_MONITOR
747     pthread_t            tid;           /* monitoring thread */
748 #endif
749 };
750
751
752 /* CyaSSL Certificate Manager */
753 struct CYASSL_CERT_MANAGER {
754     Signer*         caList;             /* the CA signer list */
755     CyaSSL_Mutex    caLock;             /* CA list lock */
756     CallbackCACache caCacheCallback;    /* CA cache addition callback */
757     void*           heap;               /* heap helper */
758     CYASSL_CRL*     crl;                /* CRL checker */
759     byte            crlEnabled;         /* is CRL on ? */
760     byte            crlCheckAll;        /* always leaf, but all ? */
761     CbMissingCRL    cbMissingCRL;       /* notify through cb of missing crl */
762 };
763
764
765 /* CyaSSL context type */
766 struct CYASSL_CTX {
767     CYASSL_METHOD* method;
768     CyaSSL_Mutex   countMutex;    /* reference count mutex */
769     int         refCount;         /* reference count */
770     buffer      certificate;
771     buffer      certChain;
772                  /* chain after self, in DER, with leading size for each cert */
773     buffer      privateKey;
774     buffer      serverDH_P;
775     buffer      serverDH_G;
776     CYASSL_CERT_MANAGER* cm;      /* our cert manager, ctx owns SSL will use */
777     Suites      suites;
778     void*       heap;             /* for user memory overrides */
779     byte        verifyPeer;
780     byte        verifyNone;
781     byte        failNoCert;
782     byte        sessionCacheOff;
783     byte        sessionCacheFlushOff;
784     byte        sendVerify;       /* for client side */
785     byte        haveDH;           /* server DH parms set by user */
786     byte        haveNTRU;         /* server private NTRU  key loaded */
787     byte        haveECDSAsig;     /* server cert signed w/ ECDSA */
788     byte        haveStaticECC;    /* static server ECC private key */
789     byte        partialWrite;     /* only one msg per write call */
790     byte        quietShutdown;    /* don't send close notify */
791     byte        groupMessages;    /* group handshake messages before sending */
792     CallbackIORecv CBIORecv;
793     CallbackIOSend CBIOSend;
794     VerifyCallback  verifyCallback;     /* cert verification callback */
795     word32          timeout;            /* session timeout */
796 #ifdef HAVE_ECC
797     word16          eccTempKeySz;       /* in octets 20 - 66 */
798 #endif
799 #ifndef NO_PSK
800     byte        havePSK;                /* psk key set by user */
801     psk_client_callback client_psk_cb;  /* client callback */
802     psk_server_callback server_psk_cb;  /* server callback */
803     char        server_hint[MAX_PSK_ID_LEN];
804 #endif /* NO_PSK */
805 #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
806     pem_password_cb passwd_cb;
807     void*            userdata;
808 #endif /* OPENSSL_EXTRA */
809 #ifdef HAVE_OCSP
810     CYASSL_OCSP      ocsp;
811 #endif
812 };
813
814
815 CYASSL_LOCAL
816 int InitSSL_Ctx(CYASSL_CTX*, CYASSL_METHOD*);
817 CYASSL_LOCAL
818 void FreeSSL_Ctx(CYASSL_CTX*);
819 CYASSL_LOCAL
820 void SSL_CtxResourceFree(CYASSL_CTX*);
821
822 CYASSL_LOCAL
823 int DeriveTlsKeys(CYASSL* ssl);
824 CYASSL_LOCAL
825 int ProcessOldClientHello(CYASSL* ssl, const byte* input, word32* inOutIdx,
826                           word32 inSz, word16 sz);
827 CYASSL_LOCAL
828 int AddCA(CYASSL_CERT_MANAGER* ctx, buffer der, int type, int verify);
829 CYASSL_LOCAL
830 int AlreadySigner(CYASSL_CERT_MANAGER* cm, byte* hash);
831
832 /* All cipher suite related info */
833 typedef struct CipherSpecs {
834     byte bulk_cipher_algorithm;
835     byte cipher_type;               /* block, stream, or aead */
836     byte mac_algorithm;
837     byte kea;                       /* key exchange algo */
838     byte sig_algo;
839     byte hash_size;
840     byte pad_size;
841     byte static_ecdh;
842     word16 key_size;
843     word16 iv_size;
844     word16 block_size;
845 } CipherSpecs;
846
847
848
849 /* Supported Ciphers from page 43  */
850 enum BulkCipherAlgorithm { 
851     cipher_null,
852     rc4,
853     rc2,
854     des,
855     triple_des,             /* leading 3 (3des) not valid identifier */
856     des40,
857     idea,
858     aes,
859     aes_gcm,
860     hc128,                  /* CyaSSL extensions */
861     rabbit
862 };
863
864
865 /* Supported Message Authentication Codes from page 43 */
866 enum MACAlgorithm { 
867     no_mac,
868     md5_mac,
869     sha_mac,
870     sha224_mac,
871     sha256_mac,
872     sha384_mac,
873     sha512_mac,
874     rmd_mac
875 };
876
877
878 /* Supported Key Exchange Protocols */
879 enum KeyExchangeAlgorithm { 
880     no_kea,
881     rsa_kea, 
882     diffie_hellman_kea, 
883     fortezza_kea,
884     psk_kea,
885     ntru_kea,
886     ecc_diffie_hellman_kea,
887     ecc_static_diffie_hellman_kea       /* for verify suite only */
888 };
889
890
891 /* Supported Authentication Schemes */
892 enum SignatureAlgorithm {
893     anonymous_sa_algo,
894     rsa_sa_algo,
895     dsa_sa_algo,
896     ecc_dsa_sa_algo
897 };
898
899
900 /* Supprted ECC Curve Types */
901 enum EccCurves {
902     named_curve = 3
903 };
904
905
906 /* Supprted ECC Named Curves */
907 enum EccNamedCurves {
908     secp256r1 = 0x17,         /* default, OpenSSL also calls it prime256v1 */
909     secp384r1 = 0x18,
910     secp521r1 = 0x19,
911
912     secp160r1 = 0x10,
913     secp192r1 = 0x13,        /*           Openssl also call it prime192v1 */
914     secp224r1 = 0x15
915 };
916
917
918 /* Valid client certificate request types from page 27 */
919 enum ClientCertificateType {    
920     rsa_sign            = 1, 
921     dss_sign            = 2,
922     rsa_fixed_dh        = 3,
923     dss_fixed_dh        = 4,
924     rsa_ephemeral_dh    = 5,
925     dss_ephemeral_dh    = 6,
926     fortezza_kea_cert   = 20
927 };
928
929
930 enum CipherType { stream, block, aead };
931
932
933 /* keys and secrets */
934 typedef struct Keys {
935     byte client_write_MAC_secret[SHA256_DIGEST_SIZE];   /* max sizes */
936     byte server_write_MAC_secret[SHA256_DIGEST_SIZE]; 
937     byte client_write_key[AES_256_KEY_SIZE];         /* max sizes */
938     byte server_write_key[AES_256_KEY_SIZE]; 
939     byte client_write_IV[AES_IV_SIZE];               /* max sizes */
940     byte server_write_IV[AES_IV_SIZE];
941
942     word32 peer_sequence_number;
943     word32 sequence_number;
944     
945 #ifdef CYASSL_DTLS
946     word32 dtls_sequence_number;
947     word32 dtls_peer_sequence_number;
948     word16 dtls_handshake_number;
949     word16 dtls_epoch;
950     word16 dtls_peer_epoch;
951 #endif
952
953     word32 encryptSz;             /* last size of encrypted data   */
954     byte   encryptionOn;          /* true after change cipher spec */
955 } Keys;
956
957
958 /* cipher for now */
959 typedef union {
960 #ifdef BUILD_ARC4
961     Arc4   arc4;
962 #endif
963 #ifdef BUILD_DES3
964     Des3   des3;
965 #endif
966 #ifdef BUILD_AES
967     Aes    aes;
968 #endif
969 #ifdef HAVE_HC128
970     HC128  hc128;
971 #endif
972 #ifdef BUILD_RABBIT
973     Rabbit rabbit;
974 #endif
975 } Ciphers;
976
977
978 /* hashes type */
979 typedef struct Hashes {
980     byte md5[MD5_DIGEST_SIZE];
981     byte sha[SHA_DIGEST_SIZE];
982 } Hashes;
983
984
985 /* Static x509 buffer */
986 typedef struct x509_buffer {
987     int  length;                  /* actual size */
988     byte buffer[MAX_X509_SIZE];   /* max static cert size */
989 } x509_buffer;
990
991
992 /* CyaSSL X509_CHAIN, for no dynamic memory SESSION_CACHE */
993 struct CYASSL_X509_CHAIN {
994     int         count;                    /* total number in chain */
995     x509_buffer certs[MAX_CHAIN_DEPTH];   /* only allow max depth 4 for now */
996 };
997
998
999 /* CyaSSL session type */
1000 struct CYASSL_SESSION {
1001     byte         sessionID[ID_LEN];
1002     byte         masterSecret[SECRET_LEN];
1003     word32       bornOn;                        /* create time in seconds   */
1004     word32       timeout;                       /* timeout in seconds       */
1005 #ifdef SESSION_CERTS
1006     CYASSL_X509_CHAIN chain;                      /* peer cert chain, static  */
1007     ProtocolVersion version;
1008     byte            cipherSuite0;               /* first byte, normally 0 */
1009     byte            cipherSuite;                /* 2nd byte, actual suite */
1010 #endif
1011 };
1012
1013
1014 CYASSL_LOCAL
1015 CYASSL_SESSION* GetSession(CYASSL*, byte*);
1016 CYASSL_LOCAL
1017 int          SetSession(CYASSL*, CYASSL_SESSION*);
1018
1019 typedef void (*hmacfp) (CYASSL*, byte*, const byte*, word32, int, int);
1020
1021
1022 /* client connect state for nonblocking restart */
1023 enum ConnectState {
1024     CONNECT_BEGIN = 0,
1025     CLIENT_HELLO_SENT,
1026     HELLO_AGAIN,               /* HELLO_AGAIN s for DTLS case */
1027     HELLO_AGAIN_REPLY,
1028     FIRST_REPLY_DONE,
1029     FIRST_REPLY_FIRST,
1030     FIRST_REPLY_SECOND,
1031     FIRST_REPLY_THIRD,
1032     FIRST_REPLY_FOURTH,
1033     FINISHED_DONE,
1034     SECOND_REPLY_DONE
1035 };
1036
1037
1038 /* server accept state for nonblocking restart */
1039 enum AcceptState {
1040     ACCEPT_BEGIN = 0,
1041     ACCEPT_CLIENT_HELLO_DONE,
1042     HELLO_VERIFY_SENT,
1043     ACCEPT_FIRST_REPLY_DONE,
1044     SERVER_HELLO_SENT,
1045     CERT_SENT,
1046     KEY_EXCHANGE_SENT,
1047     CERT_REQ_SENT,
1048     SERVER_HELLO_DONE,
1049     ACCEPT_SECOND_REPLY_DONE,
1050     CHANGE_CIPHER_SENT,
1051     ACCEPT_FINISHED_DONE,
1052     ACCEPT_THIRD_REPLY_DONE
1053 };
1054
1055
1056 typedef struct Buffers {
1057     buffer          certificate;            /* CYASSL_CTX owns, unless we own */
1058     buffer          key;                    /* CYASSL_CTX owns, unless we own */
1059     buffer          certChain;              /* CYASSL_CTX owns */
1060                  /* chain after self, in DER, with leading size for each cert */
1061     buffer          domainName;             /* for client check */
1062     buffer          serverDH_P;             /* CYASSL_CTX owns, unless we own */
1063     buffer          serverDH_G;             /* CYASSL_CTX owns, unless we own */
1064     buffer          serverDH_Pub;
1065     buffer          serverDH_Priv;
1066     bufferStatic    inputBuffer;
1067     bufferStatic    outputBuffer;
1068     buffer          clearOutputBuffer;
1069     int             prevSent;              /* previous plain text bytes sent
1070                                               when got WANT_WRITE            */
1071     int             plainSz;               /* plain text bytes in buffer to send
1072                                               when got WANT_WRITE            */
1073     byte            weOwnCert;             /* SSL own cert flag */
1074     byte            weOwnKey;              /* SSL own key  flag */
1075     byte            weOwnDH;               /* SSL own dh (p,g)  flag */
1076 } Buffers;
1077
1078
1079 typedef struct Options {
1080     byte            sessionCacheOff;
1081     byte            sessionCacheFlushOff;
1082     byte            cipherSuite0;           /* first byte, normally 0 */
1083     byte            cipherSuite;            /* second byte, actual suite */
1084     byte            serverState;
1085     byte            clientState;
1086     byte            handShakeState;
1087     byte            side;               /* client or server end */
1088     byte            verifyPeer;
1089     byte            verifyNone;
1090     byte            failNoCert;
1091     byte            downgrade;          /* allow downgrade of versions */
1092     byte            sendVerify;         /* false = 0, true = 1, sendBlank = 2 */
1093     byte            resuming;
1094     byte            haveSessionId;      /* server may not send */
1095     byte            tls;                /* using TLS ? */
1096     byte            tls1_1;             /* using TLSv1.1+ ? */
1097     byte            dtls;               /* using datagrams ? */
1098     byte            connReset;          /* has the peer reset */
1099     byte            isClosed;           /* if we consider conn closed */
1100     byte            closeNotify;        /* we've recieved a close notify */
1101     byte            sentNotify;         /* we've sent a close notify */
1102     byte            connectState;       /* nonblocking resume */
1103     byte            acceptState;        /* nonblocking resume */
1104     byte            usingCompression;   /* are we using compression */
1105     byte            haveDH;             /* server DH parms set by user */
1106     byte            haveNTRU;           /* server NTRU  private key loaded */
1107     byte            haveECDSAsig;       /* server ECDSA signed cert */
1108     byte            haveStaticECC;      /* static server ECC private key */
1109     byte            havePeerCert;       /* do we have peer's cert */
1110     byte            usingPSK_cipher;    /* whether we're using psk as cipher */
1111     byte            sendAlertState;     /* nonblocking resume */ 
1112     byte            processReply;       /* nonblocking resume */
1113     byte            partialWrite;       /* only one msg per write call */
1114     byte            quietShutdown;      /* don't send close notify */
1115     byte            certOnly;           /* stop once we get cert */
1116     byte            groupMessages;      /* group handshake messages */
1117 #ifndef NO_PSK
1118     byte            havePSK;            /* psk key set by user */
1119     psk_client_callback client_psk_cb;
1120     psk_server_callback server_psk_cb;
1121 #endif /* NO_PSK */
1122 } Options;
1123
1124
1125 typedef struct Arrays {
1126     byte            clientRandom[RAN_LEN];
1127     byte            serverRandom[RAN_LEN];
1128     byte            sessionID[ID_LEN];
1129     byte            preMasterSecret[ENCRYPT_LEN];
1130     byte            masterSecret[SECRET_LEN];
1131 #ifdef CYASSL_DTLS
1132     byte            cookie[MAX_COOKIE_LEN];
1133     byte            cookieSz;
1134 #endif
1135 #ifndef NO_PSK
1136     char            client_identity[MAX_PSK_ID_LEN];
1137     char            server_hint[MAX_PSK_ID_LEN];
1138     byte            psk_key[MAX_PSK_KEY_LEN];
1139     word32          psk_keySz;          /* acutal size */
1140 #endif
1141     word32          preMasterSz;        /* differs for DH, actual size */
1142 } Arrays;
1143
1144
1145 struct CYASSL_X509_NAME {
1146     char  name[ASN_NAME_MAX];
1147     int   sz;
1148 };
1149
1150
1151 struct CYASSL_X509 {
1152     CYASSL_X509_NAME issuer;
1153     CYASSL_X509_NAME subject;
1154     int              serialSz;
1155     byte             serial[EXTERNAL_SERIAL_SIZE];
1156     char             subjectCN[ASN_NAME_MAX];        /* common name short cut */
1157     buffer           derCert;                        /* may need  */
1158     DNS_entry*       altNames;                       /* alt names list */
1159     DNS_entry*       altNamesNext;                   /* hint for retrieval */
1160 };
1161
1162
1163 /* record layer header for PlainText, Compressed, and CipherText */
1164 typedef struct RecordLayerHeader {
1165     byte            type;
1166     ProtocolVersion version;
1167     byte            length[2];
1168 } RecordLayerHeader;
1169
1170
1171 /* record layer header for DTLS PlainText, Compressed, and CipherText */
1172 typedef struct DtlsRecordLayerHeader {
1173     byte            type;
1174     ProtocolVersion version;
1175     byte            epoch[2];             /* increment on cipher state change */
1176     byte            sequence_number[6];   /* per record */
1177     byte            length[2];
1178 } DtlsRecordLayerHeader;
1179
1180
1181 /* CyaSSL ssl type */
1182 struct CYASSL {
1183     CYASSL_CTX*     ctx;
1184     int             error;
1185     ProtocolVersion version;            /* negotiated version */
1186     ProtocolVersion chVersion;          /* client hello version */
1187     Suites          suites;
1188     Ciphers         encrypt;
1189     Ciphers         decrypt;
1190     CipherSpecs     specs;
1191     Keys            keys;
1192     int             rfd;                /* read  file descriptor */
1193     int             wfd;                /* write file descriptor */
1194     CYASSL_BIO*     biord;              /* socket bio read  to free/close */
1195     CYASSL_BIO*     biowr;              /* socket bio write to free/close */
1196     void*           IOCB_ReadCtx;
1197     void*           IOCB_WriteCtx;
1198     RNG             rng;
1199     Md5             hashMd5;            /* md5 hash of handshake msgs */
1200     Sha             hashSha;            /* sha hash of handshake msgs */
1201 #ifndef NO_SHA256
1202     Sha256          hashSha256;         /* sha256 hash of handshake msgs */
1203 #endif
1204 #ifdef CYASSL_SHA384
1205     Sha384          hashSha384;         /* sha384 hash of handshake msgs */
1206 #endif
1207     Hashes          verifyHashes;
1208     Hashes          certHashes;         /* for cert verify */
1209     Buffers         buffers;
1210     Options         options;
1211     Arrays          arrays;
1212     CYASSL_SESSION  session;
1213     VerifyCallback  verifyCallback;      /* cert verification callback */
1214     RsaKey          peerRsaKey;
1215     byte            peerRsaKeyPresent;
1216 #ifdef HAVE_NTRU
1217     word16          peerNtruKeyLen;
1218     byte            peerNtruKey[MAX_NTRU_PUB_KEY_SZ];
1219     byte            peerNtruKeyPresent;
1220 #endif
1221 #ifdef HAVE_ECC
1222     ecc_key         peerEccKey;              /* peer's  ECDHE key */
1223     ecc_key         peerEccDsaKey;           /* peer's  ECDSA key */
1224     ecc_key         eccTempKey;              /* private ECDHE key */
1225     ecc_key         eccDsaKey;               /* private ECDSA key */
1226     word16          eccTempKeySz;            /* in octets 20 - 66 */
1227     byte            peerEccKeyPresent;
1228     byte            peerEccDsaKeyPresent;
1229     byte            eccTempKeyPresent;
1230     byte            eccDsaKeyPresent;
1231 #endif
1232     hmacfp          hmac;
1233     void*           heap;               /* for user overrides */
1234     RecordLayerHeader curRL;
1235     word16            curSize;
1236     word32          timeout;            /* session timeout */
1237     CYASSL_CIPHER   cipher;
1238 #ifdef HAVE_LIBZ
1239     z_stream        c_stream;           /* compression   stream */
1240     z_stream        d_stream;           /* decompression stream */
1241     byte            didStreamInit;      /* for stream init and end */
1242 #endif
1243 #ifdef CYASSL_CALLBACKS
1244     HandShakeInfo   handShakeInfo;      /* info saved during handshake */
1245     TimeoutInfo     timeoutInfo;        /* info saved during handshake */
1246     byte            hsInfoOn;           /* track handshake info        */
1247     byte            toInfoOn;           /* track timeout   info        */
1248 #endif
1249 #ifdef OPENSSL_EXTRA
1250     CYASSL_X509     peerCert;           /* X509 peer cert */
1251 #endif
1252 #ifdef FORTRESS
1253     void*           ex_data[MAX_EX_DATA]; /* external data, for Fortress */
1254 #endif
1255 };
1256
1257
1258 CYASSL_LOCAL
1259 int  InitSSL(CYASSL*, CYASSL_CTX*);
1260 CYASSL_LOCAL
1261 void FreeSSL(CYASSL*);
1262 CYASSL_API void SSL_ResourceFree(CYASSL*);   /* Micrium uses */
1263
1264
1265 enum {
1266     IV_SZ   = 32,          /* max iv sz */
1267     NAME_SZ = 80,          /* max one line */
1268 };
1269
1270
1271 typedef struct EncryptedInfo {
1272     char     name[NAME_SZ];    /* encryption name */
1273     byte     iv[IV_SZ];        /* encrypted IV */
1274     word32   ivSz;             /* encrypted IV size */
1275     long     consumed;         /* tracks PEM bytes consumed */
1276     byte     set;              /* if encryption set */
1277     CYASSL_CTX* ctx;              /* CTX owner */
1278 } EncryptedInfo;
1279
1280 CYASSL_LOCAL int PemToDer(const unsigned char* buff, long sz, int type,
1281                           buffer* der, void* heap, EncryptedInfo* info,
1282                           int* eccKey);
1283
1284 CYASSL_LOCAL int ProcessFile(CYASSL_CTX* ctx, const char* fname, int format,
1285                              int type, CYASSL* ssl, int userChain,
1286                             CYASSL_CRL* crl);
1287
1288
1289 #ifdef CYASSL_CALLBACKS
1290     CYASSL_LOCAL
1291     void InitHandShakeInfo(HandShakeInfo*);
1292     CYASSL_LOCAL 
1293     void FinishHandShakeInfo(HandShakeInfo*, const CYASSL*);
1294     CYASSL_LOCAL 
1295     void AddPacketName(const char*, HandShakeInfo*);
1296
1297     CYASSL_LOCAL
1298     void InitTimeoutInfo(TimeoutInfo*);
1299     CYASSL_LOCAL 
1300     void FreeTimeoutInfo(TimeoutInfo*, void*);
1301     CYASSL_LOCAL 
1302     void AddPacketInfo(const char*, TimeoutInfo*, const byte*, int, void*);
1303     CYASSL_LOCAL 
1304     void AddLateName(const char*, TimeoutInfo*);
1305     CYASSL_LOCAL 
1306     void AddLateRecordHeader(const RecordLayerHeader* rl, TimeoutInfo* info);
1307 #endif
1308
1309
1310 /* Record Layer Header identifier from page 12 */
1311 enum ContentType {
1312     no_type            = 0,
1313     change_cipher_spec = 20, 
1314     alert              = 21, 
1315     handshake          = 22, 
1316     application_data   = 23 
1317 };
1318
1319
1320 /* handshake header, same for each message type, pgs 20/21 */
1321 typedef struct HandShakeHeader {
1322     byte            type;
1323     word24          length;
1324 } HandShakeHeader;
1325
1326
1327 /* DTLS handshake header, same for each message type */
1328 typedef struct DtlsHandShakeHeader {
1329     byte            type;
1330     word24          length;
1331     byte            message_seq[2];    /* start at 0, restransmit gets same # */
1332     word24          fragment_offset;   /* bytes in previous fragments */
1333     word24          fragment_length;   /* length of this fragment */
1334 } DtlsHandShakeHeader;
1335
1336
1337 enum HandShakeType {
1338     no_shake            = -1,
1339     hello_request       = 0, 
1340     client_hello        = 1, 
1341     server_hello        = 2,
1342     hello_verify_request = 3,       /* DTLS addition */
1343     session_ticket      =  4,
1344     certificate         = 11, 
1345     server_key_exchange = 12,
1346     certificate_request = 13, 
1347     server_hello_done   = 14,
1348     certificate_verify  = 15, 
1349     client_key_exchange = 16,
1350     finished            = 20
1351 };
1352
1353
1354 /* Valid Alert types from page 16/17 */
1355 enum AlertDescription {
1356     close_notify            = 0,
1357     unexpected_message      = 10,
1358     bad_record_mac          = 20,
1359     decompression_failure   = 30,
1360     handshake_failure       = 40,
1361     no_certificate          = 41,
1362     bad_certificate         = 42,
1363     unsupported_certificate = 43,
1364     certificate_revoked     = 44,
1365     certificate_expired     = 45,
1366     certificate_unknown     = 46,
1367     illegal_parameter       = 47,
1368     decrypt_error           = 51,
1369     protocol_version        = 70,
1370     no_renegotiation        = 100
1371 };
1372
1373
1374 /* I/O Callback default errors */
1375 enum IOerrors {
1376     IO_ERR_GENERAL    = -1,     /* general unexpected err, not in below group */
1377     IO_ERR_WANT_READ  = -2,     /* need to call read  again */
1378     IO_ERR_WANT_WRITE = -2,     /* need to call write again */
1379     IO_ERR_CONN_RST   = -3,     /* connection reset */
1380     IO_ERR_ISR        = -4,     /* interrupt */
1381     IO_ERR_CONN_CLOSE = -5      /* connection closed or epipe */
1382 };
1383
1384
1385 enum AlertLevel { 
1386     alert_warning = 1, 
1387     alert_fatal = 2
1388 };
1389
1390
1391 static const byte client[SIZEOF_SENDER] = { 0x43, 0x4C, 0x4E, 0x54 };
1392 static const byte server[SIZEOF_SENDER] = { 0x53, 0x52, 0x56, 0x52 };
1393
1394 static const byte tls_client[FINISHED_LABEL_SZ + 1] = "client finished";
1395 static const byte tls_server[FINISHED_LABEL_SZ + 1] = "server finished";
1396
1397
1398 /* internal functions */
1399 CYASSL_LOCAL int SendChangeCipher(CYASSL*);
1400 CYASSL_LOCAL int SendData(CYASSL*, const void*, int);
1401 CYASSL_LOCAL int SendCertificate(CYASSL*);
1402 CYASSL_LOCAL int SendCertificateRequest(CYASSL*);
1403 CYASSL_LOCAL int SendServerKeyExchange(CYASSL*);
1404 CYASSL_LOCAL int SendBuffered(CYASSL*);
1405 CYASSL_LOCAL int ReceiveData(CYASSL*, byte*, int);
1406 CYASSL_LOCAL int SendFinished(CYASSL*);
1407 CYASSL_LOCAL int SendAlert(CYASSL*, int, int);
1408 CYASSL_LOCAL int ProcessReply(CYASSL*);
1409
1410 CYASSL_LOCAL int SetCipherSpecs(CYASSL*);
1411 CYASSL_LOCAL int MakeMasterSecret(CYASSL*);
1412
1413 CYASSL_LOCAL int  AddSession(CYASSL*);
1414 CYASSL_LOCAL int  DeriveKeys(CYASSL* ssl);
1415 CYASSL_LOCAL int  StoreKeys(CYASSL* ssl, const byte* keyData);
1416
1417 CYASSL_LOCAL int IsTLS(const CYASSL* ssl);
1418 CYASSL_LOCAL int IsAtLeastTLSv1_2(const CYASSL* ssl);
1419
1420 CYASSL_LOCAL void ShrinkInputBuffer(CYASSL* ssl, int forcedFree);
1421 CYASSL_LOCAL void ShrinkOutputBuffer(CYASSL* ssl);
1422 CYASSL_LOCAL int SendHelloVerifyRequest(CYASSL* ssl);
1423 CYASSL_LOCAL Signer* GetCA(void* cm, byte* hash);
1424 CYASSL_LOCAL void BuildTlsFinished(CYASSL* ssl, Hashes* hashes,
1425                                    const byte* sender);
1426 #ifndef NO_TLS
1427     CYASSL_LOCAL int  MakeTlsMasterSecret(CYASSL*);
1428     CYASSL_LOCAL void TLS_hmac(CYASSL* ssl, byte* digest, const byte* buffer,
1429                                word32 sz, int content, int verify);
1430 #endif
1431
1432 #ifndef NO_CYASSL_CLIENT
1433     CYASSL_LOCAL int SendClientHello(CYASSL*);
1434     CYASSL_LOCAL int SendClientKeyExchange(CYASSL*);
1435     CYASSL_LOCAL int SendCertificateVerify(CYASSL*);
1436 #endif /* NO_CYASSL_CLIENT */
1437
1438 #ifndef NO_CYASSL_SERVER
1439     CYASSL_LOCAL int SendServerHello(CYASSL*);
1440     CYASSL_LOCAL int SendServerHelloDone(CYASSL*);
1441     #ifdef CYASSL_DTLS
1442         CYASSL_LOCAL int SendHelloVerifyRequest(CYASSL*);
1443     #endif
1444 #endif /* NO_CYASSL_SERVER */
1445
1446
1447 #ifndef NO_TLS
1448     
1449
1450 #endif /* NO_TLS */
1451
1452
1453
1454 typedef double timer_d;
1455
1456 CYASSL_LOCAL timer_d Timer(void);
1457 CYASSL_LOCAL word32  LowResTimer(void);
1458
1459
1460
1461 #ifdef __cplusplus
1462     }  /* extern "C" */
1463 #endif
1464
1465 #endif /* CyaSSL_INT_H */
1466