1/*
2 * Copyright (c) 2007-2016, Cameron Rich
3 *
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 * * Neither the name of the axTLS project nor the names of its contributors
15 * may be used to endorse or promote products derived from this software
16 * without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/**
32 * Common ssl/tlsv1 code to both the client and server implementations.
33 */
34
35#include <string.h>
36#include <stdlib.h>
37#include <stdio.h>
38#include <stdarg.h>
39#include "os_port.h"
40#include "ssl.h"
41
42/* The session expiry time */
43#define SSL_EXPIRY_TIME (CONFIG_SSL_EXPIRY_TIME*3600)
44
45static const uint8_t g_hello_request[] = { HS_HELLO_REQUEST, 0, 0, 0 };
46static const uint8_t g_chg_cipher_spec_pkt[] = { 1 };
47static const char * server_finished = "server finished";
48static const char * client_finished = "client finished";
49
50static int do_handshake(SSL *ssl, uint8_t *buf, int read_len);
51static int set_key_block(SSL *ssl, int is_write);
52static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len);
53static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt);
54static int send_raw_packet(SSL *ssl, uint8_t protocol);
55static int check_certificate_chain(SSL *ssl);
56
57/**
58 * The server will pick the cipher based on the order that the order that the
59 * ciphers are listed. This order is defined at compile time.
60 */
61#ifndef CONFIG_SSL_SKELETON_MODE
62static void session_free(SSL_SESSION *ssl_sessions[], int sess_index);
63#endif
64
65const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] =
66#ifdef CONFIG_SSL_PROT_LOW /* low security, fast speed */
67{ SSL_AES128_SHA, SSL_AES128_SHA256, SSL_AES256_SHA, SSL_AES256_SHA256 };
68#elif CONFIG_SSL_PROT_MEDIUM /* medium security, medium speed */
69{ SSL_AES128_SHA256, SSL_AES256_SHA256, SSL_AES256_SHA, SSL_AES128_SHA };
70#else /* CONFIG_SSL_PROT_HIGH */ /* high security, low speed */
71{ SSL_AES256_SHA256, SSL_AES128_SHA256, SSL_AES256_SHA, SSL_AES128_SHA };
72#endif
73
74/**
75 * The cipher map containing all the essentials for each cipher.
76 */
77static const cipher_info_t cipher_info[NUM_PROTOCOLS] =
78{
79 { /* AES128-SHA */
80 SSL_AES128_SHA, /* AES128-SHA */
81 16, /* key size */
82 16, /* iv size */
83 16, /* block padding size */
84 SHA1_SIZE, /* digest size */
85 2*(SHA1_SIZE+16+16), /* key block size */
86 ssl_hmac_sha1, /* hmac algorithm */
87 (crypt_func)AES_cbc_encrypt, /* encrypt */
88 (crypt_func)AES_cbc_decrypt /* decrypt */
89 },
90 { /* AES256-SHA */
91 SSL_AES256_SHA, /* AES256-SHA */
92 32, /* key size */
93 16, /* iv size */
94 16, /* block padding size */
95 SHA1_SIZE, /* digest size */
96 2*(SHA1_SIZE+32+16), /* key block size */
97 ssl_hmac_sha1, /* hmac algorithm */
98 (crypt_func)AES_cbc_encrypt, /* encrypt */
99 (crypt_func)AES_cbc_decrypt /* decrypt */
100 },
101 { /* AES128-SHA256 */
102 SSL_AES128_SHA256, /* AES128-SHA256 */
103 16, /* key size */
104 16, /* iv size */
105 16, /* block padding size */
106 SHA256_SIZE, /* digest size */
107 2*(SHA256_SIZE+32+16), /* key block size */
108 hmac_sha256, /* hmac algorithm */
109 (crypt_func)AES_cbc_encrypt, /* encrypt */
110 (crypt_func)AES_cbc_decrypt /* decrypt */
111 },
112 { /* AES256-SHA256 */
113 SSL_AES256_SHA256, /* AES256-SHA256 */
114 32, /* key size */
115 16, /* iv size */
116 16, /* block padding size */
117 SHA256_SIZE, /* digest size */
118 2*(SHA256_SIZE+32+16), /* key block size */
119 hmac_sha256, /* hmac algorithm */
120 (crypt_func)AES_cbc_encrypt, /* encrypt */
121 (crypt_func)AES_cbc_decrypt /* decrypt */
122 }
123};
124
125static void prf(SSL *ssl, const uint8_t *sec, int sec_len,
126 uint8_t *seed, int seed_len,
127 uint8_t *out, int olen);
128static const cipher_info_t *get_cipher_info(uint8_t cipher);
129static void increment_read_sequence(SSL *ssl);
130static void increment_write_sequence(SSL *ssl);
131static void add_hmac_digest(SSL *ssl, int snd, uint8_t *hmac_header,
132 const uint8_t *buf, int buf_len, uint8_t *hmac_buf);
133
134/* win32 VC6.0 doesn't have variadic macros */
135#if defined(WIN32) && !defined(CONFIG_SSL_FULL_MODE)
136void DISPLAY_BYTES(SSL *ssl, const char *format,
137 const uint8_t *data, int size, ...) {}
138#endif
139
140/**
141 * Allocates new SSL extensions structure and returns pointer to it
142 *
143 */
144EXP_FUNC SSL_EXTENSIONS * STDCALL ssl_ext_new()
145{
146 return (SSL_EXTENSIONS *)calloc(1, sizeof(SSL_EXTENSIONS));
147}
148
149/**
150 * Allocates new SSL extensions structure and returns pointer to it
151 *
152 */
153EXP_FUNC void STDCALL ssl_ext_free(SSL_EXTENSIONS *ssl_ext)
154{
155 if (ssl_ext == NULL )
156 {
157 return;
158 }
159
160 free(ssl_ext);
161}
162
163/**
164 * Establish a new client/server context.
165 */
166EXP_FUNC SSL_CTX *STDCALL ssl_ctx_new(uint32_t options, int num_sessions)
167{
168 SSL_CTX *ssl_ctx = (SSL_CTX *)calloc(1, sizeof (SSL_CTX));
169 ssl_ctx->options = options;
170 RNG_initialize();
171
172#ifdef CONFIG_SSL_ENABLE_SERVER
173 if (load_key_certs(ssl_ctx) < 0)
174 {
175 free(ssl_ctx); /* can't load our key/certificate pair, so die */
176 return NULL;
177 }
178#endif
179
180#ifndef CONFIG_SSL_SKELETON_MODE
181 ssl_ctx->num_sessions = num_sessions;
182#endif
183
184 SSL_CTX_MUTEX_INIT(ssl_ctx->mutex);
185
186#ifndef CONFIG_SSL_SKELETON_MODE
187 if (num_sessions)
188 {
189 ssl_ctx->ssl_sessions = (SSL_SESSION **)
190 calloc(1, num_sessions*sizeof(SSL_SESSION *));
191 }
192#endif
193
194 return ssl_ctx;
195}
196
197/*
198 * Remove a client/server context.
199 */
200EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx)
201{
202 SSL *ssl;
203 int i;
204
205 if (ssl_ctx == NULL)
206 return;
207
208 ssl = ssl_ctx->head;
209
210 /* clear out all the ssl entries */
211 while (ssl)
212 {
213 SSL *next = ssl->next;
214 ssl_free(ssl);
215 ssl = next;
216 }
217
218#ifndef CONFIG_SSL_SKELETON_MODE
219 /* clear out all the sessions */
220 for (i = 0; i < ssl_ctx->num_sessions; i++)
221 session_free(ssl_ctx->ssl_sessions, i);
222
223 free(ssl_ctx->ssl_sessions);
224#endif
225
226 i = 0;
227 while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf)
228 {
229 free(ssl_ctx->certs[i].buf);
230 ssl_ctx->certs[i++].buf = NULL;
231 }
232
233#ifdef CONFIG_SSL_CERT_VERIFICATION
234 remove_ca_certs(ssl_ctx->ca_cert_ctx);
235#endif
236 ssl_ctx->chain_length = 0;
237 SSL_CTX_MUTEX_DESTROY(ssl_ctx->mutex);
238 RSA_free(ssl_ctx->rsa_ctx);
239 RNG_terminate();
240 free(ssl_ctx);
241}
242
243/*
244 * Free any used resources used by this connection.
245 */
246EXP_FUNC void STDCALL ssl_free(SSL *ssl)
247{
248 SSL_CTX *ssl_ctx;
249
250 if (ssl == NULL) /* just ignore null pointers */
251 return;
252
253 /* only notify if we weren't notified first */
254 /* spec says we must notify when we are dying */
255 if (!IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY))
256 send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
257
258 ssl_ctx = ssl->ssl_ctx;
259
260 SSL_CTX_LOCK(ssl_ctx->mutex);
261
262 /* adjust the server SSL list */
263 if (ssl->prev)
264 ssl->prev->next = ssl->next;
265 else
266 ssl_ctx->head = ssl->next;
267
268 if (ssl->next)
269 ssl->next->prev = ssl->prev;
270 else
271 ssl_ctx->tail = ssl->prev;
272
273 SSL_CTX_UNLOCK(ssl_ctx->mutex);
274
275 /* may already be free - but be sure */
276 free(ssl->encrypt_ctx);
277 ssl->encrypt_ctx = NULL;
278 free(ssl->decrypt_ctx);
279 ssl->decrypt_ctx = NULL;
280 disposable_free(ssl);
281#ifdef CONFIG_SSL_CERT_VERIFICATION
282 x509_free(ssl->x509_ctx);
283#endif
284
285 ssl_ext_free(ssl->extensions);
286 ssl->extensions = NULL;
287 free(ssl);
288}
289
290/*
291 * Read the SSL connection and send any alerts for various errors.
292 */
293EXP_FUNC int STDCALL ssl_read(SSL *ssl, uint8_t **in_data)
294{
295 int ret = basic_read(ssl, in_data);
296
297 /* check for return code so we can send an alert */
298 if (ret < SSL_OK && ret != SSL_CLOSE_NOTIFY)
299 {
300 if (ret != SSL_ERROR_CONN_LOST)
301 {
302 send_alert(ssl, ret);
303#ifndef CONFIG_SSL_SKELETON_MODE
304 /* something nasty happened, so get rid of this session */
305 kill_ssl_session(ssl->ssl_ctx->ssl_sessions, ssl);
306#endif
307 }
308 }
309
310 return ret;
311}
312
313/*
314 * Write application data to the client
315 */
316EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len)
317{
318 int n = out_len, nw, i, tot = 0;
319
320 /* maximum size of a TLS packet is around 16kB, so fragment */
321 do
322 {
323 nw = n;
324
325 if (nw > RT_MAX_PLAIN_LENGTH) /* fragment if necessary */
326 nw = RT_MAX_PLAIN_LENGTH;
327
328 if ((i = send_packet(ssl, PT_APP_PROTOCOL_DATA,
329 &out_data[tot], nw)) <= 0)
330 {
331 out_len = i; /* an error */
332 break;
333 }
334
335 tot += i;
336 n -= i;
337 } while (n > 0);
338
339 return out_len;
340}
341
342/**
343 * Add a certificate to the certificate chain.
344 */
345int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
346{
347 int ret = SSL_ERROR_NO_CERT_DEFINED, i = 0;
348 SSL_CERT *ssl_cert;
349 X509_CTX *cert = NULL;
350 int offset;
351
352 while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf)
353 i++;
354
355 if (i == CONFIG_SSL_MAX_CERTS) /* too many certs */
356 {
357#ifdef CONFIG_SSL_DIAGNOSTICS
358 printf("Error: maximum number of certs added (%d) - change of "
359 "compile-time configuration required\n",
360 CONFIG_SSL_MAX_CERTS);
361#endif
362 goto error;
363 }
364
365 if ((ret = x509_new(buf, &offset, &cert)))
366 goto error;
367
368#if defined (CONFIG_SSL_FULL_MODE)
369 if (ssl_ctx->options & SSL_DISPLAY_CERTS)
370 x509_print(cert, NULL);
371#endif
372
373 ssl_cert = &ssl_ctx->certs[i];
374 ssl_cert->size = len;
375 ssl_cert->buf = (uint8_t *)malloc(len);
376
377 switch (cert->sig_type)
378 {
379 case SIG_TYPE_SHA1:
380 ssl_cert->hash_alg = SIG_ALG_SHA1;
381 break;
382
383 case SIG_TYPE_SHA256:
384 ssl_cert->hash_alg = SIG_ALG_SHA256;
385 break;
386
387 case SIG_TYPE_SHA384:
388 ssl_cert->hash_alg = SIG_ALG_SHA384;
389 break;
390
391 case SIG_TYPE_SHA512:
392 ssl_cert->hash_alg = SIG_ALG_SHA512;
393 break;
394 }
395
396 memcpy(ssl_cert->buf, buf, len);
397 ssl_ctx->chain_length++;
398 len -= offset;
399 ret = SSL_OK; /* ok so far */
400
401 /* recurse? */
402 if (len > 0)
403 {
404 ret = add_cert(ssl_ctx, &buf[offset], len);
405 }
406
407error:
408 x509_free(cert); /* don't need anymore */
409 return ret;
410}
411
412#ifdef CONFIG_SSL_CERT_VERIFICATION
413/**
414 * Add a certificate authority.
415 */
416int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
417{
418 int ret = X509_OK; /* ignore errors for now */
419 int i = 0;
420 CA_CERT_CTX *ca_cert_ctx;
421
422 if (ssl_ctx->ca_cert_ctx == NULL)
423 ssl_ctx->ca_cert_ctx = (CA_CERT_CTX *)calloc(1, sizeof(CA_CERT_CTX));
424
425 ca_cert_ctx = ssl_ctx->ca_cert_ctx;
426
427 while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i])
428 i++;
429
430 while (len > 0)
431 {
432 int offset;
433 if (i >= CONFIG_X509_MAX_CA_CERTS)
434 {
435#ifdef CONFIG_SSL_FULL_MODE
436 printf("Error: maximum number of CA certs added (%d) - change of "
437 "compile-time configuration required\n",
438 CONFIG_X509_MAX_CA_CERTS);
439#endif
440 ret = X509_MAX_CERTS;
441 break;
442 }
443
444 /* ignore the return code */
445 if (x509_new(buf, &offset, &ca_cert_ctx->cert[i]) == X509_OK)
446 {
447#if defined (CONFIG_SSL_FULL_MODE)
448 if (ssl_ctx->options & SSL_DISPLAY_CERTS)
449 x509_print(ca_cert_ctx->cert[i], NULL);
450#endif
451 }
452
453 i++;
454 len -= offset;
455 }
456
457 return ret;
458}
459
460/*
461 * Retrieve an X.509 distinguished name component
462 */
463EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
464{
465 if (ssl->x509_ctx == NULL)
466 return NULL;
467
468 switch (component)
469 {
470 case SSL_X509_CERT_COMMON_NAME:
471 return ssl->x509_ctx->cert_dn[X509_COMMON_NAME];
472
473 case SSL_X509_CERT_ORGANIZATION:
474 return ssl->x509_ctx->cert_dn[X509_ORGANIZATION];
475
476 case SSL_X509_CERT_ORGANIZATIONAL_NAME:
477 return ssl->x509_ctx->cert_dn[X509_ORGANIZATIONAL_UNIT];
478
479 case SSL_X509_CERT_LOCATION:
480 return ssl->x509_ctx->cert_dn[X509_LOCATION];
481
482 case SSL_X509_CERT_COUNTRY:
483 return ssl->x509_ctx->cert_dn[X509_COUNTRY];
484
485 case SSL_X509_CERT_STATE:
486 return ssl->x509_ctx->cert_dn[X509_STATE];
487
488 case SSL_X509_CA_CERT_COMMON_NAME:
489 return ssl->x509_ctx->ca_cert_dn[X509_COMMON_NAME];
490
491 case SSL_X509_CA_CERT_ORGANIZATION:
492 return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATION];
493
494 case SSL_X509_CA_CERT_ORGANIZATIONAL_NAME:
495 return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATIONAL_UNIT];
496
497 case SSL_X509_CA_CERT_LOCATION:
498 return ssl->x509_ctx->ca_cert_dn[X509_LOCATION];
499
500 case SSL_X509_CA_CERT_COUNTRY:
501 return ssl->x509_ctx->ca_cert_dn[X509_COUNTRY];
502
503 case SSL_X509_CA_CERT_STATE:
504 return ssl->x509_ctx->ca_cert_dn[X509_STATE];
505
506 default:
507 return NULL;
508 }
509}
510
511/*
512 * Retrieve a "Subject Alternative Name" from a v3 certificate
513 */
514EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl,
515 int dnsindex)
516{
517 int i;
518
519 if (ssl->x509_ctx == NULL || ssl->x509_ctx->subject_alt_dnsnames == NULL)
520 return NULL;
521
522 for (i = 0; i < dnsindex; ++i)
523 {
524 if (ssl->x509_ctx->subject_alt_dnsnames[i] == NULL)
525 return NULL;
526 }
527
528 return ssl->x509_ctx->subject_alt_dnsnames[dnsindex];
529}
530
531#endif /* CONFIG_SSL_CERT_VERIFICATION */
532
533/*
534 * Find an ssl object based on the client's file descriptor.
535 */
536EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, long client_fd)
537{
538 SSL *ssl;
539
540 SSL_CTX_LOCK(ssl_ctx->mutex);
541 ssl = ssl_ctx->head;
542
543 /* search through all the ssl entries */
544 while (ssl)
545 {
546 if (ssl->client_fd == client_fd)
547 {
548 SSL_CTX_UNLOCK(ssl_ctx->mutex);
549 return ssl;
550 }
551
552 ssl = ssl->next;
553 }
554
555 SSL_CTX_UNLOCK(ssl_ctx->mutex);
556 return NULL;
557}
558
559/*
560 * Force the client to perform its handshake again.
561 */
562EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl)
563{
564 int ret = SSL_OK;
565
566 disposable_new(ssl);
567#ifdef CONFIG_SSL_ENABLE_CLIENT
568 if (IS_SET_SSL_FLAG(SSL_IS_CLIENT))
569 {
570 ret = do_client_connect(ssl);
571 }
572 else
573#endif
574 {
575 send_packet(ssl, PT_HANDSHAKE_PROTOCOL,
576 g_hello_request, sizeof(g_hello_request));
577 SET_SSL_FLAG(SSL_NEED_RECORD);
578 }
579
580 return ret;
581}
582
583/**
584 * @brief Get what we need for key info.
585 * @param cipher [in] The cipher information we are after
586 * @param key_size [out] The key size for the cipher
587 * @param iv_size [out] The iv size for the cipher
588 * @return The amount of key information we need.
589 */
590static const cipher_info_t *get_cipher_info(uint8_t cipher)
591{
592 int i;
593
594 for (i = 0; i < NUM_PROTOCOLS; i++)
595 {
596 if (cipher_info[i].cipher == cipher)
597 {
598 return &cipher_info[i];
599 }
600 }
601
602 return NULL; /* error */
603}
604
605/*
606 * Get a new ssl context for a new connection.
607 */
608SSL *ssl_new(SSL_CTX *ssl_ctx, long client_fd)
609{
610 SSL *ssl = (SSL *)calloc(1, sizeof(SSL));
611 ssl->ssl_ctx = ssl_ctx;
612 ssl->need_bytes = SSL_RECORD_SIZE; /* need a record */
613 ssl->client_fd = client_fd;
614 ssl->flag = SSL_NEED_RECORD;
615 ssl->bm_data = ssl->bm_all_data+BM_RECORD_OFFSET; /* space at the start */
616 ssl->hs_status = SSL_NOT_OK; /* not connected */
617#ifdef CONFIG_ENABLE_VERIFICATION
618 ssl->ca_cert_ctx = ssl_ctx->ca_cert_ctx;
619#endif
620 disposable_new(ssl);
621
622 /* a bit hacky but saves a few bytes of memory */
623 ssl->flag |= ssl_ctx->options;
624 SSL_CTX_LOCK(ssl_ctx->mutex);
625
626 if (ssl_ctx->head == NULL)
627 {
628 ssl_ctx->head = ssl;
629 ssl_ctx->tail = ssl;
630 }
631 else
632 {
633 ssl->prev = ssl_ctx->tail;
634 ssl_ctx->tail->next = ssl;
635 ssl_ctx->tail = ssl;
636 }
637
638 SSL_CTX_UNLOCK(ssl_ctx->mutex);
639 return ssl;
640}
641
642/*
643 * Add a private key to a context.
644 */
645int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj)
646{
647 int ret = SSL_OK;
648
649 /* get the private key details */
650 if (asn1_get_private_key(ssl_obj->buf, ssl_obj->len, &ssl_ctx->rsa_ctx))
651 {
652 ret = SSL_ERROR_INVALID_KEY;
653 goto error;
654 }
655
656error:
657 return ret;
658}
659
660/**
661 * Increment the read sequence number (as a 64 bit endian indepenent #)
662 */
663static void increment_read_sequence(SSL *ssl)
664{
665 int i;
666
667 for (i = 7; i >= 0; i--)
668 {
669 if (++ssl->read_sequence[i])
670 break;
671 }
672}
673
674/**
675 * Increment the read sequence number (as a 64 bit endian indepenent #)
676 */
677static void increment_write_sequence(SSL *ssl)
678{
679 int i;
680
681 for (i = 7; i >= 0; i--)
682 {
683 if (++ssl->write_sequence[i])
684 break;
685 }
686}
687
688/**
689 * Work out the HMAC digest in a packet.
690 */
691static void add_hmac_digest(SSL *ssl, int mode, uint8_t *hmac_header,
692 const uint8_t *buf, int buf_len, uint8_t *hmac_buf)
693{
694 int hmac_len = buf_len + 8 + SSL_RECORD_SIZE;
695 uint8_t *t_buf = (uint8_t *)alloca(hmac_len);
696
697 memcpy(t_buf, (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) ?
698 ssl->write_sequence : ssl->read_sequence, 8);
699 memcpy(&t_buf[8], hmac_header, SSL_RECORD_SIZE);
700 memcpy(&t_buf[8+SSL_RECORD_SIZE], buf, buf_len);
701
702 ssl->cipher_info->hmac(t_buf, hmac_len,
703 (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) ?
704 ssl->server_mac : ssl->client_mac,
705 ssl->cipher_info->digest_size, hmac_buf);
706
707#if 0
708 print_blob("record", hmac_header, SSL_RECORD_SIZE);
709 print_blob("buf", buf, buf_len);
710 if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE)
711 {
712 print_blob("write seq", ssl->write_sequence, 8);
713 }
714 else
715 {
716 print_blob("read seq", ssl->read_sequence, 8);
717 }
718
719 if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ)
720 {
721 print_blob("server mac",
722 ssl->server_mac, ssl->cipher_info->digest_size);
723 }
724 else
725 {
726 print_blob("client mac",
727 ssl->client_mac, ssl->cipher_info->digest_size);
728 }
729 print_blob("hmac", hmac_buf, ssl->cipher_info->digest_size);
730#endif
731}
732
733/**
734 * Verify that the digest of a packet is correct.
735 */
736static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len)
737{
738 uint8_t hmac_buf[SHA256_SIZE]; // size of largest digest
739 int hmac_offset;
740
741 int last_blk_size = buf[read_len-1], i;
742 hmac_offset = read_len-last_blk_size-ssl->cipher_info->digest_size-1;
743
744 /* guard against a timing attack - make sure we do the digest */
745 if (hmac_offset < 0)
746 {
747 hmac_offset = 0;
748 }
749 else
750 {
751 /* already looked at last byte */
752 for (i = 1; i < last_blk_size; i++)
753 {
754 if (buf[read_len-i] != last_blk_size)
755 {
756 hmac_offset = 0;
757 break;
758 }
759 }
760 }
761
762 /* sanity check the offset */
763 ssl->hmac_header[3] = hmac_offset >> 8; /* insert size */
764 ssl->hmac_header[4] = hmac_offset & 0xff;
765 add_hmac_digest(ssl, mode, ssl->hmac_header, buf, hmac_offset, hmac_buf);
766
767 if (memcmp(hmac_buf, &buf[hmac_offset], ssl->cipher_info->digest_size))
768 {
769 return SSL_ERROR_INVALID_HMAC;
770 }
771
772 return hmac_offset;
773}
774
775/**
776 * Add a packet to the end of our sent and received packets, so that we may use
777 * it to calculate the hash at the end.
778 */
779void add_packet(SSL *ssl, const uint8_t *pkt, int len)
780{
781 // TLS1.2+
782 if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2 || ssl->version == 0)
783 {
784 SHA256_Update(&ssl->dc->sha256_ctx, pkt, len);
785 }
786
787 if (ssl->version < SSL_PROTOCOL_VERSION_TLS1_2 ||
788 ssl->next_state == HS_SERVER_HELLO ||
789 ssl->next_state == 0)
790 {
791 MD5_Update(&ssl->dc->md5_ctx, pkt, len);
792 SHA1_Update(&ssl->dc->sha1_ctx, pkt, len);
793 }
794}
795
796/**
797 * Work out the MD5 PRF.
798 */
799static void p_hash_md5(const uint8_t *sec, int sec_len,
800 uint8_t *seed, int seed_len, uint8_t *out, int olen)
801{
802 uint8_t a1[MD5_SIZE+77];
803
804 /* A(1) */
805 ssl_hmac_md5(seed, seed_len, sec, sec_len, a1);
806 memcpy(&a1[MD5_SIZE], seed, seed_len);
807 ssl_hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
808
809 while (olen > MD5_SIZE)
810 {
811 uint8_t a2[MD5_SIZE];
812 out += MD5_SIZE;
813 olen -= MD5_SIZE;
814
815 /* A(N) */
816 ssl_hmac_md5(a1, MD5_SIZE, sec, sec_len, a2);
817 memcpy(a1, a2, MD5_SIZE);
818
819 /* work out the actual hash */
820 ssl_hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
821 }
822}
823
824/**
825 * Work out the SHA1 PRF.
826 */
827static void p_hash_sha1(const uint8_t *sec, int sec_len,
828 uint8_t *seed, int seed_len, uint8_t *out, int olen)
829{
830 uint8_t a1[SHA1_SIZE+77];
831
832 /* A(1) */
833 ssl_hmac_sha1(seed, seed_len, sec, sec_len, a1);
834 memcpy(&a1[SHA1_SIZE], seed, seed_len);
835 ssl_hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
836
837 while (olen > SHA1_SIZE)
838 {
839 uint8_t a2[SHA1_SIZE];
840 out += SHA1_SIZE;
841 olen -= SHA1_SIZE;
842
843 /* A(N) */
844 ssl_hmac_sha1(a1, SHA1_SIZE, sec, sec_len, a2);
845 memcpy(a1, a2, SHA1_SIZE);
846
847 /* work out the actual hash */
848 ssl_hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
849 }
850}
851
852/**
853 * Work out the SHA256 PRF.
854 */
855static void p_hash_sha256(const uint8_t *sec, int sec_len,
856 uint8_t *seed, int seed_len, uint8_t *out, int olen)
857{
858 uint8_t a1[SHA256_SIZE+77];
859
860 /* A(1) */
861 hmac_sha256(seed, seed_len, sec, sec_len, a1);
862 memcpy(&a1[SHA256_SIZE], seed, seed_len);
863 hmac_sha256(a1, SHA256_SIZE+seed_len, sec, sec_len, out);
864
865 while (olen > SHA256_SIZE)
866 {
867 uint8_t a2[SHA256_SIZE];
868 out += SHA256_SIZE;
869 olen -= SHA256_SIZE;
870
871 // A(N)
872 hmac_sha256(a1, SHA256_SIZE, sec, sec_len, a2);
873 memcpy(a1, a2, SHA256_SIZE);
874
875 // work out the actual hash
876 hmac_sha256(a1, SHA256_SIZE+seed_len, sec, sec_len, out);
877 }
878}
879
880/**
881 * Work out the PRF.
882 */
883static void prf(SSL *ssl, const uint8_t *sec, int sec_len,
884 uint8_t *seed, int seed_len,
885 uint8_t *out, int olen)
886{
887 if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+
888 {
889 p_hash_sha256(sec, sec_len, seed, seed_len, out, olen);
890 }
891 else // TLS1.0/1.1
892 {
893 int len, i;
894 const uint8_t *S1, *S2;
895 uint8_t xbuf[2*(SHA256_SIZE+32+16) + MD5_SIZE]; /* max keyblock */
896 uint8_t ybuf[2*(SHA256_SIZE+32+16) + SHA1_SIZE]; /* max keyblock */
897
898 len = sec_len/2;
899 S1 = sec;
900 S2 = &sec[len];
901 len += (sec_len & 1); /* add for odd, make longer */
902
903 p_hash_md5(S1, len, seed, seed_len, xbuf, olen);
904 p_hash_sha1(S2, len, seed, seed_len, ybuf, olen);
905
906 for (i = 0; i < olen; i++)
907 out[i] = xbuf[i] ^ ybuf[i];
908 }
909}
910
911/**
912 * Generate a master secret based on the client/server random data and the
913 * premaster secret.
914 */
915void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret)
916{
917 uint8_t buf[77];
918//print_blob("premaster secret", premaster_secret, 48);
919 strcpy((char *)buf, "master secret");
920 memcpy(&buf[13], ssl->dc->client_random, SSL_RANDOM_SIZE);
921 memcpy(&buf[45], ssl->dc->server_random, SSL_RANDOM_SIZE);
922 prf(ssl, premaster_secret, SSL_SECRET_SIZE, buf, 77, ssl->dc->master_secret,
923 SSL_SECRET_SIZE);
924#if 0
925 print_blob("client random", ssl->dc->client_random, 32);
926 print_blob("server random", ssl->dc->server_random, 32);
927 print_blob("master secret", ssl->dc->master_secret, 48);
928#endif
929}
930
931/**
932 * Generate a 'random' blob of data used for the generation of keys.
933 */
934static void generate_key_block(SSL *ssl,
935 uint8_t *client_random, uint8_t *server_random,
936 uint8_t *master_secret, uint8_t *key_block, int key_block_size)
937{
938 uint8_t buf[77];
939 strcpy((char *)buf, "key expansion");
940 memcpy(&buf[13], server_random, SSL_RANDOM_SIZE);
941 memcpy(&buf[45], client_random, SSL_RANDOM_SIZE);
942 prf(ssl, master_secret, SSL_SECRET_SIZE, buf, 77,
943 key_block, key_block_size);
944}
945
946/**
947 * Calculate the digest used in the finished message. This function also
948 * doubles up as a certificate verify function.
949 */
950int finished_digest(SSL *ssl, const char *label, uint8_t *digest)
951{
952 uint8_t mac_buf[SHA1_SIZE+MD5_SIZE+15];
953 uint8_t *q = mac_buf;
954 int dgst_len;
955
956 if (label)
957 {
958 strcpy((char *)q, label);
959 q += strlen(label);
960 }
961
962 if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2) // TLS1.2+
963 {
964 SHA256_CTX sha256_ctx = ssl->dc->sha256_ctx; // interim copy
965 SHA256_Final(q, &sha256_ctx);
966 q += SHA256_SIZE;
967 dgst_len = (int)(q-mac_buf);
968 }
969 else // TLS1.0/1.1
970 {
971 MD5_CTX md5_ctx = ssl->dc->md5_ctx; // interim copy
972 SHA1_CTX sha1_ctx = ssl->dc->sha1_ctx;
973
974 MD5_Final(q, &md5_ctx);
975 q += MD5_SIZE;
976
977 SHA1_Final(q, &sha1_ctx);
978 q += SHA1_SIZE;
979 dgst_len = (int)(q-mac_buf);
980 }
981
982 if (label)
983 {
984 prf(ssl, ssl->dc->master_secret, SSL_SECRET_SIZE,
985 mac_buf, dgst_len, digest, SSL_FINISHED_HASH_SIZE);
986 }
987 else /* for use in a certificate verify */
988 {
989 memcpy(digest, mac_buf, dgst_len);
990 }
991
992#if 0
993 printf("label: %s\n", label);
994 print_blob("mac_buf", mac_buf, dgst_len);
995 print_blob("finished digest", digest, SSL_FINISHED_HASH_SIZE);
996#endif
997
998 return dgst_len;
999}
1000
1001/**
1002 * Retrieve (and initialise) the context of a cipher.
1003 */
1004static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt)
1005{
1006 switch (ssl->cipher)
1007 {
1008 case SSL_AES128_SHA:
1009 case SSL_AES128_SHA256:
1010 {
1011 AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
1012 AES_set_key(aes_ctx, key, iv, AES_MODE_128);
1013
1014 if (is_decrypt)
1015 {
1016 AES_convert_key(aes_ctx);
1017 }
1018
1019 return (void *)aes_ctx;
1020 }
1021
1022 case SSL_AES256_SHA:
1023 case SSL_AES256_SHA256:
1024 {
1025 AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
1026 AES_set_key(aes_ctx, key, iv, AES_MODE_256);
1027
1028 if (is_decrypt)
1029 {
1030 AES_convert_key(aes_ctx);
1031 }
1032
1033 return (void *)aes_ctx;
1034 }
1035
1036 }
1037
1038 return NULL; /* its all gone wrong */
1039}
1040
1041/**
1042 * Send a packet over the socket.
1043 */
1044static int send_raw_packet(SSL *ssl, uint8_t protocol)
1045{
1046 uint8_t *rec_buf = ssl->bm_all_data;
1047 int pkt_size = SSL_RECORD_SIZE+ssl->bm_index;
1048 int sent = 0;
1049 int ret = SSL_OK;
1050
1051 rec_buf[0] = protocol;
1052 rec_buf[1] = 0x03; /* version = 3.1 or higher */
1053 rec_buf[2] = ssl->version & 0x0f;
1054 rec_buf[3] = ssl->bm_index >> 8;
1055 rec_buf[4] = ssl->bm_index & 0xff;
1056
1057 DISPLAY_BYTES(ssl, "sending %d bytes", ssl->bm_all_data,
1058 pkt_size, pkt_size);
1059
1060 while (sent < pkt_size)
1061 {
1062 ret = SOCKET_WRITE(ssl->client_fd,
1063 &ssl->bm_all_data[sent], pkt_size-sent);
1064
1065 if (ret >= 0)
1066 sent += ret;
1067 else
1068 {
1069
1070#ifdef WIN32
1071 if (GetLastError() != WSAEWOULDBLOCK)
1072#else
1073 if (SOCKET_ERRNO() != EAGAIN && SOCKET_ERRNO() != EWOULDBLOCK)
1074#endif
1075 return SSL_ERROR_CONN_LOST;
1076 }
1077
1078#ifdef PORT_USE_SELECT
1079 // TODO: This should be factored into SOCKET_WAIT_WRITABLE(),
1080 // with semantic being waiting until socket can be written
1081 // regardless whether it is in blocking or non-blocking mode.
1082 /* keep going until the write buffer has some space */
1083 if (sent != pkt_size)
1084 {
1085 fd_set wfds;
1086 FD_ZERO(&wfds);
1087 FD_SET(ssl->client_fd, &wfds);
1088
1089 /* block and wait for it */
1090 if (select(ssl->client_fd + 1, NULL, &wfds, NULL, NULL) < 0)
1091 return SSL_ERROR_CONN_LOST;
1092 }
1093#endif
1094 }
1095
1096 SET_SSL_FLAG(SSL_NEED_RECORD); /* reset for next time */
1097 ssl->bm_index = 0;
1098
1099 if (protocol != PT_APP_PROTOCOL_DATA)
1100 {
1101 /* always return SSL_OK during handshake */
1102 ret = SSL_OK;
1103 }
1104
1105 return ret;
1106}
1107
1108/**
1109 * Send an encrypted packet with padding bytes if necessary.
1110 */
1111int send_packet(SSL *ssl, uint8_t protocol, const uint8_t *in, int length)
1112{
1113 int ret, msg_length = 0;
1114
1115 /* if our state is bad, don't bother */
1116 if (ssl->hs_status == SSL_ERROR_DEAD)
1117 return SSL_ERROR_CONN_LOST;
1118
1119 if (IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY))
1120 return SSL_CLOSE_NOTIFY;
1121
1122 if (in) /* has the buffer already been initialised? */
1123 {
1124 memcpy(ssl->bm_data, in, length);
1125 }
1126
1127 msg_length += length;
1128
1129 if (IS_SET_SSL_FLAG(SSL_TX_ENCRYPTED))
1130 {
1131 int mode = IS_SET_SSL_FLAG(SSL_IS_CLIENT) ?
1132 SSL_CLIENT_WRITE : SSL_SERVER_WRITE;
1133 uint8_t hmac_header[SSL_RECORD_SIZE] =
1134 {
1135 protocol,
1136 0x03, /* version = 3.1 or higher */
1137 ssl->version & 0x0f,
1138 msg_length >> 8,
1139 msg_length & 0xff
1140 };
1141
1142 if (protocol == PT_HANDSHAKE_PROTOCOL)
1143 {
1144 DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
1145
1146 if (ssl->bm_data[0] != HS_HELLO_REQUEST)
1147 {
1148 add_packet(ssl, ssl->bm_data, msg_length);
1149 }
1150 }
1151
1152 /* add the packet digest */
1153 add_hmac_digest(ssl, mode, hmac_header, ssl->bm_data, msg_length,
1154 &ssl->bm_data[msg_length]);
1155 msg_length += ssl->cipher_info->digest_size;
1156
1157 /* add padding */
1158 {
1159 int last_blk_size = msg_length%ssl->cipher_info->padding_size;
1160 int pad_bytes = ssl->cipher_info->padding_size - last_blk_size;
1161
1162 /* ensure we always have at least 1 padding byte */
1163 if (pad_bytes == 0)
1164 pad_bytes += ssl->cipher_info->padding_size;
1165
1166 memset(&ssl->bm_data[msg_length], pad_bytes-1, pad_bytes);
1167 msg_length += pad_bytes;
1168 }
1169
1170 DISPLAY_BYTES(ssl, "unencrypted write", ssl->bm_data, msg_length);
1171 increment_write_sequence(ssl);
1172
1173 /* add the explicit IV for TLS1.1 */
1174 if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_1)
1175 {
1176 uint8_t iv_size = ssl->cipher_info->iv_size;
1177 uint8_t *t_buf = alloca(msg_length + iv_size);
1178 memcpy(t_buf + iv_size, ssl->bm_data, msg_length);
1179 if (get_random(iv_size, t_buf) < 0)
1180 return SSL_NOT_OK;
1181
1182 msg_length += iv_size;
1183 memcpy(ssl->bm_data, t_buf, msg_length);
1184 }
1185
1186 /* now encrypt the packet */
1187 ssl->cipher_info->encrypt(ssl->encrypt_ctx, ssl->bm_data,
1188 ssl->bm_data, msg_length);
1189 }
1190 else if (protocol == PT_HANDSHAKE_PROTOCOL)
1191 {
1192 DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
1193
1194 if (ssl->bm_data[0] != HS_HELLO_REQUEST)
1195 {
1196 add_packet(ssl, ssl->bm_data, length);
1197 }
1198 }
1199
1200 ssl->bm_index = msg_length;
1201 if ((ret = send_raw_packet(ssl, protocol)) <= 0)
1202 return ret;
1203
1204 return length; /* just return what we wanted to send */
1205}
1206
1207/**
1208 * Work out the cipher keys we are going to use for this session based on the
1209 * master secret.
1210 */
1211static int set_key_block(SSL *ssl, int is_write)
1212{
1213 const cipher_info_t *ciph_info = get_cipher_info(ssl->cipher);
1214 uint8_t *q;
1215 uint8_t client_key[32], server_key[32]; /* big enough for AES256 */
1216 uint8_t client_iv[16], server_iv[16]; /* big enough for AES128/256 */
1217 int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1218
1219 if (ciph_info == NULL)
1220 return -1;
1221
1222 /* only do once in a handshake */
1223 if (!ssl->dc->key_block_generated)
1224 {
1225 generate_key_block(ssl, ssl->dc->client_random, ssl->dc->server_random,
1226 ssl->dc->master_secret, ssl->dc->key_block,
1227 ciph_info->key_block_size);
1228#if 0
1229 print_blob("master", ssl->dc->master_secret, SSL_SECRET_SIZE);
1230 print_blob("keyblock", ssl->dc->key_block, ciph_info->key_block_size);
1231 print_blob("client random", ssl->dc->client_random, 32);
1232 print_blob("server random", ssl->dc->server_random, 32);
1233#endif
1234 ssl->dc->key_block_generated = 1;
1235 }
1236
1237 q = ssl->dc->key_block;
1238
1239 if ((is_client && is_write) || (!is_client && !is_write))
1240 {
1241 memcpy(ssl->client_mac, q, ciph_info->digest_size);
1242 }
1243
1244 q += ciph_info->digest_size;
1245
1246 if ((!is_client && is_write) || (is_client && !is_write))
1247 {
1248 memcpy(ssl->server_mac, q, ciph_info->digest_size);
1249 }
1250
1251 q += ciph_info->digest_size;
1252 memcpy(client_key, q, ciph_info->key_size);
1253 q += ciph_info->key_size;
1254 memcpy(server_key, q, ciph_info->key_size);
1255 q += ciph_info->key_size;
1256
1257 memcpy(client_iv, q, ciph_info->iv_size);
1258 q += ciph_info->iv_size;
1259 memcpy(server_iv, q, ciph_info->iv_size);
1260 q += ciph_info->iv_size;
1261#if 0
1262 print_blob("client key", client_key, ciph_info->key_size);
1263 print_blob("server key", server_key, ciph_info->key_size);
1264 print_blob("client iv", client_iv, ciph_info->iv_size);
1265 print_blob("server iv", server_iv, ciph_info->iv_size);
1266#endif
1267
1268 free(is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx);
1269
1270 /* now initialise the ciphers */
1271 if (is_client)
1272 {
1273 finished_digest(ssl, server_finished, ssl->dc->final_finish_mac);
1274
1275 if (is_write)
1276 ssl->encrypt_ctx = crypt_new(ssl, client_key, client_iv, 0);
1277 else
1278 ssl->decrypt_ctx = crypt_new(ssl, server_key, server_iv, 1);
1279 }
1280 else
1281 {
1282 finished_digest(ssl, client_finished, ssl->dc->final_finish_mac);
1283
1284 if (is_write)
1285 ssl->encrypt_ctx = crypt_new(ssl, server_key, server_iv, 0);
1286 else
1287 ssl->decrypt_ctx = crypt_new(ssl, client_key, client_iv, 1);
1288 }
1289
1290 ssl->cipher_info = ciph_info;
1291 return 0;
1292}
1293
1294/**
1295 * Read the SSL connection.
1296 */
1297int basic_read(SSL *ssl, uint8_t **in_data)
1298{
1299 int ret = SSL_OK;
1300 int read_len, is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1301 uint8_t *buf = ssl->bm_data;
1302
1303 if (IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY))
1304 return SSL_CLOSE_NOTIFY;
1305
1306 read_len = SOCKET_READ(ssl->client_fd, &buf[ssl->bm_read_index],
1307 ssl->need_bytes-ssl->got_bytes);
1308
1309 if (read_len < 0)
1310 {
1311#ifdef WIN32
1312 if (GetLastError() == WSAEWOULDBLOCK)
1313#else
1314 if (SOCKET_ERRNO() == EAGAIN || SOCKET_ERRNO() == EWOULDBLOCK)
1315#endif
1316 return SSL_EAGAIN;
1317 }
1318
1319 /* connection has gone, so die */
1320 if (read_len <= 0)
1321 {
1322 ret = SSL_ERROR_CONN_LOST;
1323 ssl->hs_status = SSL_ERROR_DEAD; /* make sure it stays dead */
1324 goto error;
1325 }
1326
1327 DISPLAY_BYTES(ssl, "received %d bytes",
1328 &ssl->bm_data[ssl->bm_read_index], read_len, read_len);
1329
1330 ssl->got_bytes += read_len;
1331 ssl->bm_read_index += read_len;
1332
1333 /* haven't quite got what we want, so try again later */
1334 if (ssl->got_bytes < ssl->need_bytes)
1335 return SSL_OK;
1336
1337 read_len = ssl->got_bytes;
1338 ssl->got_bytes = 0;
1339
1340 if (IS_SET_SSL_FLAG(SSL_NEED_RECORD))
1341 {
1342 /* check for sslv2 "client hello" */
1343 if ((buf[0] & 0x80) && buf[2] == 1)
1344 {
1345#ifdef CONFIG_SSL_FULL_MODE
1346 printf("Error: no SSLv23 handshaking allowed\n");
1347#endif
1348 ret = SSL_ERROR_NOT_SUPPORTED;
1349 goto error; /* not an error - just get out of here */
1350 }
1351
1352 ssl->need_bytes = (buf[3] << 8) + buf[4];
1353
1354 /* do we violate the spec with the message size? */
1355 if (ssl->need_bytes > RT_MAX_PLAIN_LENGTH+RT_EXTRA-BM_RECORD_OFFSET)
1356 {
1357 printf("TLS buffer overflow, record size: %u (+5)\n", ssl->need_bytes);
1358 ret = SSL_ERROR_RECORD_OVERFLOW;
1359 goto error;
1360 }
1361
1362 CLR_SSL_FLAG(SSL_NEED_RECORD);
1363 memcpy(ssl->hmac_header, buf, 3); /* store for hmac */
1364 ssl->record_type = buf[0];
1365 goto error; /* no error, we're done */
1366 }
1367
1368 /* for next time - just do it now in case of an error */
1369 SET_SSL_FLAG(SSL_NEED_RECORD);
1370 ssl->need_bytes = SSL_RECORD_SIZE;
1371
1372 /* decrypt if we need to */
1373 if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
1374 {
1375 ssl->cipher_info->decrypt(ssl->decrypt_ctx, buf, buf, read_len);
1376
1377 if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_1)
1378 {
1379 buf += ssl->cipher_info->iv_size;
1380 read_len -= ssl->cipher_info->iv_size;
1381 }
1382
1383 read_len = verify_digest(ssl,
1384 is_client ? SSL_CLIENT_READ : SSL_SERVER_READ, buf, read_len);
1385
1386 /* does the hmac work? */
1387 if (read_len < 0)
1388 {
1389 ret = read_len;
1390 goto error;
1391 }
1392
1393 DISPLAY_BYTES(ssl, "decrypted", buf, read_len);
1394 increment_read_sequence(ssl);
1395 }
1396
1397 /* The main part of the SSL packet */
1398 switch (ssl->record_type)
1399 {
1400 case PT_HANDSHAKE_PROTOCOL:
1401 if (ssl->dc != NULL)
1402 {
1403 ssl->dc->bm_proc_index = 0;
1404 ret = do_handshake(ssl, buf, read_len);
1405 }
1406 else /* no client renegotiation allowed */
1407 {
1408 ret = SSL_ERROR_NO_CLIENT_RENOG;
1409 goto error;
1410 }
1411 break;
1412
1413 case PT_CHANGE_CIPHER_SPEC:
1414 if (ssl->next_state != HS_FINISHED)
1415 {
1416 ret = SSL_ERROR_INVALID_HANDSHAKE;
1417 goto error;
1418 }
1419
1420 if (set_key_block(ssl, 0) < 0)
1421 {
1422 ret = SSL_ERROR_INVALID_HANDSHAKE;
1423 goto error;
1424 }
1425
1426 /* all encrypted from now on */
1427 SET_SSL_FLAG(SSL_RX_ENCRYPTED);
1428 memset(ssl->read_sequence, 0, 8);
1429 break;
1430
1431 case PT_APP_PROTOCOL_DATA:
1432 if (in_data && ssl->hs_status == SSL_OK)
1433 {
1434 *in_data = buf; /* point to the work buffer */
1435 (*in_data)[read_len] = 0; /* null terminate just in case */
1436 ret = read_len;
1437 }
1438 else
1439 ret = SSL_ERROR_INVALID_PROT_MSG;
1440 break;
1441
1442 case PT_ALERT_PROTOCOL:
1443 /* return the alert # with alert bit set */
1444 if (buf[0] == SSL_ALERT_TYPE_WARNING &&
1445 buf[1] == SSL_ALERT_CLOSE_NOTIFY)
1446 {
1447 ret = SSL_CLOSE_NOTIFY;
1448 send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
1449 SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY);
1450 }
1451 else
1452 {
1453 ret = -buf[1];
1454 DISPLAY_ALERT(ssl, buf[1]);
1455 }
1456
1457 break;
1458
1459 default:
1460 ret = SSL_ERROR_INVALID_PROT_MSG;
1461 break;
1462 }
1463
1464error:
1465 ssl->bm_read_index = 0; /* reset to go again */
1466
1467 if (ret < SSL_OK && in_data)/* if all wrong, then clear this buffer ptr */
1468 *in_data = NULL;
1469
1470 return ret;
1471}
1472
1473/**
1474 * Do some basic checking of data and then perform the appropriate handshaking.
1475 */
1476static int do_handshake(SSL *ssl, uint8_t *buf, int read_len)
1477{
1478 int hs_len = (buf[2]<<8) + buf[3];
1479 uint8_t handshake_type = buf[0];
1480 int ret = SSL_OK;
1481 int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1482
1483 /* some integrity checking on the handshake */
1484 PARANOIA_CHECK(read_len-SSL_HS_HDR_SIZE, hs_len);
1485
1486 if (handshake_type != ssl->next_state)
1487 {
1488 /* handle a special case on the client */
1489 if (!is_client || handshake_type != HS_CERT_REQ ||
1490 ssl->next_state != HS_SERVER_HELLO_DONE)
1491 {
1492 ret = SSL_ERROR_INVALID_HANDSHAKE;
1493 goto error;
1494 }
1495 }
1496
1497 hs_len += SSL_HS_HDR_SIZE; /* adjust for when adding packets */
1498 ssl->bm_index = hs_len; /* store the size and check later */
1499 DISPLAY_STATE(ssl, 0, handshake_type, 0);
1500
1501 if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
1502 add_packet(ssl, buf, hs_len);
1503
1504#if defined(CONFIG_SSL_ENABLE_CLIENT) && defined(CONFIG_SSL_ENABLE_SERVER)
1505 ret = is_client ?
1506 do_clnt_handshake(ssl, handshake_type, buf, hs_len) :
1507 do_svr_handshake(ssl, handshake_type, buf, hs_len);
1508#elif defined(CONFIG_SSL_ENABLE_CLIENT)
1509 ret = do_clnt_handshake(ssl, handshake_type, buf, hs_len);
1510#else
1511 ret = do_svr_handshake(ssl, handshake_type, buf, hs_len);
1512#endif
1513
1514 /* just use recursion to get the rest */
1515 if (hs_len < read_len && ret == SSL_OK)
1516 ret = do_handshake(ssl, &buf[hs_len], read_len-hs_len);
1517
1518error:
1519 return ret;
1520}
1521
1522/**
1523 * Sends the change cipher spec message. We have just read a finished message
1524 * from the client.
1525 */
1526int send_change_cipher_spec(SSL *ssl)
1527{
1528 int ret = send_packet(ssl, PT_CHANGE_CIPHER_SPEC,
1529 g_chg_cipher_spec_pkt, sizeof(g_chg_cipher_spec_pkt));
1530
1531 if (ret >= 0 && set_key_block(ssl, 1) < 0)
1532 ret = SSL_ERROR_INVALID_HANDSHAKE;
1533
1534 if (ssl->cipher_info)
1535 SET_SSL_FLAG(SSL_TX_ENCRYPTED);
1536
1537 memset(ssl->write_sequence, 0, 8);
1538 return ret;
1539}
1540
1541/**
1542 * Send a "finished" message
1543 */
1544int send_finished(SSL *ssl)
1545{
1546 uint8_t buf[SHA1_SIZE+MD5_SIZE+15+4] = {
1547 HS_FINISHED, 0, 0, SSL_FINISHED_HASH_SIZE };
1548
1549 /* now add the finished digest mac (12 bytes) */
1550 finished_digest(ssl,
1551 IS_SET_SSL_FLAG(SSL_IS_CLIENT) ?
1552 client_finished : server_finished, &buf[4]);
1553
1554#ifndef CONFIG_SSL_SKELETON_MODE
1555 /* store in the session cache */
1556 if (!IS_SET_SSL_FLAG(SSL_SESSION_RESUME) && ssl->ssl_ctx->num_sessions)
1557 {
1558 memcpy(ssl->session->master_secret,
1559 ssl->dc->master_secret, SSL_SECRET_SIZE);
1560 }
1561#endif
1562
1563 return send_packet(ssl, PT_HANDSHAKE_PROTOCOL,
1564 buf, SSL_FINISHED_HASH_SIZE+4);
1565}
1566
1567/**
1568 * Send an alert message.
1569 * Return 1 if the alert was an "error".
1570 */
1571int send_alert(SSL *ssl, int error_code)
1572{
1573 int alert_num = 0;
1574 int is_warning = 0;
1575 uint8_t buf[2];
1576
1577 /* Don't bother, we're already dead */
1578 if (ssl->hs_status == SSL_ERROR_DEAD)
1579 {
1580 return SSL_ERROR_CONN_LOST;
1581 }
1582
1583#ifdef CONFIG_SSL_DIAGNOSTICS
1584 if (IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
1585 ssl_display_error(error_code);
1586#endif
1587
1588 switch (error_code)
1589 {
1590 case SSL_ALERT_CLOSE_NOTIFY:
1591 is_warning = 1;
1592 alert_num = SSL_ALERT_CLOSE_NOTIFY;
1593 break;
1594
1595 case SSL_ERROR_CONN_LOST: /* don't send alert just yet */
1596 is_warning = 1;
1597 break;
1598
1599 case SSL_ERROR_NO_CIPHER:
1600 alert_num = SSL_ALERT_HANDSHAKE_FAILURE;
1601 break;
1602
1603 case SSL_ERROR_INVALID_HMAC:
1604 alert_num = SSL_ALERT_BAD_RECORD_MAC;
1605 break;
1606
1607 case SSL_ERROR_FINISHED_INVALID:
1608 case SSL_ERROR_INVALID_KEY:
1609 alert_num = SSL_ALERT_DECRYPT_ERROR;
1610 break;
1611
1612 case SSL_ERROR_INVALID_VERSION:
1613 alert_num = SSL_ALERT_INVALID_VERSION;
1614 break;
1615
1616 case SSL_ERROR_INVALID_SESSION:
1617 alert_num = SSL_ALERT_ILLEGAL_PARAMETER;
1618 break;
1619
1620 case SSL_ERROR_NO_CLIENT_RENOG:
1621 alert_num = SSL_ALERT_NO_RENEGOTIATION;
1622 break;
1623
1624 case SSL_ERROR_RECORD_OVERFLOW:
1625 alert_num = SSL_ALERT_RECORD_OVERFLOW;
1626 break;
1627
1628 case SSL_X509_ERROR(X509_VFY_ERROR_EXPIRED):
1629 case SSL_X509_ERROR(X509_VFY_ERROR_NOT_YET_VALID):
1630 alert_num = SSL_ALERT_CERTIFICATE_EXPIRED;
1631 break;
1632
1633 case SSL_X509_ERROR(X509_VFY_ERROR_NO_TRUSTED_CERT):
1634 alert_num = SSL_ALERT_UNKNOWN_CA;
1635 break;
1636
1637 case SSL_X509_ERROR(X509_VFY_ERROR_UNSUPPORTED_DIGEST):
1638 case SSL_ERROR_INVALID_CERT_HASH_ALG:
1639 alert_num = SSL_ALERT_UNSUPPORTED_CERTIFICATE;
1640 break;
1641
1642 case SSL_ERROR_BAD_CERTIFICATE:
1643 case SSL_X509_ERROR(X509_VFY_ERROR_BAD_SIGNATURE):
1644 alert_num = SSL_ALERT_BAD_CERTIFICATE;
1645 break;
1646
1647 case SSL_ERROR_INVALID_HANDSHAKE:
1648 case SSL_ERROR_INVALID_PROT_MSG:
1649 default:
1650 /* a catch-all for anything bad */
1651 alert_num = (error_code <= SSL_X509_OFFSET) ?
1652 SSL_ALERT_CERTIFICATE_UNKNOWN: SSL_ALERT_UNEXPECTED_MESSAGE;
1653 break;
1654 }
1655
1656 buf[0] = is_warning ? 1 : 2;
1657 buf[1] = alert_num;
1658 send_packet(ssl, PT_ALERT_PROTOCOL, buf, sizeof(buf));
1659 DISPLAY_ALERT(ssl, alert_num);
1660 return is_warning ? 0 : 1;
1661}
1662
1663/**
1664 * Process a client finished message.
1665 */
1666int process_finished(SSL *ssl, uint8_t *buf, int hs_len)
1667{
1668 int ret = SSL_OK;
1669 int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1670 int resume = IS_SET_SSL_FLAG(SSL_SESSION_RESUME);
1671
1672 PARANOIA_CHECK(ssl->bm_index, SSL_FINISHED_HASH_SIZE+4);
1673
1674 /* check that we all work before we continue */
1675 if (memcmp(ssl->dc->final_finish_mac, &buf[4], SSL_FINISHED_HASH_SIZE))
1676 return SSL_ERROR_FINISHED_INVALID;
1677
1678 if ((!is_client && !resume) || (is_client && resume))
1679 {
1680 if ((ret = send_change_cipher_spec(ssl)) == SSL_OK)
1681 ret = send_finished(ssl);
1682 }
1683
1684 /* if we ever renegotiate */
1685 ssl->next_state = is_client ? HS_HELLO_REQUEST : HS_CLIENT_HELLO;
1686 ssl->hs_status = ret; /* set the final handshake status */
1687
1688error:
1689 return ret;
1690}
1691
1692/**
1693 * Send a certificate.
1694 */
1695int send_certificate(SSL *ssl)
1696{
1697 int ret = SSL_OK;
1698 int i = 0;
1699 uint8_t *buf = ssl->bm_data;
1700 int offset = 7;
1701 int chain_length;
1702
1703 buf[0] = HS_CERTIFICATE;
1704 buf[1] = 0;
1705 buf[4] = 0;
1706
1707 /* spec says we must check if the hash/sig algorithm is OK */
1708 if (ssl->version >= SSL_PROTOCOL_VERSION_TLS1_2 &&
1709 ((ret = check_certificate_chain(ssl)) != SSL_OK))
1710 {
1711 ret = SSL_ERROR_INVALID_CERT_HASH_ALG;
1712 goto error;
1713 }
1714
1715 while (i < ssl->ssl_ctx->chain_length)
1716 {
1717 SSL_CERT *cert = &ssl->ssl_ctx->certs[i];
1718 buf[offset++] = 0;
1719 buf[offset++] = cert->size >> 8; /* cert 1 length */
1720 buf[offset++] = cert->size & 0xff;
1721 memcpy(&buf[offset], cert->buf, cert->size);
1722 offset += cert->size;
1723 i++;
1724 }
1725
1726 chain_length = offset - 7;
1727 buf[5] = chain_length >> 8; /* cert chain length */
1728 buf[6] = chain_length & 0xff;
1729 chain_length += 3;
1730 buf[2] = chain_length >> 8; /* handshake length */
1731 buf[3] = chain_length & 0xff;
1732 ssl->bm_index = offset;
1733 ret = send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset);
1734
1735error:
1736 return ret;
1737}
1738
1739/**
1740 * Create a blob of memory that we'll get rid of once the handshake is
1741 * complete.
1742 */
1743void disposable_new(SSL *ssl)
1744{
1745 if (ssl->dc == NULL)
1746 {
1747 ssl->dc = (DISPOSABLE_CTX *)calloc(1, sizeof(DISPOSABLE_CTX));
1748 SHA256_Init(&ssl->dc->sha256_ctx);
1749 MD5_Init(&ssl->dc->md5_ctx);
1750 SHA1_Init(&ssl->dc->sha1_ctx);
1751 }
1752}
1753
1754/**
1755 * Remove the temporary blob of memory.
1756 */
1757void disposable_free(SSL *ssl)
1758{
1759 if (ssl->dc)
1760 {
1761 memset(ssl->dc, 0, sizeof(DISPOSABLE_CTX));
1762 free(ssl->dc);
1763 ssl->dc = NULL;
1764 }
1765
1766}
1767
1768#ifndef CONFIG_SSL_SKELETON_MODE /* no session resumption in this mode */
1769/**
1770 * Find if an existing session has the same session id. If so, use the
1771 * master secret from this session for session resumption.
1772 */
1773SSL_SESSION *ssl_session_update(int max_sessions, SSL_SESSION *ssl_sessions[],
1774 SSL *ssl, const uint8_t *session_id)
1775{
1776 time_t tm = time(NULL);
1777 time_t oldest_sess_time = tm;
1778 SSL_SESSION *oldest_sess = NULL;
1779 int i;
1780
1781 /* no sessions? Then bail */
1782 if (max_sessions == 0)
1783 return NULL;
1784
1785 SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1786 if (session_id)
1787 {
1788 for (i = 0; i < max_sessions; i++)
1789 {
1790 if (ssl_sessions[i])
1791 {
1792 /* kill off any expired sessions (including those in
1793 the future) */
1794 if ((tm > ssl_sessions[i]->conn_time + SSL_EXPIRY_TIME) ||
1795 (tm < ssl_sessions[i]->conn_time))
1796 {
1797 session_free(ssl_sessions, i);
1798 continue;
1799 }
1800
1801 /* if the session id matches, it must still be less than
1802 the expiry time */
1803 if (memcmp(ssl_sessions[i]->session_id, session_id,
1804 SSL_SESSION_ID_SIZE) == 0)
1805 {
1806 ssl->session_index = i;
1807 memcpy(ssl->dc->master_secret,
1808 ssl_sessions[i]->master_secret, SSL_SECRET_SIZE);
1809 SET_SSL_FLAG(SSL_SESSION_RESUME);
1810 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1811 return ssl_sessions[i]; /* a session was found */
1812 }
1813 }
1814 }
1815 }
1816
1817 /* If we've got here, no matching session was found - so create one */
1818 for (i = 0; i < max_sessions; i++)
1819 {
1820 if (ssl_sessions[i] == NULL)
1821 {
1822 /* perfect, this will do */
1823 ssl_sessions[i] = (SSL_SESSION *)calloc(1, sizeof(SSL_SESSION));
1824 ssl_sessions[i]->conn_time = tm;
1825 ssl->session_index = i;
1826 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1827 return ssl_sessions[i]; /* return the session object */
1828 }
1829 else if (ssl_sessions[i]->conn_time <= oldest_sess_time)
1830 {
1831 /* find the oldest session */
1832 oldest_sess_time = ssl_sessions[i]->conn_time;
1833 oldest_sess = ssl_sessions[i];
1834 ssl->session_index = i;
1835 }
1836 }
1837
1838 /* ok, we've used up all of our sessions. So blow the oldest session away */
1839 oldest_sess->conn_time = tm;
1840 memset(oldest_sess->session_id, 0, SSL_SESSION_ID_SIZE);
1841 memset(oldest_sess->master_secret, 0, SSL_SECRET_SIZE);
1842 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1843 return oldest_sess;
1844}
1845
1846/**
1847 * Free an existing session.
1848 */
1849static void session_free(SSL_SESSION *ssl_sessions[], int sess_index)
1850{
1851 if (ssl_sessions[sess_index])
1852 {
1853 free(ssl_sessions[sess_index]);
1854 ssl_sessions[sess_index] = NULL;
1855 }
1856}
1857
1858/**
1859 * This ssl object doesn't want this session anymore.
1860 */
1861void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl)
1862{
1863 SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1864
1865 if (ssl->ssl_ctx->num_sessions)
1866 {
1867 session_free(ssl_sessions, ssl->session_index);
1868 ssl->session = NULL;
1869 }
1870
1871 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1872}
1873#endif /* CONFIG_SSL_SKELETON_MODE */
1874
1875/*
1876 * Get the session id for a handshake. This will be a 32 byte sequence.
1877 */
1878EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl)
1879{
1880 return ssl->session_id;
1881}
1882
1883/*
1884 * Get the session id size for a handshake.
1885 */
1886EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl)
1887{
1888 return ssl->sess_id_size;
1889}
1890
1891/*
1892 * Return the cipher id (in the SSL form).
1893 */
1894EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl)
1895{
1896 return ssl->cipher;
1897}
1898
1899/*
1900 * Return the status of the handshake.
1901 */
1902EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl)
1903{
1904 return ssl->hs_status;
1905}
1906
1907/*
1908 * Retrieve various parameters about the SSL engine.
1909 */
1910EXP_FUNC int STDCALL ssl_get_config(int offset)
1911{
1912 switch (offset)
1913 {
1914 /* return the appropriate build mode */
1915 case SSL_BUILD_MODE:
1916#if defined(CONFIG_SSL_FULL_MODE)
1917 return SSL_BUILD_FULL_MODE;
1918#elif defined(CONFIG_SSL_ENABLE_CLIENT)
1919 return SSL_BUILD_ENABLE_CLIENT;
1920#elif defined(CONFIG_ENABLE_VERIFICATION)
1921 return SSL_BUILD_ENABLE_VERIFICATION;
1922#elif defined(CONFIG_SSL_SERVER_ONLY )
1923 return SSL_BUILD_SERVER_ONLY;
1924#else
1925 return SSL_BUILD_SKELETON_MODE;
1926#endif
1927
1928 case SSL_MAX_CERT_CFG_OFFSET:
1929 return CONFIG_SSL_MAX_CERTS;
1930
1931#ifdef CONFIG_SSL_CERT_VERIFICATION
1932 case SSL_MAX_CA_CERT_CFG_OFFSET:
1933 return CONFIG_X509_MAX_CA_CERTS;
1934#endif
1935#ifdef CONFIG_SSL_HAS_PEM
1936 case SSL_HAS_PEM:
1937 return 1;
1938#endif
1939 default:
1940 return 0;
1941 }
1942}
1943
1944/**
1945 * Check the certificate chain to see if the certs are supported
1946 */
1947static int check_certificate_chain(SSL *ssl)
1948{
1949 int i = 0;
1950 int ret = SSL_OK;
1951
1952 while (i < ssl->ssl_ctx->chain_length)
1953 {
1954 int j = 0;
1955 uint8_t found = 0;
1956 SSL_CERT *cert = &ssl->ssl_ctx->certs[i];
1957
1958 while (j < ssl->num_sig_algs)
1959 {
1960 if (ssl->sig_algs[j++] == cert->hash_alg)
1961 {
1962 found = 1;
1963 break;
1964 }
1965 }
1966
1967 if (!found)
1968 {
1969
1970 ret = SSL_ERROR_INVALID_CERT_HASH_ALG;
1971 goto error;
1972 }
1973
1974 i++;
1975 }
1976
1977error:
1978 return ret;
1979}
1980
1981#ifdef CONFIG_SSL_CERT_VERIFICATION
1982/**
1983 * Authenticate a received certificate.
1984 */
1985EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
1986{
1987 int ret;
1988 int pathLenConstraint = 0;
1989
1990 SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1991 ret = x509_verify(ssl->ssl_ctx->ca_cert_ctx, ssl->x509_ctx,
1992 &pathLenConstraint);
1993 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1994
1995 if (ret) /* modify into an SSL error type */
1996 {
1997 ret = SSL_X509_ERROR(ret);
1998 }
1999
2000 return ret;
2001}
2002#endif /* CONFIG_SSL_CERT_VERIFICATION */
2003
2004/**
2005 * Process a certificate message.
2006 */
2007int process_certificate(SSL *ssl, X509_CTX **x509_ctx)
2008{
2009 int ret = SSL_OK;
2010 uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index];
2011 int pkt_size = ssl->bm_index;
2012 int cert_size, offset = 5, offset_start;
2013 int total_cert_len = (buf[offset]<<8) + buf[offset+1];
2014 int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
2015 X509_CTX *chain = 0;
2016 X509_CTX **certs = 0;
2017 int *cert_used = 0;
2018 int num_certs = 0;
2019 int i = 0;
2020 offset += 2;
2021
2022 PARANOIA_CHECK(pkt_size, total_cert_len + offset);
2023
2024 // record the start point for the second pass
2025 offset_start = offset;
2026
2027 // first pass - count the certificates
2028 while (offset < total_cert_len)
2029 {
2030 offset++; /* skip empty char */
2031 cert_size = (buf[offset]<<8) + buf[offset+1];
2032 offset += 2;
2033 offset += cert_size;
2034 num_certs++;
2035 }
2036
2037 PARANOIA_CHECK(pkt_size, offset);
2038
2039 certs = (X509_CTX**) calloc(num_certs, sizeof(void*));
2040 cert_used = (int*) calloc(num_certs, sizeof(int));
2041 num_certs = 0;
2042
2043 // restore the offset from the saved value
2044 offset = offset_start;
2045
2046 // second pass - load the certificates
2047 while (offset < total_cert_len)
2048 {
2049 offset++; /* skip empty char */
2050 cert_size = (buf[offset]<<8) + buf[offset+1];
2051 offset += 2;
2052
2053 if (x509_new(&buf[offset], NULL, certs+num_certs))
2054 {
2055 ret = SSL_ERROR_BAD_CERTIFICATE;
2056 goto error;
2057 }
2058
2059#if defined (CONFIG_SSL_FULL_MODE)
2060 if (ssl->ssl_ctx->options & SSL_DISPLAY_CERTS)
2061 x509_print(certs[num_certs], NULL);
2062#endif
2063 num_certs++;
2064 offset += cert_size;
2065 }
2066
2067 PARANOIA_CHECK(pkt_size, offset);
2068
2069 // third pass - link certs together, assume server cert is the first
2070 *x509_ctx = certs[0];
2071 chain = certs[0];
2072 cert_used[0] = 1;
2073
2074#ifndef CONFIG_SSL_SKELETON_MODE
2075 // repeat until the end of the chain is found
2076 while (1)
2077 {
2078 // look for CA cert
2079 for( i = 1; i < num_certs; i++ )
2080 {
2081 if (certs[i] == chain)
2082 continue;
2083
2084 if (cert_used[i])
2085 continue; // don't allow loops
2086
2087 if (asn1_compare_dn(chain->ca_cert_dn, certs[i]->cert_dn) == 0)
2088 {
2089 // CA cert found, add it to the chain
2090 cert_used[i] = 1;
2091 chain->next = certs[i];
2092 chain = certs[i];
2093 break;
2094 }
2095 }
2096
2097 // no CA cert found, reached the end of the chain
2098 if (i >= num_certs)
2099 break;
2100 }
2101
2102 // clean up any certs that aren't part of the chain
2103 for (i = 1; i < num_certs; i++)
2104 {
2105 if (cert_used[i] == 0)
2106 x509_free(certs[i]);
2107 }
2108
2109 /* if we are client we can do the verify now or later */
2110 if (is_client && !IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER))
2111 {
2112 ret = ssl_verify_cert(ssl);
2113 }
2114#endif
2115
2116 ssl->next_state = is_client ? HS_SERVER_HELLO_DONE : HS_CLIENT_KEY_XCHG;
2117 ssl->dc->bm_proc_index += offset;
2118error:
2119 // clean up arrays
2120 if (certs)
2121 free(certs);
2122
2123 if (cert_used)
2124 free(cert_used);
2125
2126 return ret;
2127}
2128
2129//#endif /* CONFIG_SSL_CERT_VERIFICATION */
2130
2131/**
2132 * Debugging routine to display SSL handshaking stuff.
2133 */
2134#ifdef CONFIG_SSL_DIAGNOSTICS
2135/**
2136 * Debugging routine to display SSL states.
2137 */
2138void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok)
2139{
2140 const char *str;
2141
2142 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
2143 return;
2144
2145 printf(not_ok ? "Error - invalid State:\t" : "State:\t");
2146 printf(is_send ? "sending " : "receiving ");
2147
2148 switch (state)
2149 {
2150 case HS_HELLO_REQUEST:
2151 str = "Hello Request (0)";
2152 break;
2153
2154 case HS_CLIENT_HELLO:
2155 str = "Client Hello (1)";
2156 break;
2157
2158 case HS_SERVER_HELLO:
2159 str = "Server Hello (2)";
2160 break;
2161
2162 case HS_CERTIFICATE:
2163 str = "Certificate (11)";
2164 break;
2165
2166 case HS_SERVER_KEY_XCHG:
2167 str = "Certificate Request (12)";
2168 break;
2169
2170 case HS_CERT_REQ:
2171 str = "Certificate Request (13)";
2172 break;
2173
2174 case HS_SERVER_HELLO_DONE:
2175 str = "Server Hello Done (14)";
2176 break;
2177
2178 case HS_CERT_VERIFY:
2179 str = "Certificate Verify (15)";
2180 break;
2181
2182 case HS_CLIENT_KEY_XCHG:
2183 str = "Client Key Exchange (16)";
2184 break;
2185
2186 case HS_FINISHED:
2187 str = "Finished (16)";
2188 break;
2189
2190 default:
2191 str = "Error (Unknown)";
2192
2193 break;
2194 }
2195
2196 printf("%s\n", str);
2197}
2198
2199/**
2200 * Debugging routine to display RSA objects
2201 */
2202void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx)
2203{
2204#ifdef CONFIG_SSL_FULL_MODE
2205 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_RSA))
2206 return;
2207
2208 RSA_print(rsa_ctx);
2209 TTY_FLUSH();
2210#endif
2211}
2212
2213/**
2214 * Debugging routine to display SSL handshaking bytes.
2215 */
2216void DISPLAY_BYTES(SSL *ssl, const char *format,
2217 const uint8_t *data, int size, ...)
2218{
2219 va_list(ap);
2220
2221 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_BYTES))
2222 return;
2223
2224 va_start(ap, size);
2225 print_blob(format, data, size, va_arg(ap, char *));
2226 va_end(ap);
2227 TTY_FLUSH();
2228}
2229
2230/**
2231 * Debugging routine to display SSL handshaking errors.
2232 */
2233EXP_FUNC void STDCALL ssl_display_error(int error_code)
2234{
2235 if (error_code == SSL_OK)
2236 return;
2237
2238 printf("Error: ");
2239
2240 /* X509 error? */
2241 if (error_code < SSL_X509_OFFSET)
2242 {
2243 printf("%s\n", x509_display_error(error_code - SSL_X509_OFFSET));
2244 return;
2245 }
2246
2247 /* SSL alert error code */
2248 if (error_code > SSL_ERROR_CONN_LOST)
2249 {
2250 printf("SSL error %d\n", -error_code);
2251 return;
2252 }
2253
2254 switch (error_code)
2255 {
2256 case SSL_ERROR_DEAD:
2257 printf("connection dead");
2258 break;
2259
2260 case SSL_ERROR_RECORD_OVERFLOW:
2261 printf("record overflow");
2262 break;
2263
2264 case SSL_ERROR_INVALID_HANDSHAKE:
2265 printf("invalid handshake");
2266 break;
2267
2268 case SSL_ERROR_INVALID_PROT_MSG:
2269 printf("invalid protocol message");
2270 break;
2271
2272 case SSL_ERROR_INVALID_HMAC:
2273 printf("invalid mac");
2274 break;
2275
2276 case SSL_ERROR_INVALID_VERSION:
2277 printf("invalid version");
2278 break;
2279
2280 case SSL_ERROR_INVALID_SESSION:
2281 printf("invalid session");
2282 break;
2283
2284 case SSL_ERROR_NO_CIPHER:
2285 printf("no cipher");
2286 break;
2287
2288 case SSL_ERROR_INVALID_CERT_HASH_ALG:
2289 printf("invalid cert hash algorithm");
2290 break;
2291
2292 case SSL_ERROR_CONN_LOST:
2293 printf("connection lost");
2294 break;
2295
2296 case SSL_ERROR_BAD_CERTIFICATE:
2297 printf("bad certificate");
2298 break;
2299
2300 case SSL_ERROR_INVALID_KEY:
2301 printf("invalid key");
2302 break;
2303
2304 case SSL_ERROR_FINISHED_INVALID:
2305 printf("finished invalid");
2306 break;
2307
2308 case SSL_ERROR_NO_CERT_DEFINED:
2309 printf("no certificate defined");
2310 break;
2311
2312 case SSL_ERROR_NO_CLIENT_RENOG:
2313 printf("client renegotiation not supported");
2314 break;
2315
2316 case SSL_ERROR_NOT_SUPPORTED:
2317 printf("Option not supported");
2318 break;
2319
2320 default:
2321 printf("undefined as yet - %d", error_code);
2322 break;
2323 }
2324
2325 printf("\n");
2326}
2327
2328/**
2329 * Debugging routine to display alerts.
2330 */
2331
2332/**
2333 * Debugging routine to display alerts.
2334 */
2335void DISPLAY_ALERT(SSL *ssl, int alert)
2336{
2337 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
2338 return;
2339
2340 printf("Alert: ");
2341
2342 switch (alert)
2343 {
2344 case SSL_ALERT_CLOSE_NOTIFY:
2345 printf("close notify");
2346 break;
2347
2348 case SSL_ALERT_UNEXPECTED_MESSAGE:
2349 printf("unexpected message");
2350 break;
2351
2352 case SSL_ALERT_BAD_RECORD_MAC:
2353 printf("bad record mac");
2354 break;
2355
2356 case SSL_ALERT_RECORD_OVERFLOW:
2357 printf("record overlow");
2358 break;
2359
2360 case SSL_ALERT_HANDSHAKE_FAILURE:
2361 printf("handshake failure");
2362 break;
2363
2364 case SSL_ALERT_BAD_CERTIFICATE:
2365 printf("bad certificate");
2366 break;
2367
2368 case SSL_ALERT_UNSUPPORTED_CERTIFICATE:
2369 printf("unsupported certificate");
2370 break;
2371
2372 case SSL_ALERT_CERTIFICATE_EXPIRED:
2373 printf("certificate expired");
2374 break;
2375
2376 case SSL_ALERT_CERTIFICATE_UNKNOWN:
2377 printf("certificate unknown");
2378 break;
2379
2380 case SSL_ALERT_ILLEGAL_PARAMETER:
2381 printf("illegal parameter");
2382 break;
2383
2384 case SSL_ALERT_UNKNOWN_CA:
2385 printf("unknown ca");
2386 break;
2387
2388 case SSL_ALERT_DECODE_ERROR:
2389 printf("decode error");
2390 break;
2391
2392 case SSL_ALERT_DECRYPT_ERROR:
2393 printf("decrypt error");
2394 break;
2395
2396 case SSL_ALERT_INVALID_VERSION:
2397 printf("invalid version");
2398 break;
2399
2400 case SSL_ALERT_NO_RENEGOTIATION:
2401 printf("no renegotiation");
2402 break;
2403
2404 default:
2405 printf("alert - (unknown %d)", alert);
2406 break;
2407 }
2408
2409 printf("\n");
2410}
2411
2412#endif /* CONFIG_SSL_FULL_MODE */
2413
2414/**
2415 * Return the version of this library.
2416 */
2417EXP_FUNC const char * STDCALL ssl_version()
2418{
2419 static const char * axtls_version = AXTLS_VERSION;
2420 return axtls_version;
2421}
2422
2423/**
2424 * Enable the various language bindings to work regardless of the
2425 * configuration - they just return an error statement and a bad return code.
2426 */
2427#if !defined(CONFIG_SSL_DIAGNOSTICS)
2428EXP_FUNC void STDCALL ssl_display_error(int error_code) {}
2429#endif
2430
2431#ifdef CONFIG_BINDINGS
2432#if !defined(CONFIG_SSL_ENABLE_CLIENT)
2433EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, long client_fd, const
2434 uint8_t *session_id, uint8_t sess_id_size)
2435{
2436 printf("%s", unsupported_str);
2437 return NULL;
2438}
2439#endif
2440
2441#if !defined(CONFIG_SSL_CERT_VERIFICATION)
2442EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
2443{
2444 printf("%s", unsupported_str);
2445 return -1;
2446}
2447
2448
2449EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
2450{
2451 printf("%s", unsupported_str);
2452 return NULL;
2453}
2454
2455EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, int index)
2456{
2457 printf("%s", unsupported_str);
2458 return NULL;
2459}
2460
2461#endif /* CONFIG_SSL_CERT_VERIFICATION */
2462
2463#endif /* CONFIG_BINDINGS */
2464
2465