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.
44 #include "lwip/sockets.h"
50 /* The session expiry time */
51 #define SSL_EXPIRY_TIME (CONFIG_SSL_EXPIRY_TIME*3600)
53 static const uint8_t g_hello_request
[] = { HS_HELLO_REQUEST
, 0, 0, 0 };
54 static const uint8_t g_chg_cipher_spec_pkt
[] = { 1 };
55 static const char * server_finished
= "server finished";
56 static const char * client_finished
= "client finished";
58 static int do_handshake(SSL
*ssl
, uint8_t *buf
, int read_len
);
59 static int set_key_block(SSL
*ssl
, int is_write
);
60 static int verify_digest(SSL
*ssl
, int mode
, const uint8_t *buf
, int read_len
);
61 static void *crypt_new(SSL
*ssl
, uint8_t *key
, uint8_t *iv
, int is_decrypt
);
62 static int send_raw_packet(SSL
*ssl
, uint8_t protocol
);
65 * The server will pick the cipher based on the order that the order that the
66 * ciphers are listed. This order is defined at compile time.
68 #ifdef CONFIG_SSL_SKELETON_MODE
69 const uint8_t ssl_prot_prefs
[NUM_PROTOCOLS
] =
72 static void session_free(SSL_SESSION
*ssl_sessions
[], int sess_index
);
74 const uint8_t ssl_prot_prefs
[NUM_PROTOCOLS
] =
75 #ifdef CONFIG_SSL_PROT_LOW /* low security, fast speed */
76 { SSL_RC4_128_SHA
, SSL_AES128_SHA
, SSL_AES256_SHA
, SSL_RC4_128_MD5
};
77 #elif CONFIG_SSL_PROT_MEDIUM /* medium security, medium speed */
78 { SSL_AES128_SHA
, SSL_AES256_SHA
, SSL_RC4_128_SHA
, SSL_RC4_128_MD5
};
79 #else /* CONFIG_SSL_PROT_HIGH */ /* high security, low speed */
80 { SSL_AES256_SHA
, SSL_AES128_SHA
, SSL_RC4_128_SHA
, SSL_RC4_128_MD5
};
82 #endif /* CONFIG_SSL_SKELETON_MODE */
85 * The cipher map containing all the essentials for each cipher.
87 #ifdef CONFIG_SSL_SKELETON_MODE
88 static const cipher_info_t cipher_info
[NUM_PROTOCOLS
] =
91 SSL_RC4_128_SHA
, /* RC4-SHA */
94 2*(SHA1_SIZE
+16), /* key block size */
96 SHA1_SIZE
, /* digest size */
97 hmac_sha1
, /* hmac algorithm */
98 (crypt_func
)RC4_crypt
, /* encrypt */
99 (crypt_func
)RC4_crypt
/* decrypt */
103 static const cipher_info_t cipher_info
[NUM_PROTOCOLS
] =
106 SSL_AES128_SHA
, /* AES128-SHA */
109 2*(SHA1_SIZE
+16+16), /* key block size */
110 16, /* block padding size */
111 SHA1_SIZE
, /* digest size */
112 hmac_sha1
, /* hmac algorithm */
113 (crypt_func
)AES_cbc_encrypt
, /* encrypt */
114 (crypt_func
)AES_cbc_decrypt
/* decrypt */
117 SSL_AES256_SHA
, /* AES256-SHA */
120 2*(SHA1_SIZE
+32+16), /* key block size */
121 16, /* block padding size */
122 SHA1_SIZE
, /* digest size */
123 hmac_sha1
, /* hmac algorithm */
124 (crypt_func
)AES_cbc_encrypt
, /* encrypt */
125 (crypt_func
)AES_cbc_decrypt
/* decrypt */
128 SSL_RC4_128_SHA
, /* RC4-SHA */
131 2*(SHA1_SIZE
+16), /* key block size */
133 SHA1_SIZE
, /* digest size */
134 hmac_sha1
, /* hmac algorithm */
135 (crypt_func
)RC4_crypt
, /* encrypt */
136 (crypt_func
)RC4_crypt
/* decrypt */
139 * This protocol is from SSLv2 days and is unlikely to be used - but was
140 * useful for testing different possible digest algorithms.
143 SSL_RC4_128_MD5
, /* RC4-MD5 */
146 2*(MD5_SIZE
+16), /* key block size */
148 MD5_SIZE
, /* digest size */
149 hmac_md5
, /* hmac algorithm */
150 (crypt_func
)RC4_crypt
, /* encrypt */
151 (crypt_func
)RC4_crypt
/* decrypt */
156 static void prf(const uint8_t *sec
, int sec_len
, uint8_t *seed
, int seed_len
,
157 uint8_t *out
, int olen
);
158 static const cipher_info_t
*get_cipher_info(uint8_t cipher
);
159 static void increment_read_sequence(SSL
*ssl
);
160 static void increment_write_sequence(SSL
*ssl
);
161 static void add_hmac_digest(SSL
*ssl
, int snd
, uint8_t *hmac_header
,
162 const uint8_t *buf
, int buf_len
, uint8_t *hmac_buf
);
164 /* win32 VC6.0 doesn't have variadic macros */
165 #if defined(WIN32) && !defined(CONFIG_SSL_FULL_MODE)
166 void DISPLAY_BYTES(SSL
*ssl
, const char *format
,
167 const uint8_t *data
, int size
, ...) {}
171 * Establish a new client/server context.
173 EXP_FUNC SSL_CTX
*STDCALL
ssl_ctx_new(SSL_CTX
*ssl_ctx
, uint32_t options
, int num_sessions
)
175 ssl_ctx
->options
= options
;
178 if (load_key_certs(ssl_ctx
) < 0)
180 printf("error loading key certs\r\n");
181 //free(ssl_ctx); /* can't load our key/certificate pair, so die */
185 #ifndef CONFIG_SSL_SKELETON_MODE
186 ssl_ctx
->num_sessions
= num_sessions
;
189 SSL_CTX_MUTEX_INIT(ssl_ctx
->mutex
);
191 #ifndef CONFIG_SSL_SKELETON_MODE
194 ssl_ctx
->ssl_sessions
= (SSL_SESSION
**)
195 calloc(1, num_sessions
*sizeof(SSL_SESSION
*));
203 * Remove a client/server context.
205 EXP_FUNC
void STDCALL
ssl_ctx_free(SSL_CTX
*ssl_ctx
)
215 /* clear out all the ssl entries */
218 SSL
*next
= ssl
->next
;
223 #ifndef CONFIG_SSL_SKELETON_MODE
224 /* clear out all the sessions */
225 for (i
= 0; i
< ssl_ctx
->num_sessions
; i
++)
226 session_free(ssl_ctx
->ssl_sessions
, i
);
228 free(ssl_ctx
->ssl_sessions
);
232 //while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf)
234 //free(ssl_ctx->certs[i].buf);
235 //ssl_ctx->certs[i++].buf = NULL;
238 #ifdef CONFIG_SSL_CERT_VERIFICATION
239 remove_ca_certs(ssl_ctx
->ca_cert_ctx
);
241 ssl_ctx
->chain_length
= 0;
242 SSL_CTX_MUTEX_DESTROY(ssl_ctx
->mutex
);
243 RSA_free(ssl_ctx
->rsa_ctx
);
249 * Free any used resources used by this connection.
251 EXP_FUNC
void STDCALL
ssl_free(SSL
*ssl
)
255 if (ssl
== NULL
) /* just ignore null pointers */
258 /* only notify if we weren't notified first */
259 /* spec says we must notify when we are dying */
260 if (!IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY
))
261 send_alert(ssl
, SSL_ALERT_CLOSE_NOTIFY
);
263 ssl_ctx
= ssl
->ssl_ctx
;
265 SSL_CTX_LOCK(ssl_ctx
->mutex
);
267 /* adjust the server SSL list */
269 ssl
->prev
->next
= ssl
->next
;
271 ssl_ctx
->head
= ssl
->next
;
274 ssl
->next
->prev
= ssl
->prev
;
276 ssl_ctx
->tail
= ssl
->prev
;
278 SSL_CTX_UNLOCK(ssl_ctx
->mutex
);
280 /* may already be free - but be sure */
281 free(ssl
->encrypt_ctx
);
282 free(ssl
->decrypt_ctx
);
283 disposable_free(ssl
);
285 #ifdef CONFIG_SSL_CERT_VERIFICATION
286 x509_free(ssl
->x509_ctx
);
288 //free(ssl->ssl_ctx);
293 * Write application data to the client
295 EXP_FUNC
int STDCALL
ssl_write(SSL
*ssl
, const uint8_t *out_data
, int out_len
)
297 int n
= out_len
, nw
, i
, tot
= 0;
299 /* maximum size of a TLS packet is around 16kB, so fragment */
304 if (nw
> RT_MAX_PLAIN_LENGTH
) /* fragment if necessary */
305 nw
= RT_MAX_PLAIN_LENGTH
;
307 if ((i
= send_packet(ssl
, PT_APP_PROTOCOL_DATA
,
308 &out_data
[tot
], nw
)) <= 0)
310 out_len
= i
; /* an error */
322 * Add a certificate to the certificate chain.
324 int add_cert(SSL_CTX
*ssl_ctx
, const uint8_t *buf
, int len
)
326 int ret
= SSL_ERROR_NO_CERT_DEFINED
, i
= 0;
328 X509_CTX
*cert
= NULL
;
331 while (ssl_ctx
->certs
[i
].buf
&& i
< CONFIG_SSL_MAX_CERTS
)
334 if (i
== CONFIG_SSL_MAX_CERTS
) /* too many certs */
336 #ifdef CONFIG_SSL_FULL_MODE
337 printf("Error: maximum number of certs added (%d) - change of "
338 "compile-time configuration required\n",
339 CONFIG_SSL_MAX_CERTS
);
344 if ((ret
= x509_new(buf
, &offset
, &cert
)))
347 #if defined (CONFIG_SSL_FULL_MODE)
348 if (ssl_ctx
->options
& SSL_DISPLAY_CERTS
)
349 x509_print(cert
, NULL
);
352 ssl_cert
= &ssl_ctx
->certs
[i
];
353 ssl_cert
->size
= len
;
355 ssl_ctx
->chain_length
++;
357 ret
= SSL_OK
; /* ok so far */
362 ret
= add_cert(ssl_ctx
, &buf
[offset
], len
);
366 x509_free(cert
); /* don't need anymore */
370 #ifdef CONFIG_SSL_CERT_VERIFICATION
372 * Add a certificate authority.
374 int add_cert_auth(SSL_CTX
*ssl_ctx
, const uint8_t *buf
, int len
)
376 int ret
= SSL_OK
; /* ignore errors for now */
378 CA_CERT_CTX
*ca_cert_ctx
;
380 if (ssl_ctx
->ca_cert_ctx
== NULL
)
381 ssl_ctx
->ca_cert_ctx
= (CA_CERT_CTX
*)calloc(1, sizeof(CA_CERT_CTX
));
383 ca_cert_ctx
= ssl_ctx
->ca_cert_ctx
;
385 while (i
< CONFIG_X509_MAX_CA_CERTS
&& ca_cert_ctx
->cert
[i
])
391 if (i
>= CONFIG_X509_MAX_CA_CERTS
)
393 #ifdef CONFIG_SSL_FULL_MODE
394 printf("Error: maximum number of CA certs added (%d) - change of "
395 "compile-time configuration required\n",
396 CONFIG_X509_MAX_CA_CERTS
);
402 /* ignore the return code */
403 if (x509_new(buf
, &offset
, &ca_cert_ctx
->cert
[i
]) == X509_OK
)
405 #if defined (CONFIG_SSL_FULL_MODE)
406 if (ssl_ctx
->options
& SSL_DISPLAY_CERTS
)
407 x509_print(ca_cert_ctx
->cert
[i
], NULL
);
419 * Retrieve an X.509 distinguished name component
421 EXP_FUNC
const char * STDCALL
ssl_get_cert_dn(const SSL
*ssl
, int component
)
423 if (ssl
->x509_ctx
== NULL
)
428 case SSL_X509_CERT_COMMON_NAME
:
429 return ssl
->x509_ctx
->cert_dn
[X509_COMMON_NAME
];
431 case SSL_X509_CERT_ORGANIZATION
:
432 return ssl
->x509_ctx
->cert_dn
[X509_ORGANIZATION
];
434 case SSL_X509_CERT_ORGANIZATIONAL_NAME
:
435 return ssl
->x509_ctx
->cert_dn
[X509_ORGANIZATIONAL_UNIT
];
437 case SSL_X509_CA_CERT_COMMON_NAME
:
438 return ssl
->x509_ctx
->ca_cert_dn
[X509_COMMON_NAME
];
440 case SSL_X509_CA_CERT_ORGANIZATION
:
441 return ssl
->x509_ctx
->ca_cert_dn
[X509_ORGANIZATION
];
443 case SSL_X509_CA_CERT_ORGANIZATIONAL_NAME
:
444 return ssl
->x509_ctx
->ca_cert_dn
[X509_ORGANIZATIONAL_UNIT
];
452 * Retrieve a "Subject Alternative Name" from a v3 certificate
454 EXP_FUNC
const char * STDCALL
ssl_get_cert_subject_alt_dnsname(const SSL
*ssl
,
459 if (ssl
->x509_ctx
== NULL
|| ssl
->x509_ctx
->subject_alt_dnsnames
== NULL
)
462 for (i
= 0; i
< dnsindex
; ++i
)
464 if (ssl
->x509_ctx
->subject_alt_dnsnames
[i
] == NULL
)
468 return ssl
->x509_ctx
->subject_alt_dnsnames
[dnsindex
];
471 #endif /* CONFIG_SSL_CERT_VERIFICATION */
474 * Find an ssl object based on the client's file descriptor.
476 EXP_FUNC SSL
* STDCALL
ssl_find(SSL_CTX
*ssl_ctx
, int client_fd
)
480 SSL_CTX_LOCK(ssl_ctx
->mutex
);
483 /* search through all the ssl entries */
486 if (ssl
->client_fd
== client_fd
)
488 SSL_CTX_UNLOCK(ssl_ctx
->mutex
);
495 SSL_CTX_UNLOCK(ssl_ctx
->mutex
);
500 * Force the client to perform its handshake again.
502 EXP_FUNC
int STDCALL
ssl_renegotiate(SSL
*ssl
)
507 #ifdef CONFIG_SSL_ENABLE_CLIENT
508 if (IS_SET_SSL_FLAG(SSL_IS_CLIENT
))
510 ret
= do_client_connect(ssl
);
515 send_packet(ssl
, PT_HANDSHAKE_PROTOCOL
,
516 g_hello_request
, sizeof(g_hello_request
));
517 SET_SSL_FLAG(SSL_NEED_RECORD
);
524 * @brief Get what we need for key info.
525 * @param cipher [in] The cipher information we are after
526 * @param key_size [out] The key size for the cipher
527 * @param iv_size [out] The iv size for the cipher
528 * @return The amount of key information we need.
530 static const cipher_info_t
*get_cipher_info(uint8_t cipher
)
534 for (i
= 0; i
< NUM_PROTOCOLS
; i
++)
536 if (cipher_info
[i
].cipher
== cipher
)
538 return &cipher_info
[i
];
542 return NULL
; /* error */
546 * Get a new ssl context for a new connection.
548 SSL
*ssl_new(SSL
*ssl
, int client_fd
)
550 SSL_CTX
* ssl_ctx
= ssl
->ssl_ctx
;
551 ssl
->need_bytes
= SSL_RECORD_SIZE
; /* need a record */
553 ssl
->flag
= SSL_NEED_RECORD
;
554 ssl
->bm_data
= ssl
->bm_all_data
+ BM_RECORD_OFFSET
;
555 ssl
->bm_read_index
= 0;
556 ssl
->hs_status
= SSL_NOT_OK
; /* not connected */
557 #ifdef CONFIG_ENABLE_VERIFICATION
558 ssl
->ca_cert_ctx
= ssl_ctx
->ca_cert_ctx
;
562 /* a bit hacky but saves a few bytes of memory */
563 ssl
->flag
|= ssl_ctx
->options
;
564 SSL_CTX_LOCK(ssl_ctx
->mutex
);
566 if (ssl_ctx
->head
== NULL
)
573 ssl
->prev
= ssl_ctx
->tail
;
574 ssl_ctx
->tail
->next
= ssl
;
577 ssl
->encrypt_ctx
= NULL
;
578 ssl
->decrypt_ctx
= NULL
;
580 SSL_CTX_UNLOCK(ssl_ctx
->mutex
);
585 * Add a private key to a context.
587 int add_private_key(SSL_CTX
*ssl_ctx
, SSLObjLoader
*ssl_obj
)
591 /* get the private key details */
592 if (asn1_get_private_key(ssl_obj
->buf
, ssl_obj
->len
, &ssl_ctx
->rsa_ctx
))
594 ret
= SSL_ERROR_INVALID_KEY
;
603 * Increment the read sequence number (as a 64 bit endian indepenent #)
605 static void increment_read_sequence(SSL
*ssl
)
609 for (i
= 7; i
>= 0; i
--)
611 if (++ssl
->read_sequence
[i
])
617 * Increment the read sequence number (as a 64 bit endian indepenent #)
619 static void increment_write_sequence(SSL
*ssl
)
623 for (i
= 7; i
>= 0; i
--)
625 if (++ssl
->write_sequence
[i
])
631 * Work out the HMAC digest in a packet.
633 static void add_hmac_digest(SSL
*ssl
, int mode
, uint8_t *hmac_header
,
634 const uint8_t *buf
, int buf_len
, uint8_t *hmac_buf
)
636 int hmac_len
= buf_len
+ 8 + SSL_RECORD_SIZE
;
637 uint8_t *t_buf
= (uint8_t *)alloca(hmac_len
+10);
639 memcpy(t_buf
, (mode
== SSL_SERVER_WRITE
|| mode
== SSL_CLIENT_WRITE
) ?
640 ssl
->write_sequence
: ssl
->read_sequence
, 8);
641 memcpy(&t_buf
[8], hmac_header
, SSL_RECORD_SIZE
);
642 memcpy(&t_buf
[8+SSL_RECORD_SIZE
], buf
, buf_len
);
644 ssl
->cipher_info
->hmac(t_buf
, hmac_len
,
645 (mode
== SSL_SERVER_WRITE
|| mode
== SSL_CLIENT_READ
) ?
646 ssl
->server_mac
: ssl
->client_mac
,
647 ssl
->cipher_info
->digest_size
, hmac_buf
);
650 print_blob("record", hmac_header
, SSL_RECORD_SIZE
);
651 print_blob("buf", buf
, buf_len
);
652 if (mode
== SSL_SERVER_WRITE
|| mode
== SSL_CLIENT_WRITE
)
654 print_blob("write seq", ssl
->write_sequence
, 8);
658 print_blob("read seq", ssl
->read_sequence
, 8);
661 if (mode
== SSL_SERVER_WRITE
|| mode
== SSL_CLIENT_READ
)
663 print_blob("server mac",
664 ssl
->server_mac
, ssl
->cipher_info
->digest_size
);
668 print_blob("client mac",
669 ssl
->client_mac
, ssl
->cipher_info
->digest_size
);
671 print_blob("hmac", hmac_buf
, SHA1_SIZE
);
676 * Verify that the digest of a packet is correct.
678 static int verify_digest(SSL
*ssl
, int mode
, const uint8_t *buf
, int read_len
)
680 uint8_t hmac_buf
[SHA1_SIZE
];
683 if (ssl
->cipher_info
->padding_size
)
685 int last_blk_size
= buf
[read_len
-1], i
;
686 hmac_offset
= read_len
-last_blk_size
-ssl
->cipher_info
->digest_size
-1;
688 /* guard against a timing attack - make sure we do the digest */
695 /* already looked at last byte */
696 for (i
= 1; i
< last_blk_size
; i
++)
698 if (buf
[read_len
-i
] != last_blk_size
)
706 else /* stream cipher */
708 hmac_offset
= read_len
- ssl
->cipher_info
->digest_size
;
716 /* sanity check the offset */
717 ssl
->hmac_header
[3] = hmac_offset
>> 8; /* insert size */
718 ssl
->hmac_header
[4] = hmac_offset
& 0xff;
719 add_hmac_digest(ssl
, mode
, ssl
->hmac_header
, buf
, hmac_offset
, hmac_buf
);
721 if (memcmp(hmac_buf
, &buf
[hmac_offset
], ssl
->cipher_info
->digest_size
))
723 return SSL_ERROR_INVALID_HMAC
;
730 * Add a packet to the end of our sent and received packets, so that we may use
731 * it to calculate the hash at the end.
733 void add_packet(SSL
*ssl
, const uint8_t *pkt
, int len
)
735 MD5_Update(&ssl
->dc
->md5_ctx
, pkt
, len
);
736 SHA1_Update(&ssl
->dc
->sha1_ctx
, pkt
, len
);
740 * Work out the MD5 PRF.
742 static void p_hash_md5(const uint8_t *sec
, int sec_len
,
743 uint8_t *seed
, int seed_len
, uint8_t *out
, int olen
)
748 hmac_md5(seed
, seed_len
, sec
, sec_len
, a1
);
749 memcpy(&a1
[MD5_SIZE
], seed
, seed_len
);
750 hmac_md5(a1
, MD5_SIZE
+seed_len
, sec
, sec_len
, out
);
752 while (olen
> MD5_SIZE
)
754 uint8_t a2
[MD5_SIZE
];
759 hmac_md5(a1
, MD5_SIZE
, sec
, sec_len
, a2
);
760 memcpy(a1
, a2
, MD5_SIZE
);
762 /* work out the actual hash */
763 hmac_md5(a1
, MD5_SIZE
+seed_len
, sec
, sec_len
, out
);
768 * Work out the SHA1 PRF.
770 static void p_hash_sha1(const uint8_t *sec
, int sec_len
,
771 uint8_t *seed
, int seed_len
, uint8_t *out
, int olen
)
776 hmac_sha1(seed
, seed_len
, sec
, sec_len
, a1
);
777 memcpy(&a1
[SHA1_SIZE
], seed
, seed_len
);
778 hmac_sha1(a1
, SHA1_SIZE
+seed_len
, sec
, sec_len
, out
);
780 while (olen
> SHA1_SIZE
)
782 uint8_t a2
[SHA1_SIZE
];
787 hmac_sha1(a1
, SHA1_SIZE
, sec
, sec_len
, a2
);
788 memcpy(a1
, a2
, SHA1_SIZE
);
790 /* work out the actual hash */
791 hmac_sha1(a1
, SHA1_SIZE
+seed_len
, sec
, sec_len
, out
);
798 static void prf(const uint8_t *sec
, int sec_len
, uint8_t *seed
, int seed_len
,
799 uint8_t *out
, int olen
)
802 const uint8_t *S1
, *S2
;
803 uint8_t xbuf
[256]; /* needs to be > the amount of key data */
804 uint8_t ybuf
[256]; /* needs to be > the amount of key data */
809 len
+= (sec_len
& 1); /* add for odd, make longer */
811 p_hash_md5(S1
, len
, seed
, seed_len
, xbuf
, olen
);
812 p_hash_sha1(S2
, len
, seed
, seed_len
, ybuf
, olen
);
814 for (i
= 0; i
< olen
; i
++)
815 out
[i
] = xbuf
[i
] ^ ybuf
[i
];
819 * Generate a master secret based on the client/server random data and the
822 void generate_master_secret(SSL
*ssl
, const uint8_t *premaster_secret
)
824 uint8_t buf
[128]; /* needs to be > 13+32+32 in size */
825 strcpy((char *)buf
, "master secret");
826 memcpy(&buf
[13], ssl
->dc
->client_random
, SSL_RANDOM_SIZE
);
827 memcpy(&buf
[45], ssl
->dc
->server_random
, SSL_RANDOM_SIZE
);
828 prf(premaster_secret
, SSL_SECRET_SIZE
, buf
, 77, ssl
->dc
->master_secret
,
833 * Generate a 'random' blob of data used for the generation of keys.
835 static void generate_key_block(uint8_t *client_random
, uint8_t *server_random
,
836 uint8_t *master_secret
, uint8_t *key_block
, int key_block_size
)
839 strcpy((char *)buf
, "key expansion");
840 memcpy(&buf
[13], server_random
, SSL_RANDOM_SIZE
);
841 memcpy(&buf
[45], client_random
, SSL_RANDOM_SIZE
);
842 prf(master_secret
, SSL_SECRET_SIZE
, buf
, 77, key_block
, key_block_size
);
846 * Calculate the digest used in the finished message. This function also
847 * doubles up as a certificate verify function.
849 void finished_digest(SSL
*ssl
, const char *label
, uint8_t *digest
)
851 uint8_t mac_buf
[128];
852 uint8_t *q
= mac_buf
;
853 MD5_CTX md5_ctx
= ssl
->dc
->md5_ctx
;
854 SHA1_CTX sha1_ctx
= ssl
->dc
->sha1_ctx
;
858 strcpy((char *)q
, label
);
862 MD5_Final(q
, &md5_ctx
);
865 SHA1_Final(q
, &sha1_ctx
);
870 prf(ssl
->dc
->master_secret
, SSL_SECRET_SIZE
, mac_buf
, (int)(q
-mac_buf
),
871 digest
, SSL_FINISHED_HASH_SIZE
);
873 else /* for use in a certificate verify */
875 memcpy(digest
, mac_buf
, MD5_SIZE
+ SHA1_SIZE
);
879 printf("label: %s\r\n", label
);
880 print_blob("master secret", ssl
->dc
->master_secret
, 48);
881 print_blob("mac_buf", mac_buf
, q
-mac_buf
);
882 print_blob("finished digest", digest
, SSL_FINISHED_HASH_SIZE
);
887 * Retrieve (and initialise) the context of a cipher.
889 static void *crypt_new(SSL
*ssl
, uint8_t *key
, uint8_t *iv
, int is_decrypt
)
893 #ifndef CONFIG_SSL_SKELETON_MODE
896 AES_CTX
*aes_ctx
= (AES_CTX
*)malloc(sizeof(AES_CTX
));
897 AES_set_key(aes_ctx
, key
, iv
, AES_MODE_128
);
901 AES_convert_key(aes_ctx
);
904 return (void *)aes_ctx
;
909 AES_CTX
*aes_ctx
= (AES_CTX
*)malloc(sizeof(AES_CTX
));
910 AES_set_key(aes_ctx
, key
, iv
, AES_MODE_256
);
914 AES_convert_key(aes_ctx
);
917 return (void *)aes_ctx
;
920 case SSL_RC4_128_MD5
:
922 case SSL_RC4_128_SHA
:
924 RC4_CTX
*rc4_ctx
= (RC4_CTX
*)malloc(sizeof(RC4_CTX
));
925 RC4_setup(rc4_ctx
, key
, 16);
926 return (void *)rc4_ctx
;
930 return NULL
; /* its all gone wrong */
935 * Send a packet over the socket.
937 static int send_raw_packet(SSL
*ssl
, uint8_t protocol
)
939 uint8_t *rec_buf
= ssl
->bm_all_data
;
940 int pkt_size
= SSL_RECORD_SIZE
+ssl
->bm_index
;
943 rec_buf
[0] = protocol
;
944 rec_buf
[1] = 0x03; /* version = 3.1 or higher */
945 rec_buf
[2] = ssl
->version
& 0x0f;
946 rec_buf
[3] = ssl
->bm_index
>> 8;
947 rec_buf
[4] = ssl
->bm_index
& 0xff;
949 DISPLAY_BYTES(ssl
, "sending %d bytes", ssl
->bm_all_data
,
954 while (sent
< pkt_size
)
956 ret
= SOCKET_WRITE(ssl
->client_fd
,
957 &ssl
->bm_all_data
[sent
], pkt_size
-sent
);
964 if (GetLastError() != WSAEWOULDBLOCK
)
966 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
)
968 return SSL_ERROR_CONN_LOST
;
971 /* keep going until the write buffer has some space */
972 if (sent
!= pkt_size
)
976 FD_SET(ssl
->client_fd
, &wfds
);
978 /* block and wait for it */
979 if (lwip_select(FD_SETSIZE
, NULL
, &wfds
, NULL
, NULL
) < 0)
980 return SSL_ERROR_CONN_LOST
;
986 FD_SET(ssl
->client_fd
, &wfds
);
988 /* block and wait for it */
989 if (lwip_select(FD_SETSIZE
, NULL
, &wfds
, NULL
, NULL
) < 0)
990 return SSL_ERROR_CONN_LOST
;
992 SET_SSL_FLAG(SSL_NEED_RECORD
); /* reset for next time */
995 if (protocol
!= PT_APP_PROTOCOL_DATA
)
997 /* always return SSL_OK during handshake */
1005 * Send an encrypted packet with padding bytes if necessary.
1007 int send_packet(SSL
*ssl
, uint8_t protocol
, const uint8_t *in
, int length
)
1009 int ret
, msg_length
= 0;
1011 /* if our state is bad, don't bother */
1012 if (ssl
->hs_status
== SSL_ERROR_DEAD
)
1013 return SSL_ERROR_CONN_LOST
;
1015 if (in
) /* has the buffer already been initialised? */
1017 memcpy(ssl
->bm_data
, in
, length
);
1020 msg_length
+= length
;
1022 if (IS_SET_SSL_FLAG(SSL_TX_ENCRYPTED
))
1024 int mode
= IS_SET_SSL_FLAG(SSL_IS_CLIENT
) ?
1025 SSL_CLIENT_WRITE
: SSL_SERVER_WRITE
;
1026 uint8_t hmac_header
[SSL_RECORD_SIZE
] =
1029 0x03, /* version = 3.1 or higher */
1030 ssl
->version
& 0x0f,
1035 if (protocol
== PT_HANDSHAKE_PROTOCOL
)
1037 DISPLAY_STATE(ssl
, 1, ssl
->bm_data
[0], 0);
1039 if (ssl
->bm_data
[0] != HS_HELLO_REQUEST
)
1041 add_packet(ssl
, ssl
->bm_data
, msg_length
);
1045 /* add the packet digest */
1046 add_hmac_digest(ssl
, mode
, hmac_header
, ssl
->bm_data
, msg_length
,
1047 &ssl
->bm_data
[msg_length
]);
1048 msg_length
+= ssl
->cipher_info
->digest_size
;
1051 if (ssl
->cipher_info
->padding_size
)
1053 int last_blk_size
= msg_length
%ssl
->cipher_info
->padding_size
;
1054 int pad_bytes
= ssl
->cipher_info
->padding_size
- last_blk_size
;
1056 /* ensure we always have at least 1 padding byte */
1058 pad_bytes
+= ssl
->cipher_info
->padding_size
;
1060 memset(&ssl
->bm_data
[msg_length
], pad_bytes
-1, pad_bytes
);
1061 msg_length
+= pad_bytes
;
1064 DISPLAY_BYTES(ssl
, "unencrypted write", ssl
->bm_data
, msg_length
);
1065 increment_write_sequence(ssl
);
1067 /* add the explicit IV for TLS1.1 */
1068 if (ssl
->version
>= SSL_PROTOCOL_VERSION1_1
&&
1069 ssl
->cipher_info
->iv_size
)
1071 uint8_t iv_size
= ssl
->cipher_info
->iv_size
;
1072 uint8_t *t_buf
= alloca(msg_length
+ iv_size
);
1073 memcpy(t_buf
+ iv_size
, ssl
->bm_data
, msg_length
);
1074 get_random(iv_size
, t_buf
);
1075 msg_length
+= iv_size
;
1076 memcpy(ssl
->bm_data
, t_buf
, msg_length
);
1079 /* now encrypt the packet */
1080 ssl
->cipher_info
->encrypt(ssl
->encrypt_ctx
, ssl
->bm_data
,
1081 ssl
->bm_data
, msg_length
);
1083 else if (protocol
== PT_HANDSHAKE_PROTOCOL
)
1085 DISPLAY_STATE(ssl
, 1, ssl
->bm_data
[0], 0);
1087 if (ssl
->bm_data
[0] != HS_HELLO_REQUEST
)
1089 add_packet(ssl
, ssl
->bm_data
, length
);
1093 ssl
->bm_index
= msg_length
;
1094 if ((ret
= send_raw_packet(ssl
, protocol
)) <= 0)
1097 return length
; /* just return what we wanted to send */
1101 * Work out the cipher keys we are going to use for this session based on the
1104 static int set_key_block(SSL
*ssl
, int is_write
)
1106 const cipher_info_t
*ciph_info
= get_cipher_info(ssl
->cipher
);
1108 uint8_t client_key
[32], server_key
[32]; /* big enough for AES256 */
1109 uint8_t client_iv
[16], server_iv
[16]; /* big enough for AES128/256 */
1110 int is_client
= IS_SET_SSL_FLAG(SSL_IS_CLIENT
);
1112 if (ciph_info
== NULL
)
1115 uint8_t key_tmp
[MAX_KEYBLOCK_SIZE
] = {0};
1116 /* only do once in a handshake */
1117 if (memcmp(ssl
->dc
->key_block
, key_tmp
, MAX_KEYBLOCK_SIZE
) == 0)
1120 print_blob("client", ssl
->dc
->client_random
, 32);
1121 print_blob("server", ssl
->dc
->server_random
, 32);
1122 print_blob("master", ssl
->dc
->master_secret
, SSL_SECRET_SIZE
);
1124 generate_key_block(ssl
->dc
->client_random
, ssl
->dc
->server_random
,
1125 ssl
->dc
->master_secret
, ssl
->dc
->key_block
,
1126 ciph_info
->key_block_size
);
1128 print_blob("keyblock", ssl
->dc
->key_block
, ciph_info
->key_block_size
);
1132 q
= ssl
->dc
->key_block
;
1134 if ((is_client
&& is_write
) || (!is_client
&& !is_write
))
1136 memcpy(ssl
->client_mac
, q
, ciph_info
->digest_size
);
1139 q
+= ciph_info
->digest_size
;
1141 if ((!is_client
&& is_write
) || (is_client
&& !is_write
))
1143 memcpy(ssl
->server_mac
, q
, ciph_info
->digest_size
);
1146 q
+= ciph_info
->digest_size
;
1147 memcpy(client_key
, q
, ciph_info
->key_size
);
1148 q
+= ciph_info
->key_size
;
1149 memcpy(server_key
, q
, ciph_info
->key_size
);
1150 q
+= ciph_info
->key_size
;
1152 #ifndef CONFIG_SSL_SKELETON_MODE
1153 if (ciph_info
->iv_size
) /* RC4 has no IV, AES does */
1155 memcpy(client_iv
, q
, ciph_info
->iv_size
);
1156 q
+= ciph_info
->iv_size
;
1157 memcpy(server_iv
, q
, ciph_info
->iv_size
);
1158 q
+= ciph_info
->iv_size
;
1162 if( (is_write
? ssl
->encrypt_ctx
: ssl
->decrypt_ctx
) != NULL
)
1163 free(is_write
? ssl
->encrypt_ctx
: ssl
->decrypt_ctx
);
1165 /* now initialise the ciphers */
1168 finished_digest(ssl
, server_finished
, ssl
->dc
->final_finish_mac
);
1171 ssl
->encrypt_ctx
= crypt_new(ssl
, client_key
, client_iv
, 0);
1173 ssl
->decrypt_ctx
= crypt_new(ssl
, server_key
, server_iv
, 1);
1177 finished_digest(ssl
, client_finished
, ssl
->dc
->final_finish_mac
);
1180 ssl
->encrypt_ctx
= crypt_new(ssl
, server_key
, server_iv
, 0);
1182 ssl
->decrypt_ctx
= crypt_new(ssl
, client_key
, client_iv
, 1);
1185 ssl
->cipher_info
= ciph_info
;
1191 * data must be valid buffer of size length at least
1194 int basic_read2(SSL
*ssl
, uint8_t *data
, uint32_t length
)
1196 // printf("basic_read2\n");
1204 //printf("before_lwip_select\n");
1207 FD_SET(ssl
->client_fd
, &rfds
);
1209 /* block and wait for it */
1210 if (lwip_select(FD_SETSIZE
, &rfds
, NULL
, NULL
, NULL
) < 0)
1211 return SSL_ERROR_CONN_LOST
;
1212 // printf("after_lwip_select\n");
1214 int read_len
= SOCKET_READ(ssl
->client_fd
, &data
[ret
], length
-ret
);
1215 // printf("read_len = %d\n", read_len);
1221 if (GetLastError() == WSAEWOULDBLOCK
)
1223 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
)
1228 /* connection has gone, so die */
1231 printf("SSL_ERROR_CONN_LOST\n");
1232 ssl
->hs_status
= SSL_ERROR_DEAD
; /* make sure it stays dead */
1233 return SSL_ERROR_CONN_LOST
;
1238 }while(ret
< length
);
1239 DISPLAY_BYTES(ssl
, "received %d bytes", data
, ret
, ret
);
1243 int read_record(SSL
*ssl
)
1245 if(!IS_SET_SSL_FLAG(SSL_NEED_RECORD
))
1247 uint8_t record
[SSL_RECORD_SIZE
];
1248 int ret
= basic_read2(ssl
, record
, SSL_RECORD_SIZE
);
1249 if(ret
!= SSL_RECORD_SIZE
)
1252 /* check for sslv2 "client hello" */
1253 if (record
[0] & 0x80 && record
[2] == 1)
1255 #ifdef CONFIG_SSL_ENABLE_V23_HANDSHAKE
1256 uint8_t version
= (record
[3] << 4) + record
[4];
1257 DISPLAY_BYTES(ssl
, "ssl2 record", record
, 5);
1259 /* should be v3.1 (TLSv1) or better */
1260 ssl
->version
= ssl
->client_version
= version
;
1262 if (version
> SSL_PROTOCOL_VERSION_MAX
)
1264 /* use client's version */
1265 ssl
->version
= SSL_PROTOCOL_VERSION_MAX
;
1267 else if (version
< SSL_PROTOCOL_MIN_VERSION
)
1269 ret
= SSL_ERROR_INVALID_VERSION
;
1270 ssl_display_error(ret
);
1274 add_packet(ssl
, &record
[2], 3);
1275 ret
= process_sslv23_client_hello(ssl
);
1277 printf("Error: no SSLv23 handshaking allowed\n"); TTY_FLUSH();
1278 ret
= SSL_ERROR_NOT_SUPPORTED
;
1283 ssl
->need_bytes
= (record
[3] << 8) + record
[4];
1286 memcpy(ssl
->hmac_header
, record
, 3); /* store for hmac */
1287 ssl
->record_type
= record
[0];
1288 CLR_SSL_FLAG(SSL_NEED_RECORD
);
1292 int basic_decrypt(SSL
*ssl
, uint8_t *buf
, int len
)
1294 if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED
))
1296 ssl
->cipher_info
->decrypt(ssl
->decrypt_ctx
, buf
, buf
, len
);
1298 if (ssl
->version
>= SSL_PROTOCOL_VERSION1_1
&&
1299 ssl
->cipher_info
->iv_size
)
1301 buf
+= ssl
->cipher_info
->iv_size
;
1302 ssl
->need_bytes
-= ssl
->cipher_info
->iv_size
;
1304 if(ssl
->record_type
!= PT_APP_PROTOCOL_DATA
)
1305 len
= verify_digest(ssl
,
1306 IS_SET_SSL_FLAG(SSL_IS_CLIENT
) ? SSL_CLIENT_READ
: SSL_SERVER_READ
, buf
, len
);
1308 /* does the hmac work? */
1309 if (ssl
->need_bytes
< 0)
1311 return ssl
->need_bytes
;
1314 DISPLAY_BYTES(ssl
, "decrypted", buf
, len
);
1315 increment_read_sequence(ssl
);
1320 int ssl_read(SSL
*ssl
, uint8_t *in_data
, int len
)
1322 if(len
<= 0 || in_data
== NULL
)
1325 if(IS_SET_SSL_FLAG(SSL_NEED_RECORD
))
1330 return process_data(ssl
, in_data
, len
);
1333 int process_data(SSL
* ssl
, uint8_t *in_data
, int len
)
1335 /* The main part of the SSL packet */
1336 switch (ssl
->record_type
)
1338 case PT_HANDSHAKE_PROTOCOL
:
1340 if (ssl
->dc
!= NULL
)
1342 ssl
->dc
->bm_proc_index
= 0;
1343 int ret
= do_handshake(ssl
, NULL
, 0);
1344 SET_SSL_FLAG(SSL_NEED_RECORD
);
1347 else /* no client renegotiation allowed */
1349 SET_SSL_FLAG(SSL_NEED_RECORD
);
1350 return SSL_ERROR_NO_CLIENT_RENOG
;
1353 case PT_CHANGE_CIPHER_SPEC
:
1355 if(basic_read2(ssl
, ssl
->bm_data
, ssl
->need_bytes
) != ssl
->need_bytes
)
1357 ssl
->need_bytes
= basic_decrypt(ssl
, ssl
->bm_data
, ssl
->need_bytes
);
1358 if(ssl
->need_bytes
< 0)
1361 if (ssl
->next_state
!= HS_FINISHED
)
1363 return SSL_ERROR_INVALID_HANDSHAKE
;
1366 /* all encrypted from now on */
1367 SET_SSL_FLAG(SSL_RX_ENCRYPTED
);
1368 if (set_key_block(ssl
, 0) < 0)
1370 return SSL_ERROR_INVALID_HANDSHAKE
;
1373 memset(ssl
->read_sequence
, 0, 8);
1374 SET_SSL_FLAG(SSL_NEED_RECORD
);
1377 case PT_APP_PROTOCOL_DATA
:
1380 if(ssl
->need_bytes
== 0)
1384 uint16_t index
= ssl
->bm_index
% 2048;
1385 if(ssl
->bm_read_index
== 0)
1388 if(read_len
> 2048-index
)
1389 read_len
= 2048-index
;
1390 if(read_len
> ssl
->need_bytes
)
1391 read_len
= ssl
->need_bytes
;
1392 read_len
-= read_len
% AES_BLOCKSIZE
;
1395 read_len
= AES_BLOCKSIZE
;
1396 if(ssl
->need_bytes
< AES_BLOCKSIZE
)
1397 read_len
= AES_BLOCKSIZE
;
1398 int ret
= basic_read2(ssl
, ssl
->bm_all_data
+ index
, read_len
);
1402 ssl
->bm_read_index
= basic_decrypt(ssl
, ssl
->bm_all_data
+ index
, read_len
);
1403 ssl
->need_bytes
-= ssl
->bm_read_index
;
1404 if(ssl
->need_bytes
== 0)
1406 ssl
->bm_read_index
= 0;
1407 SET_SSL_FLAG(SSL_NEED_RECORD
);
1408 return ssl_read(ssl
, in_data
, len
);
1411 if(len
> ssl
->bm_read_index
)
1412 len
= ssl
->bm_read_index
;
1413 memcpy(in_data
, ssl
->bm_all_data
+index
, len
);
1414 ssl
->bm_index
+= len
;
1415 ssl
->bm_read_index
-= len
;
1417 if(ssl
->need_bytes
== 0)
1418 SET_SSL_FLAG(SSL_NEED_RECORD
);
1419 if(ssl
->bm_index
>= 2048)
1425 case PT_ALERT_PROTOCOL
:
1426 if(basic_read2(ssl
, ssl
->bm_data
, ssl
->need_bytes
) != ssl
->need_bytes
)
1428 ssl
->need_bytes
= basic_decrypt(ssl
, ssl
->bm_data
, ssl
->need_bytes
);
1429 if(ssl
->need_bytes
< 0)
1432 SET_SSL_FLAG(SSL_NEED_RECORD
);
1434 /* return the alert # with alert bit set */
1435 if(ssl
->bm_data
[0] == SSL_ALERT_TYPE_WARNING
&&
1436 ssl
->bm_data
[1] == SSL_ALERT_CLOSE_NOTIFY
)
1438 send_alert(ssl
, SSL_ALERT_CLOSE_NOTIFY
);
1439 SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY
);
1440 return SSL_CLOSE_NOTIFY
;
1444 int ret
= -ssl
->bm_data
[1];
1445 DISPLAY_ALERT(ssl
, -ret
);
1450 return SSL_ERROR_INVALID_PROT_MSG
;
1457 * Do some basic checking of data and then perform the appropriate handshaking.
1459 static int do_handshake(SSL
*ssl
, uint8_t *buf
, int read_len
)
1461 uint8_t hs_hdr
[SSL_HS_HDR_SIZE
];
1462 if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED
))
1464 if(basic_read2(ssl
, ssl
->bm_data
, ssl
->need_bytes
) != ssl
->need_bytes
)
1466 ssl
->need_bytes
= basic_decrypt(ssl
, ssl
->bm_data
, ssl
->need_bytes
);
1467 if(ssl
->need_bytes
< 0)
1473 if(basic_read2(ssl
, hs_hdr
, SSL_HS_HDR_SIZE
) != SSL_HS_HDR_SIZE
)
1478 int hs_len
= (buf
[2]<<8) + buf
[3];
1479 uint8_t handshake_type
= buf
[0];
1481 int is_client
= IS_SET_SSL_FLAG(SSL_IS_CLIENT
);
1483 /* some integrity checking on the handshake */
1484 //PARANOIA_CHECK(read_len-SSL_HS_HDR_SIZE, hs_len);
1486 if (handshake_type
!= ssl
->next_state
)
1488 /* handle a special case on the client */
1489 if (!is_client
|| handshake_type
!= HS_CERT_REQ
||
1490 ssl
->next_state
!= HS_SERVER_HELLO_DONE
)
1492 return SSL_ERROR_INVALID_HANDSHAKE
;
1496 //hs_len += SSL_HS_HDR_SIZE; /* adjust for when adding packets */
1497 ssl
->bm_index
= hs_len
+SSL_HS_HDR_SIZE
; /* store the size and check later */
1498 DISPLAY_STATE(ssl
, 0, handshake_type
, 0);
1500 if (handshake_type
!= HS_CERT_VERIFY
&& handshake_type
!= HS_HELLO_REQUEST
)
1502 add_packet(ssl
, buf
, SSL_HS_HDR_SIZE
);
1505 if(!IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED
))
1507 if(hs_len
!= 0 && handshake_type
!= HS_CERTIFICATE
)
1509 if(basic_read2(ssl
, ssl
->bm_data
, hs_len
) != hs_len
)
1511 hs_len
= basic_decrypt(ssl
, ssl
->bm_data
, hs_len
);
1516 if (handshake_type
!= HS_CERT_VERIFY
&& handshake_type
!= HS_HELLO_REQUEST
)
1517 add_packet(ssl
, buf
, hs_len
);
1520 else if (handshake_type
!= HS_CERT_VERIFY
&& handshake_type
!= HS_HELLO_REQUEST
)
1521 add_packet(ssl
, ssl
->bm_data
+SSL_HS_HDR_SIZE
, hs_len
-SSL_HS_HDR_SIZE
);
1523 #if defined(CONFIG_SSL_ENABLE_CLIENT)
1525 do_clnt_handshake(ssl
, handshake_type
, buf
, hs_len
) :
1526 do_svr_handshake(ssl
, handshake_type
, buf
, hs_len
);
1528 ret
= do_svr_handshake(ssl
, handshake_type
, buf
, hs_len
);
1531 /* just use recursion to get the rest */
1532 //if (hs_len < read_len && ret == SSL_OK)
1533 //ret = do_handshake(ssl, &buf[hs_len], read_len-hs_len);
1539 * Sends the change cipher spec message. We have just read a finished message
1542 int send_change_cipher_spec(SSL
*ssl
)
1544 int ret
= send_packet(ssl
, PT_CHANGE_CIPHER_SPEC
,
1545 g_chg_cipher_spec_pkt
, sizeof(g_chg_cipher_spec_pkt
));
1546 SET_SSL_FLAG(SSL_TX_ENCRYPTED
);
1548 if (ret
>= 0 && set_key_block(ssl
, 1) < 0)
1549 ret
= SSL_ERROR_INVALID_HANDSHAKE
;
1551 memset(ssl
->write_sequence
, 0, 8);
1556 * Send a "finished" message
1558 int send_finished(SSL
*ssl
)
1560 uint8_t buf
[SSL_FINISHED_HASH_SIZE
+4] = {
1561 HS_FINISHED
, 0, 0, SSL_FINISHED_HASH_SIZE
};
1563 /* now add the finished digest mac (12 bytes) */
1564 finished_digest(ssl
,
1565 IS_SET_SSL_FLAG(SSL_IS_CLIENT
) ?
1566 client_finished
: server_finished
, &buf
[4]);
1568 #ifndef CONFIG_SSL_SKELETON_MODE
1569 /* store in the session cache */
1570 if (!IS_SET_SSL_FLAG(SSL_SESSION_RESUME
) && ssl
->ssl_ctx
->num_sessions
)
1572 memcpy(ssl
->session
->master_secret
,
1573 ssl
->dc
->master_secret
, SSL_SECRET_SIZE
);
1577 return send_packet(ssl
, PT_HANDSHAKE_PROTOCOL
,
1578 buf
, SSL_FINISHED_HASH_SIZE
+4);
1582 * Send an alert message.
1583 * Return 1 if the alert was an "error".
1585 int send_alert(SSL
*ssl
, int error_code
)
1591 /* Don't bother we're already dead */
1592 if (ssl
->hs_status
== SSL_ERROR_DEAD
)
1594 return SSL_ERROR_CONN_LOST
;
1597 #ifdef CONFIG_SSL_FULL_MODE
1598 if (IS_SET_SSL_FLAG(SSL_DISPLAY_STATES
))
1599 ssl_display_error(error_code
);
1604 case SSL_ALERT_CLOSE_NOTIFY
:
1606 alert_num
= SSL_ALERT_CLOSE_NOTIFY
;
1609 case SSL_ERROR_CONN_LOST
: /* don't send alert just yet */
1613 case SSL_ERROR_INVALID_HANDSHAKE
:
1614 case SSL_ERROR_INVALID_PROT_MSG
:
1615 alert_num
= SSL_ALERT_HANDSHAKE_FAILURE
;
1618 case SSL_ERROR_INVALID_HMAC
:
1619 case SSL_ERROR_FINISHED_INVALID
:
1620 alert_num
= SSL_ALERT_BAD_RECORD_MAC
;
1623 case SSL_ERROR_INVALID_VERSION
:
1624 alert_num
= SSL_ALERT_INVALID_VERSION
;
1627 case SSL_ERROR_INVALID_SESSION
:
1628 case SSL_ERROR_NO_CIPHER
:
1629 case SSL_ERROR_INVALID_KEY
:
1630 alert_num
= SSL_ALERT_ILLEGAL_PARAMETER
;
1633 case SSL_ERROR_BAD_CERTIFICATE
:
1634 alert_num
= SSL_ALERT_BAD_CERTIFICATE
;
1637 case SSL_ERROR_NO_CLIENT_RENOG
:
1638 alert_num
= SSL_ALERT_NO_RENEGOTIATION
;
1642 /* a catch-all for any badly verified certificates */
1643 alert_num
= (error_code
<= SSL_X509_OFFSET
) ?
1644 SSL_ALERT_BAD_CERTIFICATE
: SSL_ALERT_UNEXPECTED_MESSAGE
;
1648 buf
[0] = is_warning
? 1 : 2;
1651 send_packet(ssl
, PT_ALERT_PROTOCOL
, buf
, sizeof(buf
));
1652 DISPLAY_ALERT(ssl
, alert_num
);
1653 return is_warning
? 0 : 1;
1657 * Process a client finished message.
1659 int process_finished(SSL
*ssl
, uint8_t *buf
, int hs_len
)
1661 int is_client
= IS_SET_SSL_FLAG(SSL_IS_CLIENT
);
1663 int resume
= IS_SET_SSL_FLAG(SSL_SESSION_RESUME
);
1665 PARANOIA_CHECK(ssl
->bm_index
, SSL_FINISHED_HASH_SIZE
);
1667 /* check that we all work before we continue */
1668 if (memcmp(ssl
->dc
->final_finish_mac
, &buf
[4], SSL_FINISHED_HASH_SIZE
))
1670 return SSL_ERROR_FINISHED_INVALID
;
1672 if ((!is_client
&& !resume
) || (is_client
&& resume
))
1674 if ((ret
= send_change_cipher_spec(ssl
)) == SSL_OK
)
1675 ret
= send_finished(ssl
);
1678 /* if we ever renegotiate */
1679 ssl
->next_state
= is_client
? HS_HELLO_REQUEST
: HS_CLIENT_HELLO
;
1680 ssl
->hs_status
= ret
; /* set the final handshake status */
1686 * Send a certificate.
1688 int send_certificate(SSL
*ssl
)
1691 uint8_t *buf
= ssl
->bm_data
;
1695 buf
[0] = HS_CERTIFICATE
;
1699 while (i
< ssl
->ssl_ctx
->chain_length
)
1701 SSL_CERT
*cert
= &ssl
->ssl_ctx
->certs
[i
];
1703 buf
[offset
++] = cert
->size
>> 8; /* cert 1 length */
1704 buf
[offset
++] = cert
->size
& 0xff;
1705 memcpy(&buf
[offset
], cert
->buf
, cert
->size
);
1706 offset
+= cert
->size
;
1710 chain_length
= offset
- 7;
1711 buf
[5] = chain_length
>> 8; /* cert chain length */
1712 buf
[6] = chain_length
& 0xff;
1714 buf
[2] = chain_length
>> 8; /* handshake length */
1715 buf
[3] = chain_length
& 0xff;
1716 ssl
->bm_index
= offset
;
1717 return send_packet(ssl
, PT_HANDSHAKE_PROTOCOL
, NULL
, offset
);
1721 * Create a blob of memory that we'll get rid of once the handshake is
1724 void disposable_new(SSL
*ssl
)
1726 if (ssl
->dc
== NULL
)
1728 ssl
->dc
= (DISPOSABLE_CTX
*)calloc(1, sizeof(DISPOSABLE_CTX
));
1729 memset(ssl
->dc
->key_block
, 0, MAX_KEYBLOCK_SIZE
);
1730 MD5_Init(&ssl
->dc
->md5_ctx
);
1731 SHA1_Init(&ssl
->dc
->sha1_ctx
);
1736 * Remove the temporary blob of memory.
1738 void disposable_free(SSL
*ssl
)
1742 //free(ssl->dc->key_block);
1743 memset(ssl
->dc
, 0, sizeof(DISPOSABLE_CTX
));
1750 #ifndef CONFIG_SSL_SKELETON_MODE /* no session resumption in this mode */
1752 * Find if an existing session has the same session id. If so, use the
1753 * master secret from this session for session resumption.
1755 SSL_SESSION
*ssl_session_update(int max_sessions
, SSL_SESSION
*ssl_sessions
[],
1756 SSL
*ssl
, const uint8_t *session_id
)
1758 time_t tm
= time(NULL
);
1759 time_t oldest_sess_time
= tm
;
1760 SSL_SESSION
*oldest_sess
= NULL
;
1763 /* no sessions? Then bail */
1764 if (max_sessions
== 0)
1767 SSL_CTX_LOCK(ssl
->ssl_ctx
->mutex
);
1770 for (i
= 0; i
< max_sessions
; i
++)
1772 if (ssl_sessions
[i
])
1774 /* kill off any expired sessions (including those in
1776 if ((tm
> ssl_sessions
[i
]->conn_time
+ SSL_EXPIRY_TIME
) ||
1777 (tm
< ssl_sessions
[i
]->conn_time
))
1779 session_free(ssl_sessions
, i
);
1783 /* if the session id matches, it must still be less than
1785 if (memcmp(ssl_sessions
[i
]->session_id
, session_id
,
1786 SSL_SESSION_ID_SIZE
) == 0)
1788 ssl
->session_index
= i
;
1789 memcpy(ssl
->dc
->master_secret
,
1790 ssl_sessions
[i
]->master_secret
, SSL_SECRET_SIZE
);
1791 SET_SSL_FLAG(SSL_SESSION_RESUME
);
1792 SSL_CTX_UNLOCK(ssl
->ssl_ctx
->mutex
);
1793 return ssl_sessions
[i
]; /* a session was found */
1799 /* If we've got here, no matching session was found - so create one */
1800 for (i
= 0; i
< max_sessions
; i
++)
1802 if (ssl_sessions
[i
] == NULL
)
1804 /* perfect, this will do */
1805 ssl_sessions
[i
] = (SSL_SESSION
*)calloc(1, sizeof(SSL_SESSION
));
1806 ssl_sessions
[i
]->conn_time
= tm
;
1807 ssl
->session_index
= i
;
1808 SSL_CTX_UNLOCK(ssl
->ssl_ctx
->mutex
);
1809 return ssl_sessions
[i
]; /* return the session object */
1811 else if (ssl_sessions
[i
]->conn_time
<= oldest_sess_time
)
1813 /* find the oldest session */
1814 oldest_sess_time
= ssl_sessions
[i
]->conn_time
;
1815 oldest_sess
= ssl_sessions
[i
];
1816 ssl
->session_index
= i
;
1820 /* ok, we've used up all of our sessions. So blow the oldest session away */
1821 oldest_sess
->conn_time
= tm
;
1822 memset(oldest_sess
->session_id
, 0, sizeof(SSL_SESSION_ID_SIZE
));
1823 memset(oldest_sess
->master_secret
, 0, sizeof(SSL_SECRET_SIZE
));
1824 SSL_CTX_UNLOCK(ssl
->ssl_ctx
->mutex
);
1829 * Free an existing session.
1831 static void session_free(SSL_SESSION
*ssl_sessions
[], int sess_index
)
1833 if (ssl_sessions
[sess_index
])
1835 free(ssl_sessions
[sess_index
]);
1836 ssl_sessions
[sess_index
] = NULL
;
1841 * This ssl object doesn't want this session anymore.
1843 void kill_ssl_session(SSL_SESSION
**ssl_sessions
, SSL
*ssl
)
1845 SSL_CTX_LOCK(ssl
->ssl_ctx
->mutex
);
1847 if (ssl
->ssl_ctx
->num_sessions
)
1849 session_free(ssl_sessions
, ssl
->session_index
);
1850 ssl
->session
= NULL
;
1853 SSL_CTX_UNLOCK(ssl
->ssl_ctx
->mutex
);
1855 #endif /* CONFIG_SSL_SKELETON_MODE */
1858 * Get the session id for a handshake. This will be a 32 byte sequence.
1860 EXP_FUNC
const uint8_t * STDCALL
ssl_get_session_id(const SSL
*ssl
)
1862 return ssl
->session_id
;
1866 * Get the session id size for a handshake.
1868 EXP_FUNC
uint8_t STDCALL
ssl_get_session_id_size(const SSL
*ssl
)
1870 return ssl
->sess_id_size
;
1874 * Return the cipher id (in the SSL form).
1876 EXP_FUNC
uint8_t STDCALL
ssl_get_cipher_id(const SSL
*ssl
)
1882 * Return the status of the handshake.
1884 EXP_FUNC
int STDCALL
ssl_handshake_status(const SSL
*ssl
)
1886 return ssl
->hs_status
;
1890 * Retrieve various parameters about the SSL engine.
1892 EXP_FUNC
int STDCALL
ssl_get_config(int offset
)
1896 /* return the appropriate build mode */
1897 case SSL_BUILD_MODE
:
1898 #if defined(CONFIG_SSL_FULL_MODE)
1899 return SSL_BUILD_FULL_MODE
;
1900 #elif defined(CONFIG_SSL_ENABLE_CLIENT)
1901 return SSL_BUILD_ENABLE_CLIENT
;
1902 #elif defined(CONFIG_ENABLE_VERIFICATION)
1903 return SSL_BUILD_ENABLE_VERIFICATION
;
1904 #elif defined(CONFIG_SSL_SERVER_ONLY )
1905 return SSL_BUILD_SERVER_ONLY
;
1907 return SSL_BUILD_SKELETON_MODE
;
1910 case SSL_MAX_CERT_CFG_OFFSET
:
1911 return CONFIG_SSL_MAX_CERTS
;
1913 #ifdef CONFIG_SSL_CERT_VERIFICATION
1914 case SSL_MAX_CA_CERT_CFG_OFFSET
:
1915 return CONFIG_X509_MAX_CA_CERTS
;
1917 #ifdef CONFIG_SSL_HAS_PEM
1926 #ifdef CONFIG_SSL_CERT_VERIFICATION
1928 * Authenticate a received certificate.
1930 EXP_FUNC
int STDCALL
ssl_verify_cert(const SSL
*ssl
)
1933 SSL_CTX_LOCK(ssl
->ssl_ctx
->mutex
);
1934 ret
= x509_verify(ssl
->ssl_ctx
->ca_cert_ctx
, ssl
->x509_ctx
);
1935 SSL_CTX_UNLOCK(ssl
->ssl_ctx
->mutex
);
1937 if (ret
) /* modify into an SSL error type */
1939 ret
= SSL_X509_ERROR(ret
);
1946 * Process a certificate message.
1948 int process_certificate(SSL
*ssl
, X509_CTX
**x509_ctx
)
1952 uint8_t cert_hdr
[3];
1953 if(basic_read2(ssl
, cert_hdr
, 3) != 3)
1959 add_packet(ssl
, cert_hdr
, 3);
1961 int pkt_size
= ssl
->bm_index
;
1963 int total_cert_size
= (cert_hdr
[1]<<8) + cert_hdr
[2];
1964 int is_client
= IS_SET_SSL_FLAG(SSL_IS_CLIENT
);
1965 X509_CTX
**chain
= x509_ctx
;
1967 PARANOIA_CHECK(total_cert_size
, 3);
1969 while (len
< total_cert_size
)
1972 if(basic_read2(ssl
, cert_hdr
, 3) != 3)
1978 add_packet(ssl
, cert_hdr
, 3);
1980 cert_size
= (cert_hdr
[1]<<8) + cert_hdr
[2];
1981 if(cert_size
> RT_MAX_PLAIN_LENGTH
)
1989 if(basic_read2(ssl
, ssl
->bm_data
, cert_size
) != cert_size
)
1994 add_packet(ssl
, ssl
->bm_data
, cert_size
);
1996 if (x509_new(ssl
->bm_data
, NULL
, chain
))
1998 ret
= SSL_ERROR_BAD_CERTIFICATE
;
2002 chain
= &((*chain
)->next
);
2005 PARANOIA_CHECK(pkt_size
, len
);
2007 /* if we are client we can do the verify now or later */
2008 if (is_client
&& !IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER
))
2010 ret
= ssl_verify_cert(ssl
);
2013 ssl
->next_state
= is_client
? HS_SERVER_HELLO_DONE
: HS_CLIENT_KEY_XCHG
;
2014 ssl
->dc
->bm_proc_index
+= len
;
2020 #endif /* CONFIG_SSL_CERT_VERIFICATION */
2023 * Debugging routine to display SSL handshaking stuff.
2025 #ifdef CONFIG_SSL_FULL_MODE
2027 * Debugging routine to display SSL states.
2029 void DISPLAY_STATE(SSL
*ssl
, int is_send
, uint8_t state
, int not_ok
)
2033 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES
))
2036 printf(not_ok
? "Error - invalid State:\t" : "State:\t");
2037 printf(is_send
? "sending " : "receiving ");
2041 case HS_HELLO_REQUEST
:
2042 str
= "Hello Request (0)";
2045 case HS_CLIENT_HELLO
:
2046 str
= "Client Hello (1)";
2049 case HS_SERVER_HELLO
:
2050 str
= "Server Hello (2)";
2053 case HS_CERTIFICATE
:
2054 str
= "Certificate (11)";
2057 case HS_SERVER_KEY_XCHG
:
2058 str
= "Certificate Request (12)";
2062 str
= "Certificate Request (13)";
2065 case HS_SERVER_HELLO_DONE
:
2066 str
= "Server Hello Done (14)";
2069 case HS_CERT_VERIFY
:
2070 str
= "Certificate Verify (15)";
2073 case HS_CLIENT_KEY_XCHG
:
2074 str
= "Client Key Exchange (16)";
2078 str
= "Finished (16)";
2082 str
= "Error (Unknown)";
2087 printf("%s\r\n", str
);
2092 * Debugging routine to display RSA objects
2094 void DISPLAY_RSA(SSL
*ssl
, const RSA_CTX
*rsa_ctx
)
2096 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_RSA
))
2104 * Debugging routine to display SSL handshaking bytes.
2106 void DISPLAY_BYTES(SSL
*ssl
, const char *format
,
2107 const uint8_t *data
, int size
, ...)
2111 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_BYTES
))
2115 print_blob(format
, data
, size
, va_arg(ap
, char *));
2121 * Debugging routine to display SSL handshaking errors.
2123 EXP_FUNC
void STDCALL
ssl_display_error(int error_code
)
2125 if (error_code
== SSL_OK
)
2131 if (error_code
< SSL_X509_OFFSET
)
2133 printf("%s\r\n", x509_display_error(error_code
- SSL_X509_OFFSET
));
2137 /* SSL alert error code */
2138 if (error_code
> SSL_ERROR_CONN_LOST
)
2140 printf("SSL error %d\n", -error_code
);
2146 case SSL_ERROR_DEAD
:
2147 printf("connection dead");
2150 case SSL_ERROR_INVALID_HANDSHAKE
:
2151 printf("invalid handshake");
2154 case SSL_ERROR_INVALID_PROT_MSG
:
2155 printf("invalid protocol message");
2158 case SSL_ERROR_INVALID_HMAC
:
2159 printf("invalid mac");
2162 case SSL_ERROR_INVALID_VERSION
:
2163 printf("invalid version");
2166 case SSL_ERROR_INVALID_SESSION
:
2167 printf("invalid session");
2170 case SSL_ERROR_NO_CIPHER
:
2171 printf("no cipher");
2174 case SSL_ERROR_CONN_LOST
:
2175 printf("connection lost");
2178 case SSL_ERROR_BAD_CERTIFICATE
:
2179 printf("bad certificate");
2182 case SSL_ERROR_INVALID_KEY
:
2183 printf("invalid key");
2186 case SSL_ERROR_FINISHED_INVALID
:
2187 printf("finished invalid");
2190 case SSL_ERROR_NO_CERT_DEFINED
:
2191 printf("no certificate defined");
2194 case SSL_ERROR_NO_CLIENT_RENOG
:
2195 printf("client renegotiation not supported");
2198 case SSL_ERROR_NOT_SUPPORTED
:
2199 printf("Option not supported");
2203 printf("undefined as yet - %d", error_code
);
2212 * Debugging routine to display alerts.
2214 void DISPLAY_ALERT(SSL
*ssl
, int alert
)
2216 if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES
))
2223 case SSL_ALERT_CLOSE_NOTIFY
:
2224 printf("close notify");
2227 case SSL_ALERT_INVALID_VERSION
:
2228 printf("invalid version");
2231 case SSL_ALERT_BAD_CERTIFICATE
:
2232 printf("bad certificate");
2235 case SSL_ALERT_UNEXPECTED_MESSAGE
:
2236 printf("unexpected message");
2239 case SSL_ALERT_BAD_RECORD_MAC
:
2240 printf("bad record mac");
2243 case SSL_ALERT_HANDSHAKE_FAILURE
:
2244 printf("handshake failure");
2247 case SSL_ALERT_ILLEGAL_PARAMETER
:
2248 printf("illegal parameter");
2251 case SSL_ALERT_DECODE_ERROR
:
2252 printf("decode error");
2255 case SSL_ALERT_DECRYPT_ERROR
:
2256 printf("decrypt error");
2259 case SSL_ALERT_NO_RENEGOTIATION
:
2260 printf("no renegotiation");
2264 printf("alert - (unknown %d)", alert
);
2272 #endif /* CONFIG_SSL_FULL_MODE */
2275 * Return the version of this library.
2277 EXP_FUNC
const char * STDCALL
ssl_version()
2279 static const char * axtls_version
= AXTLS_VERSION
;
2280 return axtls_version
;
2284 * Enable the various language bindings to work regardless of the
2285 * configuration - they just return an error statement and a bad return code.
2287 #if !defined(CONFIG_SSL_FULL_MODE)
2288 EXP_FUNC
void STDCALL
ssl_display_error(int error_code
) {}
2291 #ifdef CONFIG_BINDINGS
2292 #if !defined(CONFIG_SSL_ENABLE_CLIENT)
2293 EXP_FUNC SSL
* STDCALL
ssl_client_new(SSL_CTX
*ssl_ctx
, int client_fd
, const
2294 uint8_t *session_id
, uint8_t sess_id_size
)
2296 printf(unsupported_str
);
2301 #if !defined(CONFIG_SSL_CERT_VERIFICATION)
2302 EXP_FUNC
int STDCALL
ssl_verify_cert(const SSL
*ssl
)
2304 printf(unsupported_str
);
2309 EXP_FUNC
const char * STDCALL
ssl_get_cert_dn(const SSL
*ssl
, int component
)
2311 printf(unsupported_str
);
2315 EXP_FUNC
const char * STDCALL
ssl_get_cert_subject_alt_dnsname(const SSL
*ssl
, int index
)
2317 printf(unsupported_str
);
2321 #endif /* CONFIG_SSL_CERT_VERIFICATION */
2323 #endif /* CONFIG_BINDINGS */