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