]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/Source/WolfSSL/wolfssl/internal.h
Update WolfSSL library to the latest version.
[freertos] / FreeRTOS-Plus / Source / WolfSSL / wolfssl / internal.h
1 /* internal.h
2  *
3  * Copyright (C) 2006-2015 wolfSSL Inc.
4  *
5  * This file is part of wolfSSL. (formerly known as wolfSSL)
6  *
7  * wolfSSL 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  * wolfSSL 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22
23 #ifndef WOLFSSL_INT_H
24 #define WOLFSSL_INT_H
25
26
27 #include <wolfssl/wolfcrypt/types.h>
28 #include <wolfssl/ssl.h>
29 #ifdef HAVE_CRL
30     #include <wolfssl/crl.h>
31 #endif
32 #include <wolfssl/wolfcrypt/random.h>
33 #ifndef NO_DES3
34     #include <wolfssl/wolfcrypt/des3.h>
35 #endif
36 #ifndef NO_HC128
37     #include <wolfssl/wolfcrypt/hc128.h>
38 #endif
39 #ifndef NO_RABBIT
40     #include <wolfssl/wolfcrypt/rabbit.h>
41 #endif
42 #ifdef HAVE_CHACHA
43     #include <wolfssl/wolfcrypt/chacha.h>
44 #endif
45 #ifndef NO_ASN
46     #include <wolfssl/wolfcrypt/asn.h>
47 #endif
48 #ifndef NO_MD5
49     #include <wolfssl/wolfcrypt/md5.h>
50 #endif
51 #ifndef NO_SHA
52     #include <wolfssl/wolfcrypt/sha.h>
53 #endif
54 #ifndef NO_AES
55     #include <wolfssl/wolfcrypt/aes.h>
56 #endif
57 #ifdef HAVE_POLY1305
58     #include <wolfssl/wolfcrypt/poly1305.h>
59 #endif
60 #ifdef HAVE_CAMELLIA
61     #include <wolfssl/wolfcrypt/camellia.h>
62 #endif
63 #include <wolfssl/wolfcrypt/logging.h>
64 #ifndef NO_HMAC
65     #include <wolfssl/wolfcrypt/hmac.h>
66 #endif
67 #ifndef NO_RC4
68     #include <wolfssl/wolfcrypt/arc4.h>
69 #endif
70 #ifdef HAVE_ECC
71     #include <wolfssl/wolfcrypt/ecc.h>
72 #endif
73 #ifndef NO_SHA256
74     #include <wolfssl/wolfcrypt/sha256.h>
75 #endif
76 #ifdef HAVE_OCSP
77     #include <wolfssl/ocsp.h>
78 #endif
79 #ifdef WOLFSSL_SHA512
80     #include <wolfssl/wolfcrypt/sha512.h>
81 #endif
82
83 #ifdef HAVE_AESGCM
84     #include <wolfssl/wolfcrypt/sha512.h>
85 #endif
86
87 #ifdef WOLFSSL_RIPEMD
88     #include <wolfssl/wolfcrypt/ripemd.h>
89 #endif
90
91 #include <wolfssl/wolfcrypt/hash.h>
92
93 #ifdef WOLFSSL_CALLBACKS
94     #include <wolfssl/callbacks.h>
95     #include <signal.h>
96 #endif
97
98 #ifdef USE_WINDOWS_API
99     #ifdef WOLFSSL_GAME_BUILD
100         #include "system/xtl.h"
101     #else
102         #if defined(_WIN32_WCE) || defined(WIN32_LEAN_AND_MEAN)
103             /* On WinCE winsock2.h must be included before windows.h */
104             #include <winsock2.h>
105         #endif
106         #include <windows.h>
107     #endif
108 #elif defined(THREADX)
109     #ifndef SINGLE_THREADED
110         #include "tx_api.h"
111     #endif
112 #elif defined(MICRIUM)
113     /* do nothing, just don't pick Unix */
114 #elif defined(FREERTOS) || defined(WOLFSSL_SAFERTOS)
115     /* do nothing */
116 #elif defined(EBSNET)
117     /* do nothing */
118 #elif defined(FREESCALE_MQX)
119     /* do nothing */
120 #elif defined(WOLFSSL_MDK_ARM)
121     #if defined(WOLFSSL_MDK5)
122          #include "cmsis_os.h"
123     #else
124         #include <rtl.h>
125     #endif
126 #elif defined(MBED)
127 #elif defined(WOLFSSL_TIRTOS)
128     /* do nothing */
129 #else
130     #ifndef SINGLE_THREADED
131         #define WOLFSSL_PTHREADS
132         #include <pthread.h>
133     #endif
134     #if defined(OPENSSL_EXTRA) || defined(GOAHEAD_WS)
135         #include <unistd.h>      /* for close of BIO */
136     #endif
137 #endif
138
139
140 #ifdef HAVE_LIBZ
141     #include "zlib.h"
142 #endif
143
144 #ifdef _MSC_VER
145     /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
146     #pragma warning(disable: 4996)
147 #endif
148
149 #ifdef NO_AES
150     #if !defined (ALIGN16)
151         #define ALIGN16
152     #endif
153 #endif
154
155 #ifdef NO_SHA
156     #define SHA_DIGEST_SIZE 20
157 #endif
158
159 #ifdef NO_SHA256
160     #define SHA256_DIGEST_SIZE 32
161 #endif
162
163 #ifdef NO_MD5
164     #define MD5_DIGEST_SIZE 16
165 #endif
166
167
168 #ifdef __cplusplus
169     extern "C" {
170 #endif
171
172
173 #ifdef USE_WINDOWS_API
174     typedef unsigned int SOCKET_T;
175 #else
176     typedef int SOCKET_T;
177 #endif
178
179
180 typedef byte word24[3];
181
182 /* Define or comment out the cipher suites you'd like to be compiled in
183    make sure to use at least one BUILD_SSL_xxx or BUILD_TLS_xxx is defined
184
185    When adding cipher suites, add name to cipher_names, idx to cipher_name_idx
186
187    Now that there is a maximum strength crypto build, the following BUILD_XXX
188    flags need to be divided into two groups selected by WOLFSSL_MAX_STRENGTH.
189    Those that do not use Perfect Forward Security and do not use AEAD ciphers
190    need to be switched off. Allowed suites use (EC)DHE, AES-GCM|CCM, or
191    CHACHA-POLY.
192 */
193
194 /* Check that if WOLFSSL_MAX_STRENGTH is set that all the required options are
195  * not turned off. */
196 #if defined(WOLFSSL_MAX_STRENGTH) && \
197     ((!defined(HAVE_ECC) && (defined(NO_DH) || defined(NO_RSA))) || \
198      (!defined(HAVE_AESGCM) && !defined(HAVE_AESCCM) && \
199       (!defined(HAVE_POLY1305) || !defined(HAVE_CHACHA))) || \
200      (defined(NO_SHA256) && !defined(WOLFSSL_SHA384)) || \
201      !defined(NO_OLD_TLS))
202
203     #error "You are trying to build max strength with requirements disabled."
204 #endif
205
206 #ifndef WOLFSSL_MAX_STRENGTH
207
208     #if !defined(NO_RSA) && !defined(NO_RC4)
209         #if !defined(NO_SHA)
210             #define BUILD_SSL_RSA_WITH_RC4_128_SHA
211         #endif
212         #if !defined(NO_MD5)
213             #define BUILD_SSL_RSA_WITH_RC4_128_MD5
214         #endif
215         #if !defined(NO_TLS) && defined(HAVE_NTRU) && !defined(NO_SHA)
216             #define BUILD_TLS_NTRU_RSA_WITH_RC4_128_SHA
217         #endif
218     #endif
219
220     #if !defined(NO_RSA) && !defined(NO_DES3)
221         #if !defined(NO_SHA)
222             #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
223             #if !defined(NO_TLS) && defined(HAVE_NTRU)
224                     #define BUILD_TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA
225             #endif
226         #endif
227     #endif
228
229     #if !defined(NO_RSA) && !defined(NO_AES) && !defined(NO_TLS)
230         #if !defined(NO_SHA)
231             #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
232             #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
233             #if defined(HAVE_NTRU)
234                     #define BUILD_TLS_NTRU_RSA_WITH_AES_128_CBC_SHA
235                     #define BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA
236             #endif
237         #endif
238         #if !defined (NO_SHA256)
239             #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
240             #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
241         #endif
242         #if defined (HAVE_AESGCM)
243             #define BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
244             #if defined (WOLFSSL_SHA384)
245                 #define BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
246             #endif
247         #endif
248         #if defined (HAVE_AESCCM)
249             #define BUILD_TLS_RSA_WITH_AES_128_CCM_8
250             #define BUILD_TLS_RSA_WITH_AES_256_CCM_8
251         #endif
252         #if defined(HAVE_BLAKE2)
253             #define BUILD_TLS_RSA_WITH_AES_128_CBC_B2B256
254             #define BUILD_TLS_RSA_WITH_AES_256_CBC_B2B256
255         #endif
256     #endif
257
258     #if defined(HAVE_CAMELLIA) && !defined(NO_TLS)
259         #ifndef NO_RSA
260           #if !defined(NO_SHA)
261             #define BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
262             #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
263           #endif
264             #ifndef NO_SHA256
265                 #define BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
266                 #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
267             #endif
268             #if !defined(NO_DH)
269               #if !defined(NO_SHA)
270                 #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
271                 #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
272               #endif
273                 #ifndef NO_SHA256
274                     #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
275                     #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
276                 #endif
277             #endif
278         #endif
279     #endif
280
281     #if !defined(NO_PSK) && !defined(NO_AES) && !defined(NO_TLS)
282         #if !defined(NO_SHA)
283             #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
284             #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
285         #endif
286         #ifndef NO_SHA256
287             #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
288             #ifdef HAVE_AESGCM
289                 #define BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
290             #endif
291             #ifdef HAVE_AESCCM
292                 #define BUILD_TLS_PSK_WITH_AES_128_CCM_8
293                 #define BUILD_TLS_PSK_WITH_AES_256_CCM_8
294                 #define BUILD_TLS_PSK_WITH_AES_128_CCM
295                 #define BUILD_TLS_PSK_WITH_AES_256_CCM
296             #endif
297         #endif
298         #ifdef WOLFSSL_SHA384
299             #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
300             #ifdef HAVE_AESGCM
301                 #define BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
302             #endif
303         #endif
304     #endif
305
306     #if !defined(NO_TLS) && defined(HAVE_NULL_CIPHER)
307         #if !defined(NO_RSA)
308             #if !defined(NO_SHA)
309                 #define BUILD_TLS_RSA_WITH_NULL_SHA
310             #endif
311             #ifndef NO_SHA256
312                 #define BUILD_TLS_RSA_WITH_NULL_SHA256
313             #endif
314         #endif
315         #if !defined(NO_PSK)
316             #if !defined(NO_SHA)
317                 #define BUILD_TLS_PSK_WITH_NULL_SHA
318             #endif
319             #ifndef NO_SHA256
320                 #define BUILD_TLS_PSK_WITH_NULL_SHA256
321             #endif
322             #ifdef WOLFSSL_SHA384
323                 #define BUILD_TLS_PSK_WITH_NULL_SHA384
324             #endif
325         #endif
326     #endif
327
328     #if !defined(NO_HC128) && !defined(NO_RSA) && !defined(NO_TLS)
329         #define BUILD_TLS_RSA_WITH_HC_128_MD5
330         #if !defined(NO_SHA)
331             #define BUILD_TLS_RSA_WITH_HC_128_SHA
332         #endif
333         #if defined(HAVE_BLAKE2)
334             #define BUILD_TLS_RSA_WITH_HC_128_B2B256
335         #endif
336     #endif
337
338     #if !defined(NO_RABBIT) && !defined(NO_TLS) && !defined(NO_RSA)
339         #if !defined(NO_SHA)
340             #define BUILD_TLS_RSA_WITH_RABBIT_SHA
341         #endif
342     #endif
343
344     #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \
345         !defined(NO_RSA)
346
347         #if !defined(NO_SHA)
348             #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
349             #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
350         #endif
351         #if !defined(NO_SHA256)
352             #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
353             #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
354         #endif
355     #endif
356
357     #if defined(HAVE_ANON) && !defined(NO_TLS) && !defined(NO_DH) && \
358         !defined(NO_AES) && !defined(NO_SHA)
359         #define BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
360     #endif
361
362     #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS)
363         #ifndef NO_SHA256
364             #define BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
365             #ifdef HAVE_NULL_CIPHER
366                 #define BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
367             #endif
368         #endif
369         #ifdef WOLFSSL_SHA384
370             #define BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
371             #ifdef HAVE_NULL_CIPHER
372                 #define BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
373             #endif
374         #endif
375     #endif
376
377     #if defined(HAVE_ECC) && !defined(NO_TLS)
378         #if !defined(NO_AES)
379             #if !defined(NO_SHA)
380                 #if !defined(NO_RSA)
381                     #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
382                     #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
383                     #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
384                     #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
385                 #endif
386
387                 #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
388                 #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
389
390                 #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
391                 #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
392             #endif /* NO_SHA */
393             #ifndef NO_SHA256
394                 #if !defined(NO_RSA)
395                     #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
396                     #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
397                 #endif
398                 #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
399                 #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
400             #endif
401
402             #ifdef WOLFSSL_SHA384
403                 #if !defined(NO_RSA)
404                     #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
405                     #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
406                 #endif
407                 #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
408                 #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
409             #endif
410
411             #if defined (HAVE_AESGCM)
412                 #if !defined(NO_RSA)
413                     #define BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
414                     #if defined(WOLFSSL_SHA384)
415                         #define BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
416                     #endif
417                 #endif
418
419                 #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
420
421                 #if defined(WOLFSSL_SHA384)
422                     #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
423                 #endif
424             #endif
425         #endif /* NO_AES */
426         #if !defined(NO_RC4)
427             #if !defined(NO_SHA)
428                 #if !defined(NO_RSA)
429                     #define BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
430                     #define BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
431                 #endif
432
433                 #define BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
434                 #define BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
435             #endif
436         #endif
437         #if !defined(NO_DES3)
438             #ifndef NO_SHA
439                 #if !defined(NO_RSA)
440                     #define BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
441                     #define BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
442                 #endif
443
444                 #define BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
445                 #define BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
446             #endif /* NO_SHA */
447         #endif
448     #endif
449
450 #endif /* !WOLFSSL_MAX_STRENGTH */
451
452 #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \
453     !defined(NO_RSA) && defined(HAVE_AESGCM)
454
455     #ifndef NO_SHA256
456         #define BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
457     #endif
458
459     #ifdef WOLFSSL_SHA384
460         #define BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
461     #endif
462 #endif
463
464 #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS)
465     #ifndef NO_SHA256
466         #ifdef HAVE_AESGCM
467             #define BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
468         #endif
469         #ifdef HAVE_AESCCM
470             #define BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
471             #define BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
472         #endif
473     #endif
474     #if defined(WOLFSSL_SHA384) && defined(HAVE_AESGCM)
475         #define BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
476     #endif
477 #endif
478
479 #if defined(HAVE_ECC) && !defined(NO_TLS) && !defined(NO_AES)
480     #ifdef HAVE_AESGCM
481         #ifndef NO_SHA256
482             #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
483             #ifndef NO_RSA
484                 #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
485             #endif
486         #endif
487         #ifdef WOLFSSL_SHA384
488             #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
489             #ifndef NO_RSA
490                 #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
491             #endif
492         #endif
493     #endif
494     #if defined(HAVE_AESCCM) && !defined(NO_SHA256)
495         #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
496         #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
497     #endif
498 #endif
499
500 #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && !defined(NO_SHA256)
501     #ifdef HAVE_ECC
502         #define BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
503         #ifndef NO_RSA
504             #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
505         #endif
506     #endif
507     #if !defined(NO_DH) && !defined(NO_RSA)
508         #define BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
509     #endif
510 #endif
511
512
513 #if defined(BUILD_SSL_RSA_WITH_RC4_128_SHA) || \
514     defined(BUILD_SSL_RSA_WITH_RC4_128_MD5)
515     #define BUILD_ARC4
516 #endif
517
518 #if defined(BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA)
519     #define BUILD_DES3
520 #endif
521
522 #if defined(BUILD_TLS_RSA_WITH_AES_128_CBC_SHA) || \
523     defined(BUILD_TLS_RSA_WITH_AES_256_CBC_SHA) || \
524     defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
525     #undef  BUILD_AES
526     #define BUILD_AES
527 #endif
528
529 #if defined(BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256) || \
530     defined(BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) || \
531     defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) || \
532     defined(BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256)
533     #define BUILD_AESGCM
534 #endif
535
536 #if defined(BUILD_TLS_RSA_WITH_HC_128_SHA) || \
537     defined(BUILD_TLS_RSA_WITH_HC_128_MD5) || \
538     defined(BUILD_TLS_RSA_WITH_HC_128_B2B256)
539     #define BUILD_HC128
540 #endif
541
542 #if defined(BUILD_TLS_RSA_WITH_RABBIT_SHA)
543     #define BUILD_RABBIT
544 #endif
545
546 #ifdef NO_DES3
547     #define DES_BLOCK_SIZE 8
548 #else
549     #undef  BUILD_DES3
550     #define BUILD_DES3
551 #endif
552
553 #ifdef NO_AES
554     #define AES_BLOCK_SIZE 16
555 #else
556     #undef  BUILD_AES
557     #define BUILD_AES
558 #endif
559
560 #ifndef NO_RC4
561     #undef  BUILD_ARC4
562     #define BUILD_ARC4
563 #endif
564
565 #ifdef HAVE_CHACHA
566     #define CHACHA20_BLOCK_SIZE 16
567 #endif
568
569 #if defined(WOLFSSL_MAX_STRENGTH) || \
570     defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || \
571     (defined(HAVE_CHACHA) && defined(HAVE_POLY1305))
572
573     #define HAVE_AEAD
574 #endif
575
576 #if defined(WOLFSSL_MAX_STRENGTH) || \
577     defined(HAVE_ECC) || !defined(NO_DH)
578
579     #define HAVE_PFS
580 #endif
581
582
583 /* actual cipher values, 2nd byte */
584 enum {
585     TLS_DHE_RSA_WITH_AES_256_CBC_SHA  = 0x39,
586     TLS_DHE_RSA_WITH_AES_128_CBC_SHA  = 0x33,
587     TLS_DH_anon_WITH_AES_128_CBC_SHA  = 0x34,
588     TLS_RSA_WITH_AES_256_CBC_SHA      = 0x35,
589     TLS_RSA_WITH_AES_128_CBC_SHA      = 0x2F,
590     TLS_RSA_WITH_NULL_SHA             = 0x02,
591     TLS_PSK_WITH_AES_256_CBC_SHA      = 0x8d,
592     TLS_PSK_WITH_AES_128_CBC_SHA256   = 0xae,
593     TLS_PSK_WITH_AES_256_CBC_SHA384   = 0xaf,
594     TLS_PSK_WITH_AES_128_CBC_SHA      = 0x8c,
595     TLS_PSK_WITH_NULL_SHA256          = 0xb0,
596     TLS_PSK_WITH_NULL_SHA384          = 0xb1,
597     TLS_PSK_WITH_NULL_SHA             = 0x2c,
598     SSL_RSA_WITH_RC4_128_SHA          = 0x05,
599     SSL_RSA_WITH_RC4_128_MD5          = 0x04,
600     SSL_RSA_WITH_3DES_EDE_CBC_SHA     = 0x0A,
601
602     /* ECC suites, first byte is 0xC0 (ECC_BYTE) */
603     TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA    = 0x14,
604     TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA    = 0x13,
605     TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA  = 0x0A,
606     TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA  = 0x09,
607     TLS_ECDHE_RSA_WITH_RC4_128_SHA        = 0x11,
608     TLS_ECDHE_ECDSA_WITH_RC4_128_SHA      = 0x07,
609     TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA   = 0x12,
610     TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x08,
611     TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   = 0x27,
612     TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0x23,
613     TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   = 0x28,
614     TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0x24,
615
616     /* static ECDH, first byte is 0xC0 (ECC_BYTE) */
617     TLS_ECDH_RSA_WITH_AES_256_CBC_SHA    = 0x0F,
618     TLS_ECDH_RSA_WITH_AES_128_CBC_SHA    = 0x0E,
619     TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA  = 0x05,
620     TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA  = 0x04,
621     TLS_ECDH_RSA_WITH_RC4_128_SHA        = 0x0C,
622     TLS_ECDH_ECDSA_WITH_RC4_128_SHA      = 0x02,
623     TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA   = 0x0D,
624     TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x03,
625     TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256   = 0x29,
626     TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0x25,
627     TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384   = 0x2A,
628     TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0x26,
629
630     /* wolfSSL extension - eSTREAM */
631     TLS_RSA_WITH_HC_128_MD5       = 0xFB,
632     TLS_RSA_WITH_HC_128_SHA       = 0xFC,
633     TLS_RSA_WITH_RABBIT_SHA       = 0xFD,
634
635     /* wolfSSL extension - Blake2b 256 */
636     TLS_RSA_WITH_AES_128_CBC_B2B256   = 0xF8,
637     TLS_RSA_WITH_AES_256_CBC_B2B256   = 0xF9,
638     TLS_RSA_WITH_HC_128_B2B256        = 0xFA,   /* eSTREAM too */
639
640     /* wolfSSL extension - NTRU */
641     TLS_NTRU_RSA_WITH_RC4_128_SHA      = 0xe5,
642     TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA = 0xe6,
643     TLS_NTRU_RSA_WITH_AES_128_CBC_SHA  = 0xe7,  /* clashes w/official SHA-256 */
644     TLS_NTRU_RSA_WITH_AES_256_CBC_SHA  = 0xe8,
645
646     /* SHA256 */
647     TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x6b,
648     TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x67,
649     TLS_RSA_WITH_AES_256_CBC_SHA256     = 0x3d,
650     TLS_RSA_WITH_AES_128_CBC_SHA256     = 0x3c,
651     TLS_RSA_WITH_NULL_SHA256            = 0x3b,
652     TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = 0xb2,
653     TLS_DHE_PSK_WITH_NULL_SHA256        = 0xb4,
654
655     /* SHA384 */
656     TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = 0xb3,
657     TLS_DHE_PSK_WITH_NULL_SHA384        = 0xb5,
658
659     /* AES-GCM */
660     TLS_RSA_WITH_AES_128_GCM_SHA256          = 0x9c,
661     TLS_RSA_WITH_AES_256_GCM_SHA384          = 0x9d,
662     TLS_DHE_RSA_WITH_AES_128_GCM_SHA256      = 0x9e,
663     TLS_DHE_RSA_WITH_AES_256_GCM_SHA384      = 0x9f,
664     TLS_PSK_WITH_AES_128_GCM_SHA256          = 0xa8,
665     TLS_PSK_WITH_AES_256_GCM_SHA384          = 0xa9,
666     TLS_DHE_PSK_WITH_AES_128_GCM_SHA256      = 0xaa,
667     TLS_DHE_PSK_WITH_AES_256_GCM_SHA384      = 0xab,
668
669     /* ECC AES-GCM, first byte is 0xC0 (ECC_BYTE) */
670     TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256  = 0x2b,
671     TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384  = 0x2c,
672     TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256   = 0x2d,
673     TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384   = 0x2e,
674     TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256    = 0x2f,
675     TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384    = 0x30,
676     TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256     = 0x31,
677     TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384     = 0x32,
678
679     /* AES-CCM, first byte is 0xC0 but isn't ECC,
680      * also, in some of the other AES-CCM suites
681      * there will be second byte number conflicts
682      * with non-ECC AES-GCM */
683     TLS_RSA_WITH_AES_128_CCM_8         = 0xa0,
684     TLS_RSA_WITH_AES_256_CCM_8         = 0xa1,
685     TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xae,
686     TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = 0xaf,
687     TLS_PSK_WITH_AES_128_CCM           = 0xa4,
688     TLS_PSK_WITH_AES_256_CCM           = 0xa5,
689     TLS_PSK_WITH_AES_128_CCM_8         = 0xa8,
690     TLS_PSK_WITH_AES_256_CCM_8         = 0xa9,
691     TLS_DHE_PSK_WITH_AES_128_CCM       = 0xa6,
692     TLS_DHE_PSK_WITH_AES_256_CCM       = 0xa7,
693
694     /* Camellia */
695     TLS_RSA_WITH_CAMELLIA_128_CBC_SHA        = 0x41,
696     TLS_RSA_WITH_CAMELLIA_256_CBC_SHA        = 0x84,
697     TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256     = 0xba,
698     TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256     = 0xc0,
699     TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA    = 0x45,
700     TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA    = 0x88,
701     TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xbe,
702     TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0xc4,
703
704     TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   = 0x13,
705     TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0x14,
706     TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256     = 0x15,
707
708     /* Renegotiation Indication Extension Special Suite */
709     TLS_EMPTY_RENEGOTIATION_INFO_SCSV        = 0xff
710 };
711
712
713 #ifndef WOLFSSL_SESSION_TIMEOUT
714     #define WOLFSSL_SESSION_TIMEOUT 500
715     /* default session resumption cache timeout in seconds */
716 #endif
717
718
719 enum Misc {
720     ECC_BYTE    =  0xC0,           /* ECC first cipher suite byte */
721     CHACHA_BYTE = 0xCC,            /* ChaCha first cipher suite */
722
723     SEND_CERT       = 1,
724     SEND_BLANK_CERT = 2,
725
726     DTLS_MAJOR      = 0xfe,     /* DTLS major version number */
727     DTLS_MINOR      = 0xff,     /* DTLS minor version number */
728     DTLSv1_2_MINOR  = 0xfd,     /* DTLS minor version number */
729     SSLv3_MAJOR     = 3,        /* SSLv3 and TLSv1+  major version number */
730     SSLv3_MINOR     = 0,        /* TLSv1   minor version number */
731     TLSv1_MINOR     = 1,        /* TLSv1   minor version number */
732     TLSv1_1_MINOR   = 2,        /* TLSv1_1 minor version number */
733     TLSv1_2_MINOR   = 3,        /* TLSv1_2 minor version number */
734     OLD_HELLO_ID    = 0x01,     /* SSLv2 Client Hello Indicator */
735     INVALID_BYTE    = 0xff,     /* Used to initialize cipher specs values */
736     NO_COMPRESSION  =  0,
737     ZLIB_COMPRESSION = 221,     /* wolfSSL zlib compression */
738     HELLO_EXT_SIG_ALGO = 13,    /* ID for the sig_algo hello extension */
739     SECRET_LEN      = 48,       /* pre RSA and all master */
740     ENCRYPT_LEN     = 512,      /* allow 4096 bit static buffer */
741     SIZEOF_SENDER   =  4,       /* clnt or srvr           */
742     FINISHED_SZ     = 36,       /* MD5_DIGEST_SIZE + SHA_DIGEST_SIZE */
743     MAX_RECORD_SIZE = 16384,    /* 2^14, max size by standard */
744     MAX_MSG_EXTRA   = 38 + MAX_DIGEST_SIZE,
745                                 /* max added to msg, mac + pad  from */
746                                 /* RECORD_HEADER_SZ + BLOCK_SZ (pad) + Max
747                                    digest sz + BLOC_SZ (iv) + pad byte (1) */
748     MAX_COMP_EXTRA  = 1024,     /* max compression extra */
749     MAX_MTU         = 1500,     /* max expected MTU */
750     MAX_UDP_SIZE    = 8192 - 100, /* was MAX_MTU - 100 */
751     MAX_DH_SZ       = 1036,     /* 4096 p, pub, g + 2 byte size for each */
752     MAX_STR_VERSION = 8,        /* string rep of protocol version */
753
754     PAD_MD5        = 48,       /* pad length for finished */
755     PAD_SHA        = 40,       /* pad length for finished */
756     MAX_PAD_SIZE   = 256,      /* maximum length of padding */
757     COMPRESS_DUMMY_SIZE = 64,  /* compression dummy round size */
758     COMPRESS_CONSTANT   = 13,  /* compression calc constant */
759     COMPRESS_UPPER      = 55,  /* compression calc numerator */
760     COMPRESS_LOWER      = 64,  /* compression calc denominator */
761
762     PEM_LINE_LEN   = 80,       /* PEM line max + fudge */
763     LENGTH_SZ      =  2,       /* length field for HMAC, data only */
764     VERSION_SZ     =  2,       /* length of proctocol version */
765     SEQ_SZ         =  8,       /* 64 bit sequence number  */
766     BYTE3_LEN      =  3,       /* up to 24 bit byte lengths */
767     ALERT_SIZE     =  2,       /* level + description     */
768     VERIFY_HEADER  =  2,       /* always use 2 bytes      */
769     EXT_ID_SZ      =  2,       /* always use 2 bytes      */
770     MAX_DH_SIZE    = 513,      /* 4096 bit plus possible leading 0 */
771     SESSION_HINT_SZ = 4,       /* session timeout hint */
772
773     MAX_SUITE_SZ = 200,        /* 100 suites for now! */
774     RAN_LEN      = 32,         /* random length           */
775     SEED_LEN     = RAN_LEN * 2, /* tls prf seed length    */
776     ID_LEN       = 32,         /* session id length       */
777     MAX_COOKIE_LEN = 32,       /* max dtls cookie size    */
778     COOKIE_SZ    = 20,         /* use a 20 byte cookie    */
779     SUITE_LEN    =  2,         /* cipher suite sz length  */
780     ENUM_LEN     =  1,         /* always a byte           */
781     OPAQUE8_LEN  =  1,         /* 1 byte                  */
782     OPAQUE16_LEN =  2,         /* 2 bytes                 */
783     OPAQUE24_LEN =  3,         /* 3 bytes                 */
784     OPAQUE32_LEN =  4,         /* 4 bytes                 */
785     COMP_LEN     =  1,         /* compression length      */
786     CURVE_LEN    =  2,         /* ecc named curve length  */
787     SERVER_ID_LEN = 20,        /* server session id length  */
788     
789     HANDSHAKE_HEADER_SZ   = 4,  /* type + length(3)        */
790     RECORD_HEADER_SZ      = 5,  /* type + version + len(2) */
791     CERT_HEADER_SZ        = 3,  /* always 3 bytes          */
792     REQ_HEADER_SZ         = 2,  /* cert request header sz  */
793     HINT_LEN_SZ           = 2,  /* length of hint size field */
794     TRUNCATED_HMAC_SZ     = 10, /* length of hmac w/ truncated hmac extension */
795     HELLO_EXT_TYPE_SZ     = 2,  /* length of a hello extension type */
796     HELLO_EXT_SZ          = 8,  /* total length of the lazy hello extensions */
797     HELLO_EXT_LEN         = 6,  /* length of the lazy hello extensions */
798     HELLO_EXT_SIGALGO_SZ  = 2,  /* length of signature algo extension  */
799     HELLO_EXT_SIGALGO_MAX = 32, /* number of items in the signature algo list */
800
801     DTLS_HANDSHAKE_HEADER_SZ = 12, /* normal + seq(2) + offset(3) + length(3) */
802     DTLS_RECORD_HEADER_SZ    = 13, /* normal + epoch(2) + seq_num(6) */
803     DTLS_HANDSHAKE_EXTRA     = 8,  /* diff from normal */
804     DTLS_RECORD_EXTRA        = 8,  /* diff from normal */
805     DTLS_HANDSHAKE_SEQ_SZ    = 2,  /* handshake header sequence number */
806     DTLS_HANDSHAKE_FRAG_SZ   = 3,  /* fragment offset and length are 24 bit */
807     DTLS_POOL_SZ             = 5,  /* buffers to hold in the retry pool */
808
809     FINISHED_LABEL_SZ   = 15,  /* TLS finished label size */
810     TLS_FINISHED_SZ     = 12,  /* TLS has a shorter size  */
811     MASTER_LABEL_SZ     = 13,  /* TLS master secret label sz */
812     KEY_LABEL_SZ        = 13,  /* TLS key block expansion sz */
813     MAX_PRF_HALF        = 256, /* Maximum half secret len */
814     MAX_PRF_LABSEED     = 128, /* Maximum label + seed len */
815     MAX_PRF_DIG         = 224, /* Maximum digest len      */
816     MAX_REQUEST_SZ      = 256, /* Maximum cert req len (no auth yet */
817     SESSION_FLUSH_COUNT = 256, /* Flush session cache unless user turns off */ 
818
819     RC4_KEY_SIZE        = 16,  /* always 128bit           */
820     DES_KEY_SIZE        =  8,  /* des                     */
821     DES3_KEY_SIZE       = 24,  /* 3 des ede               */
822     DES_IV_SIZE         = DES_BLOCK_SIZE,
823     AES_256_KEY_SIZE    = 32,  /* for 256 bit             */
824     AES_192_KEY_SIZE    = 24,  /* for 192 bit             */
825     AES_IV_SIZE         = 16,  /* always block size       */
826     AES_128_KEY_SIZE    = 16,  /* for 128 bit             */
827
828     AEAD_SEQ_OFFSET     = 4,        /* Auth Data: Sequence number */
829     AEAD_TYPE_OFFSET    = 8,        /* Auth Data: Type            */
830     AEAD_VMAJ_OFFSET    = 9,        /* Auth Data: Major Version   */
831     AEAD_VMIN_OFFSET    = 10,       /* Auth Data: Minor Version   */
832     AEAD_LEN_OFFSET     = 11,       /* Auth Data: Length          */
833     AEAD_AUTH_DATA_SZ   = 13,       /* Size of the data to authenticate */
834     AEAD_IMP_IV_SZ      = 4,        /* Size of the implicit IV     */
835     AEAD_EXP_IV_SZ      = 8,        /* Size of the explicit IV     */
836     AEAD_NONCE_SZ       = AEAD_EXP_IV_SZ + AEAD_IMP_IV_SZ,
837
838     AES_GCM_AUTH_SZ     = 16, /* AES-GCM Auth Tag length    */
839     AES_CCM_16_AUTH_SZ  = 16, /* AES-CCM-16 Auth Tag length */
840     AES_CCM_8_AUTH_SZ   = 8,  /* AES-CCM-8 Auth Tag Length  */
841
842     CAMELLIA_128_KEY_SIZE = 16, /* for 128 bit */
843     CAMELLIA_192_KEY_SIZE = 24, /* for 192 bit */
844     CAMELLIA_256_KEY_SIZE = 32, /* for 256 bit */
845     CAMELLIA_IV_SIZE      = 16, /* always block size */
846
847     CHACHA20_256_KEY_SIZE = 32,  /* for 256 bit             */
848     CHACHA20_128_KEY_SIZE = 16,  /* for 128 bit             */
849     CHACHA20_IV_SIZE      =  8,  /* 64 bits for iv          */
850
851     POLY1305_AUTH_SZ    = 16,  /* 128 bits                */
852
853     HC_128_KEY_SIZE     = 16,  /* 128 bits                */
854     HC_128_IV_SIZE      = 16,  /* also 128 bits           */
855
856     RABBIT_KEY_SIZE     = 16,  /* 128 bits                */
857     RABBIT_IV_SIZE      =  8,  /* 64 bits for iv          */
858
859     EVP_SALT_SIZE       =  8,  /* evp salt size 64 bits   */
860
861     ECDHE_SIZE          = 32,  /* ECHDE server size defaults to 256 bit */
862     MAX_EXPORT_ECC_SZ   = 256, /* Export ANS X9.62 max future size */
863
864     MAX_HELLO_SZ       = 128,  /* max client or server hello */
865     MAX_CERT_VERIFY_SZ = 1024, /* max   */
866     CLIENT_HELLO_FIRST =  35,  /* Protocol + RAN_LEN + sizeof(id_len) */
867     MAX_SUITE_NAME     =  48,  /* maximum length of cipher suite string */
868
869     DTLS_TIMEOUT_INIT       =  1, /* default timeout init for DTLS receive  */
870     DTLS_TIMEOUT_MAX        = 64, /* default max timeout for DTLS receive */
871     DTLS_TIMEOUT_MULTIPLIER =  2, /* default timeout multiplier for DTLS recv */
872
873     MAX_PSK_ID_LEN     = 128,  /* max psk identity/hint supported */
874     MAX_PSK_KEY_LEN    =  64,  /* max psk key supported */
875
876     MAX_WOLFSSL_FILE_SIZE = 1024 * 1024 * 4,  /* 4 mb file size alloc limit */
877
878 #ifdef FORTRESS
879     MAX_EX_DATA        =   3,  /* allow for three items of ex_data */
880 #endif
881
882     MAX_X509_SIZE      = 2048, /* max static x509 buffer size */
883     CERT_MIN_SIZE      =  256, /* min PEM cert size with header/footer */
884     MAX_FILENAME_SZ    =  256, /* max file name length */
885     FILE_BUFFER_SIZE   = 1024, /* default static file buffer size for input,
886                                   will use dynamic buffer if not big enough */
887
888     MAX_NTRU_PUB_KEY_SZ = 1027, /* NTRU max for now */
889     MAX_NTRU_ENCRYPT_SZ = 1027, /* NTRU max for now */
890     MAX_NTRU_BITS       =  256, /* max symmetric bit strength */
891     NO_SNIFF           =   0,  /* not sniffing */
892     SNIFF              =   1,  /* currently sniffing */
893
894     HASH_SIG_SIZE      =   2,  /* default SHA1 RSA */
895
896     NO_CAVIUM_DEVICE   =  -2,  /* invalid cavium device id */
897
898     NO_COPY            =   0,  /* should we copy static buffer for write */
899     COPY               =   1   /* should we copy static buffer for write */
900 };
901
902
903 #ifndef WOLFSSL_MIN_DHKEY_BITS
904     #ifdef WOLFSSL_MAX_STRENGTH
905         #define WOLFSSL_MIN_DHKEY_BITS 2048
906     #else
907         #define WOLFSSL_MIN_DHKEY_BITS 1024
908     #endif
909 #endif
910 #if (WOLFSSL_MIN_DHKEY_BITS % 8)
911     #error DH minimum bit size must be multiple of 8
912 #endif
913 #if (WOLFSSL_MIN_DHKEY_BITS > 16000)
914     #error DH minimum bit size must not be greater than 16000
915 #endif
916 #define MIN_DHKEY_SZ (WOLFSSL_MIN_DHKEY_BITS / 8)
917
918
919 #ifdef SESSION_INDEX
920 /* Shift values for making a session index */
921 #define SESSIDX_ROW_SHIFT 4
922 #define SESSIDX_IDX_MASK  0x0F
923 #endif
924
925
926 /* max cert chain peer depth */
927 #ifndef MAX_CHAIN_DEPTH
928     #define MAX_CHAIN_DEPTH 9
929 #endif
930
931 #ifndef SESSION_TICKET_LEN
932     #define SESSION_TICKET_LEN 256
933 #endif
934
935 #ifndef SESSION_TICKET_HINT_DEFAULT
936     #define SESSION_TICKET_HINT_DEFAULT 300
937 #endif
938
939
940 /* don't use extra 3/4k stack space unless need to */
941 #ifdef HAVE_NTRU
942     #define MAX_ENCRYPT_SZ MAX_NTRU_ENCRYPT_SZ
943 #else
944     #define MAX_ENCRYPT_SZ ENCRYPT_LEN
945 #endif
946
947
948 /* states */
949 enum states {
950     NULL_STATE = 0,
951
952     SERVER_HELLOVERIFYREQUEST_COMPLETE,
953     SERVER_HELLO_COMPLETE,
954     SERVER_CERT_COMPLETE,
955     SERVER_KEYEXCHANGE_COMPLETE,
956     SERVER_HELLODONE_COMPLETE,
957     SERVER_FINISHED_COMPLETE,
958
959     CLIENT_HELLO_COMPLETE,
960     CLIENT_KEYEXCHANGE_COMPLETE,
961     CLIENT_FINISHED_COMPLETE,
962
963     HANDSHAKE_DONE
964 };
965
966
967 #if defined(__GNUC__)
968     #define WOLFSSL_PACK __attribute__ ((packed))
969 #else
970     #define WOLFSSL_PACK
971 #endif
972
973 /* SSL Version */
974 typedef struct ProtocolVersion {
975     byte major;
976     byte minor;
977 } WOLFSSL_PACK ProtocolVersion;
978
979
980 WOLFSSL_LOCAL ProtocolVersion MakeSSLv3(void);
981 WOLFSSL_LOCAL ProtocolVersion MakeTLSv1(void);
982 WOLFSSL_LOCAL ProtocolVersion MakeTLSv1_1(void);
983 WOLFSSL_LOCAL ProtocolVersion MakeTLSv1_2(void);
984
985 #ifdef WOLFSSL_DTLS
986     WOLFSSL_LOCAL ProtocolVersion MakeDTLSv1(void);
987     WOLFSSL_LOCAL ProtocolVersion MakeDTLSv1_2(void);
988 #endif
989
990
991 enum BIO_TYPE {
992     BIO_BUFFER = 1,
993     BIO_SOCKET = 2,
994     BIO_SSL    = 3,
995     BIO_MEMORY = 4
996 };
997
998
999 /* wolfSSL BIO_METHOD type */
1000 struct WOLFSSL_BIO_METHOD {
1001     byte type;               /* method type */
1002 };
1003
1004
1005 /* wolfSSL BIO type */
1006 struct WOLFSSL_BIO {
1007     byte        type;          /* method type */
1008     byte        close;         /* close flag */
1009     byte        eof;           /* eof flag */
1010     WOLFSSL*     ssl;           /* possible associated ssl */
1011     byte*       mem;           /* memory buffer */
1012     int         memLen;        /* memory buffer length */
1013     int         fd;            /* possible file descriptor */
1014     WOLFSSL_BIO* prev;          /* previous in chain */
1015     WOLFSSL_BIO* next;          /* next in chain */
1016 };
1017
1018
1019 /* wolfSSL method type */
1020 struct WOLFSSL_METHOD {
1021     ProtocolVersion version;
1022     byte            side;         /* connection side, server or client */
1023     byte            downgrade;    /* whether to downgrade version, default no */
1024 };
1025
1026
1027 /* defautls to client */
1028 WOLFSSL_LOCAL void InitSSL_Method(WOLFSSL_METHOD*, ProtocolVersion);
1029
1030 /* for sniffer */
1031 WOLFSSL_LOCAL int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
1032                             word32 size, word32 totalSz, int sniff);
1033 WOLFSSL_LOCAL int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx);
1034
1035
1036 /* wolfSSL buffer type */
1037 typedef struct buffer {
1038     byte*  buffer;
1039     word32 length;
1040 } buffer;
1041
1042
1043 enum {
1044     FORCED_FREE = 1,
1045     NO_FORCED_FREE = 0
1046 };
1047
1048
1049 /* only use compression extra if using compression */
1050 #ifdef HAVE_LIBZ
1051     #define COMP_EXTRA MAX_COMP_EXTRA
1052 #else
1053     #define COMP_EXTRA 0
1054 #endif
1055
1056 /* only the sniffer needs space in the buffer for extra MTU record(s) */
1057 #ifdef WOLFSSL_SNIFFER
1058     #define MTU_EXTRA MAX_MTU * 3 
1059 #else
1060     #define MTU_EXTRA 0
1061 #endif
1062
1063
1064 /* embedded callbacks require large static buffers, make sure on */
1065 #ifdef WOLFSSL_CALLBACKS
1066     #undef  LARGE_STATIC_BUFFERS
1067     #define LARGE_STATIC_BUFFERS
1068 #endif
1069
1070
1071 /* give user option to use 16K static buffers */
1072 #if defined(LARGE_STATIC_BUFFERS)
1073     #define RECORD_SIZE MAX_RECORD_SIZE
1074 #else
1075     #ifdef WOLFSSL_DTLS
1076         #define RECORD_SIZE MAX_MTU 
1077     #else
1078         #define RECORD_SIZE 128 
1079     #endif
1080 #endif
1081
1082
1083 /* user option to turn off 16K output option */
1084 /* if using small static buffers (default) and SSL_write tries to write data
1085    larger than the record we have, dynamically get it, unless user says only
1086    write in static buffer chuncks  */
1087 #ifndef STATIC_CHUNKS_ONLY
1088     #define OUTPUT_RECORD_SIZE MAX_RECORD_SIZE
1089 #else
1090     #define OUTPUT_RECORD_SIZE RECORD_SIZE
1091 #endif
1092
1093 /* wolfSSL input buffer
1094
1095    RFC 2246:
1096
1097    length
1098        The length (in bytes) of the following TLSPlaintext.fragment.
1099        The length should not exceed 2^14.
1100 */
1101 #if defined(LARGE_STATIC_BUFFERS)
1102     #define STATIC_BUFFER_LEN RECORD_HEADER_SZ + RECORD_SIZE + COMP_EXTRA + \
1103              MTU_EXTRA + MAX_MSG_EXTRA
1104 #else
1105     /* don't fragment memory from the record header */
1106     #define STATIC_BUFFER_LEN RECORD_HEADER_SZ
1107 #endif
1108
1109 typedef struct {
1110     ALIGN16 byte staticBuffer[STATIC_BUFFER_LEN];
1111     byte*  buffer;       /* place holder for static or dynamic buffer */
1112     word32 length;       /* total buffer length used */
1113     word32 idx;          /* idx to part of length already consumed */
1114     word32 bufferSize;   /* current buffer size */
1115     byte   dynamicFlag;  /* dynamic memory currently in use */
1116     byte   offset;       /* alignment offset attempt */
1117 } bufferStatic;
1118
1119 /* Cipher Suites holder */
1120 typedef struct Suites {
1121     word16 suiteSz;                 /* suite length in bytes        */
1122     word16 hashSigAlgoSz;           /* SigAlgo extension length in bytes */
1123     byte   suites[MAX_SUITE_SZ];
1124     byte   hashSigAlgo[HELLO_EXT_SIGALGO_MAX]; /* sig/algo to offer */
1125     byte   setSuites;               /* user set suites from default */
1126     byte   hashAlgo;                /* selected hash algorithm */
1127     byte   sigAlgo;                 /* selected sig algorithm */
1128 } Suites;
1129
1130
1131 WOLFSSL_LOCAL
1132 void InitSuites(Suites*, ProtocolVersion, word16, word16, word16, word16,
1133                 word16, word16, int);
1134 WOLFSSL_LOCAL
1135 int  SetCipherList(Suites*, const char* list);
1136
1137 #ifndef PSK_TYPES_DEFINED
1138     typedef unsigned int (*psk_client_callback)(WOLFSSL*, const char*, char*,
1139                           unsigned int, unsigned char*, unsigned int);
1140     typedef unsigned int (*psk_server_callback)(WOLFSSL*, const char*,
1141                           unsigned char*, unsigned int);
1142 #endif /* PSK_TYPES_DEFINED */
1143
1144
1145 #ifdef HAVE_NETX
1146     WOLFSSL_LOCAL int NetX_Receive(WOLFSSL *ssl, char *buf, int sz, void *ctx);
1147     WOLFSSL_LOCAL int NetX_Send(WOLFSSL *ssl, char *buf, int sz, void *ctx);
1148 #endif /* HAVE_NETX */
1149
1150
1151 /* wolfSSL Cipher type just points back to SSL */
1152 struct WOLFSSL_CIPHER {
1153     WOLFSSL* ssl;
1154 };
1155
1156
1157 typedef struct OCSP_Entry OCSP_Entry;
1158
1159 #ifdef NO_SHA
1160     #define OCSP_DIGEST_SIZE SHA256_DIGEST_SIZE
1161 #else
1162     #define OCSP_DIGEST_SIZE SHA_DIGEST_SIZE
1163 #endif
1164
1165 #ifdef NO_ASN 
1166     /* no_asn won't have */
1167     typedef struct CertStatus CertStatus;
1168 #endif
1169
1170 struct OCSP_Entry {
1171     OCSP_Entry* next;                        /* next entry             */
1172     byte    issuerHash[OCSP_DIGEST_SIZE];    /* issuer hash            */ 
1173     byte    issuerKeyHash[OCSP_DIGEST_SIZE]; /* issuer public key hash */
1174     CertStatus* status;                      /* OCSP response list     */
1175     int         totalStatus;                 /* number on list         */
1176 };
1177
1178
1179 #ifndef HAVE_OCSP
1180     typedef struct WOLFSSL_OCSP WOLFSSL_OCSP;
1181 #endif
1182
1183 /* wolfSSL OCSP controller */
1184 struct WOLFSSL_OCSP {
1185     WOLFSSL_CERT_MANAGER* cm;            /* pointer back to cert manager */
1186     OCSP_Entry*          ocspList;      /* OCSP response list */
1187     wolfSSL_Mutex         ocspLock;      /* OCSP list lock */
1188 };
1189
1190 #ifndef MAX_DATE_SIZE
1191 #define MAX_DATE_SIZE 32
1192 #endif
1193
1194 typedef struct CRL_Entry CRL_Entry;
1195
1196 #ifdef NO_SHA
1197     #define CRL_DIGEST_SIZE SHA256_DIGEST_SIZE
1198 #else
1199     #define CRL_DIGEST_SIZE SHA_DIGEST_SIZE
1200 #endif
1201
1202 #ifdef NO_ASN 
1203     typedef struct RevokedCert RevokedCert;
1204 #endif
1205
1206 /* Complete CRL */
1207 struct CRL_Entry {
1208     CRL_Entry* next;                      /* next entry */
1209     byte    issuerHash[CRL_DIGEST_SIZE];  /* issuer hash                 */ 
1210     /* byte    crlHash[CRL_DIGEST_SIZE];      raw crl data hash           */ 
1211     /* restore the hash here if needed for optimized comparisons */
1212     byte    lastDate[MAX_DATE_SIZE]; /* last date updated  */
1213     byte    nextDate[MAX_DATE_SIZE]; /* next update date   */
1214     byte    lastDateFormat;          /* last date format */
1215     byte    nextDateFormat;          /* next date format */
1216     RevokedCert* certs;              /* revoked cert list  */
1217     int          totalCerts;         /* number on list     */
1218 };
1219
1220
1221 typedef struct CRL_Monitor CRL_Monitor;
1222
1223 /* CRL directory monitor */
1224 struct CRL_Monitor {
1225     char* path;      /* full dir path, if valid pointer we're using */
1226     int   type;      /* PEM or ASN1 type */
1227 };
1228
1229
1230 #ifndef HAVE_CRL
1231     typedef struct WOLFSSL_CRL WOLFSSL_CRL;
1232 #endif
1233
1234 /* wolfSSL CRL controller */
1235 struct WOLFSSL_CRL {
1236     WOLFSSL_CERT_MANAGER* cm;            /* pointer back to cert manager */
1237     CRL_Entry*           crlList;       /* our CRL list */
1238     wolfSSL_Mutex         crlLock;       /* CRL list lock */
1239     CRL_Monitor          monitors[2];   /* PEM and DER possible */
1240 #ifdef HAVE_CRL_MONITOR
1241     pthread_t            tid;           /* monitoring thread */
1242     int                  mfd;           /* monitor fd, -1 if no init yet */
1243 #endif
1244 };
1245
1246
1247 #ifdef NO_ASN 
1248     typedef struct Signer Signer;
1249 #endif
1250
1251
1252 #ifndef CA_TABLE_SIZE
1253     #define CA_TABLE_SIZE 11
1254 #endif
1255
1256 /* wolfSSL Certificate Manager */
1257 struct WOLFSSL_CERT_MANAGER {
1258     Signer*         caTable[CA_TABLE_SIZE]; /* the CA signer table */
1259     void*           heap;               /* heap helper */
1260     WOLFSSL_CRL*    crl;                /* CRL checker */
1261     WOLFSSL_OCSP*   ocsp;               /* OCSP checker */
1262     char*           ocspOverrideURL;    /* use this responder */
1263     void*           ocspIOCtx;          /* I/O callback CTX */
1264     CallbackCACache caCacheCallback;    /* CA cache addition callback */
1265     CbMissingCRL    cbMissingCRL;       /* notify through cb of missing crl */
1266     CbOCSPIO        ocspIOCb;           /* I/O callback for OCSP lookup */
1267     CbOCSPRespFree  ocspRespFreeCb;     /* Frees OCSP Response from IO Cb */
1268     wolfSSL_Mutex   caLock;             /* CA list lock */
1269     byte            crlEnabled;         /* is CRL on ? */
1270     byte            crlCheckAll;        /* always leaf, but all ? */
1271     byte            ocspEnabled;        /* is OCSP on ? */
1272     byte            ocspCheckAll;       /* always leaf, but all ? */
1273     byte            ocspSendNonce;      /* send the OCSP nonce ? */
1274     byte            ocspUseOverrideURL; /* ignore cert's responder, override */
1275 };
1276
1277 WOLFSSL_LOCAL int CM_SaveCertCache(WOLFSSL_CERT_MANAGER*, const char*);
1278 WOLFSSL_LOCAL int CM_RestoreCertCache(WOLFSSL_CERT_MANAGER*, const char*);
1279 WOLFSSL_LOCAL int CM_MemSaveCertCache(WOLFSSL_CERT_MANAGER*, void*, int, int*);
1280 WOLFSSL_LOCAL int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER*, const void*, int);
1281 WOLFSSL_LOCAL int CM_GetCertCacheMemSize(WOLFSSL_CERT_MANAGER*);
1282
1283 /* wolfSSL Sock Addr */
1284 struct WOLFSSL_SOCKADDR {
1285     unsigned int sz; /* sockaddr size */
1286     void*        sa; /* pointer to the sockaddr_in or sockaddr_in6 */
1287 };
1288
1289 typedef struct WOLFSSL_DTLS_CTX {
1290     WOLFSSL_SOCKADDR peer;
1291     int fd;
1292 } WOLFSSL_DTLS_CTX;
1293
1294
1295 #ifdef WOLFSSL_DTLS
1296
1297     #ifdef WORD64_AVAILABLE
1298         typedef word64 DtlsSeq;
1299     #else
1300         typedef word32 DtlsSeq;
1301     #endif
1302     #define DTLS_SEQ_BITS (sizeof(DtlsSeq) * CHAR_BIT)
1303
1304     typedef struct DtlsState {
1305         DtlsSeq window;     /* Sliding window for current epoch    */
1306         word16 nextEpoch;   /* Expected epoch in next record       */
1307         word32 nextSeq;     /* Expected sequence in next record    */
1308
1309         word16 curEpoch;    /* Received epoch in current record    */
1310         word32 curSeq;      /* Received sequence in current record */
1311
1312         DtlsSeq prevWindow; /* Sliding window for old epoch        */
1313         word32 prevSeq;     /* Next sequence in allowed old epoch  */
1314     } DtlsState;
1315
1316 #endif /* WOLFSSL_DTLS */
1317
1318
1319 /* keys and secrets */
1320 typedef struct Keys {
1321     byte client_write_MAC_secret[MAX_DIGEST_SIZE];   /* max sizes */
1322     byte server_write_MAC_secret[MAX_DIGEST_SIZE];
1323     byte client_write_key[AES_256_KEY_SIZE];         /* max sizes */
1324     byte server_write_key[AES_256_KEY_SIZE];
1325     byte client_write_IV[AES_IV_SIZE];               /* max sizes */
1326     byte server_write_IV[AES_IV_SIZE];
1327 #ifdef HAVE_AEAD
1328     byte aead_exp_IV[AEAD_EXP_IV_SZ];
1329     byte aead_enc_imp_IV[AEAD_IMP_IV_SZ];
1330     byte aead_dec_imp_IV[AEAD_IMP_IV_SZ];
1331 #endif
1332
1333     word32 peer_sequence_number;
1334     word32 sequence_number;
1335
1336 #ifdef WOLFSSL_DTLS
1337     DtlsState dtls_state;                       /* Peer's state */
1338     word16 dtls_peer_handshake_number;
1339     word16 dtls_expected_peer_handshake_number;
1340
1341     word16 dtls_epoch;                          /* Current tx epoch    */
1342     word32 dtls_sequence_number;                /* Current tx sequence */
1343     word16 dtls_handshake_number;               /* Current tx handshake seq */
1344 #endif
1345
1346     word32 encryptSz;             /* last size of encrypted data   */
1347     word32 padSz;                 /* how much to advance after decrypt part */
1348     byte   encryptionOn;          /* true after change cipher spec */
1349     byte   decryptedCur;          /* only decrypt current record once */
1350 } Keys;
1351
1352
1353
1354 /* RFC 6066 TLS Extensions */
1355 #ifdef HAVE_TLS_EXTENSIONS
1356
1357 typedef enum {
1358     SERVER_NAME_INDICATION = 0x0000,
1359     MAX_FRAGMENT_LENGTH    = 0x0001,
1360     TRUNCATED_HMAC         = 0x0004,
1361     ELLIPTIC_CURVES        = 0x000a,
1362     SESSION_TICKET         = 0x0023,
1363     SECURE_RENEGOTIATION   = 0xff01
1364 } TLSX_Type;
1365
1366 typedef struct TLSX {
1367     TLSX_Type    type; /* Extension Type  */
1368     void*        data; /* Extension Data  */
1369     byte         resp; /* IsResponse Flag */
1370     struct TLSX* next; /* List Behavior   */
1371 } TLSX;
1372
1373 WOLFSSL_LOCAL TLSX*  TLSX_Find(TLSX* list, TLSX_Type type);
1374 WOLFSSL_LOCAL void   TLSX_FreeAll(TLSX* list);
1375 WOLFSSL_LOCAL int    TLSX_SupportExtensions(WOLFSSL* ssl);
1376
1377 #ifndef NO_WOLFSSL_CLIENT
1378 WOLFSSL_LOCAL word16 TLSX_GetRequestSize(WOLFSSL* ssl);
1379 WOLFSSL_LOCAL word16 TLSX_WriteRequest(WOLFSSL* ssl, byte* output);
1380 #endif
1381
1382 #ifndef NO_WOLFSSL_SERVER
1383 WOLFSSL_LOCAL word16 TLSX_GetResponseSize(WOLFSSL* ssl);
1384 WOLFSSL_LOCAL word16 TLSX_WriteResponse(WOLFSSL* ssl, byte* output);
1385 #endif
1386
1387 WOLFSSL_LOCAL int    TLSX_Parse(WOLFSSL* ssl, byte* input, word16 length,
1388                                                 byte isRequest, Suites *suites);
1389                                                 
1390 #elif defined(HAVE_SNI)                  \
1391    || defined(HAVE_MAX_FRAGMENT)         \
1392    || defined(HAVE_TRUNCATED_HMAC)       \
1393    || defined(HAVE_SUPPORTED_CURVES)     \
1394    || defined(HAVE_SECURE_RENEGOTIATION) \
1395    || defined(HAVE_SESSION_TICKET)
1396
1397 #error Using TLS extensions requires HAVE_TLS_EXTENSIONS to be defined.
1398
1399 #endif /* HAVE_TLS_EXTENSIONS */
1400
1401 /* Server Name Indication */
1402 #ifdef HAVE_SNI
1403
1404 typedef struct SNI {
1405     byte                       type;    /* SNI Type          */
1406     union { char* host_name; } data;    /* SNI Data          */
1407     struct SNI*                next;    /* List Behavior     */
1408 #ifndef NO_WOLFSSL_SERVER
1409     byte                       options; /* Behaviour options */
1410     byte                       status;  /* Matching result   */
1411 #endif
1412 } SNI;
1413
1414 WOLFSSL_LOCAL int TLSX_UseSNI(TLSX** extensions, byte type, const void* data,
1415                                                                    word16 size);
1416
1417 #ifndef NO_WOLFSSL_SERVER
1418 WOLFSSL_LOCAL void   TLSX_SNI_SetOptions(TLSX* extensions, byte type,
1419                                                                   byte options);
1420 WOLFSSL_LOCAL byte   TLSX_SNI_Status(TLSX* extensions, byte type);
1421 WOLFSSL_LOCAL word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type,
1422                                                                    void** data);
1423 WOLFSSL_LOCAL int    TLSX_SNI_GetFromBuffer(const byte* buffer, word32 bufferSz,
1424                                          byte type, byte* sni, word32* inOutSz);
1425 #endif
1426
1427 #endif /* HAVE_SNI */
1428
1429 /* Maximum Fragment Length */
1430 #ifdef HAVE_MAX_FRAGMENT
1431
1432 WOLFSSL_LOCAL int TLSX_UseMaxFragment(TLSX** extensions, byte mfl);
1433
1434 #endif /* HAVE_MAX_FRAGMENT */
1435
1436 #ifdef HAVE_TRUNCATED_HMAC
1437
1438 WOLFSSL_LOCAL int TLSX_UseTruncatedHMAC(TLSX** extensions);
1439
1440 #endif /* HAVE_TRUNCATED_HMAC */
1441
1442 #ifdef HAVE_SUPPORTED_CURVES
1443
1444 typedef struct EllipticCurve {
1445     word16                name; /* CurveNames    */
1446     struct EllipticCurve* next; /* List Behavior */
1447 } EllipticCurve;
1448
1449 WOLFSSL_LOCAL int TLSX_UseSupportedCurve(TLSX** extensions, word16 name);
1450
1451 #ifndef NO_WOLFSSL_SERVER
1452 WOLFSSL_LOCAL int TLSX_ValidateEllipticCurves(WOLFSSL* ssl, byte first,
1453                                                                    byte second);
1454 #endif
1455
1456 #endif /* HAVE_SUPPORTED_CURVES */
1457
1458 #ifdef HAVE_SECURE_RENEGOTIATION
1459
1460 enum key_cache_state {
1461     SCR_CACHE_NULL   = 0,       /* empty / begin state */
1462     SCR_CACHE_NEEDED,           /* need to cache keys */
1463     SCR_CACHE_COPY,             /* we have a cached copy */
1464     SCR_CACHE_PARTIAL,          /* partial restore to real keys */
1465     SCR_CACHE_COMPLETE          /* complete restore to real keys */
1466 };
1467
1468
1469 /* Additional Conection State according to rfc5746 section 3.1 */
1470 typedef struct SecureRenegotiation {
1471    byte                 enabled;  /* secure_renegotiation flag in rfc */
1472    byte                 startScr; /* server requested client to start scr */
1473    enum key_cache_state cache_status;  /* track key cache state */
1474    byte                 client_verify_data[TLS_FINISHED_SZ];  /* cached */
1475    byte                 server_verify_data[TLS_FINISHED_SZ];  /* cached */
1476    byte                 subject_hash[SHA_DIGEST_SIZE];  /* peer cert hash */
1477    Keys                 tmp_keys;  /* can't overwrite real keys yet */
1478 } SecureRenegotiation;
1479
1480 WOLFSSL_LOCAL int TLSX_UseSecureRenegotiation(TLSX** extensions);
1481
1482 #endif /* HAVE_SECURE_RENEGOTIATION */
1483
1484 #ifdef HAVE_SESSION_TICKET
1485
1486 typedef struct SessionTicket {
1487     word32 lifetime;
1488     byte*  data;
1489     word16 size;
1490 } SessionTicket;
1491
1492 WOLFSSL_LOCAL int  TLSX_UseSessionTicket(TLSX** extensions, 
1493                                                          SessionTicket* ticket);
1494 WOLFSSL_LOCAL SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
1495                                                        byte* data, word16 size);
1496 WOLFSSL_LOCAL void TLSX_SessionTicket_Free(SessionTicket* ticket);
1497 #endif /* HAVE_SESSION_TICKET */
1498
1499 /* wolfSSL context type */
1500 struct WOLFSSL_CTX {
1501     WOLFSSL_METHOD* method;
1502     wolfSSL_Mutex   countMutex;    /* reference count mutex */
1503     int         refCount;         /* reference count */
1504 #ifndef NO_DH
1505     buffer      serverDH_P;
1506     buffer      serverDH_G;
1507 #endif
1508 #ifndef NO_CERTS
1509     buffer      certificate;
1510     buffer      certChain;
1511                  /* chain after self, in DER, with leading size for each cert */
1512     buffer      privateKey;
1513     WOLFSSL_CERT_MANAGER* cm;      /* our cert manager, ctx owns SSL will use */
1514 #endif
1515     Suites*     suites;           /* make dynamic, user may not need/set */
1516     void*       heap;             /* for user memory overrides */
1517     byte        verifyPeer;
1518     byte        verifyNone;
1519     byte        failNoCert;
1520     byte        sessionCacheOff;
1521     byte        sessionCacheFlushOff;
1522     byte        sendVerify;       /* for client side */
1523     byte        haveRSA;          /* RSA available */
1524     byte        haveDH;           /* server DH parms set by user */
1525     byte        haveNTRU;         /* server private NTRU  key loaded */
1526     byte        haveECDSAsig;     /* server cert signed w/ ECDSA */
1527     byte        haveStaticECC;    /* static server ECC private key */
1528     byte        partialWrite;     /* only one msg per write call */
1529     byte        quietShutdown;    /* don't send close notify */
1530     byte        groupMessages;    /* group handshake messages before sending */
1531     byte        minDowngrade;     /* minimum downgrade version */
1532 #ifndef NO_DH
1533     word16      minDhKeySz;       /* minimum DH key size */
1534 #endif
1535     CallbackIORecv CBIORecv;
1536     CallbackIOSend CBIOSend;
1537 #ifdef WOLFSSL_DTLS
1538     CallbackGenCookie CBIOCookie;       /* gen cookie callback */
1539 #endif
1540     VerifyCallback  verifyCallback;     /* cert verification callback */
1541     word32          timeout;            /* session timeout */
1542 #ifdef HAVE_ECC
1543     word16          eccTempKeySz;       /* in octets 20 - 66 */
1544     word32          pkCurveOID;         /* curve Ecc_Sum */
1545 #endif
1546 #ifndef NO_PSK
1547     byte        havePSK;                /* psk key set by user */
1548     psk_client_callback client_psk_cb;  /* client callback */
1549     psk_server_callback server_psk_cb;  /* server callback */
1550     char        server_hint[MAX_PSK_ID_LEN];
1551 #endif /* NO_PSK */
1552 #ifdef HAVE_ANON
1553     byte        haveAnon;               /* User wants to allow Anon suites */
1554 #endif /* HAVE_ANON */
1555 #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
1556     pem_password_cb passwd_cb;
1557     void*            userdata;
1558 #endif /* OPENSSL_EXTRA */
1559 #ifdef HAVE_OCSP
1560     WOLFSSL_OCSP      ocsp;
1561 #endif
1562 #ifdef HAVE_CAVIUM
1563     int              devId;            /* cavium device id to use */
1564 #endif
1565 #ifdef HAVE_TLS_EXTENSIONS
1566     TLSX* extensions;                  /* RFC 6066 TLS Extensions data */
1567     #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SEVER)
1568         SessionTicketEncCb ticketEncCb;   /* enc/dec session ticket Cb */
1569         void*              ticketEncCtx;  /* session encrypt context */
1570         int                ticketHint;    /* ticket hint in seconds */
1571     #endif
1572 #endif
1573 #ifdef ATOMIC_USER
1574     CallbackMacEncrypt    MacEncryptCb;    /* Atomic User Mac/Encrypt Cb */
1575     CallbackDecryptVerify DecryptVerifyCb; /* Atomic User Decrypt/Verify Cb */
1576 #endif
1577 #ifdef HAVE_PK_CALLBACKS
1578     #ifdef HAVE_ECC
1579         CallbackEccSign   EccSignCb;    /* User EccSign   Callback handler */
1580         CallbackEccVerify EccVerifyCb;  /* User EccVerify Callback handler */
1581     #endif /* HAVE_ECC */
1582     #ifndef NO_RSA 
1583         CallbackRsaSign   RsaSignCb;    /* User RsaSign   Callback handler */
1584         CallbackRsaVerify RsaVerifyCb;  /* User RsaVerify Callback handler */
1585         CallbackRsaEnc    RsaEncCb;     /* User Rsa Public Encrypt  handler */
1586         CallbackRsaDec    RsaDecCb;     /* User Rsa Private Decrypt handler */
1587     #endif /* NO_RSA */
1588 #endif /* HAVE_PK_CALLBACKS */
1589 };
1590
1591
1592 WOLFSSL_LOCAL
1593 int InitSSL_Ctx(WOLFSSL_CTX*, WOLFSSL_METHOD*);
1594 WOLFSSL_LOCAL
1595 void FreeSSL_Ctx(WOLFSSL_CTX*);
1596 WOLFSSL_LOCAL
1597 void SSL_CtxResourceFree(WOLFSSL_CTX*);
1598
1599 WOLFSSL_LOCAL
1600 int DeriveTlsKeys(WOLFSSL* ssl);
1601 WOLFSSL_LOCAL
1602 int ProcessOldClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
1603                           word32 inSz, word16 sz);
1604 #ifndef NO_CERTS
1605     WOLFSSL_LOCAL
1606     int AddCA(WOLFSSL_CERT_MANAGER* ctx, buffer der, int type, int verify);
1607     WOLFSSL_LOCAL
1608     int AlreadySigner(WOLFSSL_CERT_MANAGER* cm, byte* hash);
1609 #endif
1610
1611 /* All cipher suite related info */
1612 typedef struct CipherSpecs {
1613     word16 key_size;
1614     word16 iv_size;
1615     word16 block_size;
1616     word16 aead_mac_size;
1617     byte bulk_cipher_algorithm;
1618     byte cipher_type;               /* block, stream, or aead */
1619     byte mac_algorithm;
1620     byte kea;                       /* key exchange algo */
1621     byte sig_algo;
1622     byte hash_size;
1623     byte pad_size;
1624     byte static_ecdh;
1625 } CipherSpecs;
1626
1627
1628 void InitCipherSpecs(CipherSpecs* cs);
1629
1630
1631 /* Supported Message Authentication Codes from page 43 */
1632 enum MACAlgorithm { 
1633     no_mac,
1634     md5_mac,
1635     sha_mac,
1636     sha224_mac,
1637     sha256_mac,     /* needs to match external KDF_MacAlgorithm */
1638     sha384_mac,
1639     sha512_mac,
1640     rmd_mac,
1641     blake2b_mac
1642 };
1643
1644
1645 /* Supported Key Exchange Protocols */
1646 enum KeyExchangeAlgorithm { 
1647     no_kea,
1648     rsa_kea, 
1649     diffie_hellman_kea, 
1650     fortezza_kea,
1651     psk_kea,
1652     dhe_psk_kea,
1653     ntru_kea,
1654     ecc_diffie_hellman_kea,
1655     ecc_static_diffie_hellman_kea       /* for verify suite only */
1656 };
1657
1658
1659 /* Supported Authentication Schemes */
1660 enum SignatureAlgorithm {
1661     anonymous_sa_algo,
1662     rsa_sa_algo,
1663     dsa_sa_algo,
1664     ecc_dsa_sa_algo
1665 };
1666
1667
1668 /* Supprted ECC Curve Types */
1669 enum EccCurves {
1670     named_curve = 3
1671 };
1672
1673
1674 /* Valid client certificate request types from page 27 */
1675 enum ClientCertificateType {    
1676     rsa_sign            = 1, 
1677     dss_sign            = 2,
1678     rsa_fixed_dh        = 3,
1679     dss_fixed_dh        = 4,
1680     rsa_ephemeral_dh    = 5,
1681     dss_ephemeral_dh    = 6,
1682     fortezza_kea_cert   = 20,
1683     ecdsa_sign          = 64,
1684     rsa_fixed_ecdh      = 65,
1685     ecdsa_fixed_ecdh    = 66
1686 };
1687
1688
1689 enum CipherType { stream, block, aead };
1690
1691
1692
1693
1694
1695
1696 /* cipher for now */
1697 typedef struct Ciphers {
1698 #ifdef BUILD_ARC4
1699     Arc4*   arc4;
1700 #endif
1701 #ifdef BUILD_DES3
1702     Des3*   des3;
1703 #endif
1704 #if defined(BUILD_AES) || defined(BUILD_AESGCM)
1705     Aes*    aes;
1706 #endif
1707 #ifdef HAVE_CAMELLIA
1708     Camellia* cam;
1709 #endif
1710 #ifdef HAVE_CHACHA
1711     ChaCha*   chacha;
1712 #endif
1713 #ifdef HAVE_HC128
1714     HC128*  hc128;
1715 #endif
1716 #ifdef BUILD_RABBIT
1717     Rabbit* rabbit;
1718 #endif
1719     byte    setup;       /* have we set it up flag for detection */
1720 } Ciphers;
1721
1722
1723 #ifdef HAVE_ONE_TIME_AUTH
1724 /* Ciphers for one time authentication such as poly1305 */
1725 typedef struct OneTimeAuth {
1726 #ifdef HAVE_POLY1305
1727     Poly1305* poly1305;
1728 #endif
1729     byte    setup;      /* flag for if a cipher has been set */
1730
1731 } OneTimeAuth;
1732 #endif
1733
1734
1735 WOLFSSL_LOCAL void InitCiphers(WOLFSSL* ssl);
1736 WOLFSSL_LOCAL void FreeCiphers(WOLFSSL* ssl);
1737
1738
1739 /* hashes type */
1740 typedef struct Hashes {
1741     #ifndef NO_OLD_TLS
1742         byte md5[MD5_DIGEST_SIZE];
1743     #endif
1744     byte sha[SHA_DIGEST_SIZE];
1745     #ifndef NO_SHA256
1746         byte sha256[SHA256_DIGEST_SIZE];
1747     #endif
1748     #ifdef WOLFSSL_SHA384
1749         byte sha384[SHA384_DIGEST_SIZE];
1750     #endif
1751     #ifdef WOLFSSL_SHA512
1752         byte sha512[SHA512_DIGEST_SIZE];
1753     #endif
1754 } Hashes;
1755
1756
1757 /* Static x509 buffer */
1758 typedef struct x509_buffer {
1759     int  length;                  /* actual size */
1760     byte buffer[MAX_X509_SIZE];   /* max static cert size */
1761 } x509_buffer;
1762
1763
1764 /* wolfSSL X509_CHAIN, for no dynamic memory SESSION_CACHE */
1765 struct WOLFSSL_X509_CHAIN {
1766     int         count;                    /* total number in chain */
1767     x509_buffer certs[MAX_CHAIN_DEPTH];   /* only allow max depth 4 for now */
1768 };
1769
1770
1771 /* wolfSSL session type */
1772 struct WOLFSSL_SESSION {
1773     word32       bornOn;                        /* create time in seconds   */
1774     word32       timeout;                       /* timeout in seconds       */
1775     byte         sessionID[ID_LEN];             /* id for protocol */
1776     byte         sessionIDSz;
1777     byte         masterSecret[SECRET_LEN];      /* stored secret */
1778 #ifdef SESSION_CERTS
1779     WOLFSSL_X509_CHAIN chain;                    /* peer cert chain, static  */
1780     ProtocolVersion version;                    /* which version was used */
1781     byte            cipherSuite0;               /* first byte, normally 0 */
1782     byte            cipherSuite;                /* 2nd byte, actual suite */
1783 #endif
1784 #ifndef NO_CLIENT_CACHE
1785     word16       idLen;                         /* serverID length */
1786     byte         serverID[SERVER_ID_LEN];       /* for easier client lookup */
1787 #endif
1788 #ifdef HAVE_SESSION_TICKET
1789     word16       ticketLen;
1790     byte         ticket[SESSION_TICKET_LEN];
1791 #endif
1792 };
1793
1794
1795 WOLFSSL_LOCAL
1796 WOLFSSL_SESSION* GetSession(WOLFSSL*, byte*);
1797 WOLFSSL_LOCAL
1798 int          SetSession(WOLFSSL*, WOLFSSL_SESSION*);
1799
1800 typedef int (*hmacfp) (WOLFSSL*, byte*, const byte*, word32, int, int);
1801
1802 #ifndef NO_CLIENT_CACHE
1803     WOLFSSL_SESSION* GetSessionClient(WOLFSSL*, const byte*, int);
1804 #endif
1805
1806 /* client connect state for nonblocking restart */
1807 enum ConnectState {
1808     CONNECT_BEGIN = 0,
1809     CLIENT_HELLO_SENT,
1810     HELLO_AGAIN,               /* HELLO_AGAIN s for DTLS case */
1811     HELLO_AGAIN_REPLY,
1812     FIRST_REPLY_DONE,
1813     FIRST_REPLY_FIRST,
1814     FIRST_REPLY_SECOND,
1815     FIRST_REPLY_THIRD,
1816     FIRST_REPLY_FOURTH,
1817     FINISHED_DONE,
1818     SECOND_REPLY_DONE
1819 };
1820
1821
1822 /* server accept state for nonblocking restart */
1823 enum AcceptState {
1824     ACCEPT_BEGIN = 0,
1825     ACCEPT_CLIENT_HELLO_DONE,
1826     HELLO_VERIFY_SENT,
1827     ACCEPT_FIRST_REPLY_DONE,
1828     SERVER_HELLO_SENT,
1829     CERT_SENT,
1830     KEY_EXCHANGE_SENT,
1831     CERT_REQ_SENT,
1832     SERVER_HELLO_DONE,
1833     ACCEPT_SECOND_REPLY_DONE,
1834     TICKET_SENT,
1835     CHANGE_CIPHER_SENT,
1836     ACCEPT_FINISHED_DONE,
1837     ACCEPT_THIRD_REPLY_DONE
1838 };
1839
1840
1841 typedef struct Buffers {
1842     bufferStatic    inputBuffer;
1843     bufferStatic    outputBuffer;
1844     buffer          domainName;             /* for client check */
1845     buffer          clearOutputBuffer;
1846     int             prevSent;              /* previous plain text bytes sent
1847                                               when got WANT_WRITE            */
1848     int             plainSz;               /* plain text bytes in buffer to send
1849                                               when got WANT_WRITE            */
1850     byte            weOwnCert;             /* SSL own cert flag */
1851     byte            weOwnCertChain;        /* SSL own cert chain flag */
1852     byte            weOwnKey;              /* SSL own key  flag */
1853     byte            weOwnDH;               /* SSL own dh (p,g)  flag */
1854 #ifndef NO_DH
1855     buffer          serverDH_P;            /* WOLFSSL_CTX owns, unless we own */
1856     buffer          serverDH_G;            /* WOLFSSL_CTX owns, unless we own */
1857     buffer          serverDH_Pub;
1858     buffer          serverDH_Priv;
1859 #endif
1860 #ifndef NO_CERTS
1861     buffer          certificate;           /* WOLFSSL_CTX owns, unless we own */
1862     buffer          key;                   /* WOLFSSL_CTX owns, unless we own */
1863     buffer          certChain;             /* WOLFSSL_CTX owns, unless we own */
1864                  /* chain after self, in DER, with leading size for each cert */
1865 #endif
1866 #ifdef WOLFSSL_DTLS
1867     WOLFSSL_DTLS_CTX dtlsCtx;               /* DTLS connection context */
1868 #endif
1869 #ifdef HAVE_PK_CALLBACKS
1870     #ifdef HAVE_ECC
1871         buffer peerEccDsaKey;              /* we own for Ecc Verify Callbacks */
1872     #endif /* HAVE_ECC */
1873     #ifndef NO_RSA
1874         buffer peerRsaKey;                 /* we own for Rsa Verify Callbacks */
1875     #endif /* NO_RSA */
1876 #endif /* HAVE_PK_CALLBACKS */
1877 } Buffers;
1878
1879 typedef struct Options {
1880 #ifndef NO_PSK
1881     psk_client_callback client_psk_cb;
1882     psk_server_callback server_psk_cb;
1883     word16            havePSK:1;            /* psk key set by user */
1884 #endif /* NO_PSK */
1885
1886     /* on/off or small bit flags, optimize layout */
1887     word16            sendVerify:2;     /* false = 0, true = 1, sendBlank = 2 */
1888     word16            sessionCacheOff:1;
1889     word16            sessionCacheFlushOff:1;
1890     word16            side:1;             /* client or server end */
1891     word16            verifyPeer:1;
1892     word16            verifyNone:1;
1893     word16            failNoCert:1;
1894     word16            downgrade:1;        /* allow downgrade of versions */
1895     word16            resuming:1;
1896     word16            haveSessionId:1;    /* server may not send */
1897     word16            tls:1;              /* using TLS ? */
1898     word16            tls1_1:1;           /* using TLSv1.1+ ? */
1899     word16            dtls:1;             /* using datagrams ? */
1900     word16            connReset:1;        /* has the peer reset */
1901     word16            isClosed:1;         /* if we consider conn closed */
1902     word16            closeNotify:1;      /* we've recieved a close notify */
1903     word16            sentNotify:1;       /* we've sent a close notify */
1904     word16            usingCompression:1; /* are we using compression */
1905     word16            haveRSA:1;          /* RSA available */
1906     word16            haveDH:1;           /* server DH parms set by user */
1907     word16            haveNTRU:1;         /* server NTRU  private key loaded */
1908     word16            haveECDSAsig:1;     /* server ECDSA signed cert */
1909     word16            haveStaticECC:1;    /* static server ECC private key */
1910     word16            havePeerCert:1;     /* do we have peer's cert */
1911     word16            havePeerVerify:1;   /* and peer's cert verify */
1912     word16            usingPSK_cipher:1;  /* are using psk as cipher */
1913     word16            usingAnon_cipher:1; /* are we using an anon cipher */
1914     word16            sendAlertState:1;   /* nonblocking resume */
1915     word16            partialWrite:1;     /* only one msg per write call */
1916     word16            quietShutdown:1;    /* don't send close notify */
1917     word16            certOnly:1;         /* stop once we get cert */
1918     word16            groupMessages:1;    /* group handshake messages */
1919     word16            usingNonblock:1;    /* are we using nonblocking socket */
1920     word16            saveArrays:1;       /* save array Memory for user get keys
1921                                            or psk */
1922 #ifdef HAVE_POLY1305
1923     word16            oldPoly:1;        /* set when to use old rfc way of poly*/
1924 #endif
1925 #ifdef HAVE_ANON
1926     word16            haveAnon:1;       /* User wants to allow Anon suites */
1927 #endif
1928 #ifdef HAVE_SESSION_TICKET
1929     word16            createTicket:1;     /* Server to create new Ticket */
1930     word16            useTicket:1;        /* Use Ticket not session cache */
1931 #endif
1932
1933     /* need full byte values for this section */
1934     byte            processReply;           /* nonblocking resume */
1935     byte            cipherSuite0;           /* first byte, normally 0 */
1936     byte            cipherSuite;            /* second byte, actual suite */
1937     byte            serverState;
1938     byte            clientState;
1939     byte            handShakeState;
1940     byte            handShakeDone;      /* at least one handshake complete */
1941     byte            minDowngrade;       /* minimum downgrade version */
1942     byte            connectState;       /* nonblocking resume */
1943     byte            acceptState;        /* nonblocking resume */
1944 #ifndef NO_DH
1945     word16          minDhKeySz;         /* minimum DH key size */
1946     word16          dhKeySz;            /* actual DH key size */
1947 #endif
1948
1949 } Options;
1950
1951 typedef struct Arrays {
1952     word32          preMasterSz;        /* differs for DH, actual size */
1953 #ifndef NO_PSK
1954     word32          psk_keySz;          /* acutal size */
1955     char            client_identity[MAX_PSK_ID_LEN];
1956     char            server_hint[MAX_PSK_ID_LEN];
1957     byte            psk_key[MAX_PSK_KEY_LEN];
1958 #endif
1959     byte            clientRandom[RAN_LEN];
1960     byte            serverRandom[RAN_LEN];
1961     byte            sessionID[ID_LEN];
1962     byte            sessionIDSz;
1963     byte            preMasterSecret[ENCRYPT_LEN];
1964     byte            masterSecret[SECRET_LEN];
1965 #ifdef WOLFSSL_DTLS
1966     byte            cookie[MAX_COOKIE_LEN];
1967     byte            cookieSz;
1968 #endif
1969 } Arrays;
1970
1971 #ifndef ASN_NAME_MAX
1972 #define ASN_NAME_MAX 256
1973 #endif
1974
1975 #ifndef MAX_DATE_SZ
1976 #define MAX_DATE_SZ 32
1977 #endif
1978
1979 struct WOLFSSL_X509_NAME {
1980     char  *name;
1981     char  staticName[ASN_NAME_MAX];
1982     int   dynamicName;
1983     int   sz;
1984 #ifdef OPENSSL_EXTRA
1985     DecodedName fullName;
1986 #endif /* OPENSSL_EXTRA */
1987 };
1988
1989 #ifndef EXTERNAL_SERIAL_SIZE
1990     #define EXTERNAL_SERIAL_SIZE 32
1991 #endif
1992
1993 #ifdef NO_ASN 
1994     typedef struct DNS_entry DNS_entry;
1995 #endif
1996
1997 struct WOLFSSL_X509 {
1998     int              version;
1999     WOLFSSL_X509_NAME issuer;
2000     WOLFSSL_X509_NAME subject;
2001     int              serialSz;
2002     byte             serial[EXTERNAL_SERIAL_SIZE];
2003     char             subjectCN[ASN_NAME_MAX];        /* common name short cut */
2004 #ifdef WOLFSSL_SEP
2005     int              deviceTypeSz;
2006     byte             deviceType[EXTERNAL_SERIAL_SIZE];
2007     int              hwTypeSz;
2008     byte             hwType[EXTERNAL_SERIAL_SIZE];
2009     int              hwSerialNumSz;
2010     byte             hwSerialNum[EXTERNAL_SERIAL_SIZE];
2011     #ifdef OPENSSL_EXTRA
2012         byte             certPolicySet;
2013         byte             certPolicyCrit;
2014     #endif /* OPENSSL_EXTRA */
2015 #endif
2016     int              notBeforeSz;
2017     byte             notBefore[MAX_DATE_SZ];
2018     int              notAfterSz;
2019     byte             notAfter[MAX_DATE_SZ];
2020     int              sigOID;
2021     buffer           sig;
2022     int              pubKeyOID;
2023     buffer           pubKey;
2024     #ifdef HAVE_ECC
2025         word32       pkCurveOID;
2026     #endif /* HAVE_ECC */
2027     buffer           derCert;                        /* may need  */
2028     DNS_entry*       altNames;                       /* alt names list */
2029     DNS_entry*       altNamesNext;                   /* hint for retrieval */
2030     byte             dynamicMemory;                  /* dynamic memory flag */
2031     byte             isCa;
2032 #ifdef OPENSSL_EXTRA
2033     word32           pathLength;
2034     word16           keyUsage;
2035     byte             basicConstSet;
2036     byte             basicConstCrit;
2037     byte             basicConstPlSet;
2038     byte             subjAltNameSet;
2039     byte             subjAltNameCrit;
2040     byte             authKeyIdSet;
2041     byte             authKeyIdCrit;
2042     byte*            authKeyId;
2043     word32           authKeyIdSz;
2044     byte             subjKeyIdSet;
2045     byte             subjKeyIdCrit;
2046     byte*            subjKeyId;
2047     word32           subjKeyIdSz;
2048     byte             keyUsageSet;
2049     byte             keyUsageCrit;
2050 #endif /* OPENSSL_EXTRA */
2051 };
2052
2053
2054 /* record layer header for PlainText, Compressed, and CipherText */
2055 typedef struct RecordLayerHeader {
2056     byte            type;
2057     byte            pvMajor;
2058     byte            pvMinor;
2059     byte            length[2];
2060 } RecordLayerHeader;
2061
2062
2063 /* record layer header for DTLS PlainText, Compressed, and CipherText */
2064 typedef struct DtlsRecordLayerHeader {
2065     byte            type;
2066     byte            pvMajor;
2067     byte            pvMinor;
2068     byte            epoch[2];             /* increment on cipher state change */
2069     byte            sequence_number[6];   /* per record */
2070     byte            length[2];
2071 } DtlsRecordLayerHeader;
2072
2073
2074 typedef struct DtlsPool {
2075     buffer          buf[DTLS_POOL_SZ];
2076     int             used;
2077 } DtlsPool;
2078
2079 typedef struct DtlsMsg {
2080     struct DtlsMsg* next;
2081     word32          seq;       /* Handshake sequence number    */
2082     word32          sz;        /* Length of whole mesage       */
2083     word32          fragSz;    /* Length of fragments received */
2084     byte            type;
2085     byte*           buf;
2086     byte*           msg;
2087 } DtlsMsg;
2088
2089
2090 #ifdef HAVE_NETX
2091
2092     /* NETX I/O Callback default */
2093     typedef struct NetX_Ctx {
2094         NX_TCP_SOCKET* nxSocket;    /* send/recv socket handle */
2095         NX_PACKET*     nxPacket;    /* incoming packet handle for short reads */
2096         ULONG          nxOffset;    /* offset already read from nxPacket */
2097         ULONG          nxWait;      /* wait option flag */
2098     } NetX_Ctx;
2099
2100 #endif
2101
2102
2103 /* Handshake messages recevied from peer (plus change cipher */
2104 typedef struct MsgsReceived {
2105     word16 got_hello_request:1;
2106     word16 got_client_hello:1;
2107     word16 got_server_hello:1;
2108     word16 got_hello_verify_request:1;
2109     word16 got_session_ticket:1;
2110     word16 got_certificate:1;
2111     word16 got_server_key_exchange:1;
2112     word16 got_certificate_request:1;
2113     word16 got_server_hello_done:1;
2114     word16 got_certificate_verify:1;
2115     word16 got_client_key_exchange:1;
2116     word16 got_finished:1;
2117     word16 got_change_cipher:1;
2118 } MsgsReceived;
2119
2120
2121 /* Handshake hashes */
2122 typedef struct HS_Hashes {
2123     Hashes          verifyHashes;
2124     Hashes          certHashes;         /* for cert verify */
2125 #ifndef NO_OLD_TLS
2126 #ifndef NO_SHA
2127     Sha             hashSha;            /* sha hash of handshake msgs */
2128 #endif
2129 #ifndef NO_MD5
2130     Md5             hashMd5;            /* md5 hash of handshake msgs */
2131 #endif
2132 #endif /* NO_OLD_TLS */
2133 #ifndef NO_SHA256
2134     Sha256          hashSha256;         /* sha256 hash of handshake msgs */
2135 #endif
2136 #ifdef WOLFSSL_SHA384
2137     Sha384          hashSha384;         /* sha384 hash of handshake msgs */
2138 #endif
2139 #ifdef WOLFSSL_SHA512
2140     Sha512          hashSha512;         /* sha512 hash of handshake msgs */
2141 #endif
2142 } HS_Hashes;
2143
2144
2145 /* wolfSSL ssl type */
2146 struct WOLFSSL {
2147     WOLFSSL_CTX*    ctx;
2148     Suites*         suites;             /* only need during handshake */
2149     Arrays*         arrays;
2150     HS_Hashes*      hsHashes;
2151     void*           IOCB_ReadCtx;
2152     void*           IOCB_WriteCtx;
2153     RNG*            rng;
2154     void*           verifyCbCtx;        /* cert verify callback user ctx*/
2155     VerifyCallback  verifyCallback;     /* cert verification callback */
2156     void*           heap;               /* for user overrides */
2157 #ifndef NO_HANDSHAKE_DONE_CB
2158     HandShakeDoneCb hsDoneCb;          /*  notify user handshake done */
2159     void*           hsDoneCtx;         /*  user handshake cb context  */
2160 #endif
2161     WOLFSSL_CIPHER  cipher;
2162     hmacfp          hmac;
2163     Ciphers         encrypt;
2164     Ciphers         decrypt;
2165     Buffers         buffers;
2166     WOLFSSL_SESSION session;
2167     WOLFSSL_ALERT_HISTORY alert_history;
2168     int             error;
2169     int             rfd;                /* read  file descriptor */
2170     int             wfd;                /* write file descriptor */
2171     int             rflags;             /* user read  flags */
2172     int             wflags;             /* user write flags */
2173     word32          timeout;            /* session timeout */
2174     word16          curSize;
2175     RecordLayerHeader curRL;
2176     MsgsReceived    msgsReceived;       /* peer messages received */
2177     ProtocolVersion version;            /* negotiated version */
2178     ProtocolVersion chVersion;          /* client hello version */
2179     CipherSpecs     specs;
2180     Keys            keys;
2181     Options         options;
2182 #ifdef OPENSSL_EXTRA
2183     WOLFSSL_BIO*     biord;              /* socket bio read  to free/close */
2184     WOLFSSL_BIO*     biowr;              /* socket bio write to free/close */
2185 #endif
2186 #ifndef NO_RSA
2187     RsaKey*         peerRsaKey;
2188     byte            peerRsaKeyPresent;
2189 #endif
2190 #ifdef HAVE_NTRU
2191     word16          peerNtruKeyLen;
2192     byte            peerNtruKey[MAX_NTRU_PUB_KEY_SZ];
2193     byte            peerNtruKeyPresent;
2194 #endif
2195 #ifdef HAVE_ECC
2196     ecc_key*        peerEccKey;              /* peer's  ECDHE key */
2197     ecc_key*        peerEccDsaKey;           /* peer's  ECDSA key */
2198     ecc_key*        eccTempKey;              /* private ECDHE key */
2199     word32          pkCurveOID;              /* curve Ecc_Sum     */
2200     word16          eccTempKeySz;            /* in octets 20 - 66 */
2201     byte            peerEccKeyPresent;
2202     byte            peerEccDsaKeyPresent;
2203     byte            eccTempKeyPresent;
2204 #endif
2205 #ifdef HAVE_LIBZ
2206     z_stream        c_stream;           /* compression   stream */
2207     z_stream        d_stream;           /* decompression stream */
2208     byte            didStreamInit;      /* for stream init and end */
2209 #endif
2210 #ifdef WOLFSSL_DTLS
2211     int             dtls_timeout_init;  /* starting timeout vaule */
2212     int             dtls_timeout_max;   /* maximum timeout value */
2213     int             dtls_timeout;       /* current timeout value, changes */
2214     DtlsPool*       dtls_pool;
2215     DtlsMsg*        dtls_msg_list;
2216     void*           IOCB_CookieCtx;     /* gen cookie ctx */
2217     word32          dtls_expected_rx;
2218 #endif
2219 #ifdef WOLFSSL_CALLBACKS
2220     HandShakeInfo   handShakeInfo;      /* info saved during handshake */
2221     TimeoutInfo     timeoutInfo;        /* info saved during handshake */
2222     byte            hsInfoOn;           /* track handshake info        */
2223     byte            toInfoOn;           /* track timeout   info        */
2224 #endif
2225 #ifdef HAVE_FUZZER
2226     CallbackFuzzer  fuzzerCb;           /* for testing with using fuzzer */
2227     void*           fuzzerCtx;          /* user defined pointer */
2228 #endif
2229 #ifdef KEEP_PEER_CERT
2230     WOLFSSL_X509     peerCert;           /* X509 peer cert */
2231 #endif
2232 #ifdef FORTRESS
2233     void*           ex_data[MAX_EX_DATA]; /* external data, for Fortress */
2234 #endif
2235 #ifdef HAVE_CAVIUM
2236     int              devId;            /* cavium device id to use */
2237 #endif
2238 #ifdef HAVE_ONE_TIME_AUTH
2239     OneTimeAuth     auth;
2240 #endif
2241 #ifdef HAVE_TLS_EXTENSIONS
2242     TLSX* extensions;                  /* RFC 6066 TLS Extensions data */
2243     #ifdef HAVE_MAX_FRAGMENT
2244         word16 max_fragment;
2245     #endif
2246     #ifdef HAVE_TRUNCATED_HMAC
2247         byte truncated_hmac;
2248     #endif
2249     #ifdef HAVE_SECURE_RENEGOTIATION
2250         SecureRenegotiation* secure_renegotiation; /* valid pointer indicates */
2251     #endif                                         /* user turned on */
2252     #if !defined(NO_WOLFSSL_CLIENT) && defined(HAVE_SESSION_TICKET)
2253         CallbackSessionTicket session_ticket_cb;
2254         void*                 session_ticket_ctx;
2255         byte                  expect_session_ticket;
2256     #endif
2257 #endif /* HAVE_TLS_EXTENSIONS */
2258 #ifdef HAVE_NETX
2259     NetX_Ctx        nxCtx;             /* NetX IO Context */
2260 #endif
2261 #ifdef SESSION_INDEX
2262     int sessionIndex;                  /* Session's location in the cache. */
2263 #endif
2264 #ifdef ATOMIC_USER
2265     void*    MacEncryptCtx;    /* Atomic User Mac/Encrypt Callback Context */
2266     void*    DecryptVerifyCtx; /* Atomic User Decrypt/Verify Callback Context */
2267 #endif
2268 #ifdef HAVE_PK_CALLBACKS
2269     #ifdef HAVE_ECC
2270         void* EccSignCtx;     /* Ecc Sign   Callback Context */
2271         void* EccVerifyCtx;   /* Ecc Verify Callback Context */
2272     #endif /* HAVE_ECC */
2273     #ifndef NO_RSA
2274         void* RsaSignCtx;     /* Rsa Sign   Callback Context */
2275         void* RsaVerifyCtx;   /* Rsa Verify Callback Context */
2276         void* RsaEncCtx;      /* Rsa Public  Encrypt   Callback Context */
2277         void* RsaDecCtx;      /* Rsa Private Decrypt   Callback Context */
2278     #endif /* NO_RSA */
2279 #endif /* HAVE_PK_CALLBACKS */
2280 #ifdef HAVE_SECRET_CALLBACK
2281         SessionSecretCb sessionSecretCb;
2282         void*           sessionSecretCtx;
2283 #endif /* HAVE_SECRET_CALLBACK */
2284 };
2285
2286
2287 WOLFSSL_LOCAL
2288 int  InitSSL(WOLFSSL*, WOLFSSL_CTX*);
2289 WOLFSSL_LOCAL
2290 void FreeSSL(WOLFSSL*);
2291 WOLFSSL_API void SSL_ResourceFree(WOLFSSL*);   /* Micrium uses */
2292
2293
2294 enum {
2295     IV_SZ   = 32,          /* max iv sz */
2296     NAME_SZ = 80          /* max one line */
2297 };
2298
2299
2300 typedef struct EncryptedInfo {
2301     char     name[NAME_SZ];    /* encryption name */
2302     byte     iv[IV_SZ];        /* encrypted IV */
2303     word32   ivSz;             /* encrypted IV size */
2304     long     consumed;         /* tracks PEM bytes consumed */
2305     byte     set;              /* if encryption set */
2306     WOLFSSL_CTX* ctx;              /* CTX owner */
2307 } EncryptedInfo;
2308
2309
2310 #ifndef NO_CERTS
2311     WOLFSSL_LOCAL int PemToDer(const unsigned char* buff, long sz, int type,
2312                               buffer* der, void* heap, EncryptedInfo* info,
2313                               int* eccKey);
2314
2315     WOLFSSL_LOCAL int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format,
2316                                  int type, WOLFSSL* ssl, int userChain,
2317                                 WOLFSSL_CRL* crl);
2318 #endif
2319
2320
2321 #ifdef WOLFSSL_CALLBACKS
2322     WOLFSSL_LOCAL
2323     void InitHandShakeInfo(HandShakeInfo*);
2324     WOLFSSL_LOCAL 
2325     void FinishHandShakeInfo(HandShakeInfo*, const WOLFSSL*);
2326     WOLFSSL_LOCAL 
2327     void AddPacketName(const char*, HandShakeInfo*);
2328
2329     WOLFSSL_LOCAL
2330     void InitTimeoutInfo(TimeoutInfo*);
2331     WOLFSSL_LOCAL 
2332     void FreeTimeoutInfo(TimeoutInfo*, void*);
2333     WOLFSSL_LOCAL 
2334     void AddPacketInfo(const char*, TimeoutInfo*, const byte*, int, void*);
2335     WOLFSSL_LOCAL 
2336     void AddLateName(const char*, TimeoutInfo*);
2337     WOLFSSL_LOCAL 
2338     void AddLateRecordHeader(const RecordLayerHeader* rl, TimeoutInfo* info);
2339 #endif
2340
2341
2342 /* Record Layer Header identifier from page 12 */
2343 enum ContentType {
2344     no_type            = 0,
2345     change_cipher_spec = 20, 
2346     alert              = 21, 
2347     handshake          = 22, 
2348     application_data   = 23 
2349 };
2350
2351
2352 /* handshake header, same for each message type, pgs 20/21 */
2353 typedef struct HandShakeHeader {
2354     byte            type;
2355     word24          length;
2356 } HandShakeHeader;
2357
2358
2359 /* DTLS handshake header, same for each message type */
2360 typedef struct DtlsHandShakeHeader {
2361     byte            type;
2362     word24          length;
2363     byte            message_seq[2];    /* start at 0, restransmit gets same # */
2364     word24          fragment_offset;   /* bytes in previous fragments */
2365     word24          fragment_length;   /* length of this fragment */
2366 } DtlsHandShakeHeader;
2367
2368
2369 enum HandShakeType {
2370     no_shake            = -1,
2371     hello_request       = 0, 
2372     client_hello        = 1, 
2373     server_hello        = 2,
2374     hello_verify_request = 3,       /* DTLS addition */
2375     session_ticket      =  4,
2376     certificate         = 11, 
2377     server_key_exchange = 12,
2378     certificate_request = 13, 
2379     server_hello_done   = 14,
2380     certificate_verify  = 15, 
2381     client_key_exchange = 16,
2382     finished            = 20,
2383     certificate_status  = 22,
2384     change_cipher_hs    = 55      /* simulate unique handshake type for sanity
2385                                      checks.  record layer change_cipher
2386                                      conflicts with handshake finished */
2387 };
2388
2389
2390 static const byte client[SIZEOF_SENDER] = { 0x43, 0x4C, 0x4E, 0x54 };
2391 static const byte server[SIZEOF_SENDER] = { 0x53, 0x52, 0x56, 0x52 };
2392
2393 static const byte tls_client[FINISHED_LABEL_SZ + 1] = "client finished";
2394 static const byte tls_server[FINISHED_LABEL_SZ + 1] = "server finished";
2395
2396
2397 /* internal functions */
2398 WOLFSSL_LOCAL int SendChangeCipher(WOLFSSL*);
2399 WOLFSSL_LOCAL int SendTicket(WOLFSSL*);
2400 WOLFSSL_LOCAL int DoClientTicket(WOLFSSL*, const byte*, word32);
2401 WOLFSSL_LOCAL int SendData(WOLFSSL*, const void*, int);
2402 WOLFSSL_LOCAL int SendCertificate(WOLFSSL*);
2403 WOLFSSL_LOCAL int SendCertificateRequest(WOLFSSL*);
2404 WOLFSSL_LOCAL int SendServerKeyExchange(WOLFSSL*);
2405 WOLFSSL_LOCAL int SendBuffered(WOLFSSL*);
2406 WOLFSSL_LOCAL int ReceiveData(WOLFSSL*, byte*, int, int);
2407 WOLFSSL_LOCAL int SendFinished(WOLFSSL*);
2408 WOLFSSL_LOCAL int SendAlert(WOLFSSL*, int, int);
2409 WOLFSSL_LOCAL int ProcessReply(WOLFSSL*);
2410
2411 WOLFSSL_LOCAL int SetCipherSpecs(WOLFSSL*);
2412 WOLFSSL_LOCAL int MakeMasterSecret(WOLFSSL*);
2413
2414 WOLFSSL_LOCAL int  AddSession(WOLFSSL*);
2415 WOLFSSL_LOCAL int  DeriveKeys(WOLFSSL* ssl);
2416 WOLFSSL_LOCAL int  StoreKeys(WOLFSSL* ssl, const byte* keyData);
2417
2418 WOLFSSL_LOCAL int IsTLS(const WOLFSSL* ssl);
2419 WOLFSSL_LOCAL int IsAtLeastTLSv1_2(const WOLFSSL* ssl);
2420
2421 WOLFSSL_LOCAL void FreeHandshakeResources(WOLFSSL* ssl);
2422 WOLFSSL_LOCAL void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree);
2423 WOLFSSL_LOCAL void ShrinkOutputBuffer(WOLFSSL* ssl);
2424
2425 WOLFSSL_LOCAL int VerifyClientSuite(WOLFSSL* ssl);
2426 #ifndef NO_CERTS
2427     WOLFSSL_LOCAL Signer* GetCA(void* cm, byte* hash);
2428     #ifndef NO_SKID
2429         WOLFSSL_LOCAL Signer* GetCAByName(void* cm, byte* hash);
2430     #endif
2431 #endif
2432 WOLFSSL_LOCAL int  BuildTlsFinished(WOLFSSL* ssl, Hashes* hashes,
2433                                    const byte* sender);
2434 WOLFSSL_LOCAL void FreeArrays(WOLFSSL* ssl, int keep);
2435 WOLFSSL_LOCAL  int CheckAvailableSize(WOLFSSL *ssl, int size);
2436 WOLFSSL_LOCAL  int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength);
2437
2438 #ifndef NO_TLS
2439     WOLFSSL_LOCAL int  MakeTlsMasterSecret(WOLFSSL*);
2440     WOLFSSL_LOCAL int  TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in,
2441                                word32 sz, int content, int verify);
2442 #endif
2443
2444 #ifndef NO_WOLFSSL_CLIENT
2445     WOLFSSL_LOCAL int SendClientHello(WOLFSSL*);
2446     WOLFSSL_LOCAL int SendClientKeyExchange(WOLFSSL*);
2447     WOLFSSL_LOCAL int SendCertificateVerify(WOLFSSL*);
2448 #endif /* NO_WOLFSSL_CLIENT */
2449
2450 #ifndef NO_WOLFSSL_SERVER
2451     WOLFSSL_LOCAL int SendServerHello(WOLFSSL*);
2452     WOLFSSL_LOCAL int SendServerHelloDone(WOLFSSL*);
2453     #ifdef WOLFSSL_DTLS
2454         WOLFSSL_LOCAL int SendHelloVerifyRequest(WOLFSSL*);
2455     #endif
2456 #endif /* NO_WOLFSSL_SERVER */
2457
2458 #ifdef WOLFSSL_DTLS
2459     WOLFSSL_LOCAL int  DtlsPoolInit(WOLFSSL*);
2460     WOLFSSL_LOCAL int  DtlsPoolSave(WOLFSSL*, const byte*, int);
2461     WOLFSSL_LOCAL int  DtlsPoolTimeout(WOLFSSL*);
2462     WOLFSSL_LOCAL int  DtlsPoolSend(WOLFSSL*);
2463     WOLFSSL_LOCAL void DtlsPoolReset(WOLFSSL*);
2464
2465     WOLFSSL_LOCAL DtlsMsg* DtlsMsgNew(word32, void*);
2466     WOLFSSL_LOCAL void DtlsMsgDelete(DtlsMsg*, void*);
2467     WOLFSSL_LOCAL void DtlsMsgListDelete(DtlsMsg*, void*);
2468     WOLFSSL_LOCAL void DtlsMsgSet(DtlsMsg*, word32, const byte*, byte,
2469                                                              word32, word32);
2470     WOLFSSL_LOCAL DtlsMsg* DtlsMsgFind(DtlsMsg*, word32);
2471     WOLFSSL_LOCAL DtlsMsg* DtlsMsgStore(DtlsMsg*, word32, const byte*, word32,
2472                                                 byte, word32, word32, void*);
2473     WOLFSSL_LOCAL DtlsMsg* DtlsMsgInsert(DtlsMsg*, DtlsMsg*);
2474 #endif /* WOLFSSL_DTLS */
2475
2476 #ifndef NO_TLS
2477     
2478
2479 #endif /* NO_TLS */
2480
2481
2482 WOLFSSL_LOCAL word32  LowResTimer(void);
2483
2484 WOLFSSL_LOCAL void InitX509Name(WOLFSSL_X509_NAME*, int);
2485 WOLFSSL_LOCAL void FreeX509Name(WOLFSSL_X509_NAME* name);
2486 WOLFSSL_LOCAL void InitX509(WOLFSSL_X509*, int);
2487 WOLFSSL_LOCAL void FreeX509(WOLFSSL_X509*);
2488 #ifndef NO_CERTS
2489     WOLFSSL_LOCAL int  CopyDecodedToX509(WOLFSSL_X509*, DecodedCert*);
2490 #endif
2491
2492 /* used by ssl.c and wolfssl_int.c */
2493 WOLFSSL_LOCAL void c32to24(word32 in, word24 out);
2494
2495 WOLFSSL_LOCAL const char* const* GetCipherNames(void);
2496 WOLFSSL_LOCAL int GetCipherNamesSize(void);
2497
2498
2499 enum encrypt_side {
2500     ENCRYPT_SIDE_ONLY = 1,
2501     DECRYPT_SIDE_ONLY,
2502     ENCRYPT_AND_DECRYPT_SIDE
2503 };
2504
2505 WOLFSSL_LOCAL int SetKeysSide(WOLFSSL*, enum encrypt_side);
2506
2507
2508 #ifdef __cplusplus
2509     }  /* extern "C" */
2510 #endif
2511
2512 #endif /* wolfSSL_INT_H */
2513