3 * Copyright (C) 2006-2012 Sawtooth Consulting Ltd.
5 * This file is part of CyaSSL.
7 * CyaSSL is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * CyaSSL is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
27 #include <cyassl/ssl.h>
28 #include <cyassl/crl.h>
29 #include <cyassl/ctaocrypt/types.h>
30 #include <cyassl/ctaocrypt/random.h>
31 #include <cyassl/ctaocrypt/des3.h>
32 #include <cyassl/ctaocrypt/hc128.h>
33 #include <cyassl/ctaocrypt/rabbit.h>
34 #include <cyassl/ctaocrypt/asn.h>
35 #include <cyassl/ctaocrypt/md5.h>
36 #include <cyassl/ctaocrypt/aes.h>
37 #include <cyassl/ctaocrypt/logging.h>
39 #include <cyassl/ctaocrypt/ecc.h>
42 #include <cyassl/ctaocrypt/sha256.h>
45 #include <cyassl/ocsp.h>
48 #ifdef CYASSL_CALLBACKS
49 #include <cyassl/openssl/cyassl_callbacks.h>
53 #ifdef USE_WINDOWS_API
54 #ifdef CYASSL_GAME_BUILD
55 #include "system/xtl.h"
57 #if defined(_WIN32_WCE) || defined(WIN32_LEAN_AND_MEAN)
58 /* On WinCE winsock2.h must be included before windows.h */
62 #if defined(FREERTOS_WINSIM) && !defined(SINGLE_THREADED)
67 #elif defined(THREADX)
68 #ifndef SINGLE_THREADED
71 #elif defined(MICRIUM)
72 /* do nothing, just don't pick Unix */
73 #elif defined(FREERTOS)
74 #ifndef SINGLE_THREADED
79 #ifndef SINGLE_THREADED
80 #define CYASSL_PTHREADS
83 #if defined(OPENSSL_EXTRA) || defined(GOAHEAD_WS)
84 #include <unistd.h> /* for close of BIO */
93 /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
94 #pragma warning(disable: 4996)
98 #if !defined (ALIGN16)
104 #define SHA256_DIGEST_SIZE 32
112 #ifdef USE_WINDOWS_API
113 typedef unsigned int SOCKET_T;
115 typedef int SOCKET_T;
119 typedef byte word24[3];
121 /* used by ssl.c and cyassl_int.c */
122 void c32to24(word32 in, word24 out);
124 /* Define or comment out the cipher suites you'd like to be compiled in
125 make sure to use at least one BUILD_SSL_xxx or BUILD_TLS_xxx is defined
127 When adding cipher suites, add name to cipher_names, idx to cipher_name_idx
130 #define BUILD_SSL_RSA_WITH_RC4_128_SHA
131 #define BUILD_SSL_RSA_WITH_RC4_128_MD5
132 #if !defined(NO_TLS) && defined(HAVE_NTRU)
133 #define BUILD_TLS_NTRU_RSA_WITH_RC4_128_SHA
138 #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
139 #if !defined(NO_TLS) && defined(HAVE_NTRU)
140 #define BUILD_TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA
144 #if !defined(NO_AES) && !defined(NO_TLS)
145 #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
146 #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
147 #if !defined (NO_PSK)
148 #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
149 #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
151 #if defined(HAVE_NTRU)
152 #define BUILD_TLS_NTRU_RSA_WITH_AES_128_CBC_SHA
153 #define BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA
155 #if !defined (NO_SHA256)
156 #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
157 #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
161 #if !defined(NO_HC128) && !defined(NO_TLS)
162 #define BUILD_TLS_RSA_WITH_HC_128_CBC_MD5
163 #define BUILD_TLS_RSA_WITH_HC_128_CBC_SHA
166 #if !defined(NO_RABBIT) && !defined(NO_TLS)
167 #define BUILD_TLS_RSA_WITH_RABBIT_CBC_SHA
170 #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && defined(OPENSSL_EXTRA)
171 #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
172 #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
173 #if !defined (NO_SHA256)
174 #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
175 #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
179 #if defined(HAVE_ECC) && !defined(NO_TLS)
181 #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
182 #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
183 #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
184 #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
186 #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
187 #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
188 #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
189 #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
192 #define BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
193 #define BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
195 #define BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
196 #define BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
198 #if !defined(NO_DES3)
199 #define BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
200 #define BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
202 #define BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
203 #define BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
208 #if defined(BUILD_SSL_RSA_WITH_RC4_128_SHA) || \
209 defined(BUILD_SSL_RSA_WITH_RC4_128_MD5)
213 #if defined(BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA)
217 #if defined(BUILD_TLS_RSA_WITH_AES_128_CBC_SHA) || \
218 defined(BUILD_TLS_RSA_WITH_AES_256_CBC_SHA)
222 #if defined(BUILD_TLS_RSA_WITH_HC_128_CBC_SHA) || \
223 defined(BUILD_TLS_RSA_WITH_HC_128_CBC_MD5)
227 #if defined(BUILD_TLS_RSA_WITH_RABBIT_CBC_SHA)
232 #define DES_BLOCK_SIZE 8
236 #define AES_BLOCK_SIZE 16
240 /* actual cipher values, 2nd byte */
242 TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x39,
243 TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x33,
244 TLS_RSA_WITH_AES_256_CBC_SHA = 0x35,
245 TLS_RSA_WITH_AES_128_CBC_SHA = 0x2F,
246 TLS_PSK_WITH_AES_256_CBC_SHA = 0x8d,
247 TLS_PSK_WITH_AES_128_CBC_SHA = 0x8c,
248 SSL_RSA_WITH_RC4_128_SHA = 0x05,
249 SSL_RSA_WITH_RC4_128_MD5 = 0x04,
250 SSL_RSA_WITH_3DES_EDE_CBC_SHA = 0x0A,
252 /* ECC suites, first byte is 0xC0 (ECC_BYTE) */
253 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0x14,
254 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0x13,
255 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0x0A,
256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0x09,
257 TLS_ECDHE_RSA_WITH_RC4_128_SHA = 0x11,
258 TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = 0x07,
259 TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x12,
260 TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x08,
262 /* static ECDH, first byte is 0xC0 (ECC_BYTE) */
263 TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = 0x0F,
264 TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = 0x0E,
265 TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = 0x05,
266 TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = 0x04,
267 TLS_ECDH_RSA_WITH_RC4_128_SHA = 0x0C,
268 TLS_ECDH_ECDSA_WITH_RC4_128_SHA = 0x02,
269 TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = 0x0D,
270 TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x03,
272 /* CyaSSL extension - eSTREAM */
273 TLS_RSA_WITH_HC_128_CBC_MD5 = 0xFB,
274 TLS_RSA_WITH_HC_128_CBC_SHA = 0xFC,
275 TLS_RSA_WITH_RABBIT_CBC_SHA = 0xFD,
277 /* CyaSSL extension - NTRU */
278 TLS_NTRU_RSA_WITH_RC4_128_SHA = 0xe5,
279 TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA = 0xe6,
280 TLS_NTRU_RSA_WITH_AES_128_CBC_SHA = 0xe7, /* clases w/ official SHA-256 */
281 TLS_NTRU_RSA_WITH_AES_256_CBC_SHA = 0xe8,
284 TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x6b,
285 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x67,
286 TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x3d,
287 TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x3c
295 ECC_BYTE = 0xC0, /* ECC first cipher suite byte */
300 DTLS_MAJOR = 0xfe, /* DTLS major version number */
301 DTLS_MINOR = 0xff, /* DTLS minor version number */
302 SSLv3_MAJOR = 3, /* SSLv3 and TLSv1+ major version number */
303 SSLv3_MINOR = 0, /* TLSv1 minor version number */
304 TLSv1_MINOR = 1, /* TLSv1 minor version number */
305 TLSv1_1_MINOR = 2, /* TLSv1_1 minor version number */
306 TLSv1_2_MINOR = 3, /* TLSv1_2 minor version number */
308 ZLIB_COMPRESSION = 221, /* CyaSSL zlib compression */
309 SECRET_LEN = 48, /* pre RSA and all master */
310 ENCRYPT_LEN = 512, /* allow 4096 bit static buffer */
311 SIZEOF_SENDER = 4, /* clnt or srvr */
312 FINISHED_SZ = MD5_DIGEST_SIZE + SHA_DIGEST_SIZE,
313 MAX_RECORD_SIZE = 16384, /* 2^14, max size by standard */
314 MAX_MSG_EXTRA = 68, /* max added to msg, mac + pad */
315 MAX_COMP_EXTRA = 1024, /* max compression extra */
316 MAX_MTU = 1500, /* max expected MTU */
317 MAX_UDP_SIZE = MAX_MTU - 100, /* don't exceed MTU w/ 100 byte header */
318 MAX_DH_SZ = 612, /* 2240 p, pub, g + 2 byte size for each */
319 MAX_STR_VERSION = 8, /* string rep of protocol version */
321 PAD_MD5 = 48, /* pad length for finished */
322 PAD_SHA = 40, /* pad length for finished */
323 PEM_LINE_LEN = 80, /* PEM line max + fudge */
324 LENGTH_SZ = 2, /* length field for HMAC, data only */
325 VERSION_SZ = 2, /* length of proctocol version */
326 SEQ_SZ = 8, /* 64 bit sequence number */
327 BYTE3_LEN = 3, /* up to 24 bit byte lengths */
328 ALERT_SIZE = 2, /* level + description */
329 REQUEST_HEADER = 2, /* always use 2 bytes */
330 VERIFY_HEADER = 2, /* always use 2 bytes */
331 MAX_DH_SIZE = 513, /* 4096 bit plus possible leading 0 */
333 MAX_SUITE_SZ = 200, /* 100 suites for now! */
334 RAN_LEN = 32, /* random length */
335 SEED_LEN = RAN_LEN * 2, /* tls prf seed length */
336 ID_LEN = 32, /* session id length */
337 MAX_COOKIE_LEN = 32, /* max dtls cookie size */
338 SUITE_LEN = 2, /* cipher suite sz length */
339 ENUM_LEN = 1, /* always a byte */
340 COMP_LEN = 1, /* compression length */
341 CURVE_LEN = 2, /* ecc named curve length */
343 HANDSHAKE_HEADER_SZ = 4, /* type + length(3) */
344 RECORD_HEADER_SZ = 5, /* type + version + len(2) */
345 CERT_HEADER_SZ = 3, /* always 3 bytes */
346 REQ_HEADER_SZ = 2, /* cert request header sz */
347 HINT_LEN_SZ = 2, /* length of hint size field */
349 DTLS_HANDSHAKE_HEADER_SZ = 12, /* normal + seq(2) + offset(3) + length(3) */
350 DTLS_RECORD_HEADER_SZ = 13, /* normal + epoch(2) + seq_num(6) */
351 DTLS_HANDSHAKE_EXTRA = 8, /* diff from normal */
352 DTLS_RECORD_EXTRA = 8, /* diff from normal */
354 FINISHED_LABEL_SZ = 15, /* TLS finished label size */
355 TLS_FINISHED_SZ = 12, /* TLS has a shorter size */
356 MASTER_LABEL_SZ = 13, /* TLS master secret label sz */
357 KEY_LABEL_SZ = 13, /* TLS key block expansion sz */
358 MAX_PRF_HALF = 128, /* Maximum half secret len */
359 MAX_PRF_LABSEED = 80, /* Maximum label + seed len */
360 MAX_PRF_DIG = 224, /* Maximum digest len */
361 MAX_REQUEST_SZ = 256, /* Maximum cert req len (no auth yet */
362 SESSION_FLUSH_COUNT = 256, /* Flush session cache unless user turns off */
364 RC4_KEY_SIZE = 16, /* always 128bit */
365 DES_KEY_SIZE = 8, /* des */
366 DES3_KEY_SIZE = 24, /* 3 des ede */
367 DES_IV_SIZE = DES_BLOCK_SIZE,
368 AES_256_KEY_SIZE = 32, /* for 256 bit */
369 AES_192_KEY_SIZE = 24, /* for 192 bit */
370 AES_IV_SIZE = 16, /* always block size */
371 AES_128_KEY_SIZE = 16, /* for 128 bit */
373 HC_128_KEY_SIZE = 16, /* 128 bits */
374 HC_128_IV_SIZE = 16, /* also 128 bits */
376 RABBIT_KEY_SIZE = 16, /* 128 bits */
377 RABBIT_IV_SIZE = 8, /* 64 bits for iv */
379 EVP_SALT_SIZE = 8, /* evp salt size 64 bits */
381 ECDHE_SIZE = 32, /* ECHDE server size defaults to 256 bit */
382 MAX_EXPORT_ECC_SZ = 256, /* Export ANS X9.62 max future size */
384 MAX_HELLO_SZ = 128, /* max client or server hello */
385 MAX_CERT_VERIFY_SZ = 1024, /* max */
386 CLIENT_HELLO_FIRST = 35, /* Protocol + RAN_LEN + sizeof(id_len) */
387 MAX_SUITE_NAME = 48, /* maximum length of cipher suite string */
388 DEFAULT_TIMEOUT = 500, /* default resumption timeout in seconds */
390 MAX_PSK_ID_LEN = 128, /* max psk identity/hint supported */
391 MAX_PSK_KEY_LEN = 64, /* max psk key supported */
394 MAX_EX_DATA = 3, /* allow for three items of ex_data */
395 MAX_CHAIN_DEPTH = 9, /* max cert chain peer depth, FORTRESS option */
397 MAX_CHAIN_DEPTH = 4, /* max cert chain peer depth */
399 MAX_X509_SIZE = 2048, /* max static x509 buffer size */
400 CERT_MIN_SIZE = 256, /* min PEM cert size with header/footer */
401 MAX_FILENAME_SZ = 256, /* max file name length */
402 FILE_BUFFER_SIZE = 1024, /* default static file buffer size for input,
403 will use dynamic buffer if not big enough */
405 MAX_NTRU_PUB_KEY_SZ = 1027, /* NTRU max for now */
406 MAX_NTRU_ENCRYPT_SZ = 1027, /* NTRU max for now */
407 MAX_NTRU_BITS = 256, /* max symmetric bit strength */
408 NO_SNIFF = 0, /* not sniffing */
409 SNIFF = 1, /* currently sniffing */
411 HASH_SIG_SIZE = 2, /* default SHA1 RSA */
413 NO_COPY = 0, /* should we copy static buffer for write */
414 COPY = 1 /* should we copy static buffer for write */
422 SERVER_HELLOVERIFYREQUEST_COMPLETE,
423 SERVER_HELLO_COMPLETE,
424 SERVER_CERT_COMPLETE,
425 SERVER_KEYEXCHANGE_COMPLETE,
426 SERVER_HELLODONE_COMPLETE,
427 SERVER_FINISHED_COMPLETE,
429 CLIENT_HELLO_COMPLETE,
430 CLIENT_KEYEXCHANGE_COMPLETE,
431 CLIENT_FINISHED_COMPLETE,
439 typedef struct ProtocolVersion {
445 CYASSL_LOCAL ProtocolVersion MakeSSLv3(void);
446 CYASSL_LOCAL ProtocolVersion MakeTLSv1(void);
447 CYASSL_LOCAL ProtocolVersion MakeTLSv1_1(void);
448 CYASSL_LOCAL ProtocolVersion MakeTLSv1_2(void);
451 CYASSL_LOCAL ProtocolVersion MakeDTLSv1(void);
463 /* CyaSSL BIO_METHOD type */
464 struct CYASSL_BIO_METHOD {
465 byte type; /* method type */
469 /* CyaSSL BIO type */
471 byte type; /* method type */
472 byte close; /* close flag */
473 byte eof; /* eof flag */
474 CYASSL* ssl; /* possible associated ssl */
475 byte* mem; /* memory buffer */
476 int memLen; /* memory buffer length */
477 int fd; /* possible file descriptor */
478 CYASSL_BIO* prev; /* previous in chain */
479 CYASSL_BIO* next; /* next in chain */
483 /* CyaSSL method type */
484 struct CYASSL_METHOD {
485 ProtocolVersion version;
486 byte side; /* connection side, server or client */
487 byte verifyPeer; /* request or send certificate */
488 byte verifyNone; /* whether to verify certificate */
489 byte failNoCert; /* fail if no certificate */
490 byte downgrade; /* whether to downgrade version, default no */
494 /* defautls to client */
495 CYASSL_LOCAL void InitSSL_Method(CYASSL_METHOD*, ProtocolVersion);
498 CYASSL_LOCAL int DoFinished(CYASSL* ssl, const byte* input, word32* inOutIdx,
500 CYASSL_LOCAL int DoApplicationData(CYASSL* ssl, byte* input, word32* inOutIdx);
503 /* CyaSSL buffer type */
504 typedef struct buffer {
516 /* only use compression extra if using compression */
518 #define COMP_EXTRA MAX_COMP_EXTRA
523 /* only the sniffer needs space in the buffer for an extra MTU record */
524 #ifdef CYASSL_SNIFFER
525 #define MTU_EXTRA MAX_MTU
530 /* give user option to use 16K static buffers, sniffer needs them too */
531 #if defined(LARGE_STATIC_BUFFERS) || defined(CYASSL_SNIFFER)
532 #define RECORD_SIZE MAX_RECORD_SIZE
535 #define RECORD_SIZE MAX_MTU
537 #define RECORD_SIZE 128
542 /* user option to turn off 16K output option */
543 /* if using small static buffers (default) and SSL_write tries to write data
544 larger than the record we have, dynamically get it, unless user says only
545 write in static buffer chuncks */
546 #ifndef STATIC_CHUNKS_ONLY
547 #define OUTPUT_RECORD_SIZE MAX_RECORD_SIZE
549 #define OUTPUT_RECORD_SIZE RECORD_SIZE
552 /* CyaSSL input buffer
557 The length (in bytes) of the following TLSPlaintext.fragment.
558 The length should not exceed 2^14.
560 #define STATIC_BUFFER_LEN RECORD_HEADER_SZ + RECORD_SIZE + COMP_EXTRA + \
561 MTU_EXTRA + MAX_MSG_EXTRA
564 word32 length; /* total buffer length used */
565 word32 idx; /* idx to part of length already consumed */
566 byte* buffer; /* place holder for static or dynamic buffer */
567 ALIGN16 byte staticBuffer[STATIC_BUFFER_LEN];
568 word32 bufferSize; /* current buffer size */
569 byte dynamicFlag; /* dynamic memory currently in use */
572 /* Cipher Suites holder */
573 typedef struct Suites {
574 int setSuites; /* user set suites from default */
575 byte suites[MAX_SUITE_SZ];
576 word16 suiteSz; /* suite length in bytes */
581 void InitSuites(Suites*, ProtocolVersion, byte, byte, byte, byte, byte, int);
583 int SetCipherList(Suites*, const char* list);
585 #ifndef PSK_TYPES_DEFINED
586 typedef unsigned int (*psk_client_callback)(CYASSL*, const char*, char*,
587 unsigned int, unsigned char*, unsigned int);
588 typedef unsigned int (*psk_server_callback)(CYASSL*, const char*,
589 unsigned char*, unsigned int);
590 #endif /* PSK_TYPES_DEFINED */
593 #ifndef CYASSL_USER_IO
594 /* default IO callbacks */
596 int EmbedReceive(char *buf, int sz, void *ctx);
598 int EmbedSend(char *buf, int sz, void *ctx);
607 /* CyaSSL Cipher type just points back to SSL */
608 struct CYASSL_CIPHER {
613 #ifdef SINGLE_THREADED
614 typedef int CyaSSL_Mutex;
615 #else /* MULTI_THREADED */
616 /* Comes first to enable use of FreeRTOS Windows simulator only. */
618 typedef xSemaphoreHandle CyaSSL_Mutex;
619 #elif defined(USE_WINDOWS_API)
620 typedef CRITICAL_SECTION CyaSSL_Mutex;
621 #elif defined(CYASSL_PTHREADS)
622 typedef pthread_mutex_t CyaSSL_Mutex;
623 #elif defined(THREADX)
624 typedef TX_MUTEX CyaSSL_Mutex;
625 #elif defined(MICRIUM)
626 typedef OS_MUTEX CyaSSL_Mutex;
628 #error Need a mutex type in multithreaded mode
629 #endif /* USE_WINDOWS_API */
630 #endif /* SINGLE_THREADED */
632 CYASSL_LOCAL int InitMutex(CyaSSL_Mutex*);
633 CYASSL_LOCAL int FreeMutex(CyaSSL_Mutex*);
634 CYASSL_LOCAL int LockMutex(CyaSSL_Mutex*);
635 CYASSL_LOCAL int UnLockMutex(CyaSSL_Mutex*);
639 typedef struct CRL_Entry CRL_Entry;
643 CRL_Entry* next; /* next entry */
644 byte issuerHash[SHA_DIGEST_SIZE]; /* issuer hash */
645 byte crlHash[MD5_DIGEST_SIZE]; /* raw crl data hash */
646 byte lastDate[MAX_DATE_SIZE]; /* last date updated */
647 byte nextDate[MAX_DATE_SIZE]; /* next update date */
648 RevokedCert* certs; /* revoked cert list */
649 int totalCerts; /* number on list */
653 /* CyaSSL CRL controller */
655 CYASSL_CERT_MANAGER* cm; /* pointer back to cert manager */
656 CRL_Entry* crlList; /* our CRL list */
657 CyaSSL_Mutex crlLock; /* CRL list lock */
661 /* CyaSSL Certificate Manager */
662 struct CYASSL_CERT_MANAGER {
663 Signer* caList; /* the CA signer list */
664 CyaSSL_Mutex caLock; /* CA list lock */
665 CallbackCACache caCacheCallback; /* CA cache addition callback */
666 void* heap; /* heap helper */
667 CYASSL_CRL* crl; /* CRL checker */
668 byte crlEnabled; /* is CRL on ? */
669 byte crlCheckAll; /* always leaf, but all ? */
670 CbMissingCRL cbMissingCRL; /* notify through cb of missing crl */
674 /* CyaSSL context type */
676 CYASSL_METHOD* method;
677 CyaSSL_Mutex countMutex; /* reference count mutex */
678 int refCount; /* reference count */
681 /* chain after self, in DER, with leading size for each cert */
685 CYASSL_CERT_MANAGER* cm; /* our cert manager, ctx owns SSL will use */
687 void* heap; /* for user memory overrides */
691 byte sessionCacheOff;
692 byte sessionCacheFlushOff;
693 byte sendVerify; /* for client side */
694 byte haveDH; /* server DH parms set by user */
695 byte haveNTRU; /* server private NTRU key loaded */
696 byte haveECDSA; /* server cert signed w/ ECDSA loaded */
697 byte haveStaticECC; /* static server ECC private key */
698 byte partialWrite; /* only one msg per write call */
699 byte quietShutdown; /* don't send close notify */
700 byte groupMessages; /* group handshake messages before sending */
701 CallbackIORecv CBIORecv;
702 CallbackIOSend CBIOSend;
703 VerifyCallback verifyCallback; /* cert verification callback */
704 word32 timeout; /* session timeout */
706 word16 eccTempKeySz; /* in octets 20 - 66 */
709 byte havePSK; /* psk key set by user */
710 psk_client_callback client_psk_cb; /* client callback */
711 psk_server_callback server_psk_cb; /* server callback */
712 char server_hint[MAX_PSK_ID_LEN];
714 #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
715 pem_password_cb passwd_cb;
717 #endif /* OPENSSL_EXTRA */
725 int InitSSL_Ctx(CYASSL_CTX*, CYASSL_METHOD*);
727 void FreeSSL_Ctx(CYASSL_CTX*);
729 void SSL_CtxResourceFree(CYASSL_CTX*);
732 int DeriveTlsKeys(CYASSL* ssl);
734 int ProcessOldClientHello(CYASSL* ssl, const byte* input, word32* inOutIdx,
735 word32 inSz, word16 sz);
737 int AddCA(CYASSL_CERT_MANAGER* ctx, buffer der, int type, int verify);
739 int AlreadySigner(CYASSL_CERT_MANAGER* cm, byte* hash);
741 /* All cipher suite related info */
742 typedef struct CipherSpecs {
743 byte bulk_cipher_algorithm;
744 byte cipher_type; /* block or stream */
746 byte kea; /* key exchange algo */
758 /* Supported Ciphers from page 43 */
759 enum BulkCipherAlgorithm {
764 triple_des, /* leading 3 (3des) not valid identifier */
768 hc128, /* CyaSSL extensions */
773 /* Supported Message Authentication Codes from page 43 */
786 /* Supported Key Exchange Protocols */
787 enum KeyExchangeAlgorithm {
794 ecc_diffie_hellman_kea
798 /* Supported Authentication Schemes */
799 enum SignatureAlgorithm {
800 anonymous_sa_algo = 0,
807 /* Supprted ECC Curve Types */
813 /* Supprted ECC Named Curves */
814 enum EccNamedCurves {
815 secp256r1 = 0x17, /* default, OpenSSL also calls it prime256v1 */
820 secp192r1 = 0x13, /* Openssl also call it prime192v1 */
825 /* Valid client certificate request types from page 27 */
826 enum ClientCertificateType {
831 rsa_ephemeral_dh = 5,
832 dss_ephemeral_dh = 6,
833 fortezza_kea_cert = 20
837 enum CipherType { stream, block };
840 /* keys and secrets */
841 typedef struct Keys {
842 byte client_write_MAC_secret[SHA256_DIGEST_SIZE]; /* max sizes */
843 byte server_write_MAC_secret[SHA256_DIGEST_SIZE];
844 byte client_write_key[AES_256_KEY_SIZE]; /* max sizes */
845 byte server_write_key[AES_256_KEY_SIZE];
846 byte client_write_IV[AES_IV_SIZE]; /* max sizes */
847 byte server_write_IV[AES_IV_SIZE];
849 word32 peer_sequence_number;
850 word32 sequence_number;
853 word32 dtls_sequence_number;
854 word32 dtls_peer_sequence_number;
855 word16 dtls_handshake_number;
857 word16 dtls_peer_epoch;
860 word32 encryptSz; /* last size of encrypted data */
861 byte encryptionOn; /* true after change cipher spec */
886 typedef struct Hashes {
887 byte md5[MD5_DIGEST_SIZE];
888 byte sha[SHA_DIGEST_SIZE];
892 /* Static x509 buffer */
893 typedef struct x509_buffer {
894 int length; /* actual size */
895 byte buffer[MAX_X509_SIZE]; /* max static cert size */
899 /* CyaSSL X509_CHAIN, for no dynamic memory SESSION_CACHE */
900 struct CYASSL_X509_CHAIN {
901 int count; /* total number in chain */
902 x509_buffer certs[MAX_CHAIN_DEPTH]; /* only allow max depth 4 for now */
906 /* CyaSSL session type */
907 struct CYASSL_SESSION {
908 byte sessionID[ID_LEN];
909 byte masterSecret[SECRET_LEN];
910 word32 bornOn; /* create time in seconds */
911 word32 timeout; /* timeout in seconds */
913 CYASSL_X509_CHAIN chain; /* peer cert chain, static */
914 ProtocolVersion version;
915 byte cipherSuite0; /* first byte, normally 0 */
916 byte cipherSuite; /* 2nd byte, actual suite */
922 CYASSL_SESSION* GetSession(CYASSL*, byte*);
924 int SetSession(CYASSL*, CYASSL_SESSION*);
926 typedef void (*hmacfp) (CYASSL*, byte*, const byte*, word32, int, int);
929 /* client connect state for nonblocking restart */
933 HELLO_AGAIN, /* HELLO_AGAIN s for DTLS case */
945 /* server accept state for nonblocking restart */
948 ACCEPT_CLIENT_HELLO_DONE,
950 ACCEPT_FIRST_REPLY_DONE,
956 ACCEPT_SECOND_REPLY_DONE,
958 ACCEPT_FINISHED_DONE,
959 ACCEPT_THIRD_REPLY_DONE
963 typedef struct Buffers {
964 buffer certificate; /* CYASSL_CTX owns, unless we own */
965 buffer key; /* CYASSL_CTX owns, unless we own */
966 buffer certChain; /* CYASSL_CTX owns */
967 /* chain after self, in DER, with leading size for each cert */
968 buffer domainName; /* for client check */
969 buffer serverDH_P; /* CYASSL_CTX owns, unless we own */
970 buffer serverDH_G; /* CYASSL_CTX owns, unless we own */
972 buffer serverDH_Priv;
973 bufferStatic inputBuffer;
974 bufferStatic outputBuffer;
975 buffer clearOutputBuffer;
976 int prevSent; /* previous plain text bytes sent
977 when got WANT_WRITE */
978 int plainSz; /* plain text bytes in buffer to send
979 when got WANT_WRITE */
980 byte weOwnCert; /* SSL own cert flag */
981 byte weOwnKey; /* SSL own key flag */
982 byte weOwnDH; /* SSL own dh (p,g) flag */
986 typedef struct Options {
987 byte sessionCacheOff;
988 byte sessionCacheFlushOff;
989 byte cipherSuite0; /* first byte, normally 0 */
990 byte cipherSuite; /* second byte, actual suite */
994 byte side; /* client or server end */
998 byte downgrade; /* allow downgrade of versions */
999 byte sendVerify; /* false = 0, true = 1, sendBlank = 2 */
1001 byte haveSessionId; /* server may not send */
1002 byte tls; /* using TLS ? */
1003 byte tls1_1; /* using TLSv1.1+ ? */
1004 byte dtls; /* using datagrams ? */
1005 byte connReset; /* has the peer reset */
1006 byte isClosed; /* if we consider conn closed */
1007 byte closeNotify; /* we've recieved a close notify */
1008 byte sentNotify; /* we've sent a close notify */
1009 byte connectState; /* nonblocking resume */
1010 byte acceptState; /* nonblocking resume */
1011 byte usingCompression; /* are we using compression */
1012 byte haveDH; /* server DH parms set by user */
1013 byte haveNTRU; /* server NTRU private key loaded */
1014 byte haveECDSA; /* server ECDSA signed cert */
1015 byte haveStaticECC; /* static server ECC private key */
1016 byte havePeerCert; /* do we have peer's cert */
1017 byte usingPSK_cipher; /* whether we're using psk as cipher */
1018 byte sendAlertState; /* nonblocking resume */
1019 byte processReply; /* nonblocking resume */
1020 byte partialWrite; /* only one msg per write call */
1021 byte quietShutdown; /* don't send close notify */
1022 byte certOnly; /* stop once we get cert */
1023 byte groupMessages; /* group handshake messages */
1025 byte havePSK; /* psk key set by user */
1026 psk_client_callback client_psk_cb;
1027 psk_server_callback server_psk_cb;
1032 typedef struct Arrays {
1033 byte clientRandom[RAN_LEN];
1034 byte serverRandom[RAN_LEN];
1035 byte sessionID[ID_LEN];
1036 byte preMasterSecret[ENCRYPT_LEN];
1037 byte masterSecret[SECRET_LEN];
1039 byte cookie[MAX_COOKIE_LEN];
1042 char client_identity[MAX_PSK_ID_LEN];
1043 char server_hint[MAX_PSK_ID_LEN];
1044 byte psk_key[MAX_PSK_KEY_LEN];
1045 word32 psk_keySz; /* acutal size */
1047 word32 preMasterSz; /* differs for DH, actual size */
1051 struct CYASSL_X509_NAME {
1052 char name[ASN_NAME_MAX];
1057 struct CYASSL_X509 {
1058 CYASSL_X509_NAME issuer;
1059 CYASSL_X509_NAME subject;
1061 byte serial[EXTERNAL_SERIAL_SIZE];
1062 char subjectCN[ASN_NAME_MAX]; /* common name short cut */
1063 buffer derCert; /* may need */
1067 /* record layer header for PlainText, Compressed, and CipherText */
1068 typedef struct RecordLayerHeader {
1070 ProtocolVersion version;
1072 } RecordLayerHeader;
1075 /* record layer header for DTLS PlainText, Compressed, and CipherText */
1076 typedef struct DtlsRecordLayerHeader {
1078 ProtocolVersion version;
1079 byte epoch[2]; /* increment on cipher state change */
1080 byte sequence_number[6]; /* per record */
1082 } DtlsRecordLayerHeader;
1085 /* CyaSSL ssl type */
1089 ProtocolVersion version; /* negotiated version */
1090 ProtocolVersion chVersion; /* client hello version */
1096 int rfd; /* read file descriptor */
1097 int wfd; /* write file descriptor */
1098 CYASSL_BIO* biord; /* socket bio read to free/close */
1099 CYASSL_BIO* biowr; /* socket bio write to free/close */
1101 void* IOCB_WriteCtx;
1103 Md5 hashMd5; /* md5 hash of handshake msgs */
1104 Sha hashSha; /* sha hash of handshake msgs */
1106 Sha256 hashSha256; /* sha256 hash of handshake msgs */
1108 Hashes verifyHashes;
1109 Hashes certHashes; /* for cert verify */
1113 CYASSL_SESSION session;
1114 VerifyCallback verifyCallback; /* cert verification callback */
1116 byte peerRsaKeyPresent;
1118 word16 peerNtruKeyLen;
1119 byte peerNtruKey[MAX_NTRU_PUB_KEY_SZ];
1120 byte peerNtruKeyPresent;
1123 ecc_key peerEccKey; /* peer's ECDHE key */
1124 ecc_key peerEccDsaKey; /* peer's ECDSA key */
1125 ecc_key eccTempKey; /* private ECDHE key */
1126 ecc_key eccDsaKey; /* private ECDSA key */
1127 word16 eccTempKeySz; /* in octets 20 - 66 */
1128 byte peerEccKeyPresent;
1129 byte peerEccDsaKeyPresent;
1130 byte eccTempKeyPresent;
1131 byte eccDsaKeyPresent;
1134 void* heap; /* for user overrides */
1135 RecordLayerHeader curRL;
1137 word32 timeout; /* session timeout */
1138 CYASSL_CIPHER cipher;
1140 z_stream c_stream; /* compression stream */
1141 z_stream d_stream; /* decompression stream */
1142 byte didStreamInit; /* for stream init and end */
1144 #ifdef CYASSL_CALLBACKS
1145 HandShakeInfo handShakeInfo; /* info saved during handshake */
1146 TimeoutInfo timeoutInfo; /* info saved during handshake */
1147 byte hsInfoOn; /* track handshake info */
1148 byte toInfoOn; /* track timeout info */
1150 #ifdef OPENSSL_EXTRA
1151 CYASSL_X509 peerCert; /* X509 peer cert */
1154 void* ex_data[MAX_EX_DATA]; /* external data, for Fortress */
1160 int InitSSL(CYASSL*, CYASSL_CTX*);
1162 void FreeSSL(CYASSL*);
1163 CYASSL_API void SSL_ResourceFree(CYASSL*); /* Micrium uses */
1167 IV_SZ = 32, /* max iv sz */
1168 NAME_SZ = 80, /* max one line */
1172 typedef struct EncryptedInfo {
1173 char name[NAME_SZ]; /* encryption name */
1174 byte iv[IV_SZ]; /* encrypted IV */
1175 word32 ivSz; /* encrypted IV size */
1176 long consumed; /* tracks PEM bytes consumed */
1177 byte set; /* if encryption set */
1178 CYASSL_CTX* ctx; /* CTX owner */
1181 CYASSL_LOCAL int PemToDer(const unsigned char* buff, long sz, int type,
1182 buffer* der, void* heap, EncryptedInfo* info,
1185 CYASSL_LOCAL int ProcessFile(CYASSL_CTX* ctx, const char* fname, int format,
1186 int type, CYASSL* ssl, int userChain,
1190 #ifdef CYASSL_CALLBACKS
1192 void InitHandShakeInfo(HandShakeInfo*);
1194 void FinishHandShakeInfo(HandShakeInfo*, const CYASSL*);
1196 void AddPacketName(const char*, HandShakeInfo*);
1199 void InitTimeoutInfo(TimeoutInfo*);
1201 void FreeTimeoutInfo(TimeoutInfo*, void*);
1203 void AddPacketInfo(const char*, TimeoutInfo*, const byte*, int, void*);
1205 void AddLateName(const char*, TimeoutInfo*);
1207 void AddLateRecordHeader(const RecordLayerHeader* rl, TimeoutInfo* info);
1211 /* Record Layer Header identifier from page 12 */
1214 change_cipher_spec = 20,
1217 application_data = 23
1221 /* handshake header, same for each message type, pgs 20/21 */
1222 typedef struct HandShakeHeader {
1228 /* DTLS handshake header, same for each message type */
1229 typedef struct DtlsHandShakeHeader {
1232 byte message_seq[2]; /* start at 0, restransmit gets same # */
1233 word24 fragment_offset; /* bytes in previous fragments */
1234 word24 fragment_length; /* length of this fragment */
1235 } DtlsHandShakeHeader;
1238 enum HandShakeType {
1243 hello_verify_request = 3, /* DTLS addition */
1245 server_key_exchange = 12,
1246 certificate_request = 13,
1247 server_hello_done = 14,
1248 certificate_verify = 15,
1249 client_key_exchange = 16,
1254 /* Valid Alert types from page 16/17 */
1255 enum AlertDescription {
1257 unexpected_message = 10,
1258 bad_record_mac = 20,
1259 decompression_failure = 30,
1260 handshake_failure = 40,
1261 no_certificate = 41,
1262 bad_certificate = 42,
1263 unsupported_certificate = 43,
1264 certificate_revoked = 44,
1265 certificate_expired = 45,
1266 certificate_unknown = 46,
1267 illegal_parameter = 47,
1269 protocol_version = 70,
1270 no_renegotiation = 100
1274 /* I/O Callback default errors */
1276 IO_ERR_GENERAL = -1, /* general unexpected err, not in below group */
1277 IO_ERR_WANT_READ = -2, /* need to call read again */
1278 IO_ERR_WANT_WRITE = -2, /* need to call write again */
1279 IO_ERR_CONN_RST = -3, /* connection reset */
1280 IO_ERR_ISR = -4, /* interrupt */
1281 IO_ERR_CONN_CLOSE = -5 /* connection closed or epipe */
1291 static const byte client[SIZEOF_SENDER] = { 0x43, 0x4C, 0x4E, 0x54 };
1292 static const byte server[SIZEOF_SENDER] = { 0x53, 0x52, 0x56, 0x52 };
1294 static const byte tls_client[FINISHED_LABEL_SZ + 1] = "client finished";
1295 static const byte tls_server[FINISHED_LABEL_SZ + 1] = "server finished";
1298 /* internal functions */
1299 CYASSL_LOCAL int SendChangeCipher(CYASSL*);
1300 CYASSL_LOCAL int SendData(CYASSL*, const void*, int);
1301 CYASSL_LOCAL int SendCertificate(CYASSL*);
1302 CYASSL_LOCAL int SendCertificateRequest(CYASSL*);
1303 CYASSL_LOCAL int SendServerKeyExchange(CYASSL*);
1304 CYASSL_LOCAL int SendBuffered(CYASSL*);
1305 CYASSL_LOCAL int ReceiveData(CYASSL*, byte*, int);
1306 CYASSL_LOCAL int SendFinished(CYASSL*);
1307 CYASSL_LOCAL int SendAlert(CYASSL*, int, int);
1308 CYASSL_LOCAL int ProcessReply(CYASSL*);
1310 CYASSL_LOCAL int SetCipherSpecs(CYASSL*);
1311 CYASSL_LOCAL int MakeMasterSecret(CYASSL*);
1313 CYASSL_LOCAL int AddSession(CYASSL*);
1314 CYASSL_LOCAL int DeriveKeys(CYASSL* ssl);
1315 CYASSL_LOCAL int StoreKeys(CYASSL* ssl, const byte* keyData);
1317 CYASSL_LOCAL int IsTLS(const CYASSL* ssl);
1318 CYASSL_LOCAL int IsAtLeastTLSv1_2(const CYASSL* ssl);
1320 CYASSL_LOCAL void ShrinkInputBuffer(CYASSL* ssl, int forcedFree);
1321 CYASSL_LOCAL void ShrinkOutputBuffer(CYASSL* ssl);
1322 CYASSL_LOCAL int SendHelloVerifyRequest(CYASSL* ssl);
1323 CYASSL_LOCAL Signer* GetCA(void* cm, byte* hash);
1324 CYASSL_LOCAL void BuildTlsFinished(CYASSL* ssl, Hashes* hashes,
1325 const byte* sender);
1327 CYASSL_LOCAL int MakeTlsMasterSecret(CYASSL*);
1328 CYASSL_LOCAL void TLS_hmac(CYASSL* ssl, byte* digest, const byte* buffer,
1329 word32 sz, int content, int verify);
1332 #ifndef NO_CYASSL_CLIENT
1333 CYASSL_LOCAL int SendClientHello(CYASSL*);
1334 CYASSL_LOCAL int SendClientKeyExchange(CYASSL*);
1335 CYASSL_LOCAL int SendCertificateVerify(CYASSL*);
1336 #endif /* NO_CYASSL_CLIENT */
1338 #ifndef NO_CYASSL_SERVER
1339 CYASSL_LOCAL int SendServerHello(CYASSL*);
1340 CYASSL_LOCAL int SendServerHelloDone(CYASSL*);
1342 CYASSL_LOCAL int SendHelloVerifyRequest(CYASSL*);
1344 #endif /* NO_CYASSL_SERVER */
1354 typedef double timer_d;
1356 CYASSL_LOCAL timer_d Timer(void);
1357 CYASSL_LOCAL word32 LowResTimer(void);
1365 #endif /* CyaSSL_INT_H */