ed1b618a5344cce5d12ec39c93e5f8686b261b29
[openssl.git] / apps / apps.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
11 /*
12  * On VMS, you need to define this to get the declaration of fileno().  The
13  * value 2 is to make sure no function defined in POSIX-2 is left undefined.
14  */
15 # define _POSIX_C_SOURCE 2
16 #endif
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/types.h>
22 #ifndef OPENSSL_NO_POSIX_IO
23 # include <sys/stat.h>
24 # include <fcntl.h>
25 #endif
26 #include <ctype.h>
27 #include <errno.h>
28 #include <openssl/err.h>
29 #include <openssl/x509.h>
30 #include <openssl/x509v3.h>
31 #include <openssl/pem.h>
32 #include <openssl/pkcs12.h>
33 #include <openssl/ui.h>
34 #include <openssl/safestack.h>
35 #ifndef OPENSSL_NO_ENGINE
36 # include <openssl/engine.h>
37 #endif
38 #ifndef OPENSSL_NO_RSA
39 # include <openssl/rsa.h>
40 #endif
41 #include <openssl/bn.h>
42 #include <openssl/ssl.h>
43 #include "s_apps.h"
44 #include "apps.h"
45
46 #ifdef _WIN32
47 static int WIN32_rename(const char *from, const char *to);
48 # define rename(from,to) WIN32_rename((from),(to))
49 #endif
50
51 typedef struct {
52     const char *name;
53     unsigned long flag;
54     unsigned long mask;
55 } NAME_EX_TBL;
56
57 static UI_METHOD *ui_method = NULL;
58 static const UI_METHOD *ui_fallback_method = NULL;
59
60 static int set_table_opts(unsigned long *flags, const char *arg,
61                           const NAME_EX_TBL * in_tbl);
62 static int set_multi_opts(unsigned long *flags, const char *arg,
63                           const NAME_EX_TBL * in_tbl);
64
65 int app_init(long mesgwin);
66
67 int chopup_args(ARGS *arg, char *buf)
68 {
69     int quoted;
70     char c = '\0', *p = NULL;
71
72     arg->argc = 0;
73     if (arg->size == 0) {
74         arg->size = 20;
75         arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
76     }
77
78     for (p = buf;;) {
79         /* Skip whitespace. */
80         while (*p && isspace(_UC(*p)))
81             p++;
82         if (!*p)
83             break;
84
85         /* The start of something good :-) */
86         if (arg->argc >= arg->size) {
87             char **tmp;
88             arg->size += 20;
89             tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
90             if (tmp == NULL)
91                 return 0;
92             arg->argv = tmp;
93         }
94         quoted = *p == '\'' || *p == '"';
95         if (quoted)
96             c = *p++;
97         arg->argv[arg->argc++] = p;
98
99         /* now look for the end of this */
100         if (quoted) {
101             while (*p && *p != c)
102                 p++;
103             *p++ = '\0';
104         } else {
105             while (*p && !isspace(_UC(*p)))
106                 p++;
107             if (*p)
108                 *p++ = '\0';
109         }
110     }
111     arg->argv[arg->argc] = NULL;
112     return 1;
113 }
114
115 #ifndef APP_INIT
116 int app_init(long mesgwin)
117 {
118     return 1;
119 }
120 #endif
121
122 int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile,
123                              const char *CApath, int noCAfile, int noCApath)
124 {
125     if (CAfile == NULL && CApath == NULL) {
126         if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
127             return 0;
128         if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
129             return 0;
130
131         return 1;
132     }
133     return SSL_CTX_load_verify_locations(ctx, CAfile, CApath);
134 }
135
136 #ifndef OPENSSL_NO_CT
137
138 int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
139 {
140     if (path == NULL)
141         return SSL_CTX_set_default_ctlog_list_file(ctx);
142
143     return SSL_CTX_set_ctlog_list_file(ctx, path);
144 }
145
146 #endif
147
148 static unsigned long nmflag = 0;
149 static char nmflag_set = 0;
150
151 int set_nameopt(const char *arg)
152 {
153     int ret = set_name_ex(&nmflag, arg);
154
155     if (ret)
156         nmflag_set = 1;
157
158     return ret;
159 }
160
161 unsigned long get_nameopt(void)
162 {
163     return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
164 }
165
166 int dump_cert_text(BIO *out, X509 *x)
167 {
168     print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
169     BIO_puts(out, "\n");
170     print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
171     BIO_puts(out, "\n");
172
173     return 0;
174 }
175
176 static int ui_open(UI *ui)
177 {
178     int (*opener)(UI *ui) = UI_method_get_opener(ui_fallback_method);
179
180     if (opener)
181         return opener(ui);
182     return 1;
183 }
184
185 static int ui_read(UI *ui, UI_STRING *uis)
186 {
187     int (*reader)(UI *ui, UI_STRING *uis) = NULL;
188
189     if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
190         && UI_get0_user_data(ui)) {
191         switch (UI_get_string_type(uis)) {
192         case UIT_PROMPT:
193         case UIT_VERIFY:
194             {
195                 const char *password =
196                     ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
197                 if (password && password[0] != '\0') {
198                     UI_set_result(ui, uis, password);
199                     return 1;
200                 }
201             }
202             break;
203         case UIT_NONE:
204         case UIT_BOOLEAN:
205         case UIT_INFO:
206         case UIT_ERROR:
207             break;
208         }
209     }
210
211     reader = UI_method_get_reader(ui_fallback_method);
212     if (reader)
213         return reader(ui, uis);
214     return 1;
215 }
216
217 static int ui_write(UI *ui, UI_STRING *uis)
218 {
219     int (*writer)(UI *ui, UI_STRING *uis) = NULL;
220
221     if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
222         && UI_get0_user_data(ui)) {
223         switch (UI_get_string_type(uis)) {
224         case UIT_PROMPT:
225         case UIT_VERIFY:
226             {
227                 const char *password =
228                     ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
229                 if (password && password[0] != '\0')
230                     return 1;
231             }
232             break;
233         case UIT_NONE:
234         case UIT_BOOLEAN:
235         case UIT_INFO:
236         case UIT_ERROR:
237             break;
238         }
239     }
240
241     writer = UI_method_get_writer(ui_fallback_method);
242     if (writer)
243         return writer(ui, uis);
244     return 1;
245 }
246
247 static int ui_close(UI *ui)
248 {
249     int (*closer)(UI *ui) = UI_method_get_closer(ui_fallback_method);
250
251     if (closer)
252         return closer(ui);
253     return 1;
254 }
255
256 int setup_ui_method(void)
257 {
258     ui_fallback_method = UI_null();
259 #ifndef OPENSSL_NO_UI_CONSOLE
260     ui_fallback_method = UI_OpenSSL();
261 #endif
262     ui_method = UI_create_method("OpenSSL application user interface");
263     UI_method_set_opener(ui_method, ui_open);
264     UI_method_set_reader(ui_method, ui_read);
265     UI_method_set_writer(ui_method, ui_write);
266     UI_method_set_closer(ui_method, ui_close);
267     return 0;
268 }
269
270 void destroy_ui_method(void)
271 {
272     if (ui_method) {
273         UI_destroy_method(ui_method);
274         ui_method = NULL;
275     }
276 }
277
278 const UI_METHOD *get_ui_method(void)
279 {
280     return ui_method;
281 }
282
283 int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_data)
284 {
285     int res = 0;
286     UI *ui;
287     int ok = 0;
288     char *buff = NULL;
289     int ui_flags = 0;
290     const char *prompt_info = NULL;
291     char *prompt;
292
293     if ((ui = UI_new_method(ui_method)) == NULL)
294         return 0;
295
296     if (cb_data != NULL && cb_data->prompt_info != NULL)
297         prompt_info = cb_data->prompt_info;
298     prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
299     if (prompt == NULL) {
300         BIO_printf(bio_err, "Out of memory\n");
301         UI_free(ui);
302         return 0;
303     }
304
305     ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
306     UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
307
308     /* We know that there is no previous user data to return to us */
309     (void)UI_add_user_data(ui, cb_data);
310
311     ok = UI_add_input_string(ui, prompt, ui_flags, buf,
312                              PW_MIN_LENGTH, bufsiz - 1);
313
314     if (ok >= 0 && verify) {
315         buff = app_malloc(bufsiz, "password buffer");
316         ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
317                                   PW_MIN_LENGTH, bufsiz - 1, buf);
318     }
319     if (ok >= 0)
320         do {
321             ok = UI_process(ui);
322         } while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
323
324     OPENSSL_clear_free(buff, (unsigned int)bufsiz);
325
326     if (ok >= 0)
327         res = strlen(buf);
328     if (ok == -1) {
329         BIO_printf(bio_err, "User interface error\n");
330         ERR_print_errors(bio_err);
331         OPENSSL_cleanse(buf, (unsigned int)bufsiz);
332         res = 0;
333     }
334     if (ok == -2) {
335         BIO_printf(bio_err, "aborted!\n");
336         OPENSSL_cleanse(buf, (unsigned int)bufsiz);
337         res = 0;
338     }
339     UI_free(ui);
340     OPENSSL_free(prompt);
341     return res;
342 }
343
344 int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
345 {
346     return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
347 }
348
349 static char *app_get_pass(const char *arg, int keepbio);
350
351 int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
352 {
353     int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
354
355     if (arg1 != NULL) {
356         *pass1 = app_get_pass(arg1, same);
357         if (*pass1 == NULL)
358             return 0;
359     } else if (pass1 != NULL) {
360         *pass1 = NULL;
361     }
362     if (arg2 != NULL) {
363         *pass2 = app_get_pass(arg2, same ? 2 : 0);
364         if (*pass2 == NULL)
365             return 0;
366     } else if (pass2 != NULL) {
367         *pass2 = NULL;
368     }
369     return 1;
370 }
371
372 static char *app_get_pass(const char *arg, int keepbio)
373 {
374     static BIO *pwdbio = NULL;
375     char *tmp, tpass[APP_PASS_LEN];
376     int i;
377
378     if (strncmp(arg, "pass:", 5) == 0)
379         return OPENSSL_strdup(arg + 5);
380     if (strncmp(arg, "env:", 4) == 0) {
381         tmp = getenv(arg + 4);
382         if (tmp == NULL) {
383             BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
384             return NULL;
385         }
386         return OPENSSL_strdup(tmp);
387     }
388     if (!keepbio || pwdbio == NULL) {
389         if (strncmp(arg, "file:", 5) == 0) {
390             pwdbio = BIO_new_file(arg + 5, "r");
391             if (pwdbio == NULL) {
392                 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
393                 return NULL;
394             }
395 #if !defined(_WIN32)
396             /*
397              * Under _WIN32, which covers even Win64 and CE, file
398              * descriptors referenced by BIO_s_fd are not inherited
399              * by child process and therefore below is not an option.
400              * It could have been an option if bss_fd.c was operating
401              * on real Windows descriptors, such as those obtained
402              * with CreateFile.
403              */
404         } else if (strncmp(arg, "fd:", 3) == 0) {
405             BIO *btmp;
406             i = atoi(arg + 3);
407             if (i >= 0)
408                 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
409             if ((i < 0) || !pwdbio) {
410                 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
411                 return NULL;
412             }
413             /*
414              * Can't do BIO_gets on an fd BIO so add a buffering BIO
415              */
416             btmp = BIO_new(BIO_f_buffer());
417             pwdbio = BIO_push(btmp, pwdbio);
418 #endif
419         } else if (strcmp(arg, "stdin") == 0) {
420             pwdbio = dup_bio_in(FORMAT_TEXT);
421             if (!pwdbio) {
422                 BIO_printf(bio_err, "Can't open BIO for stdin\n");
423                 return NULL;
424             }
425         } else {
426             BIO_printf(bio_err, "Invalid password argument \"%s\"\n", arg);
427             return NULL;
428         }
429     }
430     i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
431     if (keepbio != 1) {
432         BIO_free_all(pwdbio);
433         pwdbio = NULL;
434     }
435     if (i <= 0) {
436         BIO_printf(bio_err, "Error reading password from BIO\n");
437         return NULL;
438     }
439     tmp = strchr(tpass, '\n');
440     if (tmp != NULL)
441         *tmp = 0;
442     return OPENSSL_strdup(tpass);
443 }
444
445 CONF *app_load_config_bio(BIO *in, const char *filename)
446 {
447     long errorline = -1;
448     CONF *conf;
449     int i;
450
451     conf = NCONF_new(NULL);
452     i = NCONF_load_bio(conf, in, &errorline);
453     if (i > 0)
454         return conf;
455
456     if (errorline <= 0) {
457         BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
458     } else {
459         BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
460                    errorline);
461     }
462     if (filename != NULL)
463         BIO_printf(bio_err, "config file \"%s\"\n", filename);
464     else
465         BIO_printf(bio_err, "config input");
466
467     NCONF_free(conf);
468     return NULL;
469 }
470
471 CONF *app_load_config(const char *filename)
472 {
473     BIO *in;
474     CONF *conf;
475
476     in = bio_open_default(filename, 'r', FORMAT_TEXT);
477     if (in == NULL)
478         return NULL;
479
480     conf = app_load_config_bio(in, filename);
481     BIO_free(in);
482     return conf;
483 }
484
485 CONF *app_load_config_quiet(const char *filename)
486 {
487     BIO *in;
488     CONF *conf;
489
490     in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
491     if (in == NULL)
492         return NULL;
493
494     conf = app_load_config_bio(in, filename);
495     BIO_free(in);
496     return conf;
497 }
498
499 int app_load_modules(const CONF *config)
500 {
501     CONF *to_free = NULL;
502
503     if (config == NULL)
504         config = to_free = app_load_config_quiet(default_config_file);
505     if (config == NULL)
506         return 1;
507
508     if (CONF_modules_load(config, NULL, 0) <= 0) {
509         BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
510         ERR_print_errors(bio_err);
511         NCONF_free(to_free);
512         return 0;
513     }
514     NCONF_free(to_free);
515     return 1;
516 }
517
518 int add_oid_section(CONF *conf)
519 {
520     char *p;
521     STACK_OF(CONF_VALUE) *sktmp;
522     CONF_VALUE *cnf;
523     int i;
524
525     if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
526         ERR_clear_error();
527         return 1;
528     }
529     if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
530         BIO_printf(bio_err, "problem loading oid section %s\n", p);
531         return 0;
532     }
533     for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
534         cnf = sk_CONF_VALUE_value(sktmp, i);
535         if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
536             BIO_printf(bio_err, "problem creating object %s=%s\n",
537                        cnf->name, cnf->value);
538             return 0;
539         }
540     }
541     return 1;
542 }
543
544 static int load_pkcs12(BIO *in, const char *desc,
545                        pem_password_cb *pem_cb, PW_CB_DATA *cb_data,
546                        EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
547 {
548     const char *pass;
549     char tpass[PEM_BUFSIZE];
550     int len, ret = 0;
551     PKCS12 *p12;
552     p12 = d2i_PKCS12_bio(in, NULL);
553     if (p12 == NULL) {
554         BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
555         goto die;
556     }
557     /* See if an empty password will do */
558     if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
559         pass = "";
560     } else {
561         if (!pem_cb)
562             pem_cb = (pem_password_cb *)password_callback;
563         len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
564         if (len < 0) {
565             BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
566             goto die;
567         }
568         if (len < PEM_BUFSIZE)
569             tpass[len] = 0;
570         if (!PKCS12_verify_mac(p12, tpass, len)) {
571             BIO_printf(bio_err,
572                        "Mac verify error (wrong password?) in PKCS12 file for %s\n",
573                        desc);
574             goto die;
575         }
576         pass = tpass;
577     }
578     ret = PKCS12_parse(p12, pass, pkey, cert, ca);
579  die:
580     PKCS12_free(p12);
581     return ret;
582 }
583
584 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
585 static int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl)
586 {
587     char *host = NULL, *port = NULL, *path = NULL;
588     BIO *bio = NULL;
589     OCSP_REQ_CTX *rctx = NULL;
590     int use_ssl, rv = 0;
591     if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
592         goto err;
593     if (use_ssl) {
594         BIO_puts(bio_err, "https not supported\n");
595         goto err;
596     }
597     bio = BIO_new_connect(host);
598     if (!bio || !BIO_set_conn_port(bio, port))
599         goto err;
600     rctx = OCSP_REQ_CTX_new(bio, 1024);
601     if (rctx == NULL)
602         goto err;
603     if (!OCSP_REQ_CTX_http(rctx, "GET", path))
604         goto err;
605     if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
606         goto err;
607     if (pcert) {
608         do {
609             rv = X509_http_nbio(rctx, pcert);
610         } while (rv == -1);
611     } else {
612         do {
613             rv = X509_CRL_http_nbio(rctx, pcrl);
614         } while (rv == -1);
615     }
616
617  err:
618     OPENSSL_free(host);
619     OPENSSL_free(path);
620     OPENSSL_free(port);
621     BIO_free_all(bio);
622     OCSP_REQ_CTX_free(rctx);
623     if (rv != 1) {
624         BIO_printf(bio_err, "Error loading %s from %s\n",
625                    pcert ? "certificate" : "CRL", url);
626         ERR_print_errors(bio_err);
627     }
628     return rv;
629 }
630 #endif
631
632 X509 *load_cert(const char *file, int format, const char *cert_descrip)
633 {
634     X509 *x = NULL;
635     BIO *cert;
636
637     if (format == FORMAT_HTTP) {
638 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
639         load_cert_crl_http(file, &x, NULL);
640 #endif
641         return x;
642     }
643
644     if (file == NULL) {
645         unbuffer(stdin);
646         cert = dup_bio_in(format);
647     } else {
648         cert = bio_open_default(file, 'r', format);
649     }
650     if (cert == NULL)
651         goto end;
652
653     if (format == FORMAT_ASN1) {
654         x = d2i_X509_bio(cert, NULL);
655     } else if (format == FORMAT_PEM) {
656         x = PEM_read_bio_X509_AUX(cert, NULL,
657                                   (pem_password_cb *)password_callback, NULL);
658     } else if (format == FORMAT_PKCS12) {
659         if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
660             goto end;
661     } else {
662         BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
663         goto end;
664     }
665  end:
666     if (x == NULL) {
667         BIO_printf(bio_err, "unable to load certificate\n");
668         ERR_print_errors(bio_err);
669     }
670     BIO_free(cert);
671     return x;
672 }
673
674 X509_CRL *load_crl(const char *infile, int format)
675 {
676     X509_CRL *x = NULL;
677     BIO *in = NULL;
678
679     if (format == FORMAT_HTTP) {
680 #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
681         load_cert_crl_http(infile, NULL, &x);
682 #endif
683         return x;
684     }
685
686     in = bio_open_default(infile, 'r', format);
687     if (in == NULL)
688         goto end;
689     if (format == FORMAT_ASN1) {
690         x = d2i_X509_CRL_bio(in, NULL);
691     } else if (format == FORMAT_PEM) {
692         x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
693     } else {
694         BIO_printf(bio_err, "bad input format specified for input crl\n");
695         goto end;
696     }
697     if (x == NULL) {
698         BIO_printf(bio_err, "unable to load CRL\n");
699         ERR_print_errors(bio_err);
700         goto end;
701     }
702
703  end:
704     BIO_free(in);
705     return x;
706 }
707
708 EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
709                    const char *pass, ENGINE *e, const char *key_descrip)
710 {
711     BIO *key = NULL;
712     EVP_PKEY *pkey = NULL;
713     PW_CB_DATA cb_data;
714
715     cb_data.password = pass;
716     cb_data.prompt_info = file;
717
718     if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
719         BIO_printf(bio_err, "no keyfile specified\n");
720         goto end;
721     }
722     if (format == FORMAT_ENGINE) {
723         if (e == NULL) {
724             BIO_printf(bio_err, "no engine specified\n");
725         } else {
726 #ifndef OPENSSL_NO_ENGINE
727             if (ENGINE_init(e)) {
728                 pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
729                 ENGINE_finish(e);
730             }
731             if (pkey == NULL) {
732                 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
733                 ERR_print_errors(bio_err);
734             }
735 #else
736             BIO_printf(bio_err, "engines not supported\n");
737 #endif
738         }
739         goto end;
740     }
741     if (file == NULL && maybe_stdin) {
742         unbuffer(stdin);
743         key = dup_bio_in(format);
744     } else {
745         key = bio_open_default(file, 'r', format);
746     }
747     if (key == NULL)
748         goto end;
749     if (format == FORMAT_ASN1) {
750         pkey = d2i_PrivateKey_bio(key, NULL);
751     } else if (format == FORMAT_PEM) {
752         pkey = PEM_read_bio_PrivateKey(key, NULL, wrap_password_callback, &cb_data);
753     } else if (format == FORMAT_PKCS12) {
754         if (!load_pkcs12(key, key_descrip, wrap_password_callback, &cb_data,
755                          &pkey, NULL, NULL))
756             goto end;
757 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
758     } else if (format == FORMAT_MSBLOB) {
759         pkey = b2i_PrivateKey_bio(key);
760     } else if (format == FORMAT_PVK) {
761         pkey = b2i_PVK_bio(key, wrap_password_callback, &cb_data);
762 #endif
763     } else {
764         BIO_printf(bio_err, "bad input format specified for key file\n");
765         goto end;
766     }
767  end:
768     BIO_free(key);
769     if (pkey == NULL) {
770         BIO_printf(bio_err, "unable to load %s\n", key_descrip);
771         ERR_print_errors(bio_err);
772     }
773     return pkey;
774 }
775
776 EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
777                       const char *pass, ENGINE *e, const char *key_descrip)
778 {
779     BIO *key = NULL;
780     EVP_PKEY *pkey = NULL;
781     PW_CB_DATA cb_data;
782
783     cb_data.password = pass;
784     cb_data.prompt_info = file;
785
786     if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
787         BIO_printf(bio_err, "no keyfile specified\n");
788         goto end;
789     }
790     if (format == FORMAT_ENGINE) {
791         if (e == NULL) {
792             BIO_printf(bio_err, "no engine specified\n");
793         } else {
794 #ifndef OPENSSL_NO_ENGINE
795             pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
796             if (pkey == NULL) {
797                 BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
798                 ERR_print_errors(bio_err);
799             }
800 #else
801             BIO_printf(bio_err, "engines not supported\n");
802 #endif
803         }
804         goto end;
805     }
806     if (file == NULL && maybe_stdin) {
807         unbuffer(stdin);
808         key = dup_bio_in(format);
809     } else {
810         key = bio_open_default(file, 'r', format);
811     }
812     if (key == NULL)
813         goto end;
814     if (format == FORMAT_ASN1) {
815         pkey = d2i_PUBKEY_bio(key, NULL);
816     } else if (format == FORMAT_ASN1RSA) {
817 #ifndef OPENSSL_NO_RSA
818         RSA *rsa;
819         rsa = d2i_RSAPublicKey_bio(key, NULL);
820         if (rsa) {
821             pkey = EVP_PKEY_new();
822             if (pkey != NULL)
823                 EVP_PKEY_set1_RSA(pkey, rsa);
824             RSA_free(rsa);
825         } else
826 #else
827         BIO_printf(bio_err, "RSA keys not supported\n");
828 #endif
829             pkey = NULL;
830     } else if (format == FORMAT_PEMRSA) {
831 #ifndef OPENSSL_NO_RSA
832         RSA *rsa;
833         rsa = PEM_read_bio_RSAPublicKey(key, NULL,
834                                         (pem_password_cb *)password_callback,
835                                         &cb_data);
836         if (rsa != NULL) {
837             pkey = EVP_PKEY_new();
838             if (pkey != NULL)
839                 EVP_PKEY_set1_RSA(pkey, rsa);
840             RSA_free(rsa);
841         } else
842 #else
843         BIO_printf(bio_err, "RSA keys not supported\n");
844 #endif
845             pkey = NULL;
846     } else if (format == FORMAT_PEM) {
847         pkey = PEM_read_bio_PUBKEY(key, NULL,
848                                    (pem_password_cb *)password_callback,
849                                    &cb_data);
850 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
851     } else if (format == FORMAT_MSBLOB) {
852         pkey = b2i_PublicKey_bio(key);
853 #endif
854     }
855  end:
856     BIO_free(key);
857     if (pkey == NULL)
858         BIO_printf(bio_err, "unable to load %s\n", key_descrip);
859     return pkey;
860 }
861
862 static int load_certs_crls(const char *file, int format,
863                            const char *pass, const char *desc,
864                            STACK_OF(X509) **pcerts,
865                            STACK_OF(X509_CRL) **pcrls)
866 {
867     int i;
868     BIO *bio;
869     STACK_OF(X509_INFO) *xis = NULL;
870     X509_INFO *xi;
871     PW_CB_DATA cb_data;
872     int rv = 0;
873
874     cb_data.password = pass;
875     cb_data.prompt_info = file;
876
877     if (format != FORMAT_PEM) {
878         BIO_printf(bio_err, "bad input format specified for %s\n", desc);
879         return 0;
880     }
881
882     bio = bio_open_default(file, 'r', FORMAT_PEM);
883     if (bio == NULL)
884         return 0;
885
886     xis = PEM_X509_INFO_read_bio(bio, NULL,
887                                  (pem_password_cb *)password_callback,
888                                  &cb_data);
889
890     BIO_free(bio);
891
892     if (pcerts != NULL && *pcerts == NULL) {
893         *pcerts = sk_X509_new_null();
894         if (*pcerts == NULL)
895             goto end;
896     }
897
898     if (pcrls != NULL && *pcrls == NULL) {
899         *pcrls = sk_X509_CRL_new_null();
900         if (*pcrls == NULL)
901             goto end;
902     }
903
904     for (i = 0; i < sk_X509_INFO_num(xis); i++) {
905         xi = sk_X509_INFO_value(xis, i);
906         if (xi->x509 != NULL && pcerts != NULL) {
907             if (!sk_X509_push(*pcerts, xi->x509))
908                 goto end;
909             xi->x509 = NULL;
910         }
911         if (xi->crl != NULL && pcrls != NULL) {
912             if (!sk_X509_CRL_push(*pcrls, xi->crl))
913                 goto end;
914             xi->crl = NULL;
915         }
916     }
917
918     if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
919         rv = 1;
920
921     if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
922         rv = 1;
923
924  end:
925
926     sk_X509_INFO_pop_free(xis, X509_INFO_free);
927
928     if (rv == 0) {
929         if (pcerts != NULL) {
930             sk_X509_pop_free(*pcerts, X509_free);
931             *pcerts = NULL;
932         }
933         if (pcrls != NULL) {
934             sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
935             *pcrls = NULL;
936         }
937         BIO_printf(bio_err, "unable to load %s\n",
938                    pcerts ? "certificates" : "CRLs");
939         ERR_print_errors(bio_err);
940     }
941     return rv;
942 }
943
944 void* app_malloc(int sz, const char *what)
945 {
946     void *vp = OPENSSL_malloc(sz);
947
948     if (vp == NULL) {
949         BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
950                 opt_getprog(), sz, what);
951         ERR_print_errors(bio_err);
952         exit(1);
953     }
954     return vp;
955 }
956
957 /*
958  * Initialize or extend, if *certs != NULL, a certificate stack.
959  */
960 int load_certs(const char *file, STACK_OF(X509) **certs, int format,
961                const char *pass, const char *desc)
962 {
963     return load_certs_crls(file, format, pass, desc, certs, NULL);
964 }
965
966 /*
967  * Initialize or extend, if *crls != NULL, a certificate stack.
968  */
969 int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
970               const char *pass, const char *desc)
971 {
972     return load_certs_crls(file, format, pass, desc, NULL, crls);
973 }
974
975 #define X509V3_EXT_UNKNOWN_MASK         (0xfL << 16)
976 /* Return error for unknown extensions */
977 #define X509V3_EXT_DEFAULT              0
978 /* Print error for unknown extensions */
979 #define X509V3_EXT_ERROR_UNKNOWN        (1L << 16)
980 /* ASN1 parse unknown extensions */
981 #define X509V3_EXT_PARSE_UNKNOWN        (2L << 16)
982 /* BIO_dump unknown extensions */
983 #define X509V3_EXT_DUMP_UNKNOWN         (3L << 16)
984
985 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
986                          X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
987
988 int set_cert_ex(unsigned long *flags, const char *arg)
989 {
990     static const NAME_EX_TBL cert_tbl[] = {
991         {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
992         {"ca_default", X509_FLAG_CA, 0xffffffffl},
993         {"no_header", X509_FLAG_NO_HEADER, 0},
994         {"no_version", X509_FLAG_NO_VERSION, 0},
995         {"no_serial", X509_FLAG_NO_SERIAL, 0},
996         {"no_signame", X509_FLAG_NO_SIGNAME, 0},
997         {"no_validity", X509_FLAG_NO_VALIDITY, 0},
998         {"no_subject", X509_FLAG_NO_SUBJECT, 0},
999         {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1000         {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1001         {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1002         {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1003         {"no_aux", X509_FLAG_NO_AUX, 0},
1004         {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1005         {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1006         {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1007         {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1008         {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1009         {NULL, 0, 0}
1010     };
1011     return set_multi_opts(flags, arg, cert_tbl);
1012 }
1013
1014 int set_name_ex(unsigned long *flags, const char *arg)
1015 {
1016     static const NAME_EX_TBL ex_tbl[] = {
1017         {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1018         {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
1019         {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1020         {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1021         {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1022         {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1023         {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1024         {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1025         {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1026         {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1027         {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1028         {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1029         {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1030         {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1031         {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1032         {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1033         {"dn_rev", XN_FLAG_DN_REV, 0},
1034         {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1035         {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1036         {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1037         {"align", XN_FLAG_FN_ALIGN, 0},
1038         {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1039         {"space_eq", XN_FLAG_SPC_EQ, 0},
1040         {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1041         {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1042         {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1043         {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1044         {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1045         {NULL, 0, 0}
1046     };
1047     if (set_multi_opts(flags, arg, ex_tbl) == 0)
1048         return 0;
1049     if (*flags != XN_FLAG_COMPAT
1050         && (*flags & XN_FLAG_SEP_MASK) == 0)
1051         *flags |= XN_FLAG_SEP_CPLUS_SPC;
1052     return 1;
1053 }
1054
1055 int set_ext_copy(int *copy_type, const char *arg)
1056 {
1057     if (strcasecmp(arg, "none") == 0)
1058         *copy_type = EXT_COPY_NONE;
1059     else if (strcasecmp(arg, "copy") == 0)
1060         *copy_type = EXT_COPY_ADD;
1061     else if (strcasecmp(arg, "copyall") == 0)
1062         *copy_type = EXT_COPY_ALL;
1063     else
1064         return 0;
1065     return 1;
1066 }
1067
1068 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1069 {
1070     STACK_OF(X509_EXTENSION) *exts = NULL;
1071     X509_EXTENSION *ext, *tmpext;
1072     ASN1_OBJECT *obj;
1073     int i, idx, ret = 0;
1074     if (!x || !req || (copy_type == EXT_COPY_NONE))
1075         return 1;
1076     exts = X509_REQ_get_extensions(req);
1077
1078     for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1079         ext = sk_X509_EXTENSION_value(exts, i);
1080         obj = X509_EXTENSION_get_object(ext);
1081         idx = X509_get_ext_by_OBJ(x, obj, -1);
1082         /* Does extension exist? */
1083         if (idx != -1) {
1084             /* If normal copy don't override existing extension */
1085             if (copy_type == EXT_COPY_ADD)
1086                 continue;
1087             /* Delete all extensions of same type */
1088             do {
1089                 tmpext = X509_get_ext(x, idx);
1090                 X509_delete_ext(x, idx);
1091                 X509_EXTENSION_free(tmpext);
1092                 idx = X509_get_ext_by_OBJ(x, obj, -1);
1093             } while (idx != -1);
1094         }
1095         if (!X509_add_ext(x, ext, -1))
1096             goto end;
1097     }
1098
1099     ret = 1;
1100
1101  end:
1102
1103     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1104
1105     return ret;
1106 }
1107
1108 static int set_multi_opts(unsigned long *flags, const char *arg,
1109                           const NAME_EX_TBL * in_tbl)
1110 {
1111     STACK_OF(CONF_VALUE) *vals;
1112     CONF_VALUE *val;
1113     int i, ret = 1;
1114     if (!arg)
1115         return 0;
1116     vals = X509V3_parse_list(arg);
1117     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1118         val = sk_CONF_VALUE_value(vals, i);
1119         if (!set_table_opts(flags, val->name, in_tbl))
1120             ret = 0;
1121     }
1122     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1123     return ret;
1124 }
1125
1126 static int set_table_opts(unsigned long *flags, const char *arg,
1127                           const NAME_EX_TBL * in_tbl)
1128 {
1129     char c;
1130     const NAME_EX_TBL *ptbl;
1131     c = arg[0];
1132
1133     if (c == '-') {
1134         c = 0;
1135         arg++;
1136     } else if (c == '+') {
1137         c = 1;
1138         arg++;
1139     } else {
1140         c = 1;
1141     }
1142
1143     for (ptbl = in_tbl; ptbl->name; ptbl++) {
1144         if (strcasecmp(arg, ptbl->name) == 0) {
1145             *flags &= ~ptbl->mask;
1146             if (c)
1147                 *flags |= ptbl->flag;
1148             else
1149                 *flags &= ~ptbl->flag;
1150             return 1;
1151         }
1152     }
1153     return 0;
1154 }
1155
1156 void print_name(BIO *out, const char *title, X509_NAME *nm,
1157                 unsigned long lflags)
1158 {
1159     char *buf;
1160     char mline = 0;
1161     int indent = 0;
1162
1163     if (title)
1164         BIO_puts(out, title);
1165     if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1166         mline = 1;
1167         indent = 4;
1168     }
1169     if (lflags == XN_FLAG_COMPAT) {
1170         buf = X509_NAME_oneline(nm, 0, 0);
1171         BIO_puts(out, buf);
1172         BIO_puts(out, "\n");
1173         OPENSSL_free(buf);
1174     } else {
1175         if (mline)
1176             BIO_puts(out, "\n");
1177         X509_NAME_print_ex(out, nm, indent, lflags);
1178         BIO_puts(out, "\n");
1179     }
1180 }
1181
1182 void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1183                       int len, unsigned char *buffer)
1184 {
1185     BIO_printf(out, "    static unsigned char %s_%d[] = {", var, len);
1186     if (BN_is_zero(in)) {
1187         BIO_printf(out, "\n        0x00");
1188     } else {
1189         int i, l;
1190
1191         l = BN_bn2bin(in, buffer);
1192         for (i = 0; i < l; i++) {
1193             BIO_printf(out, (i % 10) == 0 ? "\n        " : " ");
1194             if (i < l - 1)
1195                 BIO_printf(out, "0x%02X,", buffer[i]);
1196             else
1197                 BIO_printf(out, "0x%02X", buffer[i]);
1198         }
1199     }
1200     BIO_printf(out, "\n    };\n");
1201 }
1202
1203 void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1204 {
1205     int i;
1206
1207     BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1208     for (i = 0; i < len; i++) {
1209         if ((i % 10) == 0)
1210             BIO_printf(out, "\n    ");
1211         if (i < len - 1)
1212             BIO_printf(out, "0x%02X, ", d[i]);
1213         else
1214             BIO_printf(out, "0x%02X", d[i]);
1215     }
1216     BIO_printf(out, "\n};\n");
1217 }
1218
1219 X509_STORE *setup_verify(const char *CAfile, const char *CApath, int noCAfile, int noCApath)
1220 {
1221     X509_STORE *store = X509_STORE_new();
1222     X509_LOOKUP *lookup;
1223
1224     if (store == NULL)
1225         goto end;
1226
1227     if (CAfile != NULL || !noCAfile) {
1228         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1229         if (lookup == NULL)
1230             goto end;
1231         if (CAfile) {
1232             if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1233                 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1234                 goto end;
1235             }
1236         } else {
1237             X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1238         }
1239     }
1240
1241     if (CApath != NULL || !noCApath) {
1242         lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1243         if (lookup == NULL)
1244             goto end;
1245         if (CApath) {
1246             if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1247                 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1248                 goto end;
1249             }
1250         } else {
1251             X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1252         }
1253     }
1254
1255     ERR_clear_error();
1256     return store;
1257  end:
1258     X509_STORE_free(store);
1259     return NULL;
1260 }
1261
1262 #ifndef OPENSSL_NO_ENGINE
1263 /* Try to load an engine in a shareable library */
1264 static ENGINE *try_load_engine(const char *engine)
1265 {
1266     ENGINE *e = ENGINE_by_id("dynamic");
1267     if (e) {
1268         if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1269             || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1270             ENGINE_free(e);
1271             e = NULL;
1272         }
1273     }
1274     return e;
1275 }
1276 #endif
1277
1278 ENGINE *setup_engine(const char *engine, int debug)
1279 {
1280     ENGINE *e = NULL;
1281
1282 #ifndef OPENSSL_NO_ENGINE
1283     if (engine != NULL) {
1284         if (strcmp(engine, "auto") == 0) {
1285             BIO_printf(bio_err, "enabling auto ENGINE support\n");
1286             ENGINE_register_all_complete();
1287             return NULL;
1288         }
1289         if ((e = ENGINE_by_id(engine)) == NULL
1290             && (e = try_load_engine(engine)) == NULL) {
1291             BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
1292             ERR_print_errors(bio_err);
1293             return NULL;
1294         }
1295         if (debug) {
1296             ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
1297         }
1298         ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1299         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1300             BIO_printf(bio_err, "can't use that engine\n");
1301             ERR_print_errors(bio_err);
1302             ENGINE_free(e);
1303             return NULL;
1304         }
1305
1306         BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1307     }
1308 #endif
1309     return e;
1310 }
1311
1312 void release_engine(ENGINE *e)
1313 {
1314 #ifndef OPENSSL_NO_ENGINE
1315     if (e != NULL)
1316         /* Free our "structural" reference. */
1317         ENGINE_free(e);
1318 #endif
1319 }
1320
1321 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1322 {
1323     const char *n;
1324
1325     n = a[DB_serial];
1326     while (*n == '0')
1327         n++;
1328     return OPENSSL_LH_strhash(n);
1329 }
1330
1331 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1332                             const OPENSSL_CSTRING *b)
1333 {
1334     const char *aa, *bb;
1335
1336     for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1337     for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1338     return strcmp(aa, bb);
1339 }
1340
1341 static int index_name_qual(char **a)
1342 {
1343     return (a[0][0] == 'V');
1344 }
1345
1346 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1347 {
1348     return OPENSSL_LH_strhash(a[DB_name]);
1349 }
1350
1351 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1352 {
1353     return strcmp(a[DB_name], b[DB_name]);
1354 }
1355
1356 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1357 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1358 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1359 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1360 #undef BSIZE
1361 #define BSIZE 256
1362 BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1363 {
1364     BIO *in = NULL;
1365     BIGNUM *ret = NULL;
1366     char buf[1024];
1367     ASN1_INTEGER *ai = NULL;
1368
1369     ai = ASN1_INTEGER_new();
1370     if (ai == NULL)
1371         goto err;
1372
1373     in = BIO_new_file(serialfile, "r");
1374     if (in == NULL) {
1375         if (!create) {
1376             perror(serialfile);
1377             goto err;
1378         }
1379         ERR_clear_error();
1380         ret = BN_new();
1381         if (ret == NULL || !rand_serial(ret, ai))
1382             BIO_printf(bio_err, "Out of memory\n");
1383     } else {
1384         if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1385             BIO_printf(bio_err, "unable to load number from %s\n",
1386                        serialfile);
1387             goto err;
1388         }
1389         ret = ASN1_INTEGER_to_BN(ai, NULL);
1390         if (ret == NULL) {
1391             BIO_printf(bio_err,
1392                        "error converting number from bin to BIGNUM\n");
1393             goto err;
1394         }
1395     }
1396
1397     if (ret && retai) {
1398         *retai = ai;
1399         ai = NULL;
1400     }
1401  err:
1402     BIO_free(in);
1403     ASN1_INTEGER_free(ai);
1404     return ret;
1405 }
1406
1407 int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1408                 ASN1_INTEGER **retai)
1409 {
1410     char buf[1][BSIZE];
1411     BIO *out = NULL;
1412     int ret = 0;
1413     ASN1_INTEGER *ai = NULL;
1414     int j;
1415
1416     if (suffix == NULL)
1417         j = strlen(serialfile);
1418     else
1419         j = strlen(serialfile) + strlen(suffix) + 1;
1420     if (j >= BSIZE) {
1421         BIO_printf(bio_err, "file name too long\n");
1422         goto err;
1423     }
1424
1425     if (suffix == NULL)
1426         OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1427     else {
1428 #ifndef OPENSSL_SYS_VMS
1429         j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1430 #else
1431         j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1432 #endif
1433     }
1434     out = BIO_new_file(buf[0], "w");
1435     if (out == NULL) {
1436         ERR_print_errors(bio_err);
1437         goto err;
1438     }
1439
1440     if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1441         BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1442         goto err;
1443     }
1444     i2a_ASN1_INTEGER(out, ai);
1445     BIO_puts(out, "\n");
1446     ret = 1;
1447     if (retai) {
1448         *retai = ai;
1449         ai = NULL;
1450     }
1451  err:
1452     BIO_free_all(out);
1453     ASN1_INTEGER_free(ai);
1454     return ret;
1455 }
1456
1457 int rotate_serial(const char *serialfile, const char *new_suffix,
1458                   const char *old_suffix)
1459 {
1460     char buf[2][BSIZE];
1461     int i, j;
1462
1463     i = strlen(serialfile) + strlen(old_suffix);
1464     j = strlen(serialfile) + strlen(new_suffix);
1465     if (i > j)
1466         j = i;
1467     if (j + 1 >= BSIZE) {
1468         BIO_printf(bio_err, "file name too long\n");
1469         goto err;
1470     }
1471 #ifndef OPENSSL_SYS_VMS
1472     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1473     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1474 #else
1475     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1476     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1477 #endif
1478     if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1479 #ifdef ENOTDIR
1480         && errno != ENOTDIR
1481 #endif
1482         ) {
1483         BIO_printf(bio_err,
1484                    "unable to rename %s to %s\n", serialfile, buf[1]);
1485         perror("reason");
1486         goto err;
1487     }
1488     if (rename(buf[0], serialfile) < 0) {
1489         BIO_printf(bio_err,
1490                    "unable to rename %s to %s\n", buf[0], serialfile);
1491         perror("reason");
1492         rename(buf[1], serialfile);
1493         goto err;
1494     }
1495     return 1;
1496  err:
1497     return 0;
1498 }
1499
1500 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1501 {
1502     BIGNUM *btmp;
1503     int ret = 0;
1504
1505     btmp = b == NULL ? BN_new() : b;
1506     if (btmp == NULL)
1507         return 0;
1508
1509     if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1510         goto error;
1511     if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1512         goto error;
1513
1514     ret = 1;
1515
1516  error:
1517
1518     if (btmp != b)
1519         BN_free(btmp);
1520
1521     return ret;
1522 }
1523
1524 CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1525 {
1526     CA_DB *retdb = NULL;
1527     TXT_DB *tmpdb = NULL;
1528     BIO *in;
1529     CONF *dbattr_conf = NULL;
1530     char buf[BSIZE];
1531 #ifndef OPENSSL_NO_POSIX_IO
1532     FILE *dbfp;
1533     struct stat dbst;
1534 #endif
1535
1536     in = BIO_new_file(dbfile, "r");
1537     if (in == NULL) {
1538         ERR_print_errors(bio_err);
1539         goto err;
1540     }
1541
1542 #ifndef OPENSSL_NO_POSIX_IO
1543     BIO_get_fp(in, &dbfp);
1544     if (fstat(fileno(dbfp), &dbst) == -1) {
1545         SYSerr(SYS_F_FSTAT, errno);
1546         ERR_add_error_data(3, "fstat('", dbfile, "')");
1547         ERR_print_errors(bio_err);
1548         goto err;
1549     }
1550 #endif
1551
1552     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1553         goto err;
1554
1555 #ifndef OPENSSL_SYS_VMS
1556     BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1557 #else
1558     BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1559 #endif
1560     dbattr_conf = app_load_config_quiet(buf);
1561
1562     retdb = app_malloc(sizeof(*retdb), "new DB");
1563     retdb->db = tmpdb;
1564     tmpdb = NULL;
1565     if (db_attr)
1566         retdb->attributes = *db_attr;
1567     else {
1568         retdb->attributes.unique_subject = 1;
1569     }
1570
1571     if (dbattr_conf) {
1572         char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1573         if (p) {
1574             retdb->attributes.unique_subject = parse_yesno(p, 1);
1575         }
1576     }
1577
1578     retdb->dbfname = OPENSSL_strdup(dbfile);
1579 #ifndef OPENSSL_NO_POSIX_IO
1580     retdb->dbst = dbst;
1581 #endif
1582
1583  err:
1584     NCONF_free(dbattr_conf);
1585     TXT_DB_free(tmpdb);
1586     BIO_free_all(in);
1587     return retdb;
1588 }
1589
1590 /*
1591  * Returns > 0 on success, <= 0 on error
1592  */
1593 int index_index(CA_DB *db)
1594 {
1595     if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1596                              LHASH_HASH_FN(index_serial),
1597                              LHASH_COMP_FN(index_serial))) {
1598         BIO_printf(bio_err,
1599                    "error creating serial number index:(%ld,%ld,%ld)\n",
1600                    db->db->error, db->db->arg1, db->db->arg2);
1601         return 0;
1602     }
1603
1604     if (db->attributes.unique_subject
1605         && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1606                                 LHASH_HASH_FN(index_name),
1607                                 LHASH_COMP_FN(index_name))) {
1608         BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1609                    db->db->error, db->db->arg1, db->db->arg2);
1610         return 0;
1611     }
1612     return 1;
1613 }
1614
1615 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1616 {
1617     char buf[3][BSIZE];
1618     BIO *out;
1619     int j;
1620
1621     j = strlen(dbfile) + strlen(suffix);
1622     if (j + 6 >= BSIZE) {
1623         BIO_printf(bio_err, "file name too long\n");
1624         goto err;
1625     }
1626 #ifndef OPENSSL_SYS_VMS
1627     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1628     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1629     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1630 #else
1631     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1632     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1633     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1634 #endif
1635     out = BIO_new_file(buf[0], "w");
1636     if (out == NULL) {
1637         perror(dbfile);
1638         BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1639         goto err;
1640     }
1641     j = TXT_DB_write(out, db->db);
1642     BIO_free(out);
1643     if (j <= 0)
1644         goto err;
1645
1646     out = BIO_new_file(buf[1], "w");
1647     if (out == NULL) {
1648         perror(buf[2]);
1649         BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1650         goto err;
1651     }
1652     BIO_printf(out, "unique_subject = %s\n",
1653                db->attributes.unique_subject ? "yes" : "no");
1654     BIO_free(out);
1655
1656     return 1;
1657  err:
1658     return 0;
1659 }
1660
1661 int rotate_index(const char *dbfile, const char *new_suffix,
1662                  const char *old_suffix)
1663 {
1664     char buf[5][BSIZE];
1665     int i, j;
1666
1667     i = strlen(dbfile) + strlen(old_suffix);
1668     j = strlen(dbfile) + strlen(new_suffix);
1669     if (i > j)
1670         j = i;
1671     if (j + 6 >= BSIZE) {
1672         BIO_printf(bio_err, "file name too long\n");
1673         goto err;
1674     }
1675 #ifndef OPENSSL_SYS_VMS
1676     j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1677     j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1678     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1679     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1680     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1681 #else
1682     j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1683     j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1684     j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1685     j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1686     j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1687 #endif
1688     if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1689 #ifdef ENOTDIR
1690         && errno != ENOTDIR
1691 #endif
1692         ) {
1693         BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1694         perror("reason");
1695         goto err;
1696     }
1697     if (rename(buf[0], dbfile) < 0) {
1698         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1699         perror("reason");
1700         rename(buf[1], dbfile);
1701         goto err;
1702     }
1703     if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1704 #ifdef ENOTDIR
1705         && errno != ENOTDIR
1706 #endif
1707         ) {
1708         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1709         perror("reason");
1710         rename(dbfile, buf[0]);
1711         rename(buf[1], dbfile);
1712         goto err;
1713     }
1714     if (rename(buf[2], buf[4]) < 0) {
1715         BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1716         perror("reason");
1717         rename(buf[3], buf[4]);
1718         rename(dbfile, buf[0]);
1719         rename(buf[1], dbfile);
1720         goto err;
1721     }
1722     return 1;
1723  err:
1724     return 0;
1725 }
1726
1727 void free_index(CA_DB *db)
1728 {
1729     if (db) {
1730         TXT_DB_free(db->db);
1731         OPENSSL_free(db->dbfname);
1732         OPENSSL_free(db);
1733     }
1734 }
1735
1736 int parse_yesno(const char *str, int def)
1737 {
1738     if (str) {
1739         switch (*str) {
1740         case 'f':              /* false */
1741         case 'F':              /* FALSE */
1742         case 'n':              /* no */
1743         case 'N':              /* NO */
1744         case '0':              /* 0 */
1745             return 0;
1746         case 't':              /* true */
1747         case 'T':              /* TRUE */
1748         case 'y':              /* yes */
1749         case 'Y':              /* YES */
1750         case '1':              /* 1 */
1751             return 1;
1752         }
1753     }
1754     return def;
1755 }
1756
1757 /*
1758  * name is expected to be in the format /type0=value0/type1=value1/type2=...
1759  * where characters may be escaped by \
1760  */
1761 X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
1762 {
1763     int nextismulti = 0;
1764     char *work;
1765     X509_NAME *n;
1766
1767     if (*cp++ != '/') {
1768         BIO_printf(bio_err,
1769                    "name is expected to be in the format "
1770                    "/type0=value0/type1=value1/type2=... where characters may "
1771                    "be escaped by \\. This name is not in that format: '%s'\n",
1772                    --cp);
1773         return NULL;
1774     }
1775
1776     n = X509_NAME_new();
1777     if (n == NULL)
1778         return NULL;
1779     work = OPENSSL_strdup(cp);
1780     if (work == NULL)
1781         goto err;
1782
1783     while (*cp) {
1784         char *bp = work;
1785         char *typestr = bp;
1786         unsigned char *valstr;
1787         int nid;
1788         int ismulti = nextismulti;
1789         nextismulti = 0;
1790
1791         /* Collect the type */
1792         while (*cp && *cp != '=')
1793             *bp++ = *cp++;
1794         if (*cp == '\0') {
1795             BIO_printf(bio_err,
1796                     "%s: Hit end of string before finding the equals.\n",
1797                     opt_getprog());
1798             goto err;
1799         }
1800         *bp++ = '\0';
1801         ++cp;
1802
1803         /* Collect the value. */
1804         valstr = (unsigned char *)bp;
1805         for (; *cp && *cp != '/'; *bp++ = *cp++) {
1806             if (canmulti && *cp == '+') {
1807                 nextismulti = 1;
1808                 break;
1809             }
1810             if (*cp == '\\' && *++cp == '\0') {
1811                 BIO_printf(bio_err,
1812                         "%s: escape character at end of string\n",
1813                         opt_getprog());
1814                 goto err;
1815             }
1816         }
1817         *bp++ = '\0';
1818
1819         /* If not at EOS (must be + or /), move forward. */
1820         if (*cp)
1821             ++cp;
1822
1823         /* Parse */
1824         nid = OBJ_txt2nid(typestr);
1825         if (nid == NID_undef) {
1826             BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
1827                       opt_getprog(), typestr);
1828             continue;
1829         }
1830         if (*valstr == '\0') {
1831             BIO_printf(bio_err,
1832                        "%s: No value provided for Subject Attribute %s, skipped\n",
1833                        opt_getprog(), typestr);
1834             continue;
1835         }
1836         if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1837                                         valstr, strlen((char *)valstr),
1838                                         -1, ismulti ? -1 : 0))
1839             goto err;
1840     }
1841
1842     OPENSSL_free(work);
1843     return n;
1844
1845  err:
1846     X509_NAME_free(n);
1847     OPENSSL_free(work);
1848     return NULL;
1849 }
1850
1851 /*
1852  * Read whole contents of a BIO into an allocated memory buffer and return
1853  * it.
1854  */
1855
1856 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1857 {
1858     BIO *mem;
1859     int len, ret;
1860     unsigned char tbuf[1024];
1861
1862     mem = BIO_new(BIO_s_mem());
1863     if (mem == NULL)
1864         return -1;
1865     for (;;) {
1866         if ((maxlen != -1) && maxlen < 1024)
1867             len = maxlen;
1868         else
1869             len = 1024;
1870         len = BIO_read(in, tbuf, len);
1871         if (len < 0) {
1872             BIO_free(mem);
1873             return -1;
1874         }
1875         if (len == 0)
1876             break;
1877         if (BIO_write(mem, tbuf, len) != len) {
1878             BIO_free(mem);
1879             return -1;
1880         }
1881         maxlen -= len;
1882
1883         if (maxlen == 0)
1884             break;
1885     }
1886     ret = BIO_get_mem_data(mem, (char **)out);
1887     BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1888     BIO_free(mem);
1889     return ret;
1890 }
1891
1892 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
1893 {
1894     int rv;
1895     char *stmp, *vtmp = NULL;
1896     stmp = OPENSSL_strdup(value);
1897     if (!stmp)
1898         return -1;
1899     vtmp = strchr(stmp, ':');
1900     if (vtmp) {
1901         *vtmp = 0;
1902         vtmp++;
1903     }
1904     rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
1905     OPENSSL_free(stmp);
1906     return rv;
1907 }
1908
1909 static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
1910 {
1911     X509_POLICY_NODE *node;
1912     int i;
1913
1914     BIO_printf(bio_err, "%s Policies:", name);
1915     if (nodes) {
1916         BIO_puts(bio_err, "\n");
1917         for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
1918             node = sk_X509_POLICY_NODE_value(nodes, i);
1919             X509_POLICY_NODE_print(bio_err, node, 2);
1920         }
1921     } else {
1922         BIO_puts(bio_err, " <empty>\n");
1923     }
1924 }
1925
1926 void policies_print(X509_STORE_CTX *ctx)
1927 {
1928     X509_POLICY_TREE *tree;
1929     int explicit_policy;
1930     tree = X509_STORE_CTX_get0_policy_tree(ctx);
1931     explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
1932
1933     BIO_printf(bio_err, "Require explicit Policy: %s\n",
1934                explicit_policy ? "True" : "False");
1935
1936     nodes_print("Authority", X509_policy_tree_get0_policies(tree));
1937     nodes_print("User", X509_policy_tree_get0_user_policies(tree));
1938 }
1939
1940 /*-
1941  * next_protos_parse parses a comma separated list of strings into a string
1942  * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
1943  *   outlen: (output) set to the length of the resulting buffer on success.
1944  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
1945  *   in: a NUL terminated string like "abc,def,ghi"
1946  *
1947  *   returns: a malloc'd buffer or NULL on failure.
1948  */
1949 unsigned char *next_protos_parse(size_t *outlen, const char *in)
1950 {
1951     size_t len;
1952     unsigned char *out;
1953     size_t i, start = 0;
1954
1955     len = strlen(in);
1956     if (len >= 65535)
1957         return NULL;
1958
1959     out = app_malloc(strlen(in) + 1, "NPN buffer");
1960     for (i = 0; i <= len; ++i) {
1961         if (i == len || in[i] == ',') {
1962             if (i - start > 255) {
1963                 OPENSSL_free(out);
1964                 return NULL;
1965             }
1966             out[start] = (unsigned char)(i - start);
1967             start = i + 1;
1968         } else {
1969             out[i + 1] = in[i];
1970         }
1971     }
1972
1973     *outlen = len + 1;
1974     return out;
1975 }
1976
1977 void print_cert_checks(BIO *bio, X509 *x,
1978                        const char *checkhost,
1979                        const char *checkemail, const char *checkip)
1980 {
1981     if (x == NULL)
1982         return;
1983     if (checkhost) {
1984         BIO_printf(bio, "Hostname %s does%s match certificate\n",
1985                    checkhost,
1986                    X509_check_host(x, checkhost, 0, 0, NULL) == 1
1987                        ? "" : " NOT");
1988     }
1989
1990     if (checkemail) {
1991         BIO_printf(bio, "Email %s does%s match certificate\n",
1992                    checkemail, X509_check_email(x, checkemail, 0, 0)
1993                    ? "" : " NOT");
1994     }
1995
1996     if (checkip) {
1997         BIO_printf(bio, "IP %s does%s match certificate\n",
1998                    checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
1999     }
2000 }
2001
2002 /* Get first http URL from a DIST_POINT structure */
2003
2004 static const char *get_dp_url(DIST_POINT *dp)
2005 {
2006     GENERAL_NAMES *gens;
2007     GENERAL_NAME *gen;
2008     int i, gtype;
2009     ASN1_STRING *uri;
2010     if (!dp->distpoint || dp->distpoint->type != 0)
2011         return NULL;
2012     gens = dp->distpoint->name.fullname;
2013     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2014         gen = sk_GENERAL_NAME_value(gens, i);
2015         uri = GENERAL_NAME_get0_value(gen, &gtype);
2016         if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2017             const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
2018             if (strncmp(uptr, "http://", 7) == 0)
2019                 return uptr;
2020         }
2021     }
2022     return NULL;
2023 }
2024
2025 /*
2026  * Look through a CRLDP structure and attempt to find an http URL to
2027  * downloads a CRL from.
2028  */
2029
2030 static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2031 {
2032     int i;
2033     const char *urlptr = NULL;
2034     for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2035         DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2036         urlptr = get_dp_url(dp);
2037         if (urlptr)
2038             return load_crl(urlptr, FORMAT_HTTP);
2039     }
2040     return NULL;
2041 }
2042
2043 /*
2044  * Example of downloading CRLs from CRLDP: not usable for real world as it
2045  * always downloads, doesn't support non-blocking I/O and doesn't cache
2046  * anything.
2047  */
2048
2049 static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
2050 {
2051     X509 *x;
2052     STACK_OF(X509_CRL) *crls = NULL;
2053     X509_CRL *crl;
2054     STACK_OF(DIST_POINT) *crldp;
2055
2056     crls = sk_X509_CRL_new_null();
2057     if (!crls)
2058         return NULL;
2059     x = X509_STORE_CTX_get_current_cert(ctx);
2060     crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2061     crl = load_crl_crldp(crldp);
2062     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2063     if (!crl) {
2064         sk_X509_CRL_free(crls);
2065         return NULL;
2066     }
2067     sk_X509_CRL_push(crls, crl);
2068     /* Try to download delta CRL */
2069     crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2070     crl = load_crl_crldp(crldp);
2071     sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2072     if (crl)
2073         sk_X509_CRL_push(crls, crl);
2074     return crls;
2075 }
2076
2077 void store_setup_crl_download(X509_STORE *st)
2078 {
2079     X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2080 }
2081
2082 /*
2083  * Platform-specific sections
2084  */
2085 #if defined(_WIN32)
2086 # ifdef fileno
2087 #  undef fileno
2088 #  define fileno(a) (int)_fileno(a)
2089 # endif
2090
2091 # include <windows.h>
2092 # include <tchar.h>
2093
2094 static int WIN32_rename(const char *from, const char *to)
2095 {
2096     TCHAR *tfrom = NULL, *tto;
2097     DWORD err;
2098     int ret = 0;
2099
2100     if (sizeof(TCHAR) == 1) {
2101         tfrom = (TCHAR *)from;
2102         tto = (TCHAR *)to;
2103     } else {                    /* UNICODE path */
2104
2105         size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2106         tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2107         if (tfrom == NULL)
2108             goto err;
2109         tto = tfrom + flen;
2110 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2111         if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2112 # endif
2113             for (i = 0; i < flen; i++)
2114                 tfrom[i] = (TCHAR)from[i];
2115 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2116         if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2117 # endif
2118             for (i = 0; i < tlen; i++)
2119                 tto[i] = (TCHAR)to[i];
2120     }
2121
2122     if (MoveFile(tfrom, tto))
2123         goto ok;
2124     err = GetLastError();
2125     if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2126         if (DeleteFile(tto) && MoveFile(tfrom, tto))
2127             goto ok;
2128         err = GetLastError();
2129     }
2130     if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2131         errno = ENOENT;
2132     else if (err == ERROR_ACCESS_DENIED)
2133         errno = EACCES;
2134     else
2135         errno = EINVAL;         /* we could map more codes... */
2136  err:
2137     ret = -1;
2138  ok:
2139     if (tfrom != NULL && tfrom != (TCHAR *)from)
2140         free(tfrom);
2141     return ret;
2142 }
2143 #endif
2144
2145 /* app_tminterval section */
2146 #if defined(_WIN32)
2147 double app_tminterval(int stop, int usertime)
2148 {
2149     FILETIME now;
2150     double ret = 0;
2151     static ULARGE_INTEGER tmstart;
2152     static int warning = 1;
2153 # ifdef _WIN32_WINNT
2154     static HANDLE proc = NULL;
2155
2156     if (proc == NULL) {
2157         if (check_winnt())
2158             proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2159                                GetCurrentProcessId());
2160         if (proc == NULL)
2161             proc = (HANDLE) - 1;
2162     }
2163
2164     if (usertime && proc != (HANDLE) - 1) {
2165         FILETIME junk;
2166         GetProcessTimes(proc, &junk, &junk, &junk, &now);
2167     } else
2168 # endif
2169     {
2170         SYSTEMTIME systime;
2171
2172         if (usertime && warning) {
2173             BIO_printf(bio_err, "To get meaningful results, run "
2174                        "this program on idle system.\n");
2175             warning = 0;
2176         }
2177         GetSystemTime(&systime);
2178         SystemTimeToFileTime(&systime, &now);
2179     }
2180
2181     if (stop == TM_START) {
2182         tmstart.u.LowPart = now.dwLowDateTime;
2183         tmstart.u.HighPart = now.dwHighDateTime;
2184     } else {
2185         ULARGE_INTEGER tmstop;
2186
2187         tmstop.u.LowPart = now.dwLowDateTime;
2188         tmstop.u.HighPart = now.dwHighDateTime;
2189
2190         ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2191     }
2192
2193     return ret;
2194 }
2195 #elif defined(OPENSSL_SYSTEM_VXWORKS)
2196 # include <time.h>
2197
2198 double app_tminterval(int stop, int usertime)
2199 {
2200     double ret = 0;
2201 # ifdef CLOCK_REALTIME
2202     static struct timespec tmstart;
2203     struct timespec now;
2204 # else
2205     static unsigned long tmstart;
2206     unsigned long now;
2207 # endif
2208     static int warning = 1;
2209
2210     if (usertime && warning) {
2211         BIO_printf(bio_err, "To get meaningful results, run "
2212                    "this program on idle system.\n");
2213         warning = 0;
2214     }
2215 # ifdef CLOCK_REALTIME
2216     clock_gettime(CLOCK_REALTIME, &now);
2217     if (stop == TM_START)
2218         tmstart = now;
2219     else
2220         ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2221                - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2222 # else
2223     now = tickGet();
2224     if (stop == TM_START)
2225         tmstart = now;
2226     else
2227         ret = (now - tmstart) / (double)sysClkRateGet();
2228 # endif
2229     return ret;
2230 }
2231
2232 #elif defined(OPENSSL_SYSTEM_VMS)
2233 # include <time.h>
2234 # include <times.h>
2235
2236 double app_tminterval(int stop, int usertime)
2237 {
2238     static clock_t tmstart;
2239     double ret = 0;
2240     clock_t now;
2241 # ifdef __TMS
2242     struct tms rus;
2243
2244     now = times(&rus);
2245     if (usertime)
2246         now = rus.tms_utime;
2247 # else
2248     if (usertime)
2249         now = clock();          /* sum of user and kernel times */
2250     else {
2251         struct timeval tv;
2252         gettimeofday(&tv, NULL);
2253         now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2254                         (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2255             );
2256     }
2257 # endif
2258     if (stop == TM_START)
2259         tmstart = now;
2260     else
2261         ret = (now - tmstart) / (double)(CLK_TCK);
2262
2263     return ret;
2264 }
2265
2266 #elif defined(_SC_CLK_TCK)      /* by means of unistd.h */
2267 # include <sys/times.h>
2268
2269 double app_tminterval(int stop, int usertime)
2270 {
2271     double ret = 0;
2272     struct tms rus;
2273     clock_t now = times(&rus);
2274     static clock_t tmstart;
2275
2276     if (usertime)
2277         now = rus.tms_utime;
2278
2279     if (stop == TM_START) {
2280         tmstart = now;
2281     } else {
2282         long int tck = sysconf(_SC_CLK_TCK);
2283         ret = (now - tmstart) / (double)tck;
2284     }
2285
2286     return ret;
2287 }
2288
2289 #else
2290 # include <sys/time.h>
2291 # include <sys/resource.h>
2292
2293 double app_tminterval(int stop, int usertime)
2294 {
2295     double ret = 0;
2296     struct rusage rus;
2297     struct timeval now;
2298     static struct timeval tmstart;
2299
2300     if (usertime)
2301         getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2302     else
2303         gettimeofday(&now, NULL);
2304
2305     if (stop == TM_START)
2306         tmstart = now;
2307     else
2308         ret = ((now.tv_sec + now.tv_usec * 1e-6)
2309                - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2310
2311     return ret;
2312 }
2313 #endif
2314
2315 int app_access(const char* name, int flag)
2316 {
2317 #ifdef _WIN32
2318     return _access(name, flag);
2319 #else
2320     return access(name, flag);
2321 #endif
2322 }
2323
2324 /* app_isdir section */
2325 #ifdef _WIN32
2326 int app_isdir(const char *name)
2327 {
2328     DWORD attr;
2329 # if defined(UNICODE) || defined(_UNICODE)
2330     size_t i, len_0 = strlen(name) + 1;
2331     WCHAR tempname[MAX_PATH];
2332
2333     if (len_0 > MAX_PATH)
2334         return -1;
2335
2336 #  if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2337     if (!MultiByteToWideChar(CP_ACP, 0, name, len_0, tempname, MAX_PATH))
2338 #  endif
2339         for (i = 0; i < len_0; i++)
2340             tempname[i] = (WCHAR)name[i];
2341
2342     attr = GetFileAttributes(tempname);
2343 # else
2344     attr = GetFileAttributes(name);
2345 # endif
2346     if (attr == INVALID_FILE_ATTRIBUTES)
2347         return -1;
2348     return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
2349 }
2350 #else
2351 # include <sys/stat.h>
2352 # ifndef S_ISDIR
2353 #  if defined(_S_IFMT) && defined(_S_IFDIR)
2354 #   define S_ISDIR(a)   (((a) & _S_IFMT) == _S_IFDIR)
2355 #  else
2356 #   define S_ISDIR(a)   (((a) & S_IFMT) == S_IFDIR)
2357 #  endif
2358 # endif
2359
2360 int app_isdir(const char *name)
2361 {
2362 # if defined(S_ISDIR)
2363     struct stat st;
2364
2365     if (stat(name, &st) == 0)
2366         return S_ISDIR(st.st_mode);
2367     else
2368         return -1;
2369 # else
2370     return -1;
2371 # endif
2372 }
2373 #endif
2374
2375 /* raw_read|write section */
2376 #if defined(__VMS)
2377 # include "vms_term_sock.h"
2378 static int stdin_sock = -1;
2379
2380 static void close_stdin_sock(void)
2381 {
2382     TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2383 }
2384
2385 int fileno_stdin(void)
2386 {
2387     if (stdin_sock == -1) {
2388         TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2389         atexit(close_stdin_sock);
2390     }
2391
2392     return stdin_sock;
2393 }
2394 #else
2395 int fileno_stdin(void)
2396 {
2397     return fileno(stdin);
2398 }
2399 #endif
2400
2401 int fileno_stdout(void)
2402 {
2403     return fileno(stdout);
2404 }
2405
2406 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2407 int raw_read_stdin(void *buf, int siz)
2408 {
2409     DWORD n;
2410     if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2411         return n;
2412     else
2413         return -1;
2414 }
2415 #elif defined(__VMS)
2416 # include <sys/socket.h>
2417
2418 int raw_read_stdin(void *buf, int siz)
2419 {
2420     return recv(fileno_stdin(), buf, siz, 0);
2421 }
2422 #else
2423 int raw_read_stdin(void *buf, int siz)
2424 {
2425     return read(fileno_stdin(), buf, siz);
2426 }
2427 #endif
2428
2429 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2430 int raw_write_stdout(const void *buf, int siz)
2431 {
2432     DWORD n;
2433     if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2434         return n;
2435     else
2436         return -1;
2437 }
2438 #else
2439 int raw_write_stdout(const void *buf, int siz)
2440 {
2441     return write(fileno_stdout(), buf, siz);
2442 }
2443 #endif
2444
2445 /*
2446  * Centralized handling if input and output files with format specification
2447  * The format is meant to show what the input and output is supposed to be,
2448  * and is therefore a show of intent more than anything else.  However, it
2449  * does impact behavior on some platform, such as differentiating between
2450  * text and binary input/output on non-Unix platforms
2451  */
2452 static int istext(int format)
2453 {
2454     return (format & B_FORMAT_TEXT) == B_FORMAT_TEXT;
2455 }
2456
2457 BIO *dup_bio_in(int format)
2458 {
2459     return BIO_new_fp(stdin,
2460                       BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2461 }
2462
2463 static BIO_METHOD *prefix_method = NULL;
2464
2465 BIO *dup_bio_out(int format)
2466 {
2467     BIO *b = BIO_new_fp(stdout,
2468                         BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2469     void *prefix = NULL;
2470
2471 #ifdef OPENSSL_SYS_VMS
2472     if (istext(format))
2473         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2474 #endif
2475
2476     if (istext(format) && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2477         if (prefix_method == NULL)
2478             prefix_method = apps_bf_prefix();
2479         b = BIO_push(BIO_new(prefix_method), b);
2480         BIO_ctrl(b, PREFIX_CTRL_SET_PREFIX, 0, prefix);
2481     }
2482
2483     return b;
2484 }
2485
2486 BIO *dup_bio_err(int format)
2487 {
2488     BIO *b = BIO_new_fp(stderr,
2489                         BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
2490 #ifdef OPENSSL_SYS_VMS
2491     if (istext(format))
2492         b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2493 #endif
2494     return b;
2495 }
2496
2497 void destroy_prefix_method(void)
2498 {
2499     BIO_meth_free(prefix_method);
2500     prefix_method = NULL;
2501 }
2502
2503 void unbuffer(FILE *fp)
2504 {
2505 /*
2506  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2507  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2508  * However, we trust that the C RTL will never give us a FILE pointer
2509  * above the first 4 GB of memory, so we simply turn off the warning
2510  * temporarily.
2511  */
2512 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2513 # pragma environment save
2514 # pragma message disable maylosedata2
2515 #endif
2516     setbuf(fp, NULL);
2517 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2518 # pragma environment restore
2519 #endif
2520 }
2521
2522 static const char *modestr(char mode, int format)
2523 {
2524     OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2525
2526     switch (mode) {
2527     case 'a':
2528         return istext(format) ? "a" : "ab";
2529     case 'r':
2530         return istext(format) ? "r" : "rb";
2531     case 'w':
2532         return istext(format) ? "w" : "wb";
2533     }
2534     /* The assert above should make sure we never reach this point */
2535     return NULL;
2536 }
2537
2538 static const char *modeverb(char mode)
2539 {
2540     switch (mode) {
2541     case 'a':
2542         return "appending";
2543     case 'r':
2544         return "reading";
2545     case 'w':
2546         return "writing";
2547     }
2548     return "(doing something)";
2549 }
2550
2551 /*
2552  * Open a file for writing, owner-read-only.
2553  */
2554 BIO *bio_open_owner(const char *filename, int format, int private)
2555 {
2556     FILE *fp = NULL;
2557     BIO *b = NULL;
2558     int fd = -1, bflags, mode, textmode;
2559
2560     if (!private || filename == NULL || strcmp(filename, "-") == 0)
2561         return bio_open_default(filename, 'w', format);
2562
2563     mode = O_WRONLY;
2564 #ifdef O_CREAT
2565     mode |= O_CREAT;
2566 #endif
2567 #ifdef O_TRUNC
2568     mode |= O_TRUNC;
2569 #endif
2570     textmode = istext(format);
2571     if (!textmode) {
2572 #ifdef O_BINARY
2573         mode |= O_BINARY;
2574 #elif defined(_O_BINARY)
2575         mode |= _O_BINARY;
2576 #endif
2577     }
2578
2579 #ifdef OPENSSL_SYS_VMS
2580     /* VMS doesn't have O_BINARY, it just doesn't make sense.  But,
2581      * it still needs to know that we're going binary, or fdopen()
2582      * will fail with "invalid argument"...  so we tell VMS what the
2583      * context is.
2584      */
2585     if (!textmode)
2586         fd = open(filename, mode, 0600, "ctx=bin");
2587     else
2588 #endif
2589         fd = open(filename, mode, 0600);
2590     if (fd < 0)
2591         goto err;
2592     fp = fdopen(fd, modestr('w', format));
2593     if (fp == NULL)
2594         goto err;
2595     bflags = BIO_CLOSE;
2596     if (textmode)
2597         bflags |= BIO_FP_TEXT;
2598     b = BIO_new_fp(fp, bflags);
2599     if (b)
2600         return b;
2601
2602  err:
2603     BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2604                opt_getprog(), filename, strerror(errno));
2605     ERR_print_errors(bio_err);
2606     /* If we have fp, then fdopen took over fd, so don't close both. */
2607     if (fp)
2608         fclose(fp);
2609     else if (fd >= 0)
2610         close(fd);
2611     return NULL;
2612 }
2613
2614 static BIO *bio_open_default_(const char *filename, char mode, int format,
2615                               int quiet)
2616 {
2617     BIO *ret;
2618
2619     if (filename == NULL || strcmp(filename, "-") == 0) {
2620         ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
2621         if (quiet) {
2622             ERR_clear_error();
2623             return ret;
2624         }
2625         if (ret != NULL)
2626             return ret;
2627         BIO_printf(bio_err,
2628                    "Can't open %s, %s\n",
2629                    mode == 'r' ? "stdin" : "stdout", strerror(errno));
2630     } else {
2631         ret = BIO_new_file(filename, modestr(mode, format));
2632         if (quiet) {
2633             ERR_clear_error();
2634             return ret;
2635         }
2636         if (ret != NULL)
2637             return ret;
2638         BIO_printf(bio_err,
2639                    "Can't open %s for %s, %s\n",
2640                    filename, modeverb(mode), strerror(errno));
2641     }
2642     ERR_print_errors(bio_err);
2643     return NULL;
2644 }
2645
2646 BIO *bio_open_default(const char *filename, char mode, int format)
2647 {
2648     return bio_open_default_(filename, mode, format, 0);
2649 }
2650
2651 BIO *bio_open_default_quiet(const char *filename, char mode, int format)
2652 {
2653     return bio_open_default_(filename, mode, format, 1);
2654 }
2655
2656 void wait_for_async(SSL *s)
2657 {
2658     /* On Windows select only works for sockets, so we simply don't wait  */
2659 #ifndef OPENSSL_SYS_WINDOWS
2660     int width = 0;
2661     fd_set asyncfds;
2662     OSSL_ASYNC_FD *fds;
2663     size_t numfds;
2664     size_t i;
2665
2666     if (!SSL_get_all_async_fds(s, NULL, &numfds))
2667         return;
2668     if (numfds == 0)
2669         return;
2670     fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
2671     if (!SSL_get_all_async_fds(s, fds, &numfds)) {
2672         OPENSSL_free(fds);
2673         return;
2674     }
2675
2676     FD_ZERO(&asyncfds);
2677     for (i = 0; i < numfds; i++) {
2678         if (width <= (int)fds[i])
2679             width = (int)fds[i] + 1;
2680         openssl_fdset((int)fds[i], &asyncfds);
2681     }
2682     select(width, (void *)&asyncfds, NULL, NULL, NULL);
2683     OPENSSL_free(fds);
2684 #endif
2685 }
2686
2687 /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
2688 #if defined(OPENSSL_SYS_MSDOS)
2689 int has_stdin_waiting(void)
2690 {
2691 # if defined(OPENSSL_SYS_WINDOWS)
2692     HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
2693     DWORD events = 0;
2694     INPUT_RECORD inputrec;
2695     DWORD insize = 1;
2696     BOOL peeked;
2697
2698     if (inhand == INVALID_HANDLE_VALUE) {
2699         return 0;
2700     }
2701
2702     peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
2703     if (!peeked) {
2704         /* Probably redirected input? _kbhit() does not work in this case */
2705         if (!feof(stdin)) {
2706             return 1;
2707         }
2708         return 0;
2709     }
2710 # endif
2711     return _kbhit();
2712 }
2713 #endif
2714
2715 /* Corrupt a signature by modifying final byte */
2716 void corrupt_signature(const ASN1_STRING *signature)
2717 {
2718         unsigned char *s = signature->data;
2719         s[signature->length - 1] ^= 0x1;
2720 }
2721
2722 int set_cert_times(X509 *x, const char *startdate, const char *enddate,
2723                    int days)
2724 {
2725     if (startdate == NULL || strcmp(startdate, "today") == 0) {
2726         if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
2727             return 0;
2728     } else {
2729         if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
2730             return 0;
2731     }
2732     if (enddate == NULL) {
2733         if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
2734             == NULL)
2735             return 0;
2736     } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
2737         return 0;
2738     }
2739     return 1;
2740 }
2741
2742 void make_uppercase(char *string)
2743 {
2744     int i;
2745
2746     for (i = 0; string[i] != '\0'; i++)
2747         string[i] = toupper((unsigned char)string[i]);
2748 }