]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/net/https/axTLS/ssl/loader.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / net / https / axTLS / ssl / loader.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 /**
32  * Load certificates/keys into memory. These can be in many different formats.
33  * PEM support and other formats can be processed here.
34  *
35  * The PEM private keys may be optionally encrypted with AES128 or AES256. 
36  * The encrypted PEM keys were generated with something like:
37  *
38  * openssl genrsa -aes128 -passout pass:abcd -out axTLS.key_aes128.pem 512
39  */
40
41 #include <stdlib.h>
42 #include <string.h>
43 #include <stdio.h>
44 #include "os_port.h"
45 #include "ssl.h"
46 #include "config.h"
47
48 static int do_obj(SSL_CTX *ssl_ctx, int obj_type, 
49                     SSLObjLoader *ssl_obj, const char *password);
50 #ifdef CONFIG_SSL_HAS_PEM
51 static int ssl_obj_PEM_load(SSL_CTX *ssl_ctx, int obj_type, 
52                         SSLObjLoader *ssl_obj, const char *password);
53 #endif
54
55 /*
56  * Load a file into memory that is in binary DER (or ascii PEM) format.
57  */
58 EXP_FUNC int STDCALL ssl_obj_load(SSL_CTX *ssl_ctx, int obj_type, 
59                             const char *filename, const char *password)
60 {
61 #ifndef CONFIG_SSL_SKELETON_MODE
62     static const char * const begin = "-----BEGIN";
63     int ret = SSL_OK;
64     SSLObjLoader *ssl_obj = NULL;
65
66     if (filename == NULL)
67     {
68         ret = SSL_ERROR_INVALID_KEY;
69         goto error;
70     }
71
72     ssl_obj = (SSLObjLoader *)calloc(1, sizeof(SSLObjLoader));
73     ssl_obj->len = get_file(filename, &ssl_obj->buf); 
74     if (ssl_obj->len <= 0)
75     {
76         ret = SSL_ERROR_INVALID_KEY;
77         goto error;
78     }
79
80     /* is the file a PEM file? */
81     if (strstr((char *)ssl_obj->buf, begin) != NULL)
82     {
83 #ifdef CONFIG_SSL_HAS_PEM
84         ret = ssl_obj_PEM_load(ssl_ctx, obj_type, ssl_obj, password);
85 #else
86         printf(unsupported_str);
87         ret = SSL_ERROR_NOT_SUPPORTED;
88 #endif
89     }
90     else
91         ret = do_obj(ssl_ctx, obj_type, ssl_obj, password);
92
93 error:
94     ssl_obj_free(ssl_obj);
95     return ret;
96 #else
97     printf(unsupported_str);
98     return SSL_ERROR_NOT_SUPPORTED;
99 #endif /* CONFIG_SSL_SKELETON_MODE */
100 }
101
102 /*
103  * Transfer binary data into the object loader.
104  */
105 EXP_FUNC int STDCALL ssl_obj_memory_load(SSL_CTX *ssl_ctx, int mem_type, 
106         const uint8_t *data, int len, const char *password)
107 {
108     int ret;
109     SSLObjLoader ssl_obj;
110     ssl_obj.buf = data;
111     ssl_obj.len = len;
112     ret = do_obj(ssl_ctx, mem_type, &ssl_obj, password);
113     
114     return ret;
115 }
116
117 /*
118  * Actually work out what we are doing 
119  */
120 static int do_obj(SSL_CTX *ssl_ctx, int obj_type, 
121                     SSLObjLoader *ssl_obj, const char *password)
122 {
123     int ret = SSL_OK;
124
125     switch (obj_type)
126     {
127         case SSL_OBJ_RSA_KEY:
128             ret = add_private_key(ssl_ctx, ssl_obj);
129             break;
130
131         case SSL_OBJ_X509_CERT:
132             ret = add_cert(ssl_ctx, ssl_obj->buf, ssl_obj->len);
133             break;
134
135 #ifdef CONFIG_SSL_CERT_VERIFICATION
136         case SSL_OBJ_X509_CACERT:
137             add_cert_auth(ssl_ctx, ssl_obj->buf, ssl_obj->len);
138             break;
139 #endif
140
141 #ifdef CONFIG_SSL_USE_PKCS12
142         case SSL_OBJ_PKCS8:
143             ret = pkcs8_decode(ssl_ctx, ssl_obj, password);
144             break;
145
146         case SSL_OBJ_PKCS12:
147             ret = pkcs12_decode(ssl_ctx, ssl_obj, password);
148             break;
149 #endif
150         default:
151             printf(unsupported_str);
152             ret = SSL_ERROR_NOT_SUPPORTED;
153             break;
154     }
155
156     return ret;
157 }
158
159 /*
160  * Clean up our mess.
161  */
162 void ssl_obj_free(SSLObjLoader *ssl_obj)
163 {
164     if (ssl_obj)
165     {
166         free(ssl_obj->buf);
167         free(ssl_obj);
168     }
169 }
170
171 /*
172  * Support for PEM encoded keys/certificates.
173  */
174 #ifdef CONFIG_SSL_HAS_PEM
175
176 #define NUM_PEM_TYPES               4
177 #define IV_SIZE                     16
178 #define IS_RSA_PRIVATE_KEY          0
179 #define IS_ENCRYPTED_PRIVATE_KEY    1
180 #define IS_PRIVATE_KEY              2
181 #define IS_CERTIFICATE              3
182
183 static const char * const begins[NUM_PEM_TYPES] =
184 {
185     "-----BEGIN RSA PRIVATE KEY-----",
186     "-----BEGIN ENCRYPTED PRIVATE KEY-----",
187     "-----BEGIN PRIVATE KEY-----",
188     "-----BEGIN CERTIFICATE-----",
189 };
190
191 static const char * const ends[NUM_PEM_TYPES] =
192 {
193     "-----END RSA PRIVATE KEY-----",
194     "-----END ENCRYPTED PRIVATE KEY-----",
195     "-----END PRIVATE KEY-----",
196     "-----END CERTIFICATE-----",
197 };
198
199 static const char * const aes_str[2] =
200 {
201     "DEK-Info: AES-128-CBC,",
202     "DEK-Info: AES-256-CBC," 
203 };
204
205 /**
206  * Take a base64 blob of data and decrypt it (using AES) into its 
207  * proper ASN.1 form.
208  */
209 static int pem_decrypt(const char *where, const char *end,
210                         const char *password, SSLObjLoader *ssl_obj)
211 {
212     int ret = -1;
213     int is_aes_256 = 0;
214     char *start = NULL;
215     uint8_t iv[IV_SIZE];
216     int i, pem_size;
217     MD5_CTX md5_ctx;
218     AES_CTX aes_ctx;
219     uint8_t key[32];        /* AES256 size */
220
221     if (password == NULL || strlen(password) == 0)
222     {
223 #ifdef CONFIG_SSL_FULL_MODE
224         printf("Error: Need a password for this PEM file\n"); TTY_FLUSH();
225 #endif
226         goto error;
227     }
228
229     if ((start = strstr((const char *)where, aes_str[0])))         /* AES128? */
230     {
231         start += strlen(aes_str[0]);
232     }
233     else if ((start = strstr((const char *)where, aes_str[1])))    /* AES256? */
234     {
235         is_aes_256 = 1;
236         start += strlen(aes_str[1]);
237     }
238     else 
239     {
240 #ifdef CONFIG_SSL_FULL_MODE
241         printf("Error: Unsupported password cipher\n"); TTY_FLUSH();
242 #endif
243         goto error;
244     }
245
246     /* convert from hex to binary - assumes uppercase hex */
247     for (i = 0; i < IV_SIZE; i++)
248     {
249         char c = *start++ - '0';
250         iv[i] = (c > 9 ? c + '0' - 'A' + 10 : c) << 4;
251         c = *start++ - '0';
252         iv[i] += (c > 9 ? c + '0' - 'A' + 10 : c);
253     }
254
255     while (*start == '\r' || *start == '\n')
256         start++;
257
258     /* turn base64 into binary */
259     pem_size = (int)(end-start);
260     if (base64_decode(start, pem_size, ssl_obj->buf, &ssl_obj->len) != 0)
261         goto error;
262
263     /* work out the key */
264     MD5_Init(&md5_ctx);
265     MD5_Update(&md5_ctx, (const uint8_t *)password, strlen(password));
266     MD5_Update(&md5_ctx, iv, SALT_SIZE);
267     MD5_Final(key, &md5_ctx);
268
269     if (is_aes_256)
270     {
271         MD5_Init(&md5_ctx);
272         MD5_Update(&md5_ctx, key, MD5_SIZE);
273         MD5_Update(&md5_ctx, (const uint8_t *)password, strlen(password));
274         MD5_Update(&md5_ctx, iv, SALT_SIZE);
275         MD5_Final(&key[MD5_SIZE], &md5_ctx);
276     }
277
278     /* decrypt using the key/iv */
279     AES_set_key(&aes_ctx, key, iv, is_aes_256 ? AES_MODE_256 : AES_MODE_128);
280     AES_convert_key(&aes_ctx);
281     AES_cbc_decrypt(&aes_ctx, ssl_obj->buf, ssl_obj->buf, ssl_obj->len);
282     ret = 0;
283
284 error:
285     return ret; 
286 }
287
288 /**
289  * Take a base64 blob of data and turn it into its proper ASN.1 form.
290  */
291 static int new_pem_obj(SSL_CTX *ssl_ctx, int is_cacert, char *where, 
292                     int remain, const char *password)
293 {
294     int ret = SSL_ERROR_BAD_CERTIFICATE;
295     SSLObjLoader *ssl_obj = NULL;
296
297     while (remain > 0)
298     {
299         int i, pem_size, obj_type;
300         char *start = NULL, *end = NULL;
301
302         for (i = 0; i < NUM_PEM_TYPES; i++)
303         {
304             if ((start = strstr(where, begins[i])) &&
305                     (end = strstr(where, ends[i])))
306             {
307                 remain -= (int)(end-where);
308                 start += strlen(begins[i]);
309                 pem_size = (int)(end-start);
310
311                 ssl_obj = (SSLObjLoader *)calloc(1, sizeof(SSLObjLoader));
312
313                 /* 4/3 bigger than what we need but so what */
314                 ssl_obj->buf = (uint8_t *)calloc(1, pem_size);
315                 ssl_obj->len = pem_size;
316
317                 if (i == IS_RSA_PRIVATE_KEY && 
318                             strstr(start, "Proc-Type:") && 
319                             strstr(start, "4,ENCRYPTED"))
320                 {
321                     /* check for encrypted PEM file */
322                     if (pem_decrypt(start, end, password, ssl_obj) < 0)
323                     {
324                         ret = SSL_ERROR_BAD_CERTIFICATE;
325                         goto error;
326                     }
327                 }
328                 else 
329                 {
330                     ssl_obj->len = pem_size;
331                     if (base64_decode(start, pem_size, 
332                                 ssl_obj->buf, &ssl_obj->len) != 0)
333                     {
334                         ret = SSL_ERROR_BAD_CERTIFICATE;
335                         goto error;
336                     }
337                 }
338
339                 switch (i)
340                 {
341                     case IS_RSA_PRIVATE_KEY:
342                         obj_type = SSL_OBJ_RSA_KEY;
343                         break;
344
345                     case IS_ENCRYPTED_PRIVATE_KEY:
346                     case IS_PRIVATE_KEY:
347                         obj_type = SSL_OBJ_PKCS8;
348                         break;
349
350                     case IS_CERTIFICATE:
351                         obj_type = is_cacert ?
352                                         SSL_OBJ_X509_CACERT : SSL_OBJ_X509_CERT;
353                         break;
354
355                     default:
356                         ret = SSL_ERROR_BAD_CERTIFICATE;
357                         goto error;
358                 }
359
360                 /* In a format we can now understand - so process it */
361                 if ((ret = do_obj(ssl_ctx, obj_type, ssl_obj, password)))
362                     goto error;
363
364                 end += strlen(ends[i]);
365                 remain -= strlen(ends[i]);
366                 while (remain > 0 && (*end == '\r' || *end == '\n'))
367                 {
368                     end++;
369                     remain--;
370                 }
371
372                 where = end;
373                 break;
374             }
375         }
376
377         ssl_obj_free(ssl_obj);
378         ssl_obj = NULL;
379         if (start == NULL)
380            break;
381     }
382 error:
383     ssl_obj_free(ssl_obj);
384     return ret;
385 }
386
387 /*
388  * Load a file into memory that is in ASCII PEM format.
389  */
390 static int ssl_obj_PEM_load(SSL_CTX *ssl_ctx, int obj_type, 
391                         SSLObjLoader *ssl_obj, const char *password)
392 {
393     char *start;
394
395     /* add a null terminator */
396     ssl_obj->len++;
397     ssl_obj->buf = (uint8_t *)realloc(ssl_obj->buf, ssl_obj->len);
398     ssl_obj->buf[ssl_obj->len-1] = 0;
399     start = (char *)ssl_obj->buf;
400     return new_pem_obj(ssl_ctx, obj_type == SSL_OBJ_X509_CACERT,
401                                 start, ssl_obj->len, password);
402 }
403 #endif /* CONFIG_SSL_HAS_PEM */
404
405 /**
406  * Load the key/certificates in memory depending on compile-time and user
407  * options. 
408  */
409 int load_key_certs(SSL_CTX *ssl_ctx)
410 {
411     int ret = SSL_OK;
412     uint32_t options = ssl_ctx->options;
413 #ifdef CONFIG_SSL_GENERATE_X509_CERT 
414     uint8_t *cert_data = NULL;
415     int cert_size;
416     static const char *dn[] = 
417     {
418         CONFIG_SSL_X509_COMMON_NAME,
419         CONFIG_SSL_X509_ORGANIZATION_NAME,
420         CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME
421     };
422 #endif
423
424     /* do the private key first */
425     if (strlen(CONFIG_SSL_PRIVATE_KEY_LOCATION) > 0)
426     {
427         if ((ret = ssl_obj_load(ssl_ctx, SSL_OBJ_RSA_KEY, 
428                                 CONFIG_SSL_PRIVATE_KEY_LOCATION,
429                                 CONFIG_SSL_PRIVATE_KEY_PASSWORD)) < 0)
430             goto error;
431     }
432     else if (!(options & SSL_NO_DEFAULT_KEY))
433     {
434 #if defined(CONFIG_SSL_USE_DEFAULT_KEY) || defined(CONFIG_SSL_SKELETON_MODE)
435 //        static const    /* saves a few more bytes */
436 //#include "private_key.h"
437 //       ssl_obj_memory_load(ssl_ctx, SSL_OBJ_RSA_KEY, default_private_key,
438   //              default_private_key_len, NULL); 
439 #endif
440     }
441
442     /* now load the certificate */
443 #ifdef CONFIG_SSL_GENERATE_X509_CERT 
444     if ((cert_size = ssl_x509_create(ssl_ctx, 0, dn, &cert_data)) < 0)
445     {
446         ret = cert_size;
447         goto error;
448     }
449
450     ssl_obj_memory_load(ssl_ctx, SSL_OBJ_X509_CERT, cert_data, cert_size, NULL);
451     free(cert_data);
452 #else
453     if (strlen(CONFIG_SSL_X509_CERT_LOCATION))
454     {
455         if ((ret = ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, 
456                                 CONFIG_SSL_X509_CERT_LOCATION, NULL)) < 0)
457             goto error;
458     }
459     else if (!(options & SSL_NO_DEFAULT_KEY))
460     {
461 #if defined(CONFIG_SSL_USE_DEFAULT_KEY) || defined(CONFIG_SSL_SKELETON_MODE)
462         static const    /* saves a few bytes and RAM */
463 #include "cert.h"
464         ssl_obj_memory_load(ssl_ctx, SSL_OBJ_X509_CERT, 
465                     default_certificate, default_certificate_len, NULL);
466 #endif
467     }
468 #endif
469
470 error:
471 #ifdef CONFIG_SSL_FULL_MODE
472     if (ret)
473     {
474         printf("Error: Certificate or key not loaded\n"); TTY_FLUSH();
475     }
476 #endif
477
478     return ret;
479
480 }