File Coverage

inc/matrixssl-3-9-3-open/matrixssl/matrixssllib.h
Criterion Covered Total %
statement 0 3 0.0
branch 0 2 0.0
condition n/a
subroutine n/a
pod n/a
total 0 5 0.0


line stmt bran cond sub pod time code
1             /**
2             * @file matrixssllib.h
3             * @version 950bba4 (HEAD -> master)
4             *
5             * Internal header file used for the MatrixSSL implementation..
6             * Only modifiers of the library should be intersted in this file
7             */
8             /*
9             * Copyright (c) 2013-2017 INSIDE Secure Corporation
10             * Copyright (c) PeerSec Networks, 2002-2011
11             * All Rights Reserved
12             *
13             * The latest version of this code is available at http://www.matrixssl.org
14             *
15             * This software is open source; you can redistribute it and/or modify
16             * it under the terms of the GNU General Public License as published by
17             * the Free Software Foundation; either version 2 of the License, or
18             * (at your option) any later version.
19             *
20             * This General Public License does NOT permit incorporating this software
21             * into proprietary programs. If you are unable to comply with the GPL, a
22             * commercial license for this software may be purchased from INSIDE at
23             * http://www.insidesecure.com/
24             *
25             * This program is distributed in WITHOUT ANY WARRANTY; without even the
26             * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
27             * See the GNU General Public License for more details.
28             *
29             * You should have received a copy of the GNU General Public License
30             * along with this program; if not, write to the Free Software
31             * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32             * http://www.gnu.org/copyleft/gpl.html
33             */
34             /******************************************************************************/
35              
36             #ifndef _h_MATRIXSSLLIB
37             # define _h_MATRIXSSLLIB
38              
39             # ifdef __cplusplus
40             extern "C" {
41             # endif
42              
43             /******************************************************************************/
44             /**
45             Additional 'hidden' TLS configuration here for deprecated support.
46             @security These options allow enabling/disabling features that have been
47             found to generally considered weak and should not be changed except for
48             compatibility with older software that cannot be changed.
49             @security The default value for strongest security is indicated for each
50             option.
51             */
52             /** Deprecated cipher suites. */
53             # ifndef USE_DTLS
54             /* #define USE_SSL_RSA_WITH_RC4_128_MD5 / **< @security OFF * / */
55             /* #define USE_SSL_RSA_WITH_RC4_128_SHA / **< @security OFF * / */
56             /* #define USE_TLS_RSA_WITH_SEED_CBC_SHA / **< @security OFF * / */
57             /* #define USE_TLS_RSA_WITH_IDEA_CBC_SHA / **< @security OFF * / */
58             # endif
59              
60             /** Anonymous, non authenticated ciphers. */
61             /* #define USE_TLS_DH_anon_WITH_AES_128_CBC_SHA / **< @security OFF * / */
62             /* #define USE_TLS_DH_anon_WITH_AES_256_CBC_SHA / **< @security OFF * / */
63             /* #define USE_SSL_DH_anon_WITH_3DES_EDE_CBC_SHA / **< @security OFF * / */
64             # ifndef USE_DTLS
65             /* #define USE_SSL_DH_anon_WITH_RC4_128_MD5 / **< @security OFF * / */
66             # endif
67              
68             /** Authenticated but not encrypted ciphers. */
69             /* #define USE_SSL_RSA_WITH_NULL_SHA / **< @security OFF * / */
70             /* #define USE_SSL_RSA_WITH_NULL_MD5 / **< @security OFF * / */
71              
72             /**
73             False Start support for Chrome browser.
74             @see http://tools.ietf.org/html/draft-bmoeller-tls-falsestart-00
75              
76             @note April 2012: Google has announced this feature will be removed in
77             version 20 of their browser due to industry compatibility issues.
78              
79             @note November 2017: An official IETF draft is in process for this
80             functionality to become standardized.
81             @see https://datatracker.ietf.org/doc/draft-ietf-tls-falsestart/
82             */
83             /* #define ENABLE_FALSE_START / **< @security OFF * / */
84              
85             /**
86             zlib compression support.
87             @security The CRIME attack on HTTPS has shown that compression at the
88             TLS layer can introduce vulnerabilities in higher level protocols. It is
89             recommended to NOT use compression features at the TLS level.
90             */
91             /* #define USE_ZLIB_COMPRESSION / **< @security OFF NIST_SHOULD_NOT * / */
92              
93             /******************************************************************************/
94             /**
95             Rehandshaking support.
96             In late 2009 An "authentication gap" exploit was discovered in the
97             SSL re-handshaking protocol. The fix to the exploit was introduced
98             in RFC 5746 and is referred to here as SECURE_REHANDSHAKES.
99              
100             ENABLE_SECURE_REHANDSHAKES implements RFC 5746 and will securely
101             renegotiate with any implementations that support it. It is
102             recommended to leave this disabled unless there is a specific requirement
103             to support it.
104              
105             By enabling REQUIRE_SECURE_REHANDSHAKES, the library will test that each
106             communicating peer that is attempting to connect has implemented
107             RFC 5746 and will terminate handshakes with any that have not.
108              
109             If working with SSL peers that have not implemented RFC 5746 and
110             rehandshakes are required, you may enable ENABLE_INSECURE_REHANDSHAKES
111             but it is NOT RECOMMENDED
112              
113             It is a conflict to enable both ENABLE_INSECURE_REHANDSHAKES and
114             REQUIRE_SECURE_REHANDSHAKES and a compile error will occur
115              
116             To completely disable rehandshaking comment out all three of these defines
117              
118             @security Disabling handshaking altogether is the most secure. If it must
119             be enabled, only secure rehandshakes should be allowed. Other modes below
120             are provided only for compatibility with old TLS/SSL libraries.
121             */
122             # ifdef USE_REHANDSHAKING
123             /* #define ENABLE_SECURE_REHANDSHAKES / **< @security OFF NIST_SHALL * / */
124             # define REQUIRE_SECURE_REHANDSHAKES /**< @security ON NIST_SHALL */
125             /* #define ENABLE_INSECURE_REHANDSHAKES / ** @security OFF NIST_SHALL_NOT * / */
126             # endif
127              
128             /******************************************************************************/
129             /**
130             Beast Mode.
131             In Sept. 2011 security researchers demonstrated how a previously known
132             CBC encryption weakness could be used to decrypt HTTP data over SSL.
133             The attack was named BEAST (Browser Exploit Against SSL/TLS).
134              
135             This issue only affects TLS 1.0 (and SSL) and only if the cipher suite
136             is using a symmetric CBC block cipher. Enable USE_TLS_1_1 above to
137             completely negate this workaround if TLS 1.1 is also supported by peers.
138              
139             As with previous SSL vulnerabilities, the attack is generally considered
140             a very low risk for individual browsers as it requires the attacker
141             to have control over the network to become a MITM. They will also have
142             to have knowledge of the first couple blocks of underlying plaintext
143             in order to mount the attack.
144              
145             A zero length record proceeding a data record has been a known fix to this
146             problem for years and MatrixSSL has always supported the handling of empty
147             records. So alternatively, an implementation could always encode a zero
148             length record before each record encode. Some old SSL implementations do
149             not handle decoding zero length records, however.
150              
151             This BEAST fix is on the client side and moves the implementation down to
152             the SSL library level so users do not need to manually send zero length
153             records. This fix uses the same IV obfuscation logic as a zero length
154             record by breaking up each application data record in two. Because some
155             implementations don't handle zero-length records, the the first record
156             is the first byte of the plaintext message, and the second record
157             contains the remainder of the message.
158              
159             This fix is based on the workaround implemented in Google Chrome:
160             http://src.chromium.org/viewvc/chrome?view=rev&revision=97269
161              
162             This workaround adds approximagely 53 bytes to the encoded length of each
163             SSL3.0 or TLS1.0 record that is encoded, due to the additional header,
164             padding and MAC of the second record.
165              
166             @security This mode should always be enabled unless explicit compatibility
167             with old TLS 1.0 and SSL 3.0 libraries is required.
168             */
169             # define USE_BEAST_WORKAROUND /**< @security ON */
170              
171             /******************************************************************************/
172             /**
173             Enable certificate chain message "stream" parsing. This allows single
174             certificates to be parsed on-the-fly without having to wait for the entire
175             certificate chain to be recieved in the buffer. This is a memory saving
176             feature for the application buffer but will add a small amount of code
177             size for the parsing and structure overhead.
178              
179             This feature will only save memory if the CERTIFICATE message is the
180             only message in the record, and multiple certs are present in the chain.
181              
182             @note This features is deprecated and should be enabled only if
183             processing long certificate chains with very low memory.
184             */
185             /* #define USE_CERT_CHAIN_PARSING / **< @note Setting does not affect security * / */
186              
187             /******************************************************************************/
188             /**
189             Experimental support for process-shared server session cache.
190             This allows forked copies of a process to use the same session cache.
191             @pre Supported for POSIX environments only currently.
192             */
193             /* #define USE_SHARED_SESSION_CACHE / **< @note Experimental * / */
194              
195             /******************************************************************************/
196             /**
197             - USE_TLS versions must 'stack' for compiling purposes
198             - must enable TLS if enabling TLS 1.1
199             - must enable TLS 1.1 if enabling TLS 1.2
200             - Use the DISABLE_TLS_ defines to disallow specific protocols at runtime
201             that have been enabled via USE_TLS_.
202             - There is no DISABLE_TLS_ for the latest version of the protocol. If
203             you don't want to use that version disable the USE_TLS_ define instead
204             The USE_TLS_1_x_AND_ABOVE simplifies this configuration.
205             @security To enable SSL3.0, see below.
206             */
207             # define USE_TLS /**< DO NOT DISABLE @security NIST_MAY */
208             # define USE_TLS_1_1 /**< DO NOT DISABLE @security NIST_SHALL */
209             # define USE_TLS_1_2 /**< DO NOT DISABLE @security NIST_SHOULD */
210             # define DISABLE_SSLV3 /**< DO NOT DISABLE, undef below if required
211             @security NIST_SHALL_NOT */
212              
213             # if defined USE_TLS_1_2_AND_ABOVE
214             # define DISABLE_TLS_1_1
215             # define DISABLE_TLS_1_0
216             # elif defined USE_TLS_1_1_AND_ABOVE
217             # define DISABLE_TLS_1_0
218             # elif defined USE_TLS_1_0_AND_ABOVE
219             /** @security undef DISABLE_SSLV3 here if required */
220             # else
221             # error Must define USE_TLS_1_x_AND_ABOVE
222             # endif
223              
224             # ifdef USE_DTLS
225             /******************************************************************************/
226             /** DTLS definitions */
227             # define DTLS_COOKIE_SIZE 16
228             # endif /* USE_DTLS */
229              
230             /******************************************************************************/
231             /**
232             Include matrixssl external crypto provider layer headers.
233             */
234              
235             # ifdef USE_ZLIB_COMPRESSION
236             # include "zlib.h"
237             # endif
238              
239             # if defined(USE_AES_GCM) || defined(USE_AES_CCM) || defined(USE_CHACHA20_POLY1305)
240             # define USE_AEAD_CIPHER
241             # endif
242              
243             /* PKCS11 is set in crypto. Use all modes of it if enabled */
244             # define USE_NATIVE_TLS_ALGS
245             # define USE_NATIVE_TLS_HS_HASH
246             # define USE_NATIVE_SYMMETRIC
247              
248             /******************************************************************************/
249             /**
250             Do sanity checks on configuration.
251             */
252             # include "matrixsslCheck.h"
253              
254             /******************************************************************************/
255             /*
256             Leave this enabled for run-time check of sslKeys_t content when a cipher
257             suite is matched. Disable only if you need to manage key material yourself.
258             Always conditional on whether certificate parsing is enabled because it
259             looks at members that only exist if certificates have been parsed
260             */
261             # ifdef USE_CERT_PARSE
262             # define VALIDATE_KEY_MATERIAL
263             # endif /* USE_CERT_PARSE */
264              
265             /******************************************************************************/
266             /**
267             SSL protocol and MatrixSSL defines.
268             @see https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml
269             */
270              
271             /*
272             Maximum SSL record size, per specification
273             */
274             # define SSL_MAX_PLAINTEXT_LEN 0x4000 /* 16KB */
275             # define SSL_MAX_RECORD_LEN SSL_MAX_PLAINTEXT_LEN + 2048
276             # define SSL_MAX_BUF_SIZE SSL_MAX_RECORD_LEN + 0x5
277             # define SSL_MAX_DISABLED_CIPHERS 8
278             /*
279             Maximum buffer sizes for static SSL array types
280             */
281             # define SSL_MAX_MAC_SIZE 48/* SHA384 */
282             # define SSL_MAX_IV_SIZE 16
283             # define SSL_MAX_BLOCK_SIZE 16
284             # define SSL_MAX_SYM_KEY_SIZE 32
285              
286             /*
287             Negative return codes must be between -50 and -69 in the MatrixSSL module
288             */
289             # define SSL_FULL -50 /* must call sslRead before decoding */
290             # define SSL_PARTIAL -51 /* more data reqired to parse full msg */
291             # define SSL_SEND_RESPONSE -52 /* decode produced output data */
292             # define SSL_PROCESS_DATA -53 /* succesfully decoded application data */
293             # define SSL_ALERT -54 /* we've decoded an alert */
294             # define SSL_FILE_NOT_FOUND -55 /* File not found */
295             # define SSL_MEM_ERROR PS_MEM_FAIL /* Memory allocation failure */
296             # ifdef USE_DTLS
297             # define DTLS_MUST_FRAG -60 /* Message must be fragmented */
298             # define DTLS_RETRANSMIT -61 /* Received a duplicate hs msg from peer */
299             # endif /* USE_DTLS */
300              
301             /*
302             Magic numbers for handshake header lengths
303             */
304             # define SSL2_HEADER_LEN 2
305             # define SSL3_HEADER_LEN 5
306             # define SSL3_HANDSHAKE_HEADER_LEN 4
307             # ifdef USE_DTLS
308             # define DTLS_HEADER_ADD_LEN 8
309             # endif
310              
311             # define TLS_CHACHA20_POLY1305_AAD_LEN 13
312             # define TLS_GCM_AAD_LEN 13
313             # define TLS_AEAD_SEQNB_LEN 8
314              
315             # define TLS_GCM_TAG_LEN 16
316             # define TLS_CHACHA20_POLY1305_TAG_LEN 16
317             # define TLS_CCM_TAG_LEN 16
318             # define TLS_CCM8_TAG_LEN 8
319              
320             # define TLS_AEAD_NONCE_MAXLEN 12/* Maximum length for an AEAD's nonce */
321             # define TLS_EXPLICIT_NONCE_LEN 8
322             # define TLS_CHACHA20_POLY1305_NONCE_LEN 0
323              
324             # define AEAD_NONCE_LEN(SSL) ((SSL->flags & SSL_FLAGS_NONCE_W) ? TLS_EXPLICIT_NONCE_LEN : 0)
325             # define AEAD_TAG_LEN(SSL) ((SSL->cipher->flags & CRYPTO_FLAGS_CCM8) ? 8 : 16)
326              
327             /*
328             matrixSslSetSessionOption defines
329             */
330             # define SSL_OPTION_FULL_HANDSHAKE 1
331             # ifdef USE_CLIENT_AUTH
332             # define SSL_OPTION_DISABLE_CLIENT_AUTH 2
333             # define SSL_OPTION_ENABLE_CLIENT_AUTH 3
334             # endif /* USE_CLIENT_AUTH */
335             # define SSL_OPTION_DISABLE_REHANDSHAKES 4
336             # define SSL_OPTION_REENABLE_REHANDSHAKES 5
337              
338             /*
339             SSL Alert levels and descriptions
340             This implementation treats all alerts that are not related to
341             certificate validation as fatal
342             */
343             # define SSL_ALERT_LEVEL_WARNING 1
344             # define SSL_ALERT_LEVEL_FATAL 2
345              
346             # define SSL_ALERT_CLOSE_NOTIFY 0
347             # define SSL_ALERT_UNEXPECTED_MESSAGE 10
348             # define SSL_ALERT_BAD_RECORD_MAC 20
349             # define SSL_ALERT_DECRYPTION_FAILED 21/* Do not use, per RFC 5246 */
350             # define SSL_ALERT_RECORD_OVERFLOW 22
351             # define SSL_ALERT_DECOMPRESSION_FAILURE 30
352             # define SSL_ALERT_HANDSHAKE_FAILURE 40
353             # define SSL_ALERT_NO_CERTIFICATE 41
354             # define SSL_ALERT_BAD_CERTIFICATE 42
355             # define SSL_ALERT_UNSUPPORTED_CERTIFICATE 43
356             # define SSL_ALERT_CERTIFICATE_REVOKED 44
357             # define SSL_ALERT_CERTIFICATE_EXPIRED 45
358             # define SSL_ALERT_CERTIFICATE_UNKNOWN 46
359             # define SSL_ALERT_ILLEGAL_PARAMETER 47
360             # define SSL_ALERT_UNKNOWN_CA 48
361             # define SSL_ALERT_ACCESS_DENIED 49
362             # define SSL_ALERT_DECODE_ERROR 50
363             # define SSL_ALERT_DECRYPT_ERROR 51
364             # define SSL_ALERT_PROTOCOL_VERSION 70
365             # define SSL_ALERT_INSUFFICIENT_SECURITY 71
366             # define SSL_ALERT_INTERNAL_ERROR 80
367             # define SSL_ALERT_INAPPROPRIATE_FALLBACK 86
368             # define SSL_ALERT_NO_RENEGOTIATION 100
369             # define SSL_ALERT_UNSUPPORTED_EXTENSION 110
370             # define SSL_ALERT_UNRECOGNIZED_NAME 112
371             # define SSL_ALERT_BAD_CERTIFICATE_STATUS_RESPONSE 113
372             # define SSL_ALERT_UNKNOWN_PSK_IDENTITY 115
373             # define SSL_ALERT_NO_APP_PROTOCOL 120
374              
375             /*
376             Use as return code in user validation callback to allow
377             anonymous connections to proceed.
378             MUST NOT OVERLAP WITH ANY OF THE ALERT CODES ABOVE
379             */
380             # define SSL_ALLOW_ANON_CONNECTION 254
381              
382             /* Internal values for ssl_t.flags */
383             # define SSL_FLAGS_SERVER (1 << 0)
384             # define SSL_FLAGS_READ_SECURE (1 << 1)
385             # define SSL_FLAGS_WRITE_SECURE (1 << 2)
386             # define SSL_FLAGS_RESUMED (1 << 3)
387             # define SSL_FLAGS_CLOSED (1 << 4)
388             # define SSL_FLAGS_NEED_ENCODE (1 << 5)
389             # define SSL_FLAGS_ERROR (1 << 6)
390             # define SSL_FLAGS_CLIENT_AUTH (1 << 7)
391             # define SSL_FLAGS_ANON_CIPHER (1 << 8)
392             # define SSL_FLAGS_FALSE_START (1 << 9)
393             # define SSL_FLAGS_SSLV3 (1 << 10)
394             # define SSL_FLAGS_TLS (1 << 11)
395             # define SSL_FLAGS_TLS_1_0 SSL_FLAGS_TLS /* For naming consistency */
396             # define SSL_FLAGS_TLS_1_1 (1 << 12)
397             # define SSL_FLAGS_TLS_1_2 (1 << 13)
398             # define SSL_FLAGS_DTLS (1 << 14)
399             # define SSL_FLAGS_DHE_WITH_RSA (1 << 15)
400             # define SSL_FLAGS_DHE_WITH_DSA (1 << 16)
401             # define SSL_FLAGS_DHE_KEY_EXCH (1 << 17)
402             # define SSL_FLAGS_PSK_CIPHER (1 << 18)
403             # define SSL_FLAGS_ECC_CIPHER (1 << 19)
404             # define SSL_FLAGS_AEAD_W (1 << 20)
405             # define SSL_FLAGS_AEAD_R (1 << 21)
406             # define SSL_FLAGS_NONCE_W (1 << 22)
407             # define SSL_FLAGS_NONCE_R (1 << 23)
408             # define SSL_FLAGS_HTTP2 (1 << 24)
409              
410             # define SSL_FLAGS_INTERCEPTOR (1 << 30)
411             # define SSL_FLAGS_EAP_FAST (1 << 31)
412              
413             /* Internal flags for ssl_t.hwflags */
414             # define SSL_HWFLAGS_HW (1 << 0) /* Use HW for decode/encode */
415             # define SSL_HWFLAGS_HW_SW (1 << 1) /* Use HW & SW in parallel (debug) */
416             # define SSL_HWFLAGS_NONBLOCK (1 << 2) /* Use async HW for decode/encode */
417             # define SSL_HWFLAGS_PENDING_R (1 << 3) /* Non-blocking app record read */
418             # define SSL_HWFLAGS_PENDING_W (1 << 4) /* Non-blocking app record write */
419             # define SSL_HWFLAGS_PENDING_FLIGHT_W (1 << 5) /* mid encryptFlight (hshake) */
420             # define SSL_HWFLAGS_PENDING_PKA_R (1 << 6) /* Non-blocking public key op */
421             # define SSL_HWFLAGS_PENDING_PKA_W (1 << 7) /* Non-blocking public key op */
422             # define SSL_HWFLAGS_EAGAIN (1 << 8) /* Not submitted. Skip hsHash */
423             # define SSL_HWFLAGS_HW_BAD (1 << 9) /* Bad hardware result,go software */
424              
425             /* Buffer flags (ssl->bFlags) */
426             # define BFLAG_CLOSE_AFTER_SENT (1 << 0)
427             # define BFLAG_HS_COMPLETE (1 << 1)
428             # define BFLAG_STOP_BEAST (1 << 2)
429             # define BFLAG_KEEP_PEER_CERTS (1 << 3) /* Keep peer cert chain. */
430             # define BFLAG_KEEP_PEER_CERT_DER (1 << 4) /* Keep raw DER of peer certs. */
431              
432             /*
433             Number of bytes server must send before creating a re-handshake credit
434             */
435             # define DEFAULT_RH_CREDITS 1/* Allow for one rehandshake by default */
436             # define BYTES_BEFORE_RH_CREDIT 20 * 1024 * 1024
437              
438             # ifdef USE_ECC
439             /* EC flags for sslSessOpts_t */
440             # define SSL_OPT_SECP192R1 IS_SECP192R1
441             # define SSL_OPT_SECP224R1 IS_SECP224R1
442             # define SSL_OPT_SECP256R1 IS_SECP256R1
443             # define SSL_OPT_SECP384R1 IS_SECP384R1
444             # define SSL_OPT_SECP521R1 IS_SECP521R1
445             /* WARNING: Public points on Brainpool curves are not validated */
446             # define SSL_OPT_BRAIN224R1 IS_BRAIN224R1
447             # define SSL_OPT_BRAIN256R1 IS_BRAIN256R1
448             # define SSL_OPT_BRAIN384R1 IS_BRAIN384R1
449             # define SSL_OPT_BRAIN512R1 IS_BRAIN512R1
450             # endif
451              
452             /* Cipher types (internal for CipherSpec_t.type) */
453             enum PACKED
454             {
455             CS_NULL = 0,
456             CS_RSA,
457             CS_DHE_RSA,
458             CS_DH_ANON,
459             CS_DHE_PSK,
460             CS_PSK,
461             CS_ECDHE_ECDSA,
462             CS_ECDHE_RSA,
463             CS_ECDH_ECDSA,
464             CS_ECDH_RSA
465             };
466              
467             /*
468             These are defines rather than enums because we want to store them as char,
469             not int32 (enum size)
470             */
471             # define SSL_RECORD_TYPE_CHANGE_CIPHER_SPEC (uint8_t) 20
472             # define SSL_RECORD_TYPE_ALERT (uint8_t) 21
473             # define SSL_RECORD_TYPE_HANDSHAKE (uint8_t) 22
474             # define SSL_RECORD_TYPE_APPLICATION_DATA (uint8_t) 23
475             # define SSL_RECORD_TYPE_HANDSHAKE_FIRST_FRAG (uint8_t) 90 /* internal */
476             # define SSL_RECORD_TYPE_HANDSHAKE_FRAG (uint8_t) 91 /* non-standard types */
477              
478             # define SSL_HS_HELLO_REQUEST (uint8_t) 0
479             # define SSL_HS_CLIENT_HELLO (uint8_t) 1
480             # define SSL_HS_SERVER_HELLO (uint8_t) 2
481             # define SSL_HS_HELLO_VERIFY_REQUEST (uint8_t) 3
482             # define SSL_HS_NEW_SESSION_TICKET (uint8_t) 4
483             # define SSL_HS_CERTIFICATE (uint8_t) 11
484             # define SSL_HS_SERVER_KEY_EXCHANGE (uint8_t) 12
485             # define SSL_HS_CERTIFICATE_REQUEST (uint8_t) 13
486             # define SSL_HS_SERVER_HELLO_DONE (uint8_t) 14
487             # define SSL_HS_CERTIFICATE_VERIFY (uint8_t) 15
488             # define SSL_HS_CLIENT_KEY_EXCHANGE (uint8_t) 16
489             # define SSL_HS_FINISHED (uint8_t) 20
490             # define SSL_HS_CERTIFICATE_STATUS (uint8_t) 22
491             # define SSL_HS_ALERT (uint8_t) 252 /* ChangeCipherSuite (internal) */
492             # define SSL_HS_CCC (uint8_t) 253 /* ChangeCipherSuite (internal) */
493             # define SSL_HS_NONE (uint8_t) 254 /* No recorded state (internal) */
494             # define SSL_HS_DONE (uint8_t) 255 /* Handshake complete (internal) */
495              
496             # define INIT_ENCRYPT_CIPHER 0
497             # define INIT_DECRYPT_CIPHER 1
498              
499             # define HMAC_CREATE 1
500             # define HMAC_VERIFY 2
501              
502             # ifdef USE_TLS_1_2
503             /**
504             enum {
505             none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5), sha512(6), (255)
506             } HashAlgorithm;
507             enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } SigAlgorithm;
508             */
509             enum PACKED
510             {
511             HASH_SIG_MD5 = 1,
512             HASH_SIG_SHA1,
513             HASH_SIG_SHA256 = 4,
514             HASH_SIG_SHA384,
515             HASH_SIG_SHA512
516             };
517              
518             enum PACKED
519             {
520             HASH_SIG_RSA = 1,
521             HASH_SIG_ECDSA = 3 /* This 3 is correct for hashSigAlg */
522             };
523              
524             /* Internal flag format for algorithms */
525             enum PACKED
526             {
527             /* For RSA we set a bit in the low byte */
528             HASH_SIG_MD5_RSA_MASK = 1 << HASH_SIG_MD5,
529             HASH_SIG_SHA1_RSA_MASK = 1 << HASH_SIG_SHA1,
530             HASH_SIG_SHA256_RSA_MASK = 1 << HASH_SIG_SHA256,
531             HASH_SIG_SHA384_RSA_MASK = 1 << HASH_SIG_SHA384,
532             HASH_SIG_SHA512_RSA_MASK = 1 << HASH_SIG_SHA512,
533             /* For ECDSA we set a bit in the high byte */
534             HASH_SIG_SHA1_ECDSA_MASK = 0x100 << HASH_SIG_SHA1,
535             HASH_SIG_SHA256_ECDSA_MASK = 0x100 << HASH_SIG_SHA256,
536             HASH_SIG_SHA384_ECDSA_MASK = 0x100 << HASH_SIG_SHA384,
537             HASH_SIG_SHA512_ECDSA_MASK = 0x100 << HASH_SIG_SHA512,
538             };
539              
540             /** Return a unique flag for the given HASH_SIG_ALG. */
541 0           static __inline uint16_t HASH_SIG_MASK(uint8_t hash, uint8_t sig)
542             {
543             /* TODO - do better validation on hash and sig */
544 0           hash = 1 << (hash & 0x7);
545 0 0         return sig == HASH_SIG_RSA ? hash : ((uint16_t) hash << 8);
546             }
547             # endif /* USE_TLS_1_2 */
548              
549             /* Additional ssl alert value, indicating no error has ocurred. */
550             # define SSL_ALERT_NONE 255/* No error */
551              
552             /* SSL/TLS protocol message sizes */
553             # define SSL_HS_RANDOM_SIZE 32
554             # define SSL_HS_RSA_PREMASTER_SIZE 48
555             # ifdef USE_TLS
556             # define TLS_HS_FINISHED_SIZE 12
557             # endif /* USE_TLS */
558              
559             /* Major and minor (not minimum!) version numbers for TLS */
560             # define SSL2_MAJ_VER 2
561              
562             # define SSL3_MAJ_VER 3
563             # define SSL3_MIN_VER 0
564              
565             # define TLS_MAJ_VER SSL3_MAJ_VER
566             # define TLS_MIN_VER 1
567             # define TLS_1_0_MIN_VER TLS_MIN_VER
568             # define TLS_1_1_MIN_VER 2
569             # define TLS_1_2_MIN_VER 3
570              
571             /* Based on settings, define the highest TLS version available */
572             # if defined(USE_TLS_1_2) && !defined(DISABLE_TLS_1_2)
573             # define TLS_HIGHEST_MINOR TLS_1_2_MIN_VER
574             # elif defined(USE_TLS_1_1) && !defined(DISABLE_TLS_1_1)
575             # define TLS_HIGHEST_MINOR TLS_1_1_MIN_VER
576             # elif defined(USE_TLS) && !defined(DISABLE_TLS_1_0)
577             # define TLS_HIGHEST_MINOR TLS_1_0_MIN_VER
578             # elif !defined(DISABLE_SSLV3)
579             # define TLS_HIGHEST_MINOR SSL3_MIN_VER
580             # else
581             # error Unexpected TLS Version
582             # endif
583              
584             /* Cipher suite specification IDs, in numerical order. */
585             # define SSL_NULL_WITH_NULL_NULL 0x0000
586             # define SSL_RSA_WITH_NULL_MD5 0x0001
587             # define SSL_RSA_WITH_NULL_SHA 0x0002
588             # define SSL_RSA_WITH_RC4_128_MD5 0x0004
589             # define SSL_RSA_WITH_RC4_128_SHA 0x0005
590             # define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007
591             # define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
592             # define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
593             # define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
594             # define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
595             # define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /* 47 */
596             # define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
597             # define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
598             # define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
599             # define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
600             # define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
601             # define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
602             # define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
603             # define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
604             # define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
605             # define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
606             # define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
607             # define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
608             # define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
609             # define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
610             # define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
611             # define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
612             # define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /* 156 */
613             # define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /* 157 */
614              
615             # define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF /**< @see RFC 5746 */
616             # define TLS_FALLBACK_SCSV 0x5600 /**< @see RFC 7507 */
617              
618             # define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
619             # define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
620             # define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /* 49161 */
621             # define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /* 49162 */
622             # define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
623             # define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /* 49171 */
624             # define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /* 49172 */
625             # define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
626             # define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
627             # define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /* 49187 */
628             # define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /* 49188 */
629             # define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
630             # define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
631             # define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /* 49191 */
632             # define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /* 49192 */
633             # define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
634             # define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
635             # define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /* 49195 */
636             # define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /* 49196 */
637             # define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
638             # define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
639             # define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /* 49199 */
640             # define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /* 49200 */
641             # define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
642             # define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
643             # ifdef CHACHA20POLY1305_IETF
644             /* Defined in https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305 */
645             # define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /* 52392 */
646             # define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /* 52393 */
647             # else
648             /* Defined in https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305 */
649             # define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCC13 /* 52243 */
650             # define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCC14 /* 52244 */
651             # endif
652              
653             /*
654             Supported HELLO extensions
655             Extension status stored by bitfield in ssl_t.extFlags
656             @see https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
657             */
658             # define EXT_SNI 0
659             # define EXT_MAX_FRAGMENT_LEN 1
660             # define EXT_TRUSTED_CA_KEYS 3
661             # define EXT_TRUNCATED_HMAC 4
662             # define EXT_STATUS_REQUEST 5 /* OCSP */
663             # define EXT_ELLIPTIC_CURVE 10 /* Client-send only */
664             # define EXT_ELLIPTIC_POINTS 11
665             # define EXT_SIGNATURE_ALGORITHMS 13
666             # define EXT_ALPN 16
667             # define EXT_SIGNED_CERTIFICATE_TIMESTAMP 18
668             # define EXT_EXTENDED_MASTER_SECRET 23
669             # define EXT_SESSION_TICKET 35
670             # define EXT_RENEGOTIATION_INFO 0xFF01
671              
672             /* How large the ALPN extension arrary is. Number of protos client can talk */
673             # define MAX_PROTO_EXT 8
674              
675             /*
676             Maximum key block size for any defined cipher
677             This must be validated if new ciphers are added
678             Value is largest total among all cipher suites for
679             2*macSize + 2*keySize + 2*ivSize
680             Rounded up to nearest PRF block length. We aren't really
681             rounding, but just adding another block length for simplicity.
682             */
683             # ifdef USE_TLS_1_2
684             # define SSL_MAX_KEY_BLOCK_SIZE ((2 * 48) + (2 * 32) + (2 * 16) + \
685             SHA256_HASH_SIZE)
686             # else
687             # define SSL_MAX_KEY_BLOCK_SIZE ((2 * 48) + (2 * 32) + (2 * 16) + \
688             SHA1_HASH_SIZE)
689             # endif
690             # ifdef USE_EAP_FAST
691             # define EAP_FAST_SESSION_KEY_SEED_LEN 40
692             # define EAP_FAST_PAC_KEY_LEN 32
693             # undef SSL_MAX_KEY_BLOCK_SIZE
694             # define SSL_MAX_KEY_BLOCK_SIZE ((2 * 48) + (2 * 32) + (2 * 16) + \
695             SHA256_HASH_SIZE + \
696             EAP_FAST_SESSION_KEY_SEED_LEN)
697             # endif
698              
699             /*
700             Master secret is 48 bytes, sessionId is 32 bytes max
701             */
702             # define SSL_HS_MASTER_SIZE 48
703             # define SSL_MAX_SESSION_ID_SIZE 32
704              
705             /*
706             TLS implementations supporting these ciphersuites MUST support
707             arbitrary PSK identities up to 128 octets in length, and arbitrary
708             PSKs up to 64 octets in length. Supporting longer identities and
709             keys is RECOMMENDED.
710             */
711             # define SSL_PSK_MAX_KEY_SIZE 64 /* Must be < 256 due to 'idLen' */
712             # define SSL_PSK_MAX_ID_SIZE 128 /* Must be < 256 due to 'idLen' */
713             # define SSL_PSK_MAX_HINT_SIZE 32 /* ServerKeyExchange hint is non-standard */
714              
715             # ifdef USE_DTLS
716             # define MAX_FRAGMENTS 16
717             # define PS_MIN_PMTU 256
718              
719             typedef struct
720             {
721             int32 offset;
722             int32 fragLen;
723             char *hsHeader;
724             } dtlsFragHdr_t;
725              
726             # ifndef USE_DTLS_DEBUG_TRACE
727             # define psTraceDtls(x)
728             # define psTraceIntDtls(x, y)
729             # define psTraceStrDtls(x, y)
730             # else
731             # define psTraceDtls(x) _psTrace(x)
732             # define psTraceIntDtls(x, y) _psTraceInt(x, y)
733             # define psTraceStrDtls(x, y) _psTraceStr(x, y)
734             # endif /* USE_DTLS_DEBUG_TRACE */
735              
736             # endif /* USE_DTLS */
737              
738              
739             # ifndef USE_SSL_HANDSHAKE_MSG_TRACE
740             # define psTraceHs(x)
741             # define psTraceStrHs(x, y)
742             # else
743             # define psTraceHs(x) _psTrace(x)
744             # define psTraceStrHs(x, y) _psTraceStr(x, y)
745             # endif /* USE_SSL_HANDSHAKE_MSG_TRACE */
746              
747             # ifndef USE_SSL_INFORMATIONAL_TRACE
748             # define psTraceInfo(x)
749             # define psTraceStrInfo(x, y)
750             # define psTraceIntInfo(x, y)
751             # else
752             # define psTraceInfo(x) _psTrace(x)
753             # define psTraceStrInfo(x, y) _psTraceStr(x, y)
754             # define psTraceIntInfo(x, y) _psTraceInt(x, y)
755             # endif /* USE_SSL_INFORMATIONAL_TRACE */
756              
757             /******************************************************************************/
758              
759             struct ssl;
760              
761             typedef psBuf_t sslBuf_t;
762              
763             /** Type of the expectedName parameter (expected peer identity)
764             that is passed to matrixValidateCerts or matrixSslNewClientSession.
765             These can be used to specify the field in the peer certificate
766             against which expectedName is to be matched. */
767             typedef enum
768             {
769             NAME_TYPE_ANY = 0, /* Default. Checked against everything listed below.
770             This option exists for compatibility with earlier
771             versions, where no attempt was made to distinguish
772             between different types of expectedNames.
773             New applications should prefer to pick one of the
774             more specific types below. */
775             NAME_TYPE_HOSTNAME, /* Checked against the dNSName field and the
776             subject commonName. This is the default. */
777             NAME_TYPE_CN, /* Checked against the subject commonName.
778             Note that by default, the subject commonName will only
779             be checked when there are no supported fields
780             in the SAN. The flag
781             VCERTS_MFLAG_ALWAYS_CHECK_SUBJECT_CN can be used
782             to force a commonName check. */
783             NAME_TYPE_SAN_DNS, /* Checked against the dNSName field. */
784             NAME_TYPE_SAN_EMAIL, /* Checked against the rfc822Name field. */
785             NAME_TYPE_SAN_IP_ADDRESS, /* Checked against the iPAddress field. */
786             } expectedNameType_t;
787              
788             /** This struct can be used to pass additional options
789             to matrixValidateCertsExt */
790             typedef struct
791             {
792             expectedNameType_t nameType; /* Type of expectedName. */
793             uint32_t flags; /* General flags for controling the validation
794             prodecure. The allowed flags have the
795             VCERTS_FLAG_ prefix. */
796             uint32_t mFlags; /* Flags for controlling how expectedName should
797             be matched. The allowed flags have the
798             USE VCERTS_MFLAG prefix. */
799             int32_t max_verify_depth; /* Maximum allowed depth for the peer's
800             cert chain. 0 : unrestricted,
801             1: only a single (self-signed) cert allowed,
802             2: peer cert + 1 root CA
803             3: peer cert + 1 CA + 1 root CA, etc. */
804             } matrixValidateCertsOptions_t;
805              
806             /* flags for matrixValidateCertsOptions_t: */
807             /*
808             Validate the expectedName argument against a subset of the
809             GeneralName rules for DNS, Email and IP types _before_ trying
810             to find for expectedName in the cert. Note that this is only
811             applicable if expectedName is a GeneralName, i.e. when using
812             any of the VCERTS_MFLAG_SAN flags.
813             */
814             # define VCERTS_FLAG_VALIDATE_EXPECTED_GENERAL_NAME 0x01
815              
816             /*
817             Skip the expectedName matching. This is useful e.g. when
818             matrixValidateCerts is called by the TLS server to validate
819             a client certificate. The client name is usually not known
820             in this case.
821             */
822             # define VCERTS_FLAG_SKIP_EXPECTED_NAME_VALIDATION 0x02
823              
824             /* mFlags for matrixValidateCertsOptions_t: */
825             /**
826             If expectedName is a hostname, always attempt to match it
827             with the subject CN, even if a supported, but non-matching
828             subjectAltName was presented.
829             Without this flag, the CN is checked only when no supported SAN
830             was presented. This default behaviour is in accordance with
831             Section 6.4.4 of RFC 6125, and this flag overrides it.
832             */
833             # define VCERTS_MFLAG_ALWAYS_CHECK_SUBJECT_CN 0x01
834              
835             /**
836             Use case-insensitive match for the the whole email address
837             in the rfc822Name field of the SAN. Without this flag,
838             case-sensitive matching is used for the local-part and
839             case-insensitive matching for the host-part, in accordance
840             with RFC 5280.
841             This flag requires VCERTS_MFLAG_SAN_MATCH_RFC822NAME.
842             */
843             # define VCERTS_MFLAG_SAN_EMAIL_CASE_INSENSITIVE_LOCAL_PART 0x02
844              
845             /******************************************************************************/
846              
847             # ifdef USE_PSK_CIPHER_SUITE
848             typedef struct psPsk
849             {
850             unsigned char *pskKey;
851             uint8_t pskLen;
852             unsigned char *pskId;
853             uint8_t pskIdLen;
854             struct psPsk *next;
855             } psPsk_t;
856             # endif /* USE_PSK_CIPHER_SUITE */
857              
858             typedef int32_t (*pskCb_t)(struct ssl *ssl,
859             const unsigned char pskId[SSL_PSK_MAX_ID_SIZE], uint8_t pskIdLen,
860             unsigned char *psk[SSL_PSK_MAX_KEY_SIZE], uint8_t *pskLen);
861              
862             # if defined(USE_SERVER_SIDE_SSL) && defined(USE_STATELESS_SESSION_TICKETS)
863             typedef int32 (*sslSessTicketCb_t)(void *keys, unsigned char[16], short);
864              
865             typedef struct sessTicketKey
866             {
867             unsigned char name[16];
868             unsigned char symkey[32];
869             unsigned char hashkey[32];
870             short nameLen, symkeyLen, hashkeyLen, inUse;
871             struct sessTicketKey *next;
872             } psSessionTicketKeys_t;
873             # endif
874              
875             /******************************************************************************/
876             /*
877             TLS authentication keys structures
878             */
879             # if defined(USE_ECC) || defined(REQUIRE_DH_PARAMS)
880             # define ECC_EPHEMERAL_CACHE_SECONDS (2 * 60 * 60) /**< Max lifetime in sec */
881             # ifdef NO_ECC_EPHEMERAL_CACHE
882             # define ECC_EPHEMERAL_CACHE_USAGE 0 /**< Cache not used */
883             # else
884             # define ECC_EPHEMERAL_CACHE_USAGE 1000 /**< Maximum use count of key */
885             # endif
886             typedef struct
887             {
888             # ifdef USE_MULTITHREADING
889             psMutex_t lock;
890             # endif
891             # ifdef USE_ECC
892             psEccKey_t eccPrivKey; /**< Cached ephemeral key */
893             psEccKey_t eccPubKey; /**< Cached remote ephemeral pub key */
894             psTime_t eccPrivKeyTime; /**< Time key was generated */
895             uint16_t eccPrivKeyUse; /**< Use count */
896             uint16_t eccPubKeyCurveId; /**< Curve the point is on */
897             unsigned char eccPubKeyRaw[132]; /**< Max size of secp521r1 */
898             # endif
899             # ifdef REQUIRE_DH_PARAMS
900             # endif
901             } ephemeralKeyCache_t;
902             # endif /* defined(USE_ECC) || defined(REQUIRE_DH_PARAMS) */
903              
904             typedef struct
905             {
906             psPool_t *pool;
907             # if defined(USE_SERVER_SIDE_SSL) || defined(USE_CLIENT_AUTH)
908             /* TODO - verify that the public part of the privKey is equal to the pubkey */
909             /* in the cert */
910             psPubKey_t privKey;
911             psX509Cert_t *cert;
912             # endif /* USE_SERVER_SIDE_SSL || USE_CLIENT_AUTH */
913             # if defined(USE_CLIENT_SIDE_SSL) || defined(USE_CLIENT_AUTH)
914             psX509Cert_t *CAcerts;
915             # endif /* USE_CLIENT_SIDE_SSL || USE_CLIENT_AUTH */
916             # ifdef REQUIRE_DH_PARAMS
917             psDhParams_t dhParams;
918             # endif /* REQUIRE_DH_PARAMS */
919             # ifdef USE_PSK_CIPHER_SUITE
920             psPsk_t *pskKeys;
921             # endif /* USE_PSK_CIPHER_SUITE */
922             # if defined(USE_SERVER_SIDE_SSL) && defined(USE_STATELESS_SESSION_TICKETS)
923             psSessionTicketKeys_t *sessTickets;
924             sslSessTicketCb_t ticket_cb;
925             # endif
926             # if defined(USE_OCSP) && defined(USE_SERVER_SIDE_SSL)
927             unsigned char *OCSPResponseBuf;
928             psSize_t OCSPResponseBufLen;
929             # endif
930             #if defined(USE_SCT) && defined(USE_SERVER_SIDE_SSL)
931             unsigned char *SCTResponseBuf;
932             uint16_t SCTResponseBufLen;
933             #endif
934             void *poolUserPtr; /* Data that will be given to psOpenPool
935             for any operations involving these keys */
936             # if defined(USE_ECC) || defined(REQUIRE_DH_PARAMS)
937             ephemeralKeyCache_t cache;
938             # endif
939             } sslKeys_t;
940              
941             /******************************************************************************/
942             /* Type to pass optional features to NewSession calls */
943             typedef struct
944             {
945             short ticketResumption; /* Client: 1 to use. Server N/A */
946             short maxFragLen; /* Client: 512 etc.. Server: -1 to disable */
947             short truncHmac; /* Client: 1 to use. Server: -1 to disable */
948             short extendedMasterSecret; /* On by default. -1 to disable */
949             short trustedCAindication; /* Client: 1 to use */
950             short fallbackScsv; /* Client: 1 to use */
951             # ifdef USE_OCSP
952             short OCSPstapling; /* Client: 1 to send status_request */
953             # endif
954             # ifdef USE_ECC
955             int32 ecFlags; /* Elliptic curve set (SSL_OPT_SECP192R1 etc.) */
956             # endif
957             # ifdef USE_EXT_CERTIFICATE_VERIFY_SIGNING
958             int32 useExtCvSigOp; /* Client: sign the handshake messages hash in
959             CertificateVerify externally. */
960             # endif /* USE_EXT_CERTIFICATE_VERIFY_SIGNING */
961             int32 versionFlag; /* The SSL_FLAGS_TLS_ version (+ DTLS flag here) */
962             #ifdef USE_CLIENT_SIDE_SSL
963             uint8_t clientRejectVersionDowngrade; /* Send SSL_ALERT_PROTOCOL_VERSION if server proposes
964             a lower version than what the client sent in the
965             ClientHello. Effectively, this ensures that only
966             the version in versionFlag can be negotiated. */
967             #endif /* USE_CLIENT_SIDE_SSL */
968             void *userPtr; /* Initial value of ssl->userPtr during NewSession */
969             void *memAllocPtr; /* Will be passed to psOpenPool for each call
970             related to this session */
971             psPool_t *bufferPool; /* Optional mem pool for inbuf and outbuf */
972             int32 keep_peer_cert_der; /* Keep raw DER of peer certs */
973             int32 keep_peer_certs; /* Keep peer cert chain until the session
974             is deleted */
975             matrixValidateCertsOptions_t validateCertsOpts; /* Certificate validation
976             options. */
977             void *userDataPtr; /* Initial value of ssl->userDataPtr during NewSession. */
978             } sslSessOpts_t;
979              
980             typedef struct
981             {
982             unsigned short keyType;
983             unsigned short hashAlg;
984             unsigned short curveFlags;
985             unsigned short dhParamsRequired;
986             char *serverName;
987             } sslPubkeyId_t;
988              
989             typedef sslKeys_t *(*pubkeyCb_t)(struct ssl *ssl, const sslPubkeyId_t *keyId);
990             typedef int32_t (*sslExtCb_t)(struct ssl *ssl, uint16_t extType, uint8_t extLen,
991             void *e);
992             typedef int32_t (*sslCertCb_t)(struct ssl *ssl, psX509Cert_t *cert, int32_t alert);
993              
994             # ifdef USE_OCSP
995             typedef int32_t (*ocspCb_t)(struct ssl *ssl, psOcspResponse_t *response,
996             psX509Cert_t *cert, int32_t status);
997             # endif
998              
999             /******************************************************************************/
1000             /*
1001             SSL record and session structures
1002             */
1003             typedef struct
1004             {
1005             unsigned short len;
1006             unsigned char majVer;
1007             unsigned char minVer;
1008             # ifdef USE_DTLS
1009             unsigned char epoch[2]; /* incoming epoch number */
1010             unsigned char rsn[6]; /* incoming record sequence number */
1011             # endif /* USE_DTLS */
1012             # ifdef USE_CERT_CHAIN_PARSING
1013             unsigned short hsBytesHashed;
1014             unsigned short hsBytesParsed;
1015             unsigned short trueLen;
1016             unsigned char partial;
1017             unsigned char certPad;
1018             # endif
1019             unsigned char type;
1020             unsigned char pad[3]; /* Padding for 64 bit compat */
1021             } sslRec_t;
1022              
1023             typedef struct
1024             {
1025             unsigned char clientRandom[SSL_HS_RANDOM_SIZE]; /* From ClientHello */
1026             unsigned char serverRandom[SSL_HS_RANDOM_SIZE]; /* From ServerHello */
1027             unsigned char masterSecret[SSL_HS_MASTER_SIZE];
1028             unsigned char *premaster; /* variable size */
1029             psSize_t premasterSize;
1030              
1031             unsigned char keyBlock[SSL_MAX_KEY_BLOCK_SIZE]; /* Storage for 'ptr' */
1032             # ifdef USE_NATIVE_TLS_ALGS
1033             unsigned char *wMACptr;
1034             unsigned char *rMACptr;
1035             unsigned char *wKeyptr;
1036             unsigned char *rKeyptr;
1037              
1038             /* All maximum sizes for current cipher suites */
1039             unsigned char writeMAC[SSL_MAX_MAC_SIZE];
1040             unsigned char readMAC[SSL_MAX_MAC_SIZE];
1041             unsigned char writeKey[SSL_MAX_SYM_KEY_SIZE];
1042             unsigned char readKey[SSL_MAX_SYM_KEY_SIZE];
1043             # endif
1044             unsigned char *wIVptr;
1045             unsigned char *rIVptr;
1046             unsigned char writeIV[SSL_MAX_IV_SIZE];
1047             unsigned char readIV[SSL_MAX_IV_SIZE];
1048             # ifdef USE_EAP_FAST
1049             unsigned char *eap_fast_session_key_seed;
1050             # endif
1051              
1052             unsigned char seq[8];
1053             unsigned char remSeq[8];
1054              
1055             pskCb_t pskCb;
1056              
1057             # ifndef USE_ONLY_PSK_CIPHER_SUITE
1058             pubkeyCb_t pubkeyCb;
1059             # if defined(USE_CLIENT_SIDE_SSL) || defined(USE_CLIENT_AUTH)
1060             psX509Cert_t *cert;
1061             sslCertCb_t validateCert;
1062             # endif /* USE_CLIENT_SIDE_SSL || USE_CLIENT_AUTH */
1063             # endif /* USE_ONLY_PSK_CIPHER_SUITE */
1064              
1065             # ifdef USE_CLIENT_SIDE_SSL
1066             int32 certMatch;
1067             # endif /* USE_CLIENT_SIDE_SSL */
1068              
1069             # ifdef USE_NATIVE_SYMMETRIC
1070             psCipherContext_t encryptCtx;
1071             psCipherContext_t decryptCtx;
1072             # endif
1073              
1074             # ifdef USE_NATIVE_TLS_HS_HASH
1075             # ifndef USE_ONLY_TLS_1_2
1076             psMd5Sha1_t msgHashMd5Sha1;
1077             # endif
1078             # endif
1079              
1080             # ifdef USE_TLS_1_2
1081             # ifdef USE_NATIVE_TLS_HS_HASH
1082             psSha256_t msgHashSha256;
1083              
1084             # ifdef USE_SHA1
1085             psSha1_t msgHashSha1;
1086             # endif
1087             # ifdef USE_SHA384
1088             psSha384_t msgHashSha384;
1089             # endif
1090             # ifdef USE_SHA512
1091             psSha512_t msgHashSha512;
1092             # endif
1093             # endif
1094             # endif /* USE_TLS_1_2 */
1095              
1096             # if defined(USE_SERVER_SIDE_SSL) && defined(USE_CLIENT_AUTH)
1097             unsigned char sha1Snapshot[SHA1_HASH_SIZE];
1098             unsigned char sha384Snapshot[SHA384_HASH_SIZE]; /* HW crypto uses
1099             outside TLS 1.2 */
1100             unsigned char sha512Snapshot[SHA512_HASH_SIZE];
1101             # endif
1102              
1103             # if defined(USE_PSK_CIPHER_SUITE) && defined(USE_CLIENT_SIDE_SSL)
1104             unsigned char *hint;
1105             uint8_t hintLen;
1106             # endif /* USE_PSK_CIPHER_SUITE && USE_CLIENT_SIDE_SSL */
1107              
1108             # ifdef REQUIRE_DH_PARAMS
1109             unsigned char *dhP; /* prime/modulus */
1110             unsigned char *dhG; /* base/generator */
1111             psSize_t dhPLen;
1112             psSize_t dhGLen;
1113             psDhKey_t *dhKeyPub; /* remote key */
1114             psDhKey_t *dhKeyPriv; /* local key */
1115             psPool_t *dhKeyPool; /* handshake-scope pool for clients */
1116             # endif
1117              
1118             # ifdef USE_ECC_CIPHER_SUITE
1119             psEccKey_t *eccKeyPriv; /* local key */
1120             psEccKey_t *eccKeyPub; /* remote key */
1121             psPool_t *eccDhKeyPool; /* handshake-scope pool for clients */
1122             # endif
1123              
1124             int32 anon;
1125             } sslSec_t;
1126              
1127             typedef struct
1128             {
1129             uint16_t ident; /* Official cipher ID */
1130             uint16_t type; /* Key exchange method */
1131             uint32_t flags; /* from CRYPTO_FLAGS_* */
1132             uint8_t macSize;
1133             uint8_t keySize;
1134             uint8_t ivSize;
1135             uint8_t blockSize;
1136             /* Init function */
1137             int32 (*init)(sslSec_t *sec, int32 type, uint32 keysize);
1138             /* Cipher functions */
1139             int32 (*encrypt)(void *ssl, unsigned char *in,
1140             unsigned char *out, uint32 len);
1141             int32 (*decrypt)(void *ssl, unsigned char *in,
1142             unsigned char *out, uint32 len);
1143             int32 (*generateMac)(void *ssl, unsigned char type, unsigned char *data,
1144             uint32 len, unsigned char *mac);
1145             int32 (*verifyMac)(void *ssl, unsigned char type, unsigned char *data,
1146             uint32 len, unsigned char *mac);
1147             } sslCipherSpec_t;
1148              
1149              
1150             # ifdef USE_STATELESS_SESSION_TICKETS
1151             enum sessionTicketState_e
1152             {
1153             SESS_TICKET_STATE_INIT = 0,
1154             # ifdef USE_EAP_FAST
1155             SESS_TICKET_STATE_EAP_FAST, /* Initialized with pre-provisioned key */
1156             # endif
1157             SESS_TICKET_STATE_SENT_EMPTY,
1158             SESS_TICKET_STATE_SENT_TICKET,
1159             SESS_TICKET_STATE_RECVD_EXT,
1160             SESS_TICKET_STATE_IN_LIMBO,
1161             SESS_TICKET_STATE_USING_TICKET
1162             };
1163             # endif
1164              
1165             /* Used by user code to store cached session info after the ssl_t is closed */
1166             typedef struct
1167             {
1168             psPool_t *pool;
1169             unsigned char id[SSL_MAX_SESSION_ID_SIZE];
1170             unsigned char masterSecret[SSL_HS_MASTER_SIZE];
1171             uint32 cipherId;
1172             # ifdef USE_STATELESS_SESSION_TICKETS
1173             unsigned char *sessionTicket; /* Duplicated into 'pool' */
1174             uint16 sessionTicketState; /* Not an enum to ensure 2 bytes */
1175             psSize_t sessionTicketLen; /* Max 32767 */
1176             uint32 sessionTicketLifetimeHint;
1177             # endif
1178             } sslSessionId_t;
1179              
1180             /* Used internally by the session cache table to store session parameters */
1181             typedef struct
1182             {
1183             unsigned char id[SSL_MAX_SESSION_ID_SIZE];
1184             unsigned char masterSecret[SSL_HS_MASTER_SIZE];
1185             const sslCipherSpec_t *cipher;
1186             unsigned char majVer;
1187             unsigned char minVer;
1188             short extendedMasterSecret; /* was the extension used? */
1189             psTime_t startTime;
1190             int32 inUse;
1191             DLListEntry chronList;
1192             } sslSessionEntry_t;
1193              
1194             /* Used by user code to define custom hello extensions */
1195             typedef struct tlsHelloExt
1196             {
1197             psPool_t *pool;
1198             int32 extType;
1199             uint32 extLen;
1200             unsigned char *extData;
1201             struct tlsHelloExt *next;
1202             } tlsExtension_t;
1203              
1204             /* Hold the info needed to perform a public key operation for flight writes
1205             until the very end. This is an architectural change that was added to aid
1206             the integration of non-blocking hardware acceleration */
1207             enum
1208             {
1209             PKA_AFTER_RSA_SIG_GEN_ELEMENT = 1,
1210             PKA_AFTER_RSA_SIG_GEN,
1211             PKA_AFTER_ECDSA_SIG_GEN,
1212             PKA_AFTER_RSA_ENCRYPT, /* standard RSA CKE operation */
1213             PKA_AFTER_ECDH_KEY_GEN, /* ECDH CKE operation. makeKey */
1214             PKA_AFTER_ECDH_SECRET_GEN, /* GenSecret */
1215             PKA_AFTER_ECDH_SECRET_GEN_DONE, /* Control for single-pass op */
1216             PKA_AFTER_DH_KEY_GEN /* DH CKE operation */
1217             };
1218              
1219             typedef struct
1220             {
1221             unsigned char *inbuf; /* allocated to handshake pool */
1222             unsigned char *outbuf;
1223             void *data; /* hw pkiData */
1224             psSize_t inlen;
1225             uint16_t type; /* one of PKA_AFTER_* */
1226             uint16_t user; /* user size */
1227             psPool_t *pool;
1228             } pkaAfter_t;
1229              
1230             typedef struct nextMsgInFlight
1231             {
1232             unsigned char *start;
1233             unsigned char *seqDelay;
1234             int32 len;
1235             int32 type;
1236             int32 messageSize;
1237             int32 padLen;
1238             int32 hsMsg;
1239             # ifdef USE_DTLS
1240             int32 fragCount;
1241             # endif
1242             struct nextMsgInFlight *next;
1243             } flightEncode_t;
1244              
1245             struct ssl
1246             {
1247             sslRec_t rec; /* Current SSL record information*/
1248              
1249             sslSec_t sec; /* Security structure */
1250              
1251             sslKeys_t *keys; /* SSL public and private keys */
1252              
1253             pkaAfter_t pkaAfter[2]; /* Cli-side cli-auth = two PKA in flight */
1254             # ifdef USE_EXT_CERTIFICATE_VERIFY_SIGNING
1255             uint8_t extCvSigOpInUse;
1256             uint8_t extCvSigOpPending;
1257             unsigned char *extCvHash;
1258             size_t extCvHashLen;
1259             unsigned char *extCvSig;
1260             size_t extCvSigLen;
1261             int32_t extCvSigAlg;
1262             unsigned char *extCvOrigFlightEnd;
1263             # endif /* USE_EXT_CERTIFICATE_VERIFY_SIGNING */
1264             flightEncode_t *flightEncode;
1265             unsigned char *delayHsHash;
1266             unsigned char *seqDelay; /* tmp until flightEncode_t is built */
1267              
1268             psPool_t *bufferPool; /* If user passed options.bufferPool to
1269             NewSession, this is inbuf and outbuf pool */
1270             psPool_t *sPool; /* SSL session pool */
1271             psPool_t *hsPool; /* Full session handshake pool */
1272             psPool_t *flightPool; /* Small but handy */
1273              
1274             unsigned char sessionIdLen;
1275             unsigned char sessionId[SSL_MAX_SESSION_ID_SIZE];
1276             sslSessionId_t *sid;
1277             char *expectedName; /* Clients: The expected cert subject name
1278             passed to NewClient Session
1279             Servers: Holds SNI value */
1280             # ifdef USE_SERVER_SIDE_SSL
1281             uint16 disabledCiphers[SSL_MAX_DISABLED_CIPHERS];
1282             void (*sni_cb)(void *ssl, char *hostname, int32 hostnameLen,
1283             sslKeys_t **newKeys);
1284             # ifdef USE_ALPN
1285             void (*srv_alpn_cb)(void *ssl, short protoCount,
1286             char *proto[MAX_PROTO_EXT],
1287             int32 protoLen[MAX_PROTO_EXT], int32 *index);
1288             char *alpn; /* proto user has agreed to use */
1289             int32 alpnLen;
1290             # endif /* USE_ALPN */
1291             # endif /* USE_SERVER_SIDE_SSL */
1292             # ifdef USE_CLIENT_SIDE_SSL
1293             /* Just to handle corner case of app data tacked on HELLO_REQUEST */
1294             int32 anonBk;
1295             int32 flagsBk;
1296             uint32 bFlagsBk;
1297             # endif /* USE_CLIENT_SIDE_SSL */
1298              
1299             # if defined(USE_HARDWARE_CRYPTO_RECORD) || defined (USE_HARDWARE_CRYPTO_PKA) || defined(USE_EXT_CERTIFICATE_VERIFY_SIGNING)
1300             uint32 hwflags; /* SSL_HWFLAGS_ */
1301             # endif
1302              
1303             unsigned char *inbuf;
1304             unsigned char *outbuf;
1305             int32 inlen; /* Bytes unprocessed in inbuf */
1306             int32 outlen; /* Bytes unsent in outbuf */
1307             int32 insize; /* Total allocated size of inbuf */
1308             int32 outsize; /* Total allocated size of outbuf */
1309             uint32 bFlags; /* Buffer related flags */
1310              
1311             int32 maxPtFrag; /* 16K by default - SSL_MAX_PLAINTEXT_LEN */
1312             unsigned char *fragMessage; /* holds the constructed fragmented message */
1313             uint32 fragIndex; /* How much data has been written to msg */
1314             uint32 fragTotal; /* Total length of fragmented message */
1315              
1316             /* Pointer to the negotiated cipher information */
1317             const sslCipherSpec_t *cipher;
1318              
1319             /* Symmetric cipher callbacks
1320              
1321             We duplicate these here from 'cipher' because we need to set the
1322             various callbacks at different times in the handshake protocol
1323             Also, there are 64 bit alignment issues in using the function pointers
1324             within 'cipher' directly
1325             */
1326             int32 (*encrypt)(void *ctx, unsigned char *in,
1327             unsigned char *out, uint32 len);
1328             int32 (*decrypt)(void *ctx, unsigned char *in,
1329             unsigned char *out, uint32 len);
1330             /* Message Authentication Codes */
1331             int32 (*generateMac)(void *ssl, unsigned char type, unsigned char *data,
1332             uint32 len, unsigned char *mac);
1333             int32 (*verifyMac)(void *ssl, unsigned char type, unsigned char *data,
1334             uint32 len, unsigned char *mac);
1335              
1336             /* Current encryption/decryption parameters */
1337             unsigned char enMacSize;
1338             unsigned char nativeEnMacSize; /* truncated hmac support */
1339             unsigned char enIvSize;
1340             unsigned char enBlockSize;
1341             unsigned char deMacSize;
1342             unsigned char nativeDeMacSize; /* truncated hmac support */
1343             unsigned char deIvSize;
1344             unsigned char deBlockSize;
1345              
1346             uint32_t flags; /* SSL_FLAGS_ */
1347             int32_t err; /* SSL errno of last api call */
1348             int32_t ignoredMessageCount;
1349              
1350             uint8_t hsState; /* Next expected SSL_HS_ message type */
1351             uint8_t decState; /* Most recent encoded SSL_HS_ message */
1352             uint8_t encState; /* Most recent decoded SSL_HS_ message */
1353             uint8_t reqMajVer;
1354             uint8_t reqMinVer;
1355             uint8_t majVer;
1356             uint8_t minVer;
1357             #ifdef USE_CLIENT_SIDE_SSL
1358             uint8_t clientRejectVersionDowngrade;
1359             #endif /* USE_CLIENT_SIDE_SSL */
1360             uint8_t outRecType;
1361              
1362             # ifdef ENABLE_SECURE_REHANDSHAKES
1363             unsigned char myVerifyData[SHA384_HASH_SIZE]; /*SSLv3 max*/
1364             unsigned char peerVerifyData[SHA384_HASH_SIZE];
1365             uint32 myVerifyDataLen;
1366             uint32 peerVerifyDataLen;
1367             int32 secureRenegotiationFlag;
1368             # endif /* ENABLE_SECURE_REHANDSHAKES */
1369             # ifdef SSL_REHANDSHAKES_ENABLED
1370             int32 rehandshakeCount; /* Make this an internal define of 1 */
1371             int32 rehandshakeBytes; /* Make this an internal define of 10MB */
1372             # endif /* SSL_REHANDSHAKES_ENABLED */
1373              
1374             sslExtCb_t extCb;
1375             # ifdef USE_ECC
1376             struct
1377             {
1378             uint32 ecFlags : 24;
1379             uint32 ecCurveId : 8;
1380             } ecInfo;
1381             # endif
1382             # ifdef USE_TLS_1_2
1383             uint16_t hashSigAlg;
1384             # endif
1385              
1386             # ifdef USE_DTLS
1387             # ifdef USE_SERVER_SIDE_SSL
1388             unsigned char srvCookie[DTLS_COOKIE_SIZE]; /* server can avoid allocs */
1389             # endif
1390             # ifdef USE_CLIENT_SIDE_SSL
1391             unsigned char *cookie; /* hello_verify_request cookie */
1392             int32 cookieLen; /* cookie length */
1393             int32 haveCookie; /* boolean for cookie existence */
1394             # endif
1395             unsigned char *helloExt; /* need to save the original client hello ext */
1396             int32 helloExtLen;
1397             unsigned char hsSnapshot[SHA512_HASH_SIZE]; /*SSLv3 max*/
1398             int32 hsSnapshotLen;
1399             psCipher16_t cipherSpec[8]; /* also needed for the cookie client hello */
1400             uint8_t cipherSpecLen;
1401             unsigned char epoch[2]; /* Current epoch number to send with msg */
1402             unsigned char resendEpoch[2]; /* Starting epoch to use for resends */
1403             unsigned char expectedEpoch[2]; /* Expected incoming epoch */
1404             unsigned char largestEpoch[2]; /* FINISH resends need to incr epoch */
1405             unsigned char rsn[6]; /* Last Record Sequence Number sent */
1406             unsigned char largestRsn[6]; /* Needed for resends of CCS flight */
1407             unsigned char lastRsn[6]; /* Last RSN received (for replay detection) */
1408             unsigned long dtlsBitmap; /* Record replay helper */
1409             int32 parsedCCS; /* Set between CCS parse and FINISHED parse */
1410             int32 msn; /* Current Message Sequence Number to send */
1411             int32 resendMsn; /* Starting MSN to use for resends */
1412             int32 lastMsn; /* Last MSN successfully parsed from peer */
1413             int32 pmtu; /* path maximum trasmission unit */
1414             int32 retransmit; /* Flag to know not to update handshake hash */
1415             uint16 flightDone; /* BOOL to flag when entire hs flight sent */
1416             uint16 appDataExch; /* BOOL to flag if in application data mode */
1417             int32 fragMsn; /* fragment MSN */
1418             dtlsFragHdr_t fragHeaders[MAX_FRAGMENTS]; /* header storage for hash */
1419             int32 (*oencrypt)(void *ctx, unsigned char *in,
1420             unsigned char *out, uint32 len);
1421             int32 (*ogenerateMac)(void *ssl, unsigned char type, unsigned char *data,
1422             uint32 len, unsigned char *mac);
1423             unsigned char oenMacSize;
1424             unsigned char oenNativeHmacSize;
1425             unsigned char oenIvSize;
1426             unsigned char oenBlockSize;
1427             unsigned char owriteIV[16]; /* GCM uses this in the nonce */
1428             # ifdef USE_NATIVE_TLS_ALGS
1429             unsigned char owriteMAC[SSL_MAX_MAC_SIZE];
1430             psCipherContext_t oencryptCtx;
1431             # endif
1432             # ifdef ENABLE_SECURE_REHANDSHAKES
1433             unsigned char omyVerifyData[SHA384_HASH_SIZE];
1434             uint32 omyVerifyDataLen;
1435             # endif /* ENABLE_SECURE_REHANDSHAKES */
1436             uint32 ckeSize;
1437             unsigned char *ckeMsg;
1438             unsigned char *certVerifyMsg;
1439             int32 certVerifyMsgLen;
1440             int ecdsaSizeChange; /* retransmits for ECDSA sig */
1441             # endif /* USE_DTLS */
1442              
1443             # ifdef USE_ZLIB_COMPRESSION
1444             int32 compression;
1445             z_stream inflate;
1446             z_stream deflate;
1447             unsigned char *zlibBuffer; /* scratch pad for inflate/deflate data */
1448             # endif
1449              
1450             struct
1451             {
1452             # ifdef USE_CLIENT_SIDE_SSL
1453             /* Did the client request the extension? */
1454             uint32 req_sni : 1;
1455             uint32 req_max_fragment_len : 1;
1456             uint32 req_truncated_hmac : 1;
1457             uint32 req_extended_master_secret : 1;
1458             uint32 req_elliptic_curve : 1;
1459             uint32 req_elliptic_points : 1;
1460             uint32 req_signature_algorithms : 1;
1461             uint32 req_alpn : 1;
1462             uint32 req_session_ticket : 1;
1463             uint32 req_renegotiation_info : 1;
1464             uint32 req_fallback_scsv : 1;
1465             uint32 req_status_request : 1;
1466             # endif
1467             # ifdef USE_SERVER_SIDE_SSL
1468             /* Whether the server will deny the extension */
1469             uint32 deny_truncated_hmac : 1;
1470             uint32 deny_max_fragment_len : 1;
1471             uint32 deny_session_ticket : 1;
1472             # endif
1473             /* Set if the extension was negotiated successfully */
1474             uint32 sni : 1;
1475             uint32 truncated_hmac : 1;
1476             uint32 extended_master_secret : 1;
1477             uint32 session_id : 1;
1478             uint32 session_ticket : 1;
1479             uint32 status_request : 1; /* received EXT_STATUS_REQUEST */
1480             uint32 status_request_v2 : 1; /* received EXT_STATUS_REQUEST_V2 */
1481             uint32 signed_certificate_timestamp: 1; /* received EXT_SIGNED_CERTIFICATE_TIMESTAMP */
1482             uint32 require_extended_master_secret : 1; /* peer may require */
1483             # ifdef USE_EAP_FAST
1484             uint32 eap_fast_master_secret : 1; /* Using eap_fast key derivation */
1485             # endif
1486             } extFlags; /**< Extension flags */
1487              
1488             # ifdef USE_MATRIX_OPENSSL_LAYER
1489             int (*verify_callback)(int alert, psX509Cert_t *data);
1490             # endif
1491             int32 recordHeadLen;
1492             int32 hshakeHeadLen;
1493             # ifdef USE_MATRIXSSL_STATS
1494             void (*statCb)(void *ssl, void *stats_ptr, int32 type, int32 value);
1495             void *statsPtr;
1496             # endif
1497             matrixValidateCertsOptions_t validateCertsOpts;
1498             void *memAllocPtr; /* Will be passed to psOpenPool for each call
1499             related to this session */
1500             void *userPtr;
1501             void *userDataPtr;
1502             };
1503              
1504             typedef struct ssl ssl_t;
1505              
1506             /******************************************************************************/
1507             /*
1508             Former public APIS in 1.x and 2.x. Now deprecated in 3.x
1509             These functions are still heavily used internally, just no longer publically
1510             supported.
1511             */
1512             extern int32 matrixSslDecode(ssl_t *ssl, unsigned char **buf, uint32 *len,
1513             uint32 size, uint32 *remaining, uint32 *requiredLen,
1514             int32 *error, unsigned char *alertLevel,
1515             unsigned char *alertDescription);
1516             extern int32 matrixSslEncode(ssl_t *ssl, unsigned char *buf, uint32 size,
1517             unsigned char *ptBuf, uint32 *len);
1518             extern int32 matrixSslGetEncodedSize(ssl_t *ssl, uint32 len);
1519             extern void matrixSslSetCertValidator(ssl_t *ssl, sslCertCb_t certValidator);
1520             extern int32 matrixSslNewSession(ssl_t **ssl, const sslKeys_t *keys,
1521             sslSessionId_t *session, sslSessOpts_t *options);
1522             extern void matrixSslSetSessionOption(ssl_t *ssl, int32 option, void *arg);
1523             extern int32_t matrixSslHandshakeIsComplete(const ssl_t *ssl);
1524              
1525             /* This used to be prefixed with 'matrix' */
1526             extern int32 sslEncodeClosureAlert(ssl_t *ssl, sslBuf_t *out,
1527             uint32 *reqLen);
1528              
1529             extern int32 matrixSslEncodeHelloRequest(ssl_t *ssl, sslBuf_t *out,
1530             uint32 *reqLen);
1531             extern int32_t matrixSslEncodeClientHello(ssl_t *ssl, sslBuf_t *out,
1532             const psCipher16_t cipherSpec[], uint8_t cipherSpecLen,
1533             uint32 *requiredLen, tlsExtension_t *userExt,
1534             sslSessOpts_t *options);
1535              
1536             # ifdef USE_CLIENT_SIDE_SSL
1537             extern int32 matrixSslGetSessionId(ssl_t *ssl, sslSessionId_t *sessionId);
1538             # endif /* USE_CLIENT_SIDE_SSL */
1539              
1540             # ifdef USE_SSL_INFORMATIONAL_TRACE
1541             extern void matrixSslPrintHSDetails(ssl_t *ssl);
1542             # endif /* USE_SSL_INFORMATIONAL_TRACE */
1543              
1544             # ifdef SSL_REHANDSHAKES_ENABLED
1545             PSPUBLIC int32 matrixSslGetRehandshakeCredits(ssl_t *ssl);
1546             PSPUBLIC void matrixSslAddRehandshakeCredits(ssl_t *ssl, int32 credits);
1547             # endif
1548              
1549             # ifdef USE_ZLIB_COMPRESSION
1550             PSPUBLIC int32 matrixSslIsSessionCompressionOn(ssl_t *ssl);
1551             # endif
1552              
1553             /******************************************************************************/
1554             /*
1555             MatrixSSL internal cert functions
1556             */
1557              
1558             # ifndef USE_ONLY_PSK_CIPHER_SUITE
1559             extern int32 matrixValidateCerts(psPool_t *pool, psX509Cert_t *subjectCerts,
1560             psX509Cert_t *issuerCerts, char *expectedName,
1561             psX509Cert_t **foundIssuer, void *pkiData, void *userPoolPtr);
1562             extern int32 matrixValidateCertsExt(psPool_t *pool, psX509Cert_t *subjectCerts,
1563             psX509Cert_t *issuerCerts, char *expectedName,
1564             psX509Cert_t **foundIssuer, void *pkiData, void *userPoolPtr,
1565             const matrixValidateCertsOptions_t *options);
1566             extern int32 matrixUserCertValidator(ssl_t *ssl, int32 alert,
1567             psX509Cert_t *subjectCert, sslCertCb_t certCb);
1568             # endif /* USE_ONLY_PSK_CIPHER_SUITE */
1569              
1570              
1571             /******************************************************************************/
1572             /*
1573             handshakeDecode.c and extensionDecode.c
1574             */
1575             # ifdef USE_SERVER_SIDE_SSL
1576             extern int32 parseClientHello(ssl_t *ssl, unsigned char **cp,
1577             unsigned char *end);
1578             extern int32 parseClientHelloExtensions(ssl_t *ssl, unsigned char **cp,
1579             unsigned short len);
1580             extern int32 parseClientKeyExchange(ssl_t *ssl, int32 hsLen, unsigned char **cp,
1581             unsigned char *end);
1582             # ifndef USE_ONLY_PSK_CIPHER_SUITE
1583             # ifdef USE_CLIENT_AUTH
1584             extern int32 parseCertificateVerify(ssl_t * ssl,
1585             unsigned char hsMsgHash[SHA512_HASH_SIZE], unsigned char **cp,
1586             unsigned char *end);
1587             # endif /* USE_CLIENT_AUTH */
1588             # endif /* !USE_ONLY_PSK_CIPHER_SUITE */
1589             # endif /* USE_SERVER_SIDE_SSL */
1590              
1591             # ifdef USE_CLIENT_SIDE_SSL
1592             extern int32 parseServerHello(ssl_t *ssl, int32 hsLen, unsigned char **cp,
1593             unsigned char *end);
1594             extern int32 parseServerHelloExtensions(ssl_t *ssl, int32 hsLen,
1595             unsigned char *extData, unsigned char **cp,
1596             unsigned short len);
1597             extern int32 parseServerHelloDone(ssl_t *ssl, int32 hsLen, unsigned char **cp,
1598             unsigned char *end);
1599             extern int32 parseServerKeyExchange(ssl_t * ssl,
1600             unsigned char hsMsgHash[SHA512_HASH_SIZE],
1601             unsigned char **cp, unsigned char *end);
1602             # ifdef USE_OCSP
1603             extern int32 parseCertificateStatus(ssl_t *ssl, int32 hsLen, unsigned char **cp,
1604             unsigned char *end);
1605             # endif
1606             # ifndef USE_ONLY_PSK_CIPHER_SUITE
1607             extern int32 parseCertificateRequest(ssl_t *ssl, int32 hsLen,
1608             unsigned char **cp, unsigned char *end);
1609             # endif
1610             # endif /* USE_CLIENT_SIDE_SSL */
1611              
1612             # ifndef USE_ONLY_PSK_CIPHER_SUITE
1613             # if defined(USE_CLIENT_SIDE_SSL) || defined(USE_CLIENT_AUTH)
1614             extern int32 parseCertificate(ssl_t *ssl, unsigned char **cp,
1615             unsigned char *end);
1616             # endif
1617             # endif
1618              
1619             extern int32 parseFinished(ssl_t * ssl, int32 hsLen,
1620             unsigned char hsMsgHash[SHA384_HASH_SIZE], unsigned char **cp,
1621             unsigned char *end);
1622              
1623             /******************************************************************************/
1624             /*
1625             sslEncode.c and sslDecode.c
1626             */
1627             extern int32 psWriteRecordInfo(ssl_t *ssl, unsigned char type, int32 len,
1628             unsigned char *c, int32 hsType);
1629             extern int32 psWriteHandshakeHeader(ssl_t *ssl, unsigned char type, int32 len,
1630             int32 seq, int32 fragOffset, int32 fragLen,
1631             unsigned char *c);
1632             extern int32 sslEncodeResponse(ssl_t *ssl, psBuf_t *out, uint32 *requiredLen);
1633             extern int32 sslActivateReadCipher(ssl_t *ssl);
1634             extern int32 sslActivateWriteCipher(ssl_t *ssl);
1635             extern int32_t sslUpdateHSHash(ssl_t *ssl, const unsigned char *in, psSize_t len);
1636             extern int32 sslInitHSHash(ssl_t *ssl);
1637             extern int32 sslSnapshotHSHash(ssl_t *ssl, unsigned char *out, int32 senderFlag);
1638             extern int32 sslWritePad(unsigned char *p, unsigned char padLen);
1639             extern int32 sslCreateKeys(ssl_t *ssl);
1640             extern void sslResetContext(ssl_t *ssl);
1641             extern void clearPkaAfter(ssl_t *ssl);
1642             extern pkaAfter_t *getPkaAfter(ssl_t *ssl);
1643             extern void freePkaAfter(ssl_t *ssl);
1644             extern void clearFlightList(ssl_t *ssl);
1645              
1646             # ifdef USE_SERVER_SIDE_SSL
1647             extern int32 matrixRegisterSession(ssl_t *ssl);
1648             extern int32 matrixResumeSession(ssl_t *ssl);
1649             extern int32 matrixClearSession(ssl_t *ssl, int32 remove);
1650             extern int32 matrixUpdateSession(ssl_t *ssl);
1651             extern int32 matrixServerSetKeysSNI(ssl_t *ssl, char *host, int32 hostLen);
1652              
1653             # ifdef USE_STATELESS_SESSION_TICKETS
1654             extern int32 matrixSessionTicketLen(void);
1655             extern int32 matrixCreateSessionTicket(ssl_t *ssl, unsigned char *out,
1656             int32 *outLen);
1657             extern int32 matrixUnlockSessionTicket(ssl_t *ssl, unsigned char *in,
1658             int32 inLen);
1659             extern int32 matrixSessionTicketLen(void);
1660             # endif
1661             # endif /* USE_SERVER_SIDE_SSL */
1662              
1663             # ifdef USE_DTLS
1664             extern int32 dtlsChkReplayWindow(ssl_t *ssl, unsigned char *seq64);
1665             extern int32 dtlsWriteCertificate(ssl_t *ssl, int32 certLen,
1666             int32 lsize, unsigned char *c);
1667             extern int32 dtlsWriteCertificateRequest(psPool_t *pool, ssl_t *ssl, int32 certLen,
1668             int32 certCount, int32 sigHashLen, unsigned char *c);
1669             extern int32 dtlsComputeCookie(ssl_t *ssl, unsigned char *helloBytes,
1670             int32 helloLen);
1671             extern void dtlsInitFrag(ssl_t *ssl);
1672             extern int32 dtlsSeenFrag(ssl_t *ssl, int32 fragOffset, int32 *hdrIndex);
1673             extern int32 dtlsHsHashFragMsg(ssl_t *ssl);
1674             extern int32 dtlsCompareEpoch(unsigned char *incoming, unsigned char *expected);
1675             extern void incrTwoByte(ssl_t *ssl, unsigned char *c, int sending);
1676             extern void zeroTwoByte(unsigned char *c);
1677             extern void dtlsIncrRsn(ssl_t *ssl);
1678             extern void zeroSixByte(unsigned char *c);
1679             extern int32 dtlsGenCookieSecret(void);
1680             extern int32 dtlsEncryptFragRecord(ssl_t *ssl, flightEncode_t *msg,
1681             sslBuf_t *out, unsigned char **c);
1682             # endif /* USE_DTLS */
1683              
1684             /*
1685             cipherSuite.c
1686             */
1687             extern int32 chooseCipherSuite(ssl_t *ssl, unsigned char *listStart,
1688             int32 listLen);
1689             extern const sslCipherSpec_t *sslGetDefinedCipherSpec(uint16_t id);
1690             extern const sslCipherSpec_t *sslGetCipherSpec(const ssl_t *ssl, uint16_t id);
1691             extern int32_t sslGetCipherSpecListLen(const ssl_t *ssl);
1692             extern int32_t sslGetCipherSpecList(ssl_t *ssl, unsigned char *c, int32 len,
1693             int32 addScsv);
1694             extern int32_t haveKeyMaterial(const ssl_t *ssl, int32 cipherType, short reallyTest);
1695             # ifdef USE_CLIENT_SIDE_SSL
1696             int32 csCheckCertAgainstCipherSuite(int32 sigAlg, int32 cipherType);
1697             # endif
1698             extern void matrixSslSetKexFlags(ssl_t *ssl);
1699              
1700             # ifndef DISABLE_SSLV3
1701             /******************************************************************************/
1702             /*
1703             sslv3.c
1704             */
1705             extern int32_t sslGenerateFinishedHash(psMd5Sha1_t *md,
1706             const unsigned char *masterSecret,
1707             unsigned char *out, int32 senderFlag);
1708              
1709             extern int32_t sslDeriveKeys(ssl_t *ssl);
1710              
1711             # ifdef USE_SHA_MAC
1712             extern int32 ssl3HMACSha1(unsigned char *key, unsigned char *seq,
1713             unsigned char type, unsigned char *data, uint32 len,
1714             unsigned char *mac);
1715             # endif /* USE_SHA_MAC */
1716              
1717             # ifdef USE_MD5_MAC
1718             extern int32 ssl3HMACMd5(unsigned char *key, unsigned char *seq,
1719             unsigned char type, unsigned char *data, uint32 len,
1720             unsigned char *mac);
1721             # endif /* USE_MD5_MAC */
1722             # endif /* DISABLE_SSLV3 */
1723              
1724             # ifdef USE_TLS
1725             /******************************************************************************/
1726             /*
1727             tls.c
1728             */
1729             extern int32 tlsDeriveKeys(ssl_t *ssl);
1730             extern int32 tlsExtendedDeriveKeys(ssl_t *ssl);
1731             extern int32 tlsHMACSha1(ssl_t *ssl, int32 mode, unsigned char type,
1732             unsigned char *data, uint32 len, unsigned char *mac);
1733              
1734             extern int32 tlsHMACMd5(ssl_t *ssl, int32 mode, unsigned char type,
1735             unsigned char *data, uint32 len, unsigned char *mac);
1736             # ifdef USE_SHA256
1737             extern int32 tlsHMACSha2(ssl_t *ssl, int32 mode, unsigned char type,
1738             unsigned char *data, uint32 len, unsigned char *mac,
1739             int32 hashSize);
1740             # endif
1741              
1742             /******************************************************************************/
1743              
1744             # ifdef USE_TLS_1_2
1745             # if defined(USE_SERVER_SIDE_SSL) && defined(USE_CLIENT_AUTH)
1746             extern int32 sslSha1RetrieveHSHash(ssl_t *ssl, unsigned char *out);
1747             # ifdef USE_SHA384
1748             extern int32 sslSha384RetrieveHSHash(ssl_t *ssl, unsigned char *out);
1749             # endif
1750             # ifdef USE_SHA512
1751             extern int32 sslSha512RetrieveHSHash(ssl_t *ssl, unsigned char *out);
1752             # endif
1753             # endif
1754             # ifdef USE_CLIENT_SIDE_SSL
1755             extern void sslSha1SnapshotHSHash(ssl_t *ssl, unsigned char *out);
1756             # ifdef USE_SHA384
1757             extern void sslSha384SnapshotHSHash(ssl_t *ssl, unsigned char *out);
1758             # endif
1759             # ifdef USE_SHA512
1760             extern void sslSha512SnapshotHSHash(ssl_t *ssl, unsigned char *out);
1761             # endif
1762             # endif
1763             # endif /* USE_TLS_1_2 */
1764              
1765             extern int32_t extMasterSecretSnapshotHSHash(ssl_t *ssl, unsigned char *out,
1766             uint32 *outLen);
1767              
1768             /******************************************************************************/
1769             /*
1770             prf.c
1771             */
1772             # if defined(USE_NATIVE_TLS_ALGS) || defined(USE_NATIVE_TLS_HS_HASH)
1773             extern int32_t prf(const unsigned char *sec, psSize_t secLen,
1774             const unsigned char *seed, psSize_t seedLen,
1775             unsigned char *out, psSize_t outLen);
1776             # ifdef USE_TLS_1_2
1777             extern int32_t prf2(const unsigned char *sec, psSize_t secLen,
1778             const unsigned char *seed, psSize_t seedLen,
1779             unsigned char *out, psSize_t outLen, uint32_t flags);
1780             # endif /* USE_TLS_1_2 */
1781             # endif /* USE_NATIVE_TLS_ALGS || USE_NATIVE_TLS_HS_HASH */
1782             # endif /* USE_TLS */
1783              
1784             # ifdef USE_AES_CIPHER_SUITE
1785             extern int32 csAesInit(sslSec_t *sec, int32 type, uint32 keysize);
1786             extern int32 csAesEncrypt(void *ssl, unsigned char *pt,
1787             unsigned char *ct, uint32 len);
1788             extern int32 csAesDecrypt(void *ssl, unsigned char *ct,
1789             unsigned char *pt, uint32 len);
1790             # ifdef USE_AES_GCM
1791             extern int32 csAesGcmInit(sslSec_t *sec, int32 type, uint32 keysize);
1792             extern int32 csAesGcmEncrypt(void *ssl, unsigned char *pt,
1793             unsigned char *ct, uint32 len);
1794             extern int32 csAesGcmDecrypt(void *ssl, unsigned char *ct,
1795             unsigned char *pt, uint32 len);
1796             # endif
1797             # endif /* USE_AES_CIPHER_SUITE */
1798             # ifdef USE_3DES_CIPHER_SUITE
1799             extern int32 csDes3Encrypt(void *ssl, unsigned char *pt,
1800             unsigned char *ct, uint32 len);
1801             extern int32 csDes3Decrypt(void *ssl, unsigned char *ct,
1802             unsigned char *pt, uint32 len);
1803             # endif /* USE_3DES_CIPHER_SUITE */
1804             # ifdef USE_ARC4_CIPHER_SUITE
1805             extern int32 csArc4Encrypt(void *ssl, unsigned char *pt, unsigned char *ct,
1806             uint32 len);
1807             extern int32 csArc4Decrypt(void *ssl, unsigned char *pt, unsigned char *ct,
1808             uint32 len);
1809             # endif /* USE_ARC4_CIPHER_SUITE */
1810             # ifdef USE_SEED_CIPHER_SUITE
1811             extern int32 csSeedEncrypt(void *ssl, unsigned char *pt,
1812             unsigned char *ct, uint32 len);
1813             extern int32 csSeedDecrypt(void *ssl, unsigned char *ct,
1814             unsigned char *pt, uint32 len);
1815             # endif /* USE_SEED_CIPHER_SUITE */
1816              
1817             # ifdef USE_IDEA_CIPHER_SUITE
1818             extern int32 csIdeaInit(sslSec_t *sec, int32 type, uint32 keysize);
1819             extern int32 csIdeaEncrypt(void *ssl, unsigned char *pt,
1820             unsigned char *ct, uint32 len);
1821             extern int32 csIdeaDecrypt(void *ssl, unsigned char *ct,
1822             unsigned char *pt, uint32 len);
1823             # endif /* USE_IDEA_CIPHER_SUITE */
1824              
1825             # ifdef USE_PSK_CIPHER_SUITE
1826              
1827             extern int32_t matrixSslPskGetKey(ssl_t * ssl,
1828             const unsigned char id[SSL_PSK_MAX_ID_SIZE], uint8_t idLen,
1829             unsigned char *key[SSL_PSK_MAX_KEY_SIZE], uint8_t * keyLen);
1830             extern int32_t matrixSslPskGetKeyId(ssl_t * ssl,
1831             unsigned char *id[SSL_PSK_MAX_ID_SIZE], uint8_t * idLen,
1832             const unsigned char hint[SSL_PSK_MAX_HINT_SIZE], uint8_t hintLen);
1833             extern int32_t matrixPskGetHint(ssl_t * ssl,
1834             unsigned char *hint[SSL_PSK_MAX_HINT_SIZE], uint8_t * hintLen);
1835             # endif /* USE_PSK_CIPHER_SUITE */
1836              
1837             # ifdef USE_ECC
1838             extern int32 psTestUserEcID(int32 id, int32 ecFlags);
1839             extern int32 curveIdToFlag(int32 id);
1840             # endif
1841              
1842             # ifdef USE_ECC_CIPHER_SUITE
1843             extern int32_t eccSuitesSupported(const ssl_t *ssl,
1844             const psCipher16_t cipherSpecs[], uint8_t cipherSpecLen);
1845             # endif /* USE_ECC_CIPHER_SUITE */
1846              
1847             # ifdef USE_EAP_FAST
1848             /******************************************************************************/
1849             extern void matrixSslSetSessionIdEapFast(sslSessionId_t *sess,
1850             const unsigned char *pac_key, psSize_t pac_key_len,
1851             const unsigned char *pac_opaque, psSize_t pac_opaque_len);
1852              
1853             extern int32_t matrixSslGetEapFastSKS(const ssl_t * ssl,
1854             unsigned char session_key_seed[EAP_FAST_SESSION_KEY_SEED_LEN]);
1855              
1856             extern int32_t tprf(const unsigned char *key, psSize_t keyLen,
1857             const unsigned char seed, psSize_t seedLen,
1858             unsigned char out[SSL_HS_MASTER_SIZE]);
1859             # endif
1860              
1861             /******************************************************************************/
1862             /* Deprected defines for compatibility */
1863             # define CH_RECV_STAT 1
1864             # define CH_SENT_STAT 2
1865             # define SH_RECV_STAT 3
1866             # define SH_SENT_STAT 4
1867             # define ALERT_SENT_STAT 5
1868             # define RESUMPTIONS_STAT 6
1869             # define FAILED_RESUMPTIONS_STAT 7
1870             # define APP_DATA_RECV_STAT 8
1871             # define APP_DATA_SENT_STAT 9
1872              
1873             # ifdef USE_MATRIXSSL_STATS
1874             extern void matrixsslUpdateStat(ssl_t *ssl, int32_t type, int32_t value);
1875             # else
1876             # ifdef __GNUC__
1877             static __inline
1878             void matrixsslUpdateStat(ssl_t *ssl __attribute__((__unused__)),
1879             int32_t type __attribute__((__unused__)),
1880             int32_t value __attribute__((__unused__)))
1881             {
1882             }
1883             # else
1884             static __inline
1885             void matrixsslUpdateStat(ssl_t *ssl, int32_t type, int32_t value)
1886             {
1887             }
1888             # endif
1889             # endif /* USE_MATRIXSSL_STATS */
1890              
1891             # ifdef __cplusplus
1892             }
1893             # endif
1894              
1895             #endif /* _h_MATRIXSSLLIB */
1896              
1897             /******************************************************************************/
1898