2 * Copyright (c) 2007, Cameron Rich
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
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.
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.
32 * Common ssl/tlsv1 code to both the client and server implementations.
41 /* The session expiry time */
42 #define SSL_EXPIRY_TIME (CONFIG_SSL_EXPIRY_TIME*3600)
44 static const uint8_t g_hello_request[] = { HS_HELLO_REQUEST, 0, 0, 0 };
45 static const uint8_t g_chg_cipher_spec_pkt[] = { 1 };
46 static const char * server_finished = "server finished";
47 static const char * client_finished = "client finished";
49 static int do_handshake(SSL *ssl, uint8_t *buf, int read_len);
50 static void set_key_block(SSL *ssl, int is_write);
51 static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len);
52 static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt);
53 static int send_raw_packet(SSL *ssl, uint8_t protocol);
56 * The server will pick the cipher based on the order that the order that the
57 * ciphers are listed. This order is defined at compile time.
59 #ifdef CONFIG_SSL_SKELETON_MODE
60 const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] =
63 static void session_free(SSL_SESSION *ssl_sessions[], int sess_index);
65 const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] =
66 #ifdef CONFIG_SSL_PROT_LOW /* low security, fast speed */
67 { SSL_RC4_128_SHA, SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_MD5 };
68 #elif CONFIG_SSL_PROT_MEDIUM /* medium security, medium speed */
69 { SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 };
70 #else /* CONFIG_SSL_PROT_HIGH */ /* high security, low speed */
71 { SSL_AES256_SHA, SSL_AES128_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 };
73 #endif /* CONFIG_SSL_SKELETON_MODE */
76 * The cipher map containing all the essentials for each cipher.
78 #ifdef CONFIG_SSL_SKELETON_MODE
79 static const cipher_info_t cipher_info[NUM_PROTOCOLS] =
82 SSL_RC4_128_SHA, /* RC4-SHA */
85 2*(SHA1_SIZE+16), /* key block size */
87 SHA1_SIZE, /* digest size */
88 hmac_sha1, /* hmac algorithm */
89 (crypt_func)RC4_crypt, /* encrypt */
90 (crypt_func)RC4_crypt /* decrypt */
94 static const cipher_info_t cipher_info[NUM_PROTOCOLS] =
97 SSL_AES128_SHA, /* AES128-SHA */
100 2*(SHA1_SIZE+16+16), /* key block size */
101 16, /* block padding size */
102 SHA1_SIZE, /* digest size */
103 hmac_sha1, /* hmac algorithm */
104 (crypt_func)AES_cbc_encrypt, /* encrypt */
105 (crypt_func)AES_cbc_decrypt /* decrypt */
108 SSL_AES256_SHA, /* AES256-SHA */
111 2*(SHA1_SIZE+32+16), /* key block size */
112 16, /* block padding size */
113 SHA1_SIZE, /* digest size */
114 hmac_sha1, /* hmac algorithm */
115 (crypt_func)AES_cbc_encrypt, /* encrypt */
116 (crypt_func)AES_cbc_decrypt /* decrypt */
119 SSL_RC4_128_SHA, /* RC4-SHA */
122 2*(SHA1_SIZE+16), /* key block size */
124 SHA1_SIZE, /* digest size */
125 hmac_sha1, /* hmac algorithm */
126 (crypt_func)RC4_crypt, /* encrypt */
127 (crypt_func)RC4_crypt /* decrypt */
130 * This protocol is from SSLv2 days and is unlikely to be used - but was
131 * useful for testing different possible digest algorithms.
134 SSL_RC4_128_MD5, /* RC4-MD5 */
137 2*(MD5_SIZE+16), /* key block size */
139 MD5_SIZE, /* digest size */
140 hmac_md5, /* hmac algorithm */
141 (crypt_func)RC4_crypt, /* encrypt */
142 (crypt_func)RC4_crypt /* decrypt */
147 static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len,
148 uint8_t *out, int olen);
149 static const cipher_info_t *get_cipher_info(uint8_t cipher);
150 static void increment_read_sequence(SSL *ssl);
151 static void increment_write_sequence(SSL *ssl);
152 static void add_hmac_digest(SSL *ssl, int snd, uint8_t *hmac_header,
153 const uint8_t *buf, int buf_len, uint8_t *hmac_buf);
155 /* win32 VC6.0 doesn't have variadic macros */
156 #if defined(WIN32) && !defined(CONFIG_SSL_FULL_MODE)
157 void DISPLAY_BYTES(SSL *ssl, const char *format,
158 const uint8_t *data, int size, ...) {}
162 * Establish a new client/server context.
164 EXP_FUNC SSL_CTX *STDCALL ssl_ctx_new(uint32_t options, int num_sessions)
166 SSL_CTX *ssl_ctx = (SSL_CTX *)calloc(1, sizeof (SSL_CTX));
167 ssl_ctx->options = options;
169 if (load_key_certs(ssl_ctx) < 0)
171 free(ssl_ctx); /* can't load our key/certificate pair, so die */
175 #ifndef CONFIG_SSL_SKELETON_MODE
176 ssl_ctx->num_sessions = num_sessions;
179 SSL_CTX_MUTEX_INIT(ssl_ctx->mutex);
181 #ifndef CONFIG_SSL_SKELETON_MODE
184 ssl_ctx->ssl_sessions = (SSL_SESSION **)
185 calloc(1, num_sessions*sizeof(SSL_SESSION *));
193 * Remove a client/server context.
195 EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx)
205 /* clear out all the ssl entries */
208 SSL *next = ssl->next;
213 #ifndef CONFIG_SSL_SKELETON_MODE
214 /* clear out all the sessions */
215 for (i = 0; i < ssl_ctx->num_sessions; i++)
216 session_free(ssl_ctx->ssl_sessions, i);
218 free(ssl_ctx->ssl_sessions);
222 while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf)
224 free(ssl_ctx->certs[i].buf);
225 ssl_ctx->certs[i++].buf = NULL;
228 #ifdef CONFIG_SSL_CERT_VERIFICATION
229 remove_ca_certs(ssl_ctx->ca_cert_ctx);
231 ssl_ctx->chain_length = 0;
232 SSL_CTX_MUTEX_DESTROY(ssl_ctx->mutex);
233 RSA_free(ssl_ctx->rsa_ctx);
239 * Free any used resources used by this connection.
241 EXP_FUNC void STDCALL ssl_free(SSL *ssl)
245 if (ssl == NULL) /* just ignore null pointers */
248 /* spec says we must notify when we are dying */
249 send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
251 ssl_ctx = ssl->ssl_ctx;
253 SSL_CTX_LOCK(ssl_ctx->mutex);
255 /* adjust the server SSL list */
257 ssl->prev->next = ssl->next;
259 ssl_ctx->head = ssl->next;
262 ssl->next->prev = ssl->prev;
264 ssl_ctx->tail = ssl->prev;
266 SSL_CTX_UNLOCK(ssl_ctx->mutex);
268 /* may already be free - but be sure */
269 free(ssl->encrypt_ctx);
270 free(ssl->decrypt_ctx);
271 disposable_free(ssl);
272 #ifdef CONFIG_SSL_CERT_VERIFICATION
273 x509_free(ssl->x509_ctx);
280 * Read the SSL connection and send any alerts for various errors.
282 EXP_FUNC int STDCALL ssl_read(SSL *ssl, uint8_t **in_data)
284 int ret = basic_read(ssl, in_data);
286 /* check for return code so we can send an alert */
289 if (ret != SSL_ERROR_CONN_LOST)
291 send_alert(ssl, ret);
292 #ifndef CONFIG_SSL_SKELETON_MODE
293 /* something nasty happened, so get rid of this session */
294 kill_ssl_session(ssl->ssl_ctx->ssl_sessions, ssl);
303 * Write application data to the client
305 EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len)
307 int n = out_len, nw, i, tot = 0;
309 /* maximum size of a TLS packet is around 16kB, so fragment */
314 if (nw > RT_MAX_PLAIN_LENGTH) /* fragment if necessary */
315 nw = RT_MAX_PLAIN_LENGTH;
317 if ((i = send_packet(ssl, PT_APP_PROTOCOL_DATA,
318 &out_data[tot], nw)) <= 0)
320 out_len = i; /* an error */
332 * Add a certificate to the certificate chain.
334 int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
336 int ret = SSL_ERROR_NO_CERT_DEFINED, i = 0;
338 X509_CTX *cert = NULL;
341 while (ssl_ctx->certs[i].buf && i < CONFIG_SSL_MAX_CERTS)
344 if (i == CONFIG_SSL_MAX_CERTS) /* too many certs */
346 #ifdef CONFIG_SSL_FULL_MODE
347 printf("Error: maximum number of certs added - change of "
348 "compile-time configuration required\n");
353 if ((ret = x509_new(buf, &offset, &cert)))
356 #if defined (CONFIG_SSL_FULL_MODE)
357 if (ssl_ctx->options & SSL_DISPLAY_CERTS)
358 x509_print(cert, NULL);
361 ssl_cert = &ssl_ctx->certs[i];
362 ssl_cert->size = len;
363 ssl_cert->buf = (uint8_t *)malloc(len);
364 memcpy(ssl_cert->buf, buf, len);
365 ssl_ctx->chain_length++;
367 ret = SSL_OK; /* ok so far */
372 ret = add_cert(ssl_ctx, &buf[offset], len);
376 x509_free(cert); /* don't need anymore */
380 #ifdef CONFIG_SSL_CERT_VERIFICATION
382 * Add a certificate authority.
384 int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
386 int ret = SSL_ERROR_NO_CERT_DEFINED;
389 CA_CERT_CTX *ca_cert_ctx;
391 if (ssl_ctx->ca_cert_ctx == NULL)
392 ssl_ctx->ca_cert_ctx = (CA_CERT_CTX *)calloc(1, sizeof(CA_CERT_CTX));
394 ca_cert_ctx = ssl_ctx->ca_cert_ctx;
396 while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i])
399 if (i > CONFIG_X509_MAX_CA_CERTS)
401 #ifdef CONFIG_SSL_FULL_MODE
402 printf("Error: maximum number of CA certs added - change of "
403 "compile-time configuration required\n");
408 if ((ret = x509_new(buf, &offset, &ca_cert_ctx->cert[i])))
412 ret = SSL_OK; /* ok so far */
416 ret = add_cert_auth(ssl_ctx, &buf[offset], len);
423 * Retrieve an X.509 distinguished name component
425 EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
427 if (ssl->x509_ctx == NULL)
432 case SSL_X509_CERT_COMMON_NAME:
433 return ssl->x509_ctx->cert_dn[X509_COMMON_NAME];
435 case SSL_X509_CERT_ORGANIZATION:
436 return ssl->x509_ctx->cert_dn[X509_ORGANIZATION];
438 case SSL_X509_CERT_ORGANIZATIONAL_NAME:
439 return ssl->x509_ctx->cert_dn[X509_ORGANIZATIONAL_UNIT];
441 case SSL_X509_CA_CERT_COMMON_NAME:
442 return ssl->x509_ctx->ca_cert_dn[X509_COMMON_NAME];
444 case SSL_X509_CA_CERT_ORGANIZATION:
445 return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATION];
447 case SSL_X509_CA_CERT_ORGANIZATIONAL_NAME:
448 return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATIONAL_UNIT];
458 * Find an ssl object based on the client's file descriptor.
460 EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd)
464 SSL_CTX_LOCK(ssl_ctx->mutex);
467 /* search through all the ssl entries */
470 if (ssl->client_fd == client_fd)
472 SSL_CTX_UNLOCK(ssl_ctx->mutex);
479 SSL_CTX_UNLOCK(ssl_ctx->mutex);
484 * Force the client to perform its handshake again.
486 EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl)
491 #ifdef CONFIG_SSL_ENABLE_CLIENT
492 if (IS_SET_SSL_FLAG(SSL_IS_CLIENT))
494 ret = do_client_connect(ssl);
499 send_packet(ssl, PT_HANDSHAKE_PROTOCOL,
500 g_hello_request, sizeof(g_hello_request));
501 SET_SSL_FLAG(SSL_NEED_RECORD);
508 * @brief Get what we need for key info.
509 * @param cipher [in] The cipher information we are after
510 * @param key_size [out] The key size for the cipher
511 * @param iv_size [out] The iv size for the cipher
512 * @return The amount of key information we need.
514 static const cipher_info_t *get_cipher_info(uint8_t cipher)
518 for (i = 0; i < NUM_PROTOCOLS; i++)
520 if (cipher_info[i].cipher == cipher)
522 return &cipher_info[i];
526 return NULL; /* error */
530 * Get a new ssl context for a new connection.
532 SSL *ssl_new(SSL_CTX *ssl_ctx, int client_fd)
534 SSL *ssl = (SSL *)calloc(1, sizeof(SSL));
535 ssl->ssl_ctx = ssl_ctx;
536 ssl->need_bytes = SSL_RECORD_SIZE; /* need a record */
537 ssl->client_fd = client_fd;
538 ssl->flag = SSL_NEED_RECORD;
539 ssl->bm_data = ssl->bm_all_data+BM_RECORD_OFFSET; /* space at the start */
540 ssl->hs_status = SSL_NOT_OK; /* not connected */
541 #ifdef CONFIG_ENABLE_VERIFICATION
542 ssl->ca_cert_ctx = ssl_ctx->ca_cert_ctx;
546 /* a bit hacky but saves a few bytes of memory */
547 ssl->flag |= ssl_ctx->options;
548 SSL_CTX_LOCK(ssl_ctx->mutex);
550 if (ssl_ctx->head == NULL)
557 ssl->prev = ssl_ctx->tail;
558 ssl_ctx->tail->next = ssl;
562 SSL_CTX_UNLOCK(ssl_ctx->mutex);
567 * Add a private key to a context.
569 int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj)
573 /* get the private key details */
574 if (asn1_get_private_key(ssl_obj->buf, ssl_obj->len, &ssl_ctx->rsa_ctx))
576 ret = SSL_ERROR_INVALID_KEY;
585 * Increment the read sequence number (as a 64 bit endian indepenent #)
587 static void increment_read_sequence(SSL *ssl)
591 for (i = 7; i >= 0; i--)
593 if (++ssl->read_sequence[i])
599 * Increment the read sequence number (as a 64 bit endian indepenent #)
601 static void increment_write_sequence(SSL *ssl)
605 for (i = 7; i >= 0; i--)
607 if (++ssl->write_sequence[i])
613 * Work out the HMAC digest in a packet.
615 static void add_hmac_digest(SSL *ssl, int mode, uint8_t *hmac_header,
616 const uint8_t *buf, int buf_len, uint8_t *hmac_buf)
618 int hmac_len = buf_len + 8 + SSL_RECORD_SIZE;
619 uint8_t *t_buf = (uint8_t *)alloca(hmac_len+10);
621 memcpy(t_buf, (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) ?
622 ssl->write_sequence : ssl->read_sequence, 8);
623 memcpy(&t_buf[8], hmac_header, SSL_RECORD_SIZE);
624 memcpy(&t_buf[8+SSL_RECORD_SIZE], buf, buf_len);
626 ssl->cipher_info->hmac(t_buf, hmac_len,
627 (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) ?
628 ssl->server_mac : ssl->client_mac,
629 ssl->cipher_info->digest_size, hmac_buf);
632 print_blob("record", ssl->hmac_tx, SSL_RECORD_SIZE);
633 print_blob("buf", buf, buf_len);
634 if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE)
636 print_blob("write seq", ssl->write_sequence, 8);
640 print_blob("read seq", ssl->read_sequence, 8);
643 if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ)
645 print_blob("server mac",
646 ssl->server_mac, ssl->cipher_info->digest_size);
650 print_blob("client mac",
651 ssl->client_mac, ssl->cipher_info->digest_size);
653 print_blob("hmac", hmac_buf, SHA1_SIZE);
658 * Verify that the digest of a packet is correct.
660 static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len)
662 uint8_t hmac_buf[SHA1_SIZE];
665 if (ssl->cipher_info->padding_size)
667 hmac_offset = read_len-buf[read_len-1]-ssl->cipher_info->digest_size-1;
671 hmac_offset = read_len - ssl->cipher_info->digest_size;
674 /* sanity check the offset */
677 return SSL_ERROR_INVALID_HMAC;
680 ssl->hmac_header[3] = hmac_offset >> 8; /* insert size */
681 ssl->hmac_header[4] = hmac_offset & 0xff;
682 add_hmac_digest(ssl, mode, ssl->hmac_header, buf, hmac_offset, hmac_buf);
684 if (memcmp(hmac_buf, &buf[hmac_offset], ssl->cipher_info->digest_size))
686 return SSL_ERROR_INVALID_HMAC;
693 * Add a packet to the end of our sent and received packets, so that we may use
694 * it to calculate the hash at the end.
696 void add_packet(SSL *ssl, const uint8_t *pkt, int len)
698 MD5_Update(&ssl->dc->md5_ctx, pkt, len);
699 SHA1_Update(&ssl->dc->sha1_ctx, pkt, len);
703 * Work out the MD5 PRF.
705 static void p_hash_md5(const uint8_t *sec, int sec_len,
706 uint8_t *seed, int seed_len, uint8_t *out, int olen)
711 hmac_md5(seed, seed_len, sec, sec_len, a1);
712 memcpy(&a1[MD5_SIZE], seed, seed_len);
713 hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
715 while (olen > MD5_SIZE)
717 uint8_t a2[MD5_SIZE];
722 hmac_md5(a1, MD5_SIZE, sec, sec_len, a2);
723 memcpy(a1, a2, MD5_SIZE);
725 /* work out the actual hash */
726 hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
731 * Work out the SHA1 PRF.
733 static void p_hash_sha1(const uint8_t *sec, int sec_len,
734 uint8_t *seed, int seed_len, uint8_t *out, int olen)
739 hmac_sha1(seed, seed_len, sec, sec_len, a1);
740 memcpy(&a1[SHA1_SIZE], seed, seed_len);
741 hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
743 while (olen > SHA1_SIZE)
745 uint8_t a2[SHA1_SIZE];
750 hmac_sha1(a1, SHA1_SIZE, sec, sec_len, a2);
751 memcpy(a1, a2, SHA1_SIZE);
753 /* work out the actual hash */
754 hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
761 static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len,
762 uint8_t *out, int olen)
765 const uint8_t *S1, *S2;
766 uint8_t xbuf[256]; /* needs to be > the amount of key data */
767 uint8_t ybuf[256]; /* needs to be > the amount of key data */
772 len += (sec_len & 1); /* add for odd, make longer */
774 p_hash_md5(S1, len, seed, seed_len, xbuf, olen);
775 p_hash_sha1(S2, len, seed, seed_len, ybuf, olen);
777 for (i = 0; i < olen; i++)
778 out[i] = xbuf[i] ^ ybuf[i];
782 * Generate a master secret based on the client/server random data and the
785 void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret)
787 uint8_t buf[128]; /* needs to be > 13+32+32 in size */
788 strcpy((char *)buf, "master secret");
789 memcpy(&buf[13], ssl->dc->client_random, SSL_RANDOM_SIZE);
790 memcpy(&buf[45], ssl->dc->server_random, SSL_RANDOM_SIZE);
791 prf(premaster_secret, SSL_SECRET_SIZE, buf, 77, ssl->dc->master_secret,
796 * Generate a 'random' blob of data used for the generation of keys.
798 static void generate_key_block(uint8_t *client_random, uint8_t *server_random,
799 uint8_t *master_secret, uint8_t *key_block, int key_block_size)
802 strcpy((char *)buf, "key expansion");
803 memcpy(&buf[13], server_random, SSL_RANDOM_SIZE);
804 memcpy(&buf[45], client_random, SSL_RANDOM_SIZE);
805 prf(master_secret, SSL_SECRET_SIZE, buf, 77, key_block, key_block_size);
809 * Calculate the digest used in the finished message. This function also
810 * doubles up as a certificate verify function.
812 void finished_digest(SSL *ssl, const char *label, uint8_t *digest)
814 uint8_t mac_buf[128];
815 uint8_t *q = mac_buf;
816 MD5_CTX md5_ctx = ssl->dc->md5_ctx;
817 SHA1_CTX sha1_ctx = ssl->dc->sha1_ctx;
821 strcpy((char *)q, label);
825 MD5_Final(q, &md5_ctx);
828 SHA1_Final(q, &sha1_ctx);
833 prf(ssl->dc->master_secret, SSL_SECRET_SIZE, mac_buf, (int)(q-mac_buf),
834 digest, SSL_FINISHED_HASH_SIZE);
836 else /* for use in a certificate verify */
838 memcpy(digest, mac_buf, MD5_SIZE + SHA1_SIZE);
842 printf("label: %s\n", label);
843 print_blob("master secret", ssl->dc->master_secret, 48);
844 print_blob("mac_buf", mac_buf, q-mac_buf);
845 print_blob("finished digest", digest, SSL_FINISHED_HASH_SIZE);
850 * Retrieve (and initialise) the context of a cipher.
852 static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt)
856 #ifndef CONFIG_SSL_SKELETON_MODE
859 AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
860 AES_set_key(aes_ctx, key, iv, AES_MODE_128);
864 AES_convert_key(aes_ctx);
867 return (void *)aes_ctx;
872 AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
873 AES_set_key(aes_ctx, key, iv, AES_MODE_256);
877 AES_convert_key(aes_ctx);
880 return (void *)aes_ctx;
884 case SSL_RC4_128_MD5:
886 case SSL_RC4_128_SHA:
888 RC4_CTX *rc4_ctx = (RC4_CTX *)malloc(sizeof(RC4_CTX));
889 RC4_setup(rc4_ctx, key, 16);
890 return (void *)rc4_ctx;
895 return NULL; /* its all gone wrong */
899 * Send a packet over the socket.
901 static int send_raw_packet(SSL *ssl, uint8_t protocol)
903 uint8_t *rec_buf = ssl->bm_all_data;
904 int pkt_size = SSL_RECORD_SIZE+ssl->bm_index;
908 rec_buf[0] = protocol;
909 rec_buf[1] = 0x03; /* version = 3.1 (TLS) */
911 rec_buf[3] = ssl->bm_index >> 8;
912 rec_buf[4] = ssl->bm_index & 0xff;
914 DISPLAY_BYTES(ssl, "sending %d bytes", ssl->bm_all_data,
917 while (sent < pkt_size)
919 if ((ret = SOCKET_WRITE(ssl->client_fd,
920 &ssl->bm_all_data[sent], pkt_size)) < 0)
922 ret = SSL_ERROR_CONN_LOST;
928 /* keep going until the write buffer has some space */
929 if (sent != pkt_size)
933 FD_SET(ssl->client_fd, &wfds);
935 if (select(ssl->client_fd + 1, NULL, &wfds, NULL, NULL) < 0)
937 ret = SSL_ERROR_CONN_LOST;
943 SET_SSL_FLAG(SSL_NEED_RECORD); /* reset for next time */
946 if (protocol != PT_APP_PROTOCOL_DATA)
948 /* always return SSL_OK during handshake */
956 * Send an encrypted packet with padding bytes if necessary.
958 int send_packet(SSL *ssl, uint8_t protocol, const uint8_t *in, int length)
960 int msg_length = length;
961 int ret, pad_bytes = 0;
962 ssl->bm_index = msg_length;
964 /* if our state is bad, don't bother */
965 if (ssl->hs_status == SSL_ERROR_DEAD)
966 return SSL_ERROR_CONN_LOST;
968 if (in) /* has the buffer already been initialised? */
970 memcpy(ssl->bm_data, in, length);
973 if (IS_SET_SSL_FLAG(SSL_TX_ENCRYPTED))
975 int mode = IS_SET_SSL_FLAG(SSL_IS_CLIENT) ?
976 SSL_CLIENT_WRITE : SSL_SERVER_WRITE;
977 uint8_t hmac_header[SSL_RECORD_SIZE];
979 hmac_header[0] = protocol;
980 hmac_header[1] = 0x03;
981 hmac_header[2] = 0x01;
982 hmac_header[3] = length >> 8;
983 hmac_header[4] = length & 0xff;
985 if (protocol == PT_HANDSHAKE_PROTOCOL)
987 DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
989 if (ssl->bm_data[0] != HS_HELLO_REQUEST)
991 add_packet(ssl, ssl->bm_data, ssl->bm_index);
995 /* add the packet digest */
996 msg_length += ssl->cipher_info->digest_size;
997 ssl->bm_index = msg_length;
998 add_hmac_digest(ssl, mode, hmac_header, ssl->bm_data, length,
999 &ssl->bm_data[length]);
1002 if (ssl->cipher_info->padding_size)
1004 int last_blk_size = msg_length%ssl->cipher_info->padding_size;
1005 pad_bytes = ssl->cipher_info->padding_size - last_blk_size;
1007 /* ensure we always have at least 1 padding byte */
1009 pad_bytes += ssl->cipher_info->padding_size;
1011 memset(&ssl->bm_data[msg_length], pad_bytes-1, pad_bytes);
1012 msg_length += pad_bytes;
1013 ssl->bm_index = msg_length;
1016 DISPLAY_BYTES(ssl, "unencrypted write", ssl->bm_data, msg_length);
1017 increment_write_sequence(ssl);
1019 /* now encrypt the packet */
1020 ssl->cipher_info->encrypt(ssl->encrypt_ctx, ssl->bm_data,
1021 ssl->bm_data, msg_length);
1023 else if (protocol == PT_HANDSHAKE_PROTOCOL)
1025 DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
1027 if (ssl->bm_data[0] != HS_HELLO_REQUEST)
1029 add_packet(ssl, ssl->bm_data, ssl->bm_index);
1033 if ((ret = send_raw_packet(ssl, protocol)) <= 0)
1036 return length; /* just return what we wanted to send */
1040 * Work out the cipher keys we are going to use for this session based on the
1043 static void set_key_block(SSL *ssl, int is_write)
1045 const cipher_info_t *ciph_info = get_cipher_info(ssl->cipher);
1047 uint8_t client_key[32], server_key[32]; /* big enough for AES256 */
1048 uint8_t client_iv[16], server_iv[16]; /* big enough for AES128/256 */
1049 int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1051 /* only do once in a handshake */
1052 if (ssl->dc->key_block == NULL)
1054 ssl->dc->key_block = (uint8_t *)malloc(ciph_info->key_block_size);
1057 print_blob("client", ssl->dc->client_random, 32);
1058 print_blob("server", ssl->dc->server_random, 32);
1059 print_blob("master", ssl->dc->master_secret, SSL_SECRET_SIZE);
1061 generate_key_block(ssl->dc->client_random, ssl->dc->server_random,
1062 ssl->dc->master_secret, ssl->dc->key_block,
1063 ciph_info->key_block_size);
1065 print_blob("keyblock", ssl->key_block, ciph_info->key_block_size);
1069 q = ssl->dc->key_block;
1071 if ((is_client && is_write) || (!is_client && !is_write))
1073 memcpy(ssl->client_mac, q, ciph_info->digest_size);
1076 q += ciph_info->digest_size;
1078 if ((!is_client && is_write) || (is_client && !is_write))
1080 memcpy(ssl->server_mac, q, ciph_info->digest_size);
1083 q += ciph_info->digest_size;
1084 memcpy(client_key, q, ciph_info->key_size);
1085 q += ciph_info->key_size;
1086 memcpy(server_key, q, ciph_info->key_size);
1087 q += ciph_info->key_size;
1089 #ifndef CONFIG_SSL_SKELETON_MODE
1090 if (ciph_info->iv_size) /* RC4 has no IV, AES does */
1092 memcpy(client_iv, q, ciph_info->iv_size);
1093 q += ciph_info->iv_size;
1094 memcpy(server_iv, q, ciph_info->iv_size);
1095 q += ciph_info->iv_size;
1099 free(is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx);
1101 /* now initialise the ciphers */
1104 finished_digest(ssl, server_finished, ssl->dc->final_finish_mac);
1107 ssl->encrypt_ctx = crypt_new(ssl, client_key, client_iv, 0);
1109 ssl->decrypt_ctx = crypt_new(ssl, server_key, server_iv, 1);
1113 finished_digest(ssl, client_finished, ssl->dc->final_finish_mac);
1116 ssl->encrypt_ctx = crypt_new(ssl, server_key, server_iv, 0);
1118 ssl->decrypt_ctx = crypt_new(ssl, client_key, client_iv, 1);
1121 ssl->cipher_info = ciph_info;
1125 * Read the SSL connection.
1127 int basic_read(SSL *ssl, uint8_t **in_data)
1130 int read_len, is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1131 uint8_t *buf = ssl->bm_data;
1133 read_len = SOCKET_READ(ssl->client_fd, &buf[ssl->bm_read_index],
1134 ssl->need_bytes-ssl->got_bytes);
1136 /* connection has gone, so die */
1139 ret = SSL_ERROR_CONN_LOST;
1140 ssl->hs_status = SSL_ERROR_DEAD; /* make sure it stays dead */
1144 DISPLAY_BYTES(ssl, "received %d bytes",
1145 &ssl->bm_data[ssl->bm_read_index], read_len, read_len);
1147 ssl->got_bytes += read_len;
1148 ssl->bm_read_index += read_len;
1150 /* haven't quite got what we want, so try again later */
1151 if (ssl->got_bytes < ssl->need_bytes)
1154 read_len = ssl->got_bytes;
1157 if (IS_SET_SSL_FLAG(SSL_NEED_RECORD))
1159 /* check for sslv2 "client hello" */
1160 if (buf[0] & 0x80 && buf[2] == 1 && buf[3] == 0x03)
1162 #ifdef CONFIG_SSL_ENABLE_V23_HANDSHAKE
1163 DISPLAY_BYTES(ssl, "ssl2 record", buf, 5);
1164 add_packet(ssl, &buf[2], 3);
1165 ret = process_sslv23_client_hello(ssl);
1167 printf("Error: no SSLv23 handshaking allowed\n"); TTY_FLUSH();
1168 ret = SSL_ERROR_NOT_SUPPORTED;
1170 goto error; /* not an error - just get out of here */
1173 ssl->need_bytes = (buf[3] << 8) + buf[4];
1175 /* do we violate the spec with the message size? */
1176 if (ssl->need_bytes > RT_MAX_PLAIN_LENGTH+RT_EXTRA-BM_RECORD_OFFSET)
1178 ret = SSL_ERROR_INVALID_PROT_MSG;
1182 CLR_SSL_FLAG(SSL_NEED_RECORD);
1183 memcpy(ssl->hmac_header, buf, 3); /* store for hmac */
1184 ssl->record_type = buf[0];
1185 goto error; /* no error, we're done */
1188 /* for next time - just do it now in case of an error */
1189 SET_SSL_FLAG(SSL_NEED_RECORD);
1190 ssl->need_bytes = SSL_RECORD_SIZE;
1192 /* decrypt if we need to */
1193 if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
1195 ssl->cipher_info->decrypt(ssl->decrypt_ctx, buf, buf, read_len);
1196 read_len = verify_digest(ssl,
1197 is_client ? SSL_CLIENT_READ : SSL_SERVER_READ, buf, read_len);
1199 /* does the hmac work? */
1206 DISPLAY_BYTES(ssl, "decrypted", buf, read_len);
1207 increment_read_sequence(ssl);
1210 /* The main part of the SSL packet */
1211 switch (ssl->record_type)
1213 case PT_HANDSHAKE_PROTOCOL:
1214 ssl->dc->bm_proc_index = 0;
1215 ret = do_handshake(ssl, buf, read_len);
1218 case PT_CHANGE_CIPHER_SPEC:
1219 if (ssl->next_state != HS_FINISHED)
1221 ret = SSL_ERROR_INVALID_HANDSHAKE;
1225 /* all encrypted from now on */
1226 SET_SSL_FLAG(SSL_RX_ENCRYPTED);
1227 set_key_block(ssl, 0);
1228 memset(ssl->read_sequence, 0, 8);
1231 case PT_APP_PROTOCOL_DATA:
1234 *in_data = ssl->bm_data; /* point to the work buffer */
1235 (*in_data)[read_len] = 0; /* null terminate just in case */
1241 case PT_ALERT_PROTOCOL:
1242 /* return the alert # with alert bit set */
1244 DISPLAY_ALERT(ssl, buf[1]);
1248 ret = SSL_ERROR_INVALID_PROT_MSG;
1253 ssl->bm_read_index = 0; /* reset to go again */
1255 if (ret < SSL_OK && in_data)/* if all wrong, then clear this buffer ptr */
1262 * Do some basic checking of data and then perform the appropriate handshaking.
1264 static int do_handshake(SSL *ssl, uint8_t *buf, int read_len)
1266 int hs_len = (buf[2]<<8) + buf[3];
1267 uint8_t handshake_type = buf[0];
1269 int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1271 /* some integrity checking on the handshake */
1272 PARANOIA_CHECK(read_len-SSL_HS_HDR_SIZE, hs_len);
1274 if (handshake_type != ssl->next_state)
1276 /* handle a special case on the client */
1277 if (!is_client || handshake_type != HS_CERT_REQ ||
1278 ssl->next_state != HS_SERVER_HELLO_DONE)
1280 ret = SSL_ERROR_INVALID_HANDSHAKE;
1285 hs_len += SSL_HS_HDR_SIZE; /* adjust for when adding packets */
1286 ssl->bm_index = hs_len; /* store the size and check later */
1287 DISPLAY_STATE(ssl, 0, handshake_type, 0);
1289 if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
1290 add_packet(ssl, buf, hs_len);
1292 #if defined(CONFIG_SSL_ENABLE_CLIENT)
1294 do_clnt_handshake(ssl, handshake_type, buf, hs_len) :
1295 do_svr_handshake(ssl, handshake_type, buf, hs_len);
1297 ret = do_svr_handshake(ssl, handshake_type, buf, hs_len);
1300 /* just use recursion to get the rest */
1301 if (hs_len < read_len && ret == SSL_OK)
1302 ret = do_handshake(ssl, &buf[hs_len], read_len-hs_len);
1309 * Sends the change cipher spec message. We have just read a finished message
1312 int send_change_cipher_spec(SSL *ssl)
1314 int ret = send_packet(ssl, PT_CHANGE_CIPHER_SPEC,
1315 g_chg_cipher_spec_pkt, sizeof(g_chg_cipher_spec_pkt));
1316 SET_SSL_FLAG(SSL_TX_ENCRYPTED);
1317 set_key_block(ssl, 1);
1318 memset(ssl->write_sequence, 0, 8);
1323 * Send a "finished" message
1325 int send_finished(SSL *ssl)
1327 uint8_t *buf = ssl->bm_data;
1329 buf[0] = HS_FINISHED;
1332 buf[3] = SSL_FINISHED_HASH_SIZE;
1334 /* now add the finished digest mac (12 bytes) */
1335 finished_digest(ssl,
1336 IS_SET_SSL_FLAG(SSL_IS_CLIENT) ?
1337 client_finished : server_finished, &buf[4]);
1339 #ifndef CONFIG_SSL_SKELETON_MODE
1340 /* store in the session cache */
1341 if (!IS_SET_SSL_FLAG(SSL_SESSION_RESUME) && ssl->ssl_ctx->num_sessions)
1343 memcpy(ssl->session->master_secret,
1344 ssl->dc->master_secret, SSL_SECRET_SIZE);
1348 return send_packet(ssl, PT_HANDSHAKE_PROTOCOL,
1349 NULL, SSL_FINISHED_HASH_SIZE+4);
1353 * Send an alert message.
1354 * Return 1 if the alert was an "error".
1356 int send_alert(SSL *ssl, int error_code)
1362 /* Don't bother we're already dead */
1363 if (ssl->hs_status == SSL_ERROR_DEAD)
1365 return SSL_ERROR_CONN_LOST;
1368 #ifdef CONFIG_SSL_FULL_MODE
1369 if (IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
1370 ssl_display_error(error_code);
1375 case SSL_ALERT_CLOSE_NOTIFY:
1377 alert_num = SSL_ALERT_CLOSE_NOTIFY;
1380 case SSL_ERROR_CONN_LOST: /* don't send alert just yet */
1384 case SSL_ERROR_INVALID_HANDSHAKE:
1385 case SSL_ERROR_INVALID_PROT_MSG:
1386 alert_num = SSL_ALERT_HANDSHAKE_FAILURE;
1389 case SSL_ERROR_INVALID_HMAC:
1390 case SSL_ERROR_FINISHED_INVALID:
1391 alert_num = SSL_ALERT_BAD_RECORD_MAC;
1394 case SSL_ERROR_INVALID_VERSION:
1395 alert_num = SSL_ALERT_INVALID_VERSION;
1398 case SSL_ERROR_INVALID_SESSION:
1399 case SSL_ERROR_NO_CIPHER:
1400 case SSL_ERROR_INVALID_KEY:
1401 alert_num = SSL_ALERT_ILLEGAL_PARAMETER;
1404 case SSL_ERROR_BAD_CERTIFICATE:
1405 alert_num = SSL_ALERT_BAD_CERTIFICATE;
1409 /* a catch-all for any badly verified certificates */
1410 alert_num = (error_code <= SSL_X509_OFFSET) ?
1411 SSL_ALERT_BAD_CERTIFICATE : SSL_ALERT_UNEXPECTED_MESSAGE;
1415 buf[0] = is_warning ? 1 : 2;
1417 send_packet(ssl, PT_ALERT_PROTOCOL, buf, sizeof(buf));
1418 DISPLAY_ALERT(ssl, alert_num);
1419 return is_warning ? 0 : 1;
1423 * Process a client finished message.
1425 int process_finished(SSL *ssl, int hs_len)
1427 uint8_t *buf = ssl->bm_data;
1429 int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1430 int resume = IS_SET_SSL_FLAG(SSL_SESSION_RESUME);
1432 PARANOIA_CHECK(ssl->bm_index, SSL_FINISHED_HASH_SIZE+4);
1434 /* check that we all work before we continue */
1435 if (memcmp(ssl->dc->final_finish_mac, &buf[4], SSL_FINISHED_HASH_SIZE))
1436 return SSL_ERROR_FINISHED_INVALID;
1438 if ((!is_client && !resume) || (is_client && resume))
1440 if ((ret = send_change_cipher_spec(ssl)) == SSL_OK)
1441 ret = send_finished(ssl);
1444 /* if we ever renegotiate */
1445 ssl->next_state = is_client ? HS_HELLO_REQUEST : HS_CLIENT_HELLO;
1446 ssl->hs_status = ret; /* set the final handshake status */
1453 * Send a certificate.
1455 int send_certificate(SSL *ssl)
1458 uint8_t *buf = ssl->bm_data;
1462 buf[0] = HS_CERTIFICATE;
1466 while (i < ssl->ssl_ctx->chain_length)
1468 SSL_CERT *cert = &ssl->ssl_ctx->certs[i];
1470 buf[offset++] = cert->size >> 8; /* cert 1 length */
1471 buf[offset++] = cert->size & 0xff;
1472 memcpy(&buf[offset], cert->buf, cert->size);
1473 offset += cert->size;
1477 chain_length = offset - 7;
1478 buf[5] = chain_length >> 8; /* cert chain length */
1479 buf[6] = chain_length & 0xff;
1481 buf[2] = chain_length >> 8; /* handshake length */
1482 buf[3] = chain_length & 0xff;
1483 ssl->bm_index = offset;
1484 return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset);
1488 * Create a blob of memory that we'll get rid of once the handshake is
1491 void disposable_new(SSL *ssl)
1493 if (ssl->dc == NULL)
1495 ssl->dc = (DISPOSABLE_CTX *)calloc(1, sizeof(DISPOSABLE_CTX));
1496 MD5_Init(&ssl->dc->md5_ctx);
1497 SHA1_Init(&ssl->dc->sha1_ctx);
1502 * Remove the temporary blob of memory.
1504 void disposable_free(SSL *ssl)
1508 free(ssl->dc->key_block);
1509 memset(ssl->dc, 0, sizeof(DISPOSABLE_CTX));
1516 #ifndef CONFIG_SSL_SKELETON_MODE /* no session resumption in this mode */
1518 * Find if an existing session has the same session id. If so, use the
1519 * master secret from this session for session resumption.
1521 SSL_SESSION *ssl_session_update(int max_sessions, SSL_SESSION *ssl_sessions[],
1522 SSL *ssl, const uint8_t *session_id)
1524 time_t tm = time(NULL);
1525 time_t oldest_sess_time = tm;
1526 SSL_SESSION *oldest_sess = NULL;
1529 /* no sessions? Then bail */
1530 if (max_sessions == 0)
1533 SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1536 for (i = 0; i < max_sessions; i++)
1538 if (ssl_sessions[i])
1540 /* kill off any expired sessions */
1541 if (tm > ssl_sessions[i]->conn_time + SSL_EXPIRY_TIME)
1543 session_free(ssl_sessions, i);
1547 /* if the session id matches, it must still be less than
1549 if (memcmp(ssl_sessions[i]->session_id, session_id,
1550 SSL_SESSION_ID_SIZE) == 0)
1552 ssl->session_index = i;
1553 memcpy(ssl->dc->master_secret,
1554 ssl_sessions[i]->master_secret, SSL_SECRET_SIZE);
1555 SET_SSL_FLAG(SSL_SESSION_RESUME);
1556 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1557 return ssl_sessions[i]; /* a session was found */
1563 /* If we've got here, no matching session was found - so create one */
1564 for (i = 0; i < max_sessions; i++)
1566 if (ssl_sessions[i] == NULL)
1568 /* perfect, this will do */
1569 ssl_sessions[i] = (SSL_SESSION *)calloc(1, sizeof(SSL_SESSION));
1570 ssl_sessions[i]->conn_time = tm;
1571 ssl->session_index = i;
1572 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1573 return ssl_sessions[i]; /* return the session object */
1575 else if (ssl_sessions[i]->conn_time <= oldest_sess_time)
1577 /* find the oldest session */
1578 oldest_sess_time = ssl_sessions[i]->conn_time;
1579 oldest_sess = ssl_sessions[i];
1580 ssl->session_index = i;
1584 /* ok, we've used up all of our sessions. So blow the oldest session away */
1585 oldest_sess->conn_time = tm;
1586 memset(oldest_sess->session_id, 0, sizeof(SSL_SESSION_ID_SIZE));
1587 memset(oldest_sess->master_secret, 0, sizeof(SSL_SECRET_SIZE));
1588 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1593 * Free an existing session.
1595 static void session_free(SSL_SESSION *ssl_sessions[], int sess_index)
1597 if (ssl_sessions[sess_index])
1599 free(ssl_sessions[sess_index]);
1600 ssl_sessions[sess_index] = NULL;
1605 * This ssl object doesn't want this session anymore.
1607 void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl)
1609 SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1611 if (ssl->ssl_ctx->num_sessions)
1613 session_free(ssl_sessions, ssl->session_index);
1614 ssl->session = NULL;
1617 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1619 #endif /* CONFIG_SSL_SKELETON_MODE */
1622 * Get the session id for a handshake. This will be a 32 byte sequence.
1624 EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl)
1626 return ssl->session_id;
1630 * Get the session id size for a handshake.
1632 EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl)
1634 return ssl->sess_id_size;
1638 * Return the cipher id (in the SSL form).
1640 EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl)
1646 * Return the status of the handshake.
1648 EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl)
1650 return ssl->hs_status;
1654 * Retrieve various parameters about the SSL engine.
1656 EXP_FUNC int STDCALL ssl_get_config(int offset)
1660 /* return the appropriate build mode */
1661 case SSL_BUILD_MODE:
1662 #if defined(CONFIG_SSL_FULL_MODE)
1663 return SSL_BUILD_FULL_MODE;
1664 #elif defined(CONFIG_SSL_ENABLE_CLIENT)
1665 return SSL_BUILD_ENABLE_CLIENT;
1666 #elif defined(CONFIG_ENABLE_VERIFICATION)
1667 return SSL_BUILD_ENABLE_VERIFICATION;
1668 #elif defined(CONFIG_SSL_SERVER_ONLY )
1669 return SSL_BUILD_SERVER_ONLY;
1671 return SSL_BUILD_SKELETON_MODE;
1674 case SSL_MAX_CERT_CFG_OFFSET:
1675 return CONFIG_SSL_MAX_CERTS;
1677 #ifdef CONFIG_SSL_CERT_VERIFICATION
1678 case SSL_MAX_CA_CERT_CFG_OFFSET:
1679 return CONFIG_X509_MAX_CA_CERTS;
1681 #ifdef CONFIG_SSL_HAS_PEM
1690 #ifdef CONFIG_SSL_CERT_VERIFICATION
1692 * Authenticate a received certificate.
1694 EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
1697 SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
1698 ret = x509_verify(ssl->ssl_ctx->ca_cert_ctx, ssl->x509_ctx);
1699 SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
1701 if (ret) /* modify into an SSL error type */
1703 ret = SSL_X509_ERROR(ret);
1710 * Process a certificate message.
1712 int process_certificate(SSL *ssl, X509_CTX **x509_ctx)
1715 uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index];
1716 int pkt_size = ssl->bm_index;
1717 int cert_size, offset = 5;
1718 int total_cert_size = (buf[offset]<<8) + buf[offset+1];
1719 int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
1720 X509_CTX **chain = x509_ctx;
1723 PARANOIA_CHECK(total_cert_size, offset);
1725 while (offset < total_cert_size)
1727 offset++; /* skip empty char */
1728 cert_size = (buf[offset]<<8) + buf[offset+1];
1731 if (x509_new(&buf[offset], NULL, chain))
1733 ret = SSL_ERROR_BAD_CERTIFICATE;
1737 /* DISPLAY_CERT(ssl, *chain); */
1738 chain = &((*chain)->next);
1739 offset += cert_size;
1742 PARANOIA_CHECK(pkt_size, offset);
1744 /* if we are client we can do the verify now or later */
1745 if (is_client && !IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER))
1747 ret = ssl_verify_cert(ssl);
1750 ssl->next_state = is_client ? HS_SERVER_HELLO_DONE : HS_CLIENT_KEY_XCHG;
1751 ssl->dc->bm_proc_index += offset;
1756 #endif /* CONFIG_SSL_CERT_VERIFICATION */
1759 * Debugging routine to display SSL handshaking stuff.
1761 #ifdef CONFIG_SSL_FULL_MODE
1763 * Debugging routine to display SSL states.
1765 void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok)
1769 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
1772 printf(not_ok ? "Error - invalid State:\t" : "State:\t");
1773 printf(is_send ? "sending " : "receiving ");
1777 case HS_HELLO_REQUEST:
1778 str = "Hello Request (0)";
1781 case HS_CLIENT_HELLO:
1782 str = "Client Hello (1)";
1785 case HS_SERVER_HELLO:
1786 str = "Server Hello (2)";
1789 case HS_CERTIFICATE:
1790 str = "Certificate (11)";
1793 case HS_SERVER_KEY_XCHG:
1794 str = "Certificate Request (12)";
1798 str = "Certificate Request (13)";
1801 case HS_SERVER_HELLO_DONE:
1802 str = "Server Hello Done (14)";
1805 case HS_CERT_VERIFY:
1806 str = "Certificate Verify (15)";
1809 case HS_CLIENT_KEY_XCHG:
1810 str = "Client Key Exchange (16)";
1814 str = "Finished (16)";
1818 str = "Error (Unknown)";
1823 printf("%s\n", str);
1828 * Debugging routine to display X509 certificates.
1830 void DISPLAY_CERT(SSL *ssl, const X509_CTX *x509_ctx)
1832 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_CERTS))
1835 x509_print(x509_ctx, ssl->ssl_ctx->ca_cert_ctx);
1840 * Debugging routine to display RSA objects
1842 void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx)
1844 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_RSA))
1852 * Debugging routine to display SSL handshaking bytes.
1854 void DISPLAY_BYTES(SSL *ssl, const char *format,
1855 const uint8_t *data, int size, ...)
1859 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_BYTES))
1863 print_blob(format, data, size, va_arg(ap, char *));
1869 * Debugging routine to display SSL handshaking errors.
1871 EXP_FUNC void STDCALL ssl_display_error(int error_code)
1873 if (error_code == SSL_OK)
1879 if (error_code < SSL_X509_OFFSET)
1881 printf("%s\n", x509_display_error(error_code - SSL_X509_OFFSET));
1885 /* SSL alert error code */
1886 if (error_code > SSL_ERROR_CONN_LOST)
1888 printf("SSL error %d\n", -error_code);
1894 case SSL_ERROR_DEAD:
1895 printf("connection dead");
1898 case SSL_ERROR_INVALID_HANDSHAKE:
1899 printf("invalid handshake");
1902 case SSL_ERROR_INVALID_PROT_MSG:
1903 printf("invalid protocol message");
1906 case SSL_ERROR_INVALID_HMAC:
1907 printf("invalid mac");
1910 case SSL_ERROR_INVALID_VERSION:
1911 printf("invalid version");
1914 case SSL_ERROR_INVALID_SESSION:
1915 printf("invalid session");
1918 case SSL_ERROR_NO_CIPHER:
1919 printf("no cipher");
1922 case SSL_ERROR_CONN_LOST:
1923 printf("connection lost");
1926 case SSL_ERROR_BAD_CERTIFICATE:
1927 printf("bad certificate");
1930 case SSL_ERROR_INVALID_KEY:
1931 printf("invalid key");
1934 case SSL_ERROR_FINISHED_INVALID:
1935 printf("finished invalid");
1938 case SSL_ERROR_NO_CERT_DEFINED:
1939 printf("no certificate defined");
1942 case SSL_ERROR_NOT_SUPPORTED:
1943 printf("Option not supported");
1947 printf("undefined as yet - %d", error_code);
1956 * Debugging routine to display alerts.
1958 void DISPLAY_ALERT(SSL *ssl, int alert)
1960 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
1967 case SSL_ALERT_CLOSE_NOTIFY:
1968 printf("close notify");
1971 case SSL_ALERT_INVALID_VERSION:
1972 printf("invalid version");
1975 case SSL_ALERT_BAD_CERTIFICATE:
1976 printf("bad certificate");
1979 case SSL_ALERT_UNEXPECTED_MESSAGE:
1980 printf("unexpected message");
1983 case SSL_ALERT_BAD_RECORD_MAC:
1984 printf("bad record mac");
1987 case SSL_ALERT_HANDSHAKE_FAILURE:
1988 printf("handshake failure");
1991 case SSL_ALERT_ILLEGAL_PARAMETER:
1992 printf("illegal parameter");
1995 case SSL_ALERT_DECODE_ERROR:
1996 printf("decode error");
1999 case SSL_ALERT_DECRYPT_ERROR:
2000 printf("decrypt error");
2004 printf("alert - (unknown %d)", alert);
2012 #endif /* CONFIG_SSL_FULL_MODE */
2015 * Return the version of this library.
2017 EXP_FUNC const char * STDCALL ssl_version()
2019 static const char * axtls_version = AXTLS_VERSION;
2020 return axtls_version;
2024 * Enable the various language bindings to work regardless of the
2025 * configuration - they just return an error statement and a bad return code.
2027 #if !defined(CONFIG_SSL_FULL_MODE)
2028 EXP_FUNC void STDCALL ssl_display_error(int error_code) {}
2031 #ifdef CONFIG_BINDINGS
2032 #if !defined(CONFIG_SSL_ENABLE_CLIENT)
2033 EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const
2034 uint8_t *session_id, uint8_t sess_id_size)
2036 printf(unsupported_str);
2041 #if !defined(CONFIG_SSL_CERT_VERIFICATION)
2042 EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
2044 printf(unsupported_str);
2048 EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
2050 printf(unsupported_str);
2054 #endif /* CONFIG_SSL_CERT_VERIFICATION */
2056 #endif /* CONFIG_BINDINGS */