Debian Codegraph @

ccast/axTLS/tls1.c

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