Add a STORE loader for the "file" scheme
[openssl.git] / crypto / store / loader_file.c
1 /*
2  * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <string.h>
11
12 #include <openssl/bio.h>
13 #include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
14 #include <openssl/err.h>
15 #include <openssl/evp.h>
16 #include <openssl/pem.h>
17 #include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
18 #include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
19 #include <openssl/safestack.h>
20 #include <openssl/store.h>
21 #include <openssl/ui.h>
22 #include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
23 #include "internal/asn1_int.h"
24 #include "store_locl.h"
25
26 #include "e_os.h"
27
28 /*
29  *  Password prompting
30  */
31
32 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
33                            size_t maxsize, const char *prompt_info, void *data)
34 {
35     UI *ui = UI_new();
36     char *prompt = NULL;
37
38     if (ui == NULL) {
39         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
40         return NULL;
41     }
42
43     if (ui_method != NULL)
44         UI_set_method(ui, ui_method);
45     UI_add_user_data(ui, data);
46
47     if ((prompt = UI_construct_prompt(ui, "pass phrase",
48                                       prompt_info)) == NULL) {
49         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
50         pass = NULL;
51     } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
52                                     pass, 0, maxsize - 1)) {
53         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
54         pass = NULL;
55     } else {
56         switch (UI_process(ui)) {
57         case -2:
58             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
59                           OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
60             pass = NULL;
61             break;
62         case -1:
63             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
64             pass = NULL;
65             break;
66         default:
67             break;
68         }
69     }
70
71     OPENSSL_free(prompt);
72     UI_free(ui);
73     return pass;
74 }
75
76 struct pem_pass_data {
77     const UI_METHOD *ui_method;
78     void *data;
79     const char *prompt_info;
80 };
81 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
82                                    const char *prompt_info,
83                                    const UI_METHOD *ui_method, void *ui_data)
84 {
85     if (pass_data == NULL)
86         return 0;
87     pass_data->ui_method = ui_method;
88     pass_data->data = ui_data;
89     pass_data->prompt_info = prompt_info;
90     return 1;
91 }
92 static int file_get_pem_pass(char *buf, int num, int w, void *data)
93 {
94     struct pem_pass_data *pass_data = data;
95     char *pass = file_get_pass(pass_data->ui_method, buf, num,
96                                pass_data->prompt_info, pass_data->data);
97
98     return pass == NULL ? 0 : strlen(pass);
99 }
100
101 /*
102  *  The file scheme handlers
103  */
104
105 /*-
106  * The try_decode function is called to check if the blob of data can
107  * be used by this handler, and if it can, decodes it into a supported
108  * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
109  * Input:
110  *    pem_name:     If this blob comes from a PEM file, this holds
111  *                  the PEM name.  If it comes from another type of
112  *                  file, this is NULL.
113  *    pem_header:   If this blob comes from a PEM file, this holds
114  *                  the PEM headers.  If it comes from another type of
115  *                  file, this is NULL.
116  *    blob:         The blob of data to match with what this handler
117  *                  can use.
118  *    len:          The length of the blob.
119  *    ui_method:    Application UI method for getting a password, pin
120  *                  or any other interactive data.
121  *    ui_data:      Application data to be passed to ui_method when
122  *                  it's called.
123  * Output:
124  *    a OSSL_STORE_INFO
125  */
126 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
127                                                const char *pem_header,
128                                                const unsigned char *blob,
129                                                size_t len,
130                                                const UI_METHOD *ui_method,
131                                                void *ui_data);
132
133 typedef struct file_handler_st {
134     const char *name;
135     file_try_decode_fn try_decode;
136 } FILE_HANDLER;
137
138 int pem_check_suffix(const char *pem_str, const char *suffix);
139 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
140                                               const char *pem_header,
141                                               const unsigned char *blob,
142                                               size_t len,
143                                               const UI_METHOD *ui_method,
144                                               void *ui_data)
145 {
146     OSSL_STORE_INFO *store_info = NULL;
147     EVP_PKEY *pkey = NULL;
148     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
149
150     if (pem_name != NULL) {
151         int slen;
152
153         if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
154             && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, slen)) != NULL)
155             pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
156     } else {
157         int i;
158
159         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
160             ameth = EVP_PKEY_asn1_get0(i);
161             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
162                 continue;
163             pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
164             if (pkey != NULL)
165                 break;
166         }
167     }
168     if (pkey == NULL)
169         /* No match */
170         return NULL;
171
172     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
173     if (store_info == NULL)
174         EVP_PKEY_free(pkey);
175
176     return store_info;
177 }
178 static FILE_HANDLER PrivateKey_handler = {
179     "PrivateKey",
180     try_decode_PrivateKey
181 };
182
183 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
184                                           const char *pem_header,
185                                           const unsigned char *blob,
186                                           size_t len,
187                                           const UI_METHOD *ui_method,
188                                           void *ui_data)
189 {
190     OSSL_STORE_INFO *store_info = NULL;
191     EVP_PKEY *pkey = NULL;
192
193     if (pem_name != NULL && strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
194         /* No match */
195         return NULL;
196
197     if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL)
198         store_info = OSSL_STORE_INFO_new_PKEY(pkey);
199
200     return store_info;
201 }
202 static FILE_HANDLER PUBKEY_handler = {
203     "PUBKEY",
204     try_decode_PUBKEY
205 };
206
207 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
208                                           const char *pem_header,
209                                           const unsigned char *blob,
210                                           size_t len,
211                                           const UI_METHOD *ui_method,
212                                           void *ui_data)
213 {
214     OSSL_STORE_INFO *store_info = NULL;
215     EVP_PKEY *pkey = EVP_PKEY_new();
216     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
217     int ok = 0;
218
219     if (pkey == NULL) {
220         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
221         return NULL;
222     }
223
224     if (pem_name != NULL) {
225         int slen;
226
227         if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) > 0
228             && EVP_PKEY_set_type_str(pkey, pem_name, slen)
229             && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
230             && ameth->param_decode != NULL
231             && ameth->param_decode(pkey, &blob, len))
232             ok = 1;
233     } else {
234         int i;
235
236         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
237             ameth = EVP_PKEY_asn1_get0(i);
238             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
239                 continue;
240             if (EVP_PKEY_set_type(pkey, ameth->pkey_id)
241                 && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
242                 && ameth->param_decode != NULL
243                 && ameth->param_decode(pkey, &blob, len)) {
244                 ok = 1;
245                 break;
246             }
247         }
248     }
249
250     if (ok)
251         store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
252     if (store_info == NULL)
253         EVP_PKEY_free(pkey);
254
255     return store_info;
256 }
257 static FILE_HANDLER params_handler = {
258     "params",
259     try_decode_params
260 };
261
262 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
263                                                    const char *pem_header,
264                                                    const unsigned char *blob,
265                                                    size_t len,
266                                                    const UI_METHOD *ui_method,
267                                                    void *ui_data)
268 {
269     OSSL_STORE_INFO *store_info = NULL;
270     X509 *cert = NULL;
271
272     /*
273      * In most cases, we can try to interpret the serialized data as a trusted
274      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
275      * (just X509), but if the PEM name specifically declares it as a trusted
276      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
277      * the fallback can be used (1) or not (0).
278      */
279     int ignore_trusted = 1;
280
281     if (pem_name != NULL) {
282         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
283             ignore_trusted = 0;
284         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
285                  && strcmp(pem_name, PEM_STRING_X509) != 0)
286             /* No match */
287             return NULL;
288     }
289
290     if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
291         || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL))
292         store_info = OSSL_STORE_INFO_new_CERT(cert);
293
294     if (store_info == NULL)
295         X509_free(cert);
296
297     return store_info;
298 }
299 static FILE_HANDLER X509Certificate_handler = {
300     "X509Certificate",
301     try_decode_X509Certificate
302 };
303
304 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
305                                            const char *pem_header,
306                                            const unsigned char *blob,
307                                            size_t len,
308                                            const UI_METHOD *ui_method,
309                                            void *ui_data)
310 {
311     OSSL_STORE_INFO *store_info = NULL;
312     X509_CRL *crl = NULL;
313
314     if (pem_name != NULL
315         && strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
316         /* No match */
317         return NULL;
318
319     if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL)
320         store_info = OSSL_STORE_INFO_new_CRL(crl);
321
322     if (store_info == NULL)
323         X509_CRL_free(crl);
324
325     return store_info;
326 }
327 static FILE_HANDLER X509CRL_handler = {
328     "X509CRL",
329     try_decode_X509CRL
330 };
331
332 static const FILE_HANDLER *file_handlers[] = {
333     &X509Certificate_handler,
334     &X509CRL_handler,
335     &params_handler,
336     &PUBKEY_handler,
337     &PrivateKey_handler,
338 };
339
340
341 /*
342  *  The loader itself
343  */
344
345 struct ossl_store_loader_ctx_st {
346     BIO *file;
347     int is_pem;
348     int errcnt;
349 };
350
351 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
352                                         const char *uri,
353                                         const UI_METHOD *ui_method,
354                                         void *ui_data)
355 {
356     BIO *buff = NULL;
357     char peekbuf[4096];
358     OSSL_STORE_LOADER_CTX *ctx = NULL;
359     const char *path = NULL;
360
361     if (strncasecmp(uri, "file:", 5) == 0) {
362         if (strncmp(&uri[5], "//localhost/", 12) == 0) {
363             path = &uri[16];
364         } else if (strncmp(&uri[5], "///", 3) == 0) {
365             path = &uri[7];
366         } else if (strncmp(&uri[5], "//", 2) != 0) {
367             path = &uri[5];
368         } else {
369             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
370                           OSSL_STORE_R_URI_AUTHORITY_UNSUPPORED);
371             return NULL;
372         }
373
374         /*
375          * If the scheme "file" was an explicit part of the URI, the path must
376          * be absolute.  So says RFC 8089
377          */
378         if (path[0] != '/') {
379             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
380                           OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
381             return NULL;
382         }
383
384 #ifdef _WIN32
385         /* Windows file: URIs with a drive letter start with a / */
386         if (path[0] == '/' && path[2] == ':' && path[3] == '/')
387             path++;
388 #endif
389     } else {
390         path = uri;
391     }
392
393
394     ctx = OPENSSL_zalloc(sizeof(*ctx));
395     if (ctx == NULL) {
396         OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
397         return NULL;
398     }
399
400     if ((buff = BIO_new(BIO_f_buffer())) == NULL)
401         goto err;
402     if ((ctx->file = BIO_new_file(path, "rb")) == NULL) {
403         goto err;
404     }
405     ctx->file = BIO_push(buff, ctx->file);
406     if (BIO_buffer_peek(ctx->file, peekbuf, sizeof(peekbuf)-1) > 0) {
407         peekbuf[sizeof(peekbuf)-1] = '\0';
408         if (strstr(peekbuf, "-----BEGIN ") != NULL)
409             ctx->is_pem = 1;
410     }
411
412     return ctx;
413  err:
414     if (buff != NULL)
415         BIO_free(buff);
416     OPENSSL_free(ctx);
417     return NULL;
418 }
419
420 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
421 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
422 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
423                                   const UI_METHOD *ui_method, void *ui_data)
424 {
425     OSSL_STORE_INFO *result = NULL;
426     int matchcount = -1;
427
428     if (file_error(ctx))
429         return NULL;
430
431     do {
432         char *pem_name = NULL;      /* PEM record name */
433         char *pem_header = NULL;    /* PEM record header */
434         unsigned char *data = NULL; /* DER encoded data */
435         BUF_MEM *mem = NULL;
436         long len = 0;               /* DER encoded data length */
437         int r = 0;
438         size_t i = 0;
439         file_try_decode_fn *matching_functions = NULL;
440
441         matchcount = -1;
442         if (ctx->is_pem) {
443             r = PEM_read_bio(ctx->file, &pem_name, &pem_header, &data, &len);
444             if (r <= 0) {
445                 if (!file_eof(ctx))
446                     ctx->errcnt++;
447                 goto end;
448             }
449
450             /*
451              * 10 is the number of characters in "Proc-Type:", which
452              * PEM_get_EVP_CIPHER_INFO() requires to be present.
453              * If the PEM header has less characters than that, it's
454              * not worth spending cycles on it.
455              */
456             if (strlen(pem_header) > 10) {
457                 EVP_CIPHER_INFO cipher;
458                 struct pem_pass_data pass_data;
459
460                 if (!PEM_get_EVP_CIPHER_INFO(pem_header, &cipher)
461                     || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method,
462                                                 ui_data)
463                     || !PEM_do_header(&cipher, data, &len, file_get_pem_pass,
464                                       &pass_data)) {
465                     ctx->errcnt++;
466                     goto err;
467                 }
468             }
469         } else {
470 #if 0                          /* PKCS12 not yet ready */
471             PKCS12 *pkcs12 =NULL;
472 #endif
473
474             if ((len = asn1_d2i_read_bio(ctx->file, &mem)) < 0) {
475                 if (!file_eof(ctx))
476                     ctx->errcnt++;
477                 goto err;
478             }
479
480             data = (unsigned char *)mem->data;
481             len = (long)mem->length;
482
483 #if 0                          /* PKCS12 not yet ready */
484             /* Try and see if we loaded a PKCS12 */
485             pkcs12 = d2i_PKCS12(NULL, &data, len);
486 #endif
487         }
488
489         result = NULL;
490         matchcount = 0;
491         matching_functions = OPENSSL_zalloc(sizeof(*matching_functions)
492                                             * OSSL_NELEM(file_handlers));
493
494         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
495             const FILE_HANDLER *handler = file_handlers[i];
496             OSSL_STORE_INFO *tmp_result =
497                 handler->try_decode(pem_name, pem_header, data, len, ui_method,
498                                     ui_data);
499
500             if (tmp_result != NULL) {
501                 if (matching_functions)
502                     matching_functions[matchcount] = handler->try_decode;
503
504                 if (++matchcount == 1) {
505                     result = tmp_result;
506                     tmp_result = NULL;
507                 } else {
508                     /* more than one match => ambiguous, kill any result */
509                     OSSL_STORE_INFO_free(result);
510                     OSSL_STORE_INFO_free(tmp_result);
511                     result = NULL;
512                 }
513             }
514         }
515
516         if (matchcount > 1)
517             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
518                           OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
519         if (matchcount == 0)
520             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
521                           OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
522
523         if (result)
524             ERR_clear_error();
525
526      err:
527         OPENSSL_free(matching_functions);
528         OPENSSL_free(pem_name);
529         OPENSSL_free(pem_header);
530         if (mem == NULL)
531             OPENSSL_free(data);
532         else
533             BUF_MEM_free(mem);
534     } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
535
536     /* We bail out on ambiguity */
537     if (matchcount > 1)
538         return NULL;
539
540  end:
541     return result;
542 }
543
544 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
545 {
546     return ctx->errcnt > 0;
547 }
548
549 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
550 {
551     return BIO_eof(ctx->file);
552 }
553
554 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
555 {
556     BIO_free_all(ctx->file);
557     OPENSSL_free(ctx);
558     return 1;
559 }
560
561 static OSSL_STORE_LOADER file_loader =
562     {
563         "file",
564         file_open,
565         NULL,
566         file_load,
567         file_eof,
568         file_error,
569         file_close
570     };
571
572 static void store_file_loader_deinit(void)
573 {
574     ossl_store_unregister_loader_int(file_loader.scheme);
575 }
576
577 int ossl_store_file_loader_init(void)
578 {
579     int ret = ossl_store_register_loader_int(&file_loader);
580
581     OPENSSL_atexit(store_file_loader_deinit);
582     return ret;
583 }