]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/net/https/axTLS/ssl/tls1_clnt.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / net / https / axTLS / ssl / tls1_clnt.c
1 /*
2  * Copyright (c) 2007, Cameron Rich
3  * 
4  * All rights reserved.
5  * 
6  * Redistribution and use in source and binary forms, with or without 
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * * Redistributions of source code must retain the above copyright notice, 
10  *   this list of conditions and the following disclaimer.
11  * * Redistributions in binary form must reproduce the above copyright notice, 
12  *   this list of conditions and the following disclaimer in the documentation 
13  *   and/or other materials provided with the distribution.
14  * * Neither the name of the axTLS project nor the names of its contributors 
15  *   may be used to endorse or promote products derived from this software 
16  *   without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include <stdlib.h>
32 #include <string.h>
33 #include <time.h>
34 #include <stdio.h>
35 #include "os_port.h"
36 #include "ssl.h"
37
38 #ifdef CONFIG_SSL_ENABLE_CLIENT        /* all commented out if no client */
39
40 static int send_client_hello(SSL *ssl);
41 static int process_server_hello(SSL *ssl);
42 static int process_server_hello_done(SSL *ssl);
43 static int send_client_key_xchg(SSL *ssl);
44 static int process_cert_req(SSL *ssl);
45 static int send_cert_verify(SSL *ssl);
46
47 /*
48  * Establish a new SSL connection to an SSL server.
49  */
50 EXP_FUNC SSL * STDCALL ssl_client_new(SSL *ssl, int client_fd, const
51         uint8_t *session_id, uint8_t sess_id_size)
52 {
53     SSL_CTX *ssl_ctx = ssl->ssl_ctx;
54     ssl_new(ssl, client_fd);
55     ssl->version = SSL_PROTOCOL_VERSION_MAX; /* try top version first */
56
57     if (session_id && ssl_ctx->num_sessions)
58     {
59         if (sess_id_size > SSL_SESSION_ID_SIZE) /* validity check */
60         {
61             ssl_free(ssl);
62             return NULL;
63         }
64
65         memcpy(ssl->session_id, session_id, sess_id_size);
66         ssl->sess_id_size = sess_id_size;
67         SET_SSL_FLAG(SSL_SESSION_RESUME);   /* just flag for later */
68     }
69
70     SET_SSL_FLAG(SSL_IS_CLIENT);
71     do_client_connect(ssl);
72     return ssl;
73 }
74
75 /*
76  * Process the handshake record.
77  */
78 int do_clnt_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len)
79 {
80     int ret;
81
82     /* To get here the state must be valid */
83     switch (handshake_type)
84     {
85         case HS_SERVER_HELLO:
86             ret = process_server_hello(ssl);
87             break;
88
89         case HS_CERTIFICATE:
90             ret = process_certificate(ssl, &ssl->x509_ctx);
91             break;
92
93         case HS_SERVER_HELLO_DONE:
94             if ((ret = process_server_hello_done(ssl)) == SSL_OK)
95             {
96                 if (IS_SET_SSL_FLAG(SSL_HAS_CERT_REQ))
97                 {
98                     if ((ret = send_certificate(ssl)) == SSL_OK &&
99                         (ret = send_client_key_xchg(ssl)) == SSL_OK)
100                     {
101                         send_cert_verify(ssl);
102                     }
103                 }
104                 else
105                 {
106                     ret = send_client_key_xchg(ssl);
107                 }
108
109                 if (ret == SSL_OK && 
110                      (ret = send_change_cipher_spec(ssl)) == SSL_OK)
111                 {
112                     ret = send_finished(ssl);
113                 }
114             }
115             break;
116
117         case HS_CERT_REQ:
118             ret = process_cert_req(ssl);
119             break;
120
121         case HS_FINISHED:
122             ret = process_finished(ssl, buf, hs_len);
123             disposable_free(ssl);   /* free up some memory */
124             /* note: client renegotiation is not allowed after this */
125             break;
126
127         case HS_HELLO_REQUEST:
128             disposable_new(ssl);
129             ret = do_client_connect(ssl);
130             break;
131
132         default:
133             ret = SSL_ERROR_INVALID_HANDSHAKE;
134             break;
135     }
136
137     return ret;
138 }
139
140 /*
141  * Do the handshaking from the beginning.
142  */
143 int do_client_connect(SSL *ssl)
144 {
145     int ret = SSL_OK;
146
147     send_client_hello(ssl);                 /* send the client hello */
148     ssl->bm_read_index = 0;
149     ssl->next_state = HS_SERVER_HELLO;
150     ssl->hs_status = SSL_NOT_OK;            /* not connected */
151
152     /* sit in a loop until it all looks good */
153     if (!IS_SET_SSL_FLAG(SSL_CONNECT_IN_PARTS))
154     {
155         while (ssl->hs_status != SSL_OK)
156         {
157             ret = read_record(ssl);
158             if (ret < SSL_OK)
159                 break;
160             ret = process_data(ssl, NULL, 0);
161             if (ret < SSL_OK)
162                 break;    
163         }
164         ssl->hs_status = ret;            /* connected? */    
165     }
166     return ret;
167 }
168
169 static int compute_size_send_client_hello(SSL *ssl)
170 {
171     int size = 6 + SSL_RANDOM_SIZE;
172     size++;
173     if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME))
174     {
175
176         size += ssl->sess_id_size;
177     }
178     size += 2;
179     int i;
180     for (i = 0; i < NUM_PROTOCOLS; i++)
181         size += 2;
182     size += 2;
183     return size+BM_RECORD_OFFSET;
184 }
185
186 /*
187  * Send the initial client hello.
188  */
189 static int send_client_hello(SSL *ssl)
190 {
191     uint8_t *buf = ssl->bm_data;
192     time_t tm = time(NULL);
193     uint8_t *tm_ptr = &buf[6]; /* time will go here */
194     int i, offset;
195
196     buf[0] = HS_CLIENT_HELLO;
197     buf[1] = 0;
198     buf[2] = 0;
199     /* byte 3 is calculated later */
200     buf[4] = 0x03;
201     buf[5] = ssl->version & 0x0f;
202
203     /* client random value - spec says that 1st 4 bytes are big endian time */
204     *tm_ptr++ = (uint8_t)(((long)tm & 0xff000000) >> 24);
205     *tm_ptr++ = (uint8_t)(((long)tm & 0x00ff0000) >> 16);
206     *tm_ptr++ = (uint8_t)(((long)tm & 0x0000ff00) >> 8);
207     *tm_ptr++ = (uint8_t)(((long)tm & 0x000000ff));
208     get_random(SSL_RANDOM_SIZE-4, &buf[10]);
209     memcpy(ssl->dc->client_random, &buf[6], SSL_RANDOM_SIZE);
210     offset = 6 + SSL_RANDOM_SIZE;
211
212     /* give session resumption a go */
213     if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME))    /* set initially by user */
214     {
215         buf[offset++] = ssl->sess_id_size;
216         memcpy(&buf[offset], ssl->session_id, ssl->sess_id_size);
217         offset += ssl->sess_id_size;
218         CLR_SSL_FLAG(SSL_SESSION_RESUME);       /* clear so we can set later */
219     }
220     else
221     {
222         /* no session id - because no session resumption just yet */
223         buf[offset++] = 0;
224     }
225
226     buf[offset++] = 0;              /* number of ciphers */
227     buf[offset++] = NUM_PROTOCOLS*2;/* number of ciphers */
228
229     /* put all our supported protocols in our request */
230     for (i = 0; i < NUM_PROTOCOLS; i++)
231     {
232         buf[offset++] = 0;          /* cipher we are using */
233         buf[offset++] = ssl_prot_prefs[i];
234     }
235
236     buf[offset++] = 1;              /* no compression */
237     buf[offset++] = 0;
238     buf[3] = offset - 4;            /* handshake size */
239
240     return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset);
241 }
242
243 /*
244  * Process the server hello.
245  */
246 static int process_server_hello(SSL *ssl)
247 {
248     uint8_t *buf = ssl->bm_data;
249     int pkt_size = ssl->bm_index;
250     int num_sessions = ssl->ssl_ctx->num_sessions;
251     uint8_t sess_id_size;
252     int offset, ret = SSL_OK;
253
254     /* check that we are talking to a TLSv1 server */
255     uint8_t version = (buf[0] << 4) + buf[1];
256     if (version > SSL_PROTOCOL_VERSION_MAX)
257     {
258         version = SSL_PROTOCOL_VERSION_MAX;
259     }
260     else if (ssl->version < SSL_PROTOCOL_MIN_VERSION)
261     {
262         ret = SSL_ERROR_INVALID_VERSION;
263         ssl_display_error(ret);
264         goto error;
265     }
266
267     ssl->version = version;
268
269     /* get the server random value */
270     memcpy(ssl->dc->server_random, &buf[2], SSL_RANDOM_SIZE);
271     offset = 2 + SSL_RANDOM_SIZE; /* skip of session id size */
272     sess_id_size = buf[offset++];
273
274     if (sess_id_size > SSL_SESSION_ID_SIZE)
275     {
276         ret = SSL_ERROR_INVALID_SESSION;
277         goto error;
278     }
279
280     if (num_sessions)
281     {
282         ssl->session = ssl_session_update(num_sessions,
283                 ssl->ssl_ctx->ssl_sessions, ssl, &buf[offset]);
284         memcpy(ssl->session->session_id, &buf[offset], sess_id_size);
285
286         /* pad the rest with 0's */
287         if (sess_id_size < SSL_SESSION_ID_SIZE)
288         {
289             memset(&ssl->session->session_id[sess_id_size], 0,
290                 SSL_SESSION_ID_SIZE-sess_id_size);
291         }
292     }
293
294     memcpy(ssl->session_id, &buf[offset], sess_id_size);
295     ssl->sess_id_size = sess_id_size;
296     offset += sess_id_size;
297
298     /* get the real cipher we are using */
299     ssl->cipher = buf[++offset];
300     ssl->next_state = IS_SET_SSL_FLAG(SSL_SESSION_RESUME) ? 
301                                         HS_FINISHED : HS_CERTIFICATE;
302
303     offset++;   // skip the compr
304     PARANOIA_CHECK(pkt_size, offset);
305     ssl->dc->bm_proc_index = offset+1; 
306
307 error:
308     return ret;
309 }
310
311 /**
312  * Process the server hello done message.
313  */
314 static int process_server_hello_done(SSL *ssl)
315 {
316     ssl->next_state = HS_FINISHED;
317     return SSL_OK;
318 }
319
320 /*
321  * Send a client key exchange message.
322  */
323 static int send_client_key_xchg(SSL *ssl)
324 {
325     uint8_t *buf = ssl->bm_data;
326     uint8_t premaster_secret[SSL_SECRET_SIZE];
327     int enc_secret_size = -1;
328
329     buf[0] = HS_CLIENT_KEY_XCHG;
330     buf[1] = 0;
331
332     premaster_secret[0] = 0x03; /* encode the version number */
333     premaster_secret[1] = SSL_PROTOCOL_MINOR_VERSION; /* must be TLS 1.1 */
334     get_random(SSL_SECRET_SIZE-2, &premaster_secret[2]);
335     DISPLAY_RSA(ssl, ssl->x509_ctx->rsa_ctx);
336
337     /* rsa_ctx->bi_ctx is not thread-safe */
338     SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
339     enc_secret_size = RSA_encrypt(ssl->x509_ctx->rsa_ctx, premaster_secret,
340             SSL_SECRET_SIZE, &buf[6], 0);
341     SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
342
343     buf[2] = (enc_secret_size + 2) >> 8;
344     buf[3] = (enc_secret_size + 2) & 0xff;
345     buf[4] = enc_secret_size >> 8;
346     buf[5] = enc_secret_size & 0xff;
347
348     generate_master_secret(ssl, premaster_secret);
349
350     return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, enc_secret_size+6);
351 }
352
353 /*
354  * Process the certificate request.
355  */
356 static int process_cert_req(SSL *ssl)
357 {
358     uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index];
359     int ret = SSL_OK;
360     int offset = (buf[2] << 4) + buf[3];
361     int pkt_size = ssl->bm_index;
362
363     /* don't do any processing - we will send back an RSA certificate anyway */
364     ssl->next_state = HS_SERVER_HELLO_DONE;
365     SET_SSL_FLAG(SSL_HAS_CERT_REQ);
366     ssl->dc->bm_proc_index += offset;
367     PARANOIA_CHECK(pkt_size, offset);
368 error:
369     return ret;
370 }
371
372 /*
373  * Send a certificate verify message.
374  */
375 static int send_cert_verify(SSL *ssl)
376 {
377     uint8_t *buf = ssl->bm_data;
378     uint8_t dgst[MD5_SIZE+SHA1_SIZE];
379     RSA_CTX *rsa_ctx = ssl->ssl_ctx->rsa_ctx;
380     int n = 0, ret;
381
382     DISPLAY_RSA(ssl, rsa_ctx);
383
384     buf[0] = HS_CERT_VERIFY;
385     buf[1] = 0;
386
387     finished_digest(ssl, NULL, dgst);   /* calculate the digest */
388
389     /* rsa_ctx->bi_ctx is not thread-safe */
390     if (rsa_ctx)
391     {
392         SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
393         n = RSA_encrypt(rsa_ctx, dgst, sizeof(dgst), &buf[6], 1);
394         SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
395
396         if (n == 0)
397         {
398             ret = SSL_ERROR_INVALID_KEY;
399             goto error;
400         }
401     }
402     
403     buf[4] = n >> 8;        /* add the RSA size (not officially documented) */
404     buf[5] = n & 0xff;
405     n += 2;
406     buf[2] = n >> 8;
407     buf[3] = n & 0xff;
408     ret = send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, n+4);
409
410 error:
411     return ret;
412 }
413
414 #endif      /* CONFIG_SSL_ENABLE_CLIENT */