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