]> git.ipfire.org Git - thirdparty/openssl.git/blame - apps/apps.c
Engage OPENSSL_NO_POSIX_IO on Windows CE.
[thirdparty/openssl.git] / apps / apps.c
CommitLineData
d02b48c6 1/* apps/apps.c */
58964a49 2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
d02b48c6
RE
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
a661b653
BM
58/* ====================================================================
59 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
d02b48c6
RE
111
112#include <stdio.h>
113#include <stdlib.h>
114#include <string.h>
115#include <sys/types.h>
116#include <sys/stat.h>
d652a095 117#include <ctype.h>
90ae4673
RL
118#include <openssl/err.h>
119#include <openssl/x509.h>
535d79da 120#include <openssl/x509v3.h>
90ae4673
RL
121#include <openssl/pem.h>
122#include <openssl/pkcs12.h>
2fe5adc3 123#include <openssl/ui.h>
90ae4673 124#include <openssl/safestack.h>
0b13e9f0 125#ifndef OPENSSL_NO_ENGINE
1372965e 126#include <openssl/engine.h>
0b13e9f0 127#endif
3eeaab4b 128#ifndef OPENSSL_NO_RSA
823a67b0 129#include <openssl/rsa.h>
3eeaab4b 130#endif
f0eae953 131#include <openssl/bn.h>
d02b48c6 132
d610d27f
RL
133#define NON_MAIN
134#include "apps.h"
135#undef NON_MAIN
136
8ca533e3 137typedef struct {
7d727231 138 const char *name;
8ca533e3
DSH
139 unsigned long flag;
140 unsigned long mask;
141} NAME_EX_TBL;
142
2fe5adc3
RL
143static UI_METHOD *ui_method = NULL;
144
8ca533e3 145static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl);
535d79da 146static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl);
8ca533e3 147
690ecff7 148#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
80bb905d
RL
149/* Looks like this stuff is worth moving into separate function */
150static EVP_PKEY *
151load_netscape_key(BIO *err, BIO *key, const char *file,
152 const char *key_descrip, int format);
153#endif
154
d02b48c6 155int app_init(long mesgwin);
d02b48c6 156#ifdef undef /* never finished - probably never will be :-) */
6b691a5c 157int args_from_file(char *file, int *argc, char **argv[])
d02b48c6
RE
158 {
159 FILE *fp;
160 int num,i;
161 unsigned int len;
162 static char *buf=NULL;
163 static char **arg=NULL;
164 char *p;
165 struct stat stbuf;
166
167 if (stat(file,&stbuf) < 0) return(0);
168
169 fp=fopen(file,"r");
170 if (fp == NULL)
171 return(0);
172
173 *argc=0;
174 *argv=NULL;
175
176 len=(unsigned int)stbuf.st_size;
26a3a48d
RL
177 if (buf != NULL) OPENSSL_free(buf);
178 buf=(char *)OPENSSL_malloc(len+1);
d02b48c6
RE
179 if (buf == NULL) return(0);
180
181 len=fread(buf,1,len,fp);
182 if (len <= 1) return(0);
183 buf[len]='\0';
184
185 i=0;
186 for (p=buf; *p; p++)
187 if (*p == '\n') i++;
26a3a48d
RL
188 if (arg != NULL) OPENSSL_free(arg);
189 arg=(char **)OPENSSL_malloc(sizeof(char *)*(i*2));
d02b48c6
RE
190
191 *argv=arg;
192 num=0;
193 p=buf;
194 for (;;)
195 {
196 if (!*p) break;
197 if (*p == '#') /* comment line */
198 {
199 while (*p && (*p != '\n')) p++;
200 continue;
201 }
202 /* else we have a line */
203 *(arg++)=p;
204 num++;
205 while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
206 p++;
207 if (!*p) break;
208 if (*p == '\n')
209 {
210 *(p++)='\0';
211 continue;
212 }
213 /* else it is a tab or space */
214 p++;
215 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
216 p++;
217 if (!*p) break;
218 if (*p == '\n')
219 {
220 p++;
221 continue;
222 }
223 *(arg++)=p++;
224 num++;
225 while (*p && (*p != '\n')) p++;
226 if (!*p) break;
227 /* else *p == '\n' */
228 *(p++)='\0';
229 }
230 *argc=num;
231 return(1);
232 }
233#endif
234
6b691a5c 235int str2fmt(char *s)
d02b48c6
RE
236 {
237 if ((*s == 'D') || (*s == 'd'))
238 return(FORMAT_ASN1);
239 else if ((*s == 'T') || (*s == 't'))
240 return(FORMAT_TEXT);
241 else if ((*s == 'P') || (*s == 'p'))
a0156a92
DSH
242 {
243 if (s[1] == 'V' || s[1] == 'v')
244 return FORMAT_PVK;
245 else
246 return(FORMAT_PEM);
247 }
248 else if ((*s == 'N') || (*s == 'n'))
249 return(FORMAT_NETSCAPE);
250 else if ((*s == 'S') || (*s == 's'))
251 return(FORMAT_SMIME);
252 else if ((*s == 'M') || (*s == 'm'))
253 return(FORMAT_MSBLOB);
90ae4673
RL
254 else if ((*s == '1')
255 || (strcmp(s,"PKCS12") == 0) || (strcmp(s,"pkcs12") == 0)
256 || (strcmp(s,"P12") == 0) || (strcmp(s,"p12") == 0))
257 return(FORMAT_PKCS12);
5270e702
RL
258 else if ((*s == 'E') || (*s == 'e'))
259 return(FORMAT_ENGINE);
d02b48c6
RE
260 else
261 return(FORMAT_UNDEF);
262 }
263
4d8743f4 264#if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_NETWARE)
6b691a5c 265void program_name(char *in, char *out, int size)
d02b48c6
RE
266 {
267 int i,n;
268 char *p=NULL;
269
270 n=strlen(in);
271 /* find the last '/', '\' or ':' */
272 for (i=n-1; i>0; i--)
273 {
274 if ((in[i] == '/') || (in[i] == '\\') || (in[i] == ':'))
275 {
276 p= &(in[i+1]);
277 break;
278 }
279 }
280 if (p == NULL)
281 p=in;
282 n=strlen(p);
4d8743f4
RL
283
284#if defined(OPENSSL_SYS_NETWARE)
285 /* strip off trailing .nlm if present. */
286 if ((n > 4) && (p[n-4] == '.') &&
287 ((p[n-3] == 'n') || (p[n-3] == 'N')) &&
288 ((p[n-2] == 'l') || (p[n-2] == 'L')) &&
289 ((p[n-1] == 'm') || (p[n-1] == 'M')))
290 n-=4;
291#else
d02b48c6
RE
292 /* strip off trailing .exe if present. */
293 if ((n > 4) && (p[n-4] == '.') &&
294 ((p[n-3] == 'e') || (p[n-3] == 'E')) &&
295 ((p[n-2] == 'x') || (p[n-2] == 'X')) &&
296 ((p[n-1] == 'e') || (p[n-1] == 'E')))
297 n-=4;
4d8743f4
RL
298#endif
299
d02b48c6
RE
300 if (n > size-1)
301 n=size-1;
302
303 for (i=0; i<n; i++)
304 {
305 if ((p[i] >= 'A') && (p[i] <= 'Z'))
306 out[i]=p[i]-'A'+'a';
307 else
308 out[i]=p[i];
309 }
310 out[n]='\0';
311 }
312#else
bc36ee62 313#ifdef OPENSSL_SYS_VMS
7d7d2cbc
UM
314void program_name(char *in, char *out, int size)
315 {
316 char *p=in, *q;
317 char *chars=":]>";
318
319 while(*chars != '\0')
320 {
321 q=strrchr(p,*chars);
322 if (q > p)
323 p = q + 1;
324 chars++;
325 }
326
327 q=strrchr(p,'.');
328 if (q == NULL)
6298bf90
RL
329 q = p + strlen(p);
330 strncpy(out,p,size-1);
331 if (q-p >= size)
332 {
333 out[size-1]='\0';
334 }
335 else
336 {
337 out[q-p]='\0';
338 }
7d7d2cbc
UM
339 }
340#else
6b691a5c 341void program_name(char *in, char *out, int size)
d02b48c6
RE
342 {
343 char *p;
344
345 p=strrchr(in,'/');
346 if (p != NULL)
347 p++;
348 else
349 p=in;
54a656ef 350 BUF_strlcpy(out,p,size);
d02b48c6
RE
351 }
352#endif
7d7d2cbc 353#endif
d02b48c6 354
6b691a5c 355int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
d02b48c6
RE
356 {
357 int num,len,i;
358 char *p;
359
360 *argc=0;
361 *argv=NULL;
362
363 len=strlen(buf);
364 i=0;
365 if (arg->count == 0)
366 {
367 arg->count=20;
26a3a48d 368 arg->data=(char **)OPENSSL_malloc(sizeof(char *)*arg->count);
d02b48c6
RE
369 }
370 for (i=0; i<arg->count; i++)
371 arg->data[i]=NULL;
372
373 num=0;
374 p=buf;
375 for (;;)
376 {
377 /* first scan over white space */
378 if (!*p) break;
379 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
380 p++;
381 if (!*p) break;
382
383 /* The start of something good :-) */
384 if (num >= arg->count)
385 {
9e1a1123
NL
386 char **tmp_p;
387 int tlen = arg->count + 20;
388 tmp_p = (char **)OPENSSL_realloc(arg->data,
389 sizeof(char *)*tlen);
390 if (tmp_p == NULL)
391 return 0;
392 arg->data = tmp_p;
393 arg->count = tlen;
394 /* initialize newly allocated data */
395 for (i = num; i < arg->count; i++)
396 arg->data[i] = NULL;
d02b48c6
RE
397 }
398 arg->data[num++]=p;
399
400 /* now look for the end of this */
401 if ((*p == '\'') || (*p == '\"')) /* scan for closing quote */
402 {
403 i= *(p++);
404 arg->data[num-1]++; /* jump over quote */
405 while (*p && (*p != i))
406 p++;
407 *p='\0';
408 }
409 else
410 {
411 while (*p && ((*p != ' ') &&
412 (*p != '\t') && (*p != '\n')))
413 p++;
414
415 if (*p == '\0')
416 p--;
417 else
418 *p='\0';
419 }
420 p++;
421 }
422 *argc=num;
423 *argv=arg->data;
424 return(1);
425 }
426
427#ifndef APP_INIT
6b691a5c 428int app_init(long mesgwin)
d02b48c6
RE
429 {
430 return(1);
431 }
432#endif
53b1899e 433
a3fe382e 434
954ef7ef
DSH
435int dump_cert_text (BIO *out, X509 *x)
436{
54a656ef
BL
437 char *p;
438
439 p=X509_NAME_oneline(X509_get_subject_name(x),NULL,0);
954ef7ef 440 BIO_puts(out,"subject=");
54a656ef
BL
441 BIO_puts(out,p);
442 OPENSSL_free(p);
954ef7ef 443
54a656ef
BL
444 p=X509_NAME_oneline(X509_get_issuer_name(x),NULL,0);
445 BIO_puts(out,"\nissuer=");
446 BIO_puts(out,p);
954ef7ef 447 BIO_puts(out,"\n");
54a656ef
BL
448 OPENSSL_free(p);
449
450 return 0;
954ef7ef 451}
a3fe382e 452
2fe5adc3
RL
453static int ui_open(UI *ui)
454 {
455 return UI_method_get_opener(UI_OpenSSL())(ui);
456 }
457static int ui_read(UI *ui, UI_STRING *uis)
458 {
459 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
460 && UI_get0_user_data(ui))
461 {
462 switch(UI_get_string_type(uis))
463 {
464 case UIT_PROMPT:
465 case UIT_VERIFY:
466 {
467 const char *password =
468 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
f35232e6 469 if (password && password[0] != '\0')
2fe5adc3 470 {
4f272c17 471 UI_set_result(ui, uis, password);
2fe5adc3
RL
472 return 1;
473 }
474 }
475 default:
476 break;
477 }
478 }
479 return UI_method_get_reader(UI_OpenSSL())(ui, uis);
480 }
481static int ui_write(UI *ui, UI_STRING *uis)
482 {
483 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
484 && UI_get0_user_data(ui))
485 {
486 switch(UI_get_string_type(uis))
487 {
488 case UIT_PROMPT:
489 case UIT_VERIFY:
490 {
491 const char *password =
492 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
f35232e6 493 if (password && password[0] != '\0')
2fe5adc3
RL
494 return 1;
495 }
496 default:
497 break;
498 }
499 }
500 return UI_method_get_writer(UI_OpenSSL())(ui, uis);
501 }
502static int ui_close(UI *ui)
503 {
504 return UI_method_get_closer(UI_OpenSSL())(ui);
505 }
40889b9c 506int setup_ui_method(void)
2fe5adc3
RL
507 {
508 ui_method = UI_create_method("OpenSSL application user interface");
509 UI_method_set_opener(ui_method, ui_open);
510 UI_method_set_reader(ui_method, ui_read);
511 UI_method_set_writer(ui_method, ui_write);
512 UI_method_set_closer(ui_method, ui_close);
513 return 0;
514 }
40889b9c 515void destroy_ui_method(void)
2c7bc88d
DSH
516 {
517 if(ui_method)
518 {
519 UI_destroy_method(ui_method);
520 ui_method = NULL;
521 }
522 }
30b4c272 523int password_callback(char *buf, int bufsiz, int verify,
2fe5adc3 524 PW_CB_DATA *cb_tmp)
30b4c272 525 {
2fe5adc3
RL
526 UI *ui = NULL;
527 int res = 0;
30b4c272
RL
528 const char *prompt_info = NULL;
529 const char *password = NULL;
2fe5adc3 530 PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
30b4c272
RL
531
532 if (cb_data)
533 {
534 if (cb_data->password)
535 password = cb_data->password;
536 if (cb_data->prompt_info)
537 prompt_info = cb_data->prompt_info;
538 }
539
b65f8513
DSH
540 if (password)
541 {
542 res = strlen(password);
543 if (res > bufsiz)
544 res = bufsiz;
545 memcpy(buf, password, res);
546 return res;
547 }
548
2fe5adc3
RL
549 ui = UI_new_method(ui_method);
550 if (ui)
551 {
2fe5adc3
RL
552 int ok = 0;
553 char *buff = NULL;
554 int ui_flags = 0;
555 char *prompt = NULL;
30b4c272 556
2fe5adc3 557 prompt = UI_construct_prompt(ui, "pass phrase",
151368cc 558 prompt_info);
30b4c272 559
2fe5adc3 560 ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
4f272c17 561 UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
2fe5adc3
RL
562
563 if (ok >= 0)
4f272c17
RL
564 ok = UI_add_input_string(ui,prompt,ui_flags,buf,
565 PW_MIN_LENGTH,BUFSIZ-1);
2fe5adc3
RL
566 if (ok >= 0 && verify)
567 {
568 buff = (char *)OPENSSL_malloc(bufsiz);
4f272c17
RL
569 ok = UI_add_verify_string(ui,prompt,ui_flags,buff,
570 PW_MIN_LENGTH,BUFSIZ-1, buf);
2fe5adc3
RL
571 }
572 if (ok >= 0)
4f272c17 573 do
2fe5adc3 574 {
4f272c17 575 ok = UI_process(ui);
2fe5adc3 576 }
4f272c17
RL
577 while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
578
2fe5adc3 579 if (buff)
30b4c272 580 {
4579924b 581 OPENSSL_cleanse(buff,(unsigned int)bufsiz);
2fe5adc3 582 OPENSSL_free(buff);
30b4c272 583 }
2fe5adc3 584
4f272c17
RL
585 if (ok >= 0)
586 res = strlen(buf);
2fe5adc3 587 if (ok == -1)
30b4c272 588 {
2fe5adc3
RL
589 BIO_printf(bio_err, "User interface error\n");
590 ERR_print_errors(bio_err);
4579924b 591 OPENSSL_cleanse(buf,(unsigned int)bufsiz);
2fe5adc3 592 res = 0;
30b4c272 593 }
2fe5adc3
RL
594 if (ok == -2)
595 {
596 BIO_printf(bio_err,"aborted!\n");
4579924b 597 OPENSSL_cleanse(buf,(unsigned int)bufsiz);
2fe5adc3
RL
598 res = 0;
599 }
600 UI_free(ui);
4f272c17 601 OPENSSL_free(prompt);
30b4c272 602 }
2fe5adc3 603 return res;
30b4c272
RL
604 }
605
a3fe382e
DSH
606static char *app_get_pass(BIO *err, char *arg, int keepbio);
607
608int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
609{
610 int same;
611 if(!arg2 || !arg1 || strcmp(arg1, arg2)) same = 0;
612 else same = 1;
613 if(arg1) {
614 *pass1 = app_get_pass(err, arg1, same);
615 if(!*pass1) return 0;
616 } else if(pass1) *pass1 = NULL;
617 if(arg2) {
618 *pass2 = app_get_pass(err, arg2, same ? 2 : 0);
619 if(!*pass2) return 0;
620 } else if(pass2) *pass2 = NULL;
621 return 1;
622}
623
624static char *app_get_pass(BIO *err, char *arg, int keepbio)
625{
626 char *tmp, tpass[APP_PASS_LEN];
627 static BIO *pwdbio = NULL;
628 int i;
629 if(!strncmp(arg, "pass:", 5)) return BUF_strdup(arg + 5);
630 if(!strncmp(arg, "env:", 4)) {
631 tmp = getenv(arg + 4);
632 if(!tmp) {
633 BIO_printf(err, "Can't read environment variable %s\n", arg + 4);
634 return NULL;
635 }
636 return BUF_strdup(tmp);
637 }
638 if(!keepbio || !pwdbio) {
639 if(!strncmp(arg, "file:", 5)) {
640 pwdbio = BIO_new_file(arg + 5, "r");
641 if(!pwdbio) {
642 BIO_printf(err, "Can't open file %s\n", arg + 5);
643 return NULL;
644 }
eff7cb41
AP
645#if !defined(_WIN32)
646 /*
647 * Under _WIN32, which covers even Win64 and CE, file
648 * descriptors referenced by BIO_s_fd are not inherited
649 * by child process and therefore below is not an option.
650 * It could have been an option if bss_fd.c was operating
651 * on real Windows descriptors, such as those obtained
652 * with CreateFile.
653 */
a3fe382e
DSH
654 } else if(!strncmp(arg, "fd:", 3)) {
655 BIO *btmp;
656 i = atoi(arg + 3);
657 if(i >= 0) pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
658 if((i < 0) || !pwdbio) {
659 BIO_printf(err, "Can't access file descriptor %s\n", arg + 3);
660 return NULL;
661 }
662 /* Can't do BIO_gets on an fd BIO so add a buffering BIO */
663 btmp = BIO_new(BIO_f_buffer());
664 pwdbio = BIO_push(btmp, pwdbio);
eff7cb41 665#endif
a3fe382e
DSH
666 } else if(!strcmp(arg, "stdin")) {
667 pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
668 if(!pwdbio) {
669 BIO_printf(err, "Can't open BIO for stdin\n");
670 return NULL;
671 }
672 } else {
673 BIO_printf(err, "Invalid password argument \"%s\"\n", arg);
674 return NULL;
675 }
676 }
677 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
678 if(keepbio != 1) {
679 BIO_free_all(pwdbio);
680 pwdbio = NULL;
681 }
682 if(i <= 0) {
683 BIO_printf(err, "Error reading password from BIO\n");
684 return NULL;
685 }
686 tmp = strchr(tpass, '\n');
687 if(tmp) *tmp = 0;
688 return BUF_strdup(tpass);
689}
90ae4673 690
b7a26e6d 691int add_oid_section(BIO *err, CONF *conf)
431b0cce
RL
692{
693 char *p;
694 STACK_OF(CONF_VALUE) *sktmp;
695 CONF_VALUE *cnf;
696 int i;
b7a26e6d 697 if(!(p=NCONF_get_string(conf,NULL,"oid_section")))
2c0d1012
BM
698 {
699 ERR_clear_error();
700 return 1;
701 }
b7a26e6d 702 if(!(sktmp = NCONF_get_section(conf, p))) {
431b0cce
RL
703 BIO_printf(err, "problem loading oid section %s\n", p);
704 return 0;
705 }
706 for(i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
707 cnf = sk_CONF_VALUE_value(sktmp, i);
708 if(OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
709 BIO_printf(err, "problem creating object %s=%s\n",
710 cnf->name, cnf->value);
711 return 0;
712 }
713 }
714 return 1;
715}
716
e90fadda
DSH
717static int load_pkcs12(BIO *err, BIO *in, const char *desc,
718 pem_password_cb *pem_cb, void *cb_data,
719 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
720 {
721 const char *pass;
722 char tpass[PEM_BUFSIZE];
723 int len, ret = 0;
724 PKCS12 *p12;
725 p12 = d2i_PKCS12_bio(in, NULL);
726 if (p12 == NULL)
727 {
728 BIO_printf(err, "Error loading PKCS12 file for %s\n", desc);
3ffb8d42 729 goto die;
e90fadda
DSH
730 }
731 /* See if an empty password will do */
732 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
733 pass = "";
734 else
735 {
736 if (!pem_cb)
737 pem_cb = (pem_password_cb *)password_callback;
738 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
739 if (len < 0)
740 {
741 BIO_printf(err, "Passpharse callback error for %s\n",
742 desc);
3ffb8d42 743 goto die;
e90fadda
DSH
744 }
745 if (len < PEM_BUFSIZE)
746 tpass[len] = 0;
747 if (!PKCS12_verify_mac(p12, tpass, len))
748 {
749 BIO_printf(err,
750 "Mac verify error (wrong password?) in PKCS12 file for %s\n", desc);
3ffb8d42 751 goto die;
e90fadda
DSH
752 }
753 pass = tpass;
754 }
755 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
3ffb8d42 756 die:
e90fadda
DSH
757 if (p12)
758 PKCS12_free(p12);
759 return ret;
760 }
761
30b4c272
RL
762X509 *load_cert(BIO *err, const char *file, int format,
763 const char *pass, ENGINE *e, const char *cert_descrip)
90ae4673 764 {
90ae4673
RL
765 X509 *x=NULL;
766 BIO *cert;
767
768 if ((cert=BIO_new(BIO_s_file())) == NULL)
769 {
431b0cce 770 ERR_print_errors(err);
90ae4673
RL
771 goto end;
772 }
773
774 if (file == NULL)
620cea37
BM
775 {
776 setvbuf(stdin, NULL, _IONBF, 0);
90ae4673 777 BIO_set_fp(cert,stdin,BIO_NOCLOSE);
620cea37 778 }
90ae4673
RL
779 else
780 {
781 if (BIO_read_filename(cert,file) <= 0)
782 {
30b4c272
RL
783 BIO_printf(err, "Error opening %s %s\n",
784 cert_descrip, file);
785 ERR_print_errors(err);
90ae4673
RL
786 goto end;
787 }
788 }
789
790 if (format == FORMAT_ASN1)
791 x=d2i_X509_bio(cert,NULL);
792 else if (format == FORMAT_NETSCAPE)
793 {
45e27385
DSH
794 NETSCAPE_X509 *nx;
795 nx=ASN1_item_d2i_bio(ASN1_ITEM_rptr(NETSCAPE_X509),cert,NULL);
796 if (nx == NULL)
90ae4673 797 goto end;
90ae4673 798
45e27385
DSH
799 if ((strncmp(NETSCAPE_CERT_HDR,(char *)nx->header->data,
800 nx->header->length) != 0))
90ae4673 801 {
45e27385 802 NETSCAPE_X509_free(nx);
431b0cce 803 BIO_printf(err,"Error reading header on certificate\n");
90ae4673
RL
804 goto end;
805 }
45e27385
DSH
806 x=nx->cert;
807 nx->cert = NULL;
808 NETSCAPE_X509_free(nx);
90ae4673
RL
809 }
810 else if (format == FORMAT_PEM)
30b4c272
RL
811 x=PEM_read_bio_X509_AUX(cert,NULL,
812 (pem_password_cb *)password_callback, NULL);
90ae4673
RL
813 else if (format == FORMAT_PKCS12)
814 {
e90fadda
DSH
815 if (!load_pkcs12(err, cert,cert_descrip, NULL, NULL,
816 NULL, &x, NULL))
817 goto end;
90ae4673
RL
818 }
819 else {
30b4c272
RL
820 BIO_printf(err,"bad input format specified for %s\n",
821 cert_descrip);
90ae4673
RL
822 goto end;
823 }
824end:
825 if (x == NULL)
826 {
431b0cce
RL
827 BIO_printf(err,"unable to load certificate\n");
828 ERR_print_errors(err);
90ae4673 829 }
90ae4673 830 if (cert != NULL) BIO_free(cert);
90ae4673
RL
831 return(x);
832 }
833
da9b9724 834EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
30b4c272 835 const char *pass, ENGINE *e, const char *key_descrip)
90ae4673
RL
836 {
837 BIO *key=NULL;
838 EVP_PKEY *pkey=NULL;
30b4c272
RL
839 PW_CB_DATA cb_data;
840
841 cb_data.password = pass;
842 cb_data.prompt_info = file;
90ae4673 843
da9b9724 844 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE))
90ae4673 845 {
431b0cce 846 BIO_printf(err,"no keyfile specified\n");
90ae4673
RL
847 goto end;
848 }
0b13e9f0 849#ifndef OPENSSL_NO_ENGINE
32d862ed
RL
850 if (format == FORMAT_ENGINE)
851 {
852 if (!e)
853 BIO_printf(bio_err,"no engine specified\n");
854 else
30b4c272 855 pkey = ENGINE_load_private_key(e, file,
2fe5adc3 856 ui_method, &cb_data);
32d862ed
RL
857 goto end;
858 }
0b13e9f0 859#endif
90ae4673
RL
860 key=BIO_new(BIO_s_file());
861 if (key == NULL)
862 {
431b0cce 863 ERR_print_errors(err);
90ae4673
RL
864 goto end;
865 }
da9b9724 866 if (file == NULL && maybe_stdin)
90ae4673 867 {
da9b9724
RL
868 setvbuf(stdin, NULL, _IONBF, 0);
869 BIO_set_fp(key,stdin,BIO_NOCLOSE);
90ae4673 870 }
da9b9724
RL
871 else
872 if (BIO_read_filename(key,file) <= 0)
873 {
874 BIO_printf(err, "Error opening %s %s\n",
875 key_descrip, file);
876 ERR_print_errors(err);
877 goto end;
878 }
90ae4673
RL
879 if (format == FORMAT_ASN1)
880 {
881 pkey=d2i_PrivateKey_bio(key, NULL);
882 }
883 else if (format == FORMAT_PEM)
884 {
30b4c272
RL
885 pkey=PEM_read_bio_PrivateKey(key,NULL,
886 (pem_password_cb *)password_callback, &cb_data);
90ae4673 887 }
690ecff7 888#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
80bb905d
RL
889 else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
890 pkey = load_netscape_key(err, key, file, key_descrip, format);
891#endif
90ae4673
RL
892 else if (format == FORMAT_PKCS12)
893 {
e90fadda
DSH
894 if (!load_pkcs12(err, key, key_descrip,
895 (pem_password_cb *)password_callback, &cb_data,
896 &pkey, NULL, NULL))
897 goto end;
90ae4673 898 }
a0156a92
DSH
899 else if (format == FORMAT_MSBLOB)
900 pkey = b2i_PrivateKey_bio(key);
901 else if (format == FORMAT_PVK)
902 pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback,
903 &cb_data);
90ae4673
RL
904 else
905 {
30b4c272 906 BIO_printf(err,"bad input format specified for key file\n");
90ae4673
RL
907 goto end;
908 }
909 end:
910 if (key != NULL) BIO_free(key);
911 if (pkey == NULL)
30b4c272 912 BIO_printf(err,"unable to load %s\n", key_descrip);
90ae4673
RL
913 return(pkey);
914 }
915
da9b9724 916EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
30b4c272 917 const char *pass, ENGINE *e, const char *key_descrip)
bd08a2bd
DSH
918 {
919 BIO *key=NULL;
920 EVP_PKEY *pkey=NULL;
30b4c272
RL
921 PW_CB_DATA cb_data;
922
923 cb_data.password = pass;
924 cb_data.prompt_info = file;
bd08a2bd 925
da9b9724 926 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE))
bd08a2bd
DSH
927 {
928 BIO_printf(err,"no keyfile specified\n");
929 goto end;
930 }
0b13e9f0 931#ifndef OPENSSL_NO_ENGINE
32d862ed
RL
932 if (format == FORMAT_ENGINE)
933 {
934 if (!e)
935 BIO_printf(bio_err,"no engine specified\n");
936 else
30b4c272 937 pkey = ENGINE_load_public_key(e, file,
2fe5adc3 938 ui_method, &cb_data);
32d862ed
RL
939 goto end;
940 }
0b13e9f0 941#endif
bd08a2bd
DSH
942 key=BIO_new(BIO_s_file());
943 if (key == NULL)
944 {
945 ERR_print_errors(err);
946 goto end;
947 }
da9b9724 948 if (file == NULL && maybe_stdin)
bd08a2bd 949 {
da9b9724
RL
950 setvbuf(stdin, NULL, _IONBF, 0);
951 BIO_set_fp(key,stdin,BIO_NOCLOSE);
952 }
953 else
954 if (BIO_read_filename(key,file) <= 0)
955 {
956 BIO_printf(err, "Error opening %s %s\n",
957 key_descrip, file);
958 ERR_print_errors(err);
959 goto end;
bd08a2bd
DSH
960 }
961 if (format == FORMAT_ASN1)
962 {
963 pkey=d2i_PUBKEY_bio(key, NULL);
964 }
eea374fd
DSH
965 else if (format == FORMAT_ASN1RSA)
966 {
967 RSA *rsa;
968 rsa = d2i_RSAPublicKey_bio(key, NULL);
969 if (rsa)
970 {
971 pkey = EVP_PKEY_new();
972 if (pkey)
973 EVP_PKEY_set1_RSA(pkey, rsa);
974 RSA_free(rsa);
975 }
976 else
977 pkey = NULL;
978 }
979 else if (format == FORMAT_PEMRSA)
980 {
981 RSA *rsa;
982 rsa = PEM_read_bio_RSAPublicKey(key, NULL,
983 (pem_password_cb *)password_callback, &cb_data);
984 if (rsa)
985 {
986 pkey = EVP_PKEY_new();
987 if (pkey)
988 EVP_PKEY_set1_RSA(pkey, rsa);
989 RSA_free(rsa);
990 }
991 else
992 pkey = NULL;
993 }
994
bd08a2bd
DSH
995 else if (format == FORMAT_PEM)
996 {
30b4c272
RL
997 pkey=PEM_read_bio_PUBKEY(key,NULL,
998 (pem_password_cb *)password_callback, &cb_data);
bd08a2bd 999 }
690ecff7 1000#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
80bb905d
RL
1001 else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
1002 pkey = load_netscape_key(err, key, file, key_descrip, format);
1003#endif
a0156a92
DSH
1004 else if (format == FORMAT_MSBLOB)
1005 pkey = b2i_PublicKey_bio(key);
bd08a2bd
DSH
1006 else
1007 {
30b4c272 1008 BIO_printf(err,"bad input format specified for key file\n");
bd08a2bd
DSH
1009 goto end;
1010 }
1011 end:
1012 if (key != NULL) BIO_free(key);
1013 if (pkey == NULL)
30b4c272 1014 BIO_printf(err,"unable to load %s\n", key_descrip);
bd08a2bd
DSH
1015 return(pkey);
1016 }
1017
690ecff7 1018#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
1c02ca53 1019static EVP_PKEY *
80bb905d
RL
1020load_netscape_key(BIO *err, BIO *key, const char *file,
1021 const char *key_descrip, int format)
1022 {
1023 EVP_PKEY *pkey;
1024 BUF_MEM *buf;
1025 RSA *rsa;
1026 const unsigned char *p;
1027 int size, i;
1028
1029 buf=BUF_MEM_new();
1030 pkey = EVP_PKEY_new();
1031 size = 0;
1032 if (buf == NULL || pkey == NULL)
1033 goto error;
1034 for (;;)
1035 {
54a656ef 1036 if (!BUF_MEM_grow_clean(buf,size+1024*10))
80bb905d
RL
1037 goto error;
1038 i = BIO_read(key, &(buf->data[size]), 1024*10);
1039 size += i;
1040 if (i == 0)
1041 break;
1042 if (i < 0)
1043 {
1044 BIO_printf(err, "Error reading %s %s",
1045 key_descrip, file);
1046 goto error;
1047 }
1048 }
1049 p=(unsigned char *)buf->data;
1050 rsa = d2i_RSA_NET(NULL,&p,(long)size,NULL,
1051 (format == FORMAT_IISSGC ? 1 : 0));
1052 if (rsa == NULL)
1053 goto error;
1054 BUF_MEM_free(buf);
1055 EVP_PKEY_set1_RSA(pkey, rsa);
1056 return pkey;
1057error:
1058 BUF_MEM_free(buf);
1059 EVP_PKEY_free(pkey);
1060 return NULL;
1061 }
1062#endif /* ndef OPENSSL_NO_RC4 */
1063
30b4c272
RL
1064STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
1065 const char *pass, ENGINE *e, const char *cert_descrip)
90ae4673
RL
1066 {
1067 BIO *certs;
1068 int i;
1069 STACK_OF(X509) *othercerts = NULL;
1070 STACK_OF(X509_INFO) *allcerts = NULL;
1071 X509_INFO *xi;
30b4c272
RL
1072 PW_CB_DATA cb_data;
1073
1074 cb_data.password = pass;
1075 cb_data.prompt_info = file;
90ae4673
RL
1076
1077 if((certs = BIO_new(BIO_s_file())) == NULL)
1078 {
431b0cce 1079 ERR_print_errors(err);
90ae4673
RL
1080 goto end;
1081 }
1082
1083 if (file == NULL)
1084 BIO_set_fp(certs,stdin,BIO_NOCLOSE);
1085 else
1086 {
1087 if (BIO_read_filename(certs,file) <= 0)
1088 {
30b4c272
RL
1089 BIO_printf(err, "Error opening %s %s\n",
1090 cert_descrip, file);
1091 ERR_print_errors(err);
90ae4673
RL
1092 goto end;
1093 }
1094 }
1095
1096 if (format == FORMAT_PEM)
1097 {
62324627 1098 othercerts = sk_X509_new_null();
90ae4673
RL
1099 if(!othercerts)
1100 {
1101 sk_X509_free(othercerts);
1102 othercerts = NULL;
1103 goto end;
1104 }
30b4c272
RL
1105 allcerts = PEM_X509_INFO_read_bio(certs, NULL,
1106 (pem_password_cb *)password_callback, &cb_data);
90ae4673
RL
1107 for(i = 0; i < sk_X509_INFO_num(allcerts); i++)
1108 {
1109 xi = sk_X509_INFO_value (allcerts, i);
1110 if (xi->x509)
1111 {
1112 sk_X509_push(othercerts, xi->x509);
1113 xi->x509 = NULL;
1114 }
1115 }
1116 goto end;
1117 }
1118 else {
30b4c272
RL
1119 BIO_printf(err,"bad input format specified for %s\n",
1120 cert_descrip);
90ae4673
RL
1121 goto end;
1122 }
1123end:
1124 if (othercerts == NULL)
1125 {
431b0cce
RL
1126 BIO_printf(err,"unable to load certificates\n");
1127 ERR_print_errors(err);
90ae4673
RL
1128 }
1129 if (allcerts) sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
1130 if (certs != NULL) BIO_free(certs);
1131 return(othercerts);
1132 }
1133
8ca533e3
DSH
1134
1135#define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1136/* Return error for unknown extensions */
1137#define X509V3_EXT_DEFAULT 0
1138/* Print error for unknown extensions */
1139#define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
1140/* ASN1 parse unknown extensions */
1141#define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
1142/* BIO_dump unknown extensions */
1143#define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
1144
535d79da
DSH
1145#define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1146 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1147
8ca533e3
DSH
1148int set_cert_ex(unsigned long *flags, const char *arg)
1149{
1150 static const NAME_EX_TBL cert_tbl[] = {
1151 { "compatible", X509_FLAG_COMPAT, 0xffffffffl},
535d79da 1152 { "ca_default", X509_FLAG_CA, 0xffffffffl},
8ca533e3
DSH
1153 { "no_header", X509_FLAG_NO_HEADER, 0},
1154 { "no_version", X509_FLAG_NO_VERSION, 0},
1155 { "no_serial", X509_FLAG_NO_SERIAL, 0},
1156 { "no_signame", X509_FLAG_NO_SIGNAME, 0},
1157 { "no_validity", X509_FLAG_NO_VALIDITY, 0},
1158 { "no_subject", X509_FLAG_NO_SUBJECT, 0},
0a3ea5d3 1159 { "no_issuer", X509_FLAG_NO_ISSUER, 0},
8ca533e3
DSH
1160 { "no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1161 { "no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1162 { "no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1163 { "no_aux", X509_FLAG_NO_AUX, 0},
fc85ac20 1164 { "no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
8ca533e3
DSH
1165 { "ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1166 { "ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1167 { "ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1168 { "ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1169 { NULL, 0, 0}
1170 };
535d79da 1171 return set_multi_opts(flags, arg, cert_tbl);
8ca533e3 1172}
a657546f
DSH
1173
1174int set_name_ex(unsigned long *flags, const char *arg)
1175{
8ca533e3 1176 static const NAME_EX_TBL ex_tbl[] = {
a657546f
DSH
1177 { "esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1178 { "esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1179 { "esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1180 { "use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1181 { "utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
bd4e1527
DSH
1182 { "ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1183 { "show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
a657546f
DSH
1184 { "dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1185 { "dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1186 { "dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1187 { "compat", XN_FLAG_COMPAT, 0xffffffffL},
1188 { "sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1189 { "sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1190 { "sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1191 { "sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1192 { "dn_rev", XN_FLAG_DN_REV, 0},
1193 { "nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1194 { "sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1195 { "lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
e890dcdb 1196 { "align", XN_FLAG_FN_ALIGN, 0},
a657546f
DSH
1197 { "oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1198 { "space_eq", XN_FLAG_SPC_EQ, 0},
1199 { "dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1200 { "RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1201 { "oneline", XN_FLAG_ONELINE, 0xffffffffL},
1202 { "multiline", XN_FLAG_MULTILINE, 0xffffffffL},
535d79da 1203 { "ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
a657546f
DSH
1204 { NULL, 0, 0}
1205 };
535d79da
DSH
1206 return set_multi_opts(flags, arg, ex_tbl);
1207}
1208
791bd0cd
DSH
1209int set_ext_copy(int *copy_type, const char *arg)
1210{
1211 if (!strcasecmp(arg, "none"))
1212 *copy_type = EXT_COPY_NONE;
1213 else if (!strcasecmp(arg, "copy"))
1214 *copy_type = EXT_COPY_ADD;
1215 else if (!strcasecmp(arg, "copyall"))
1216 *copy_type = EXT_COPY_ALL;
1217 else
1218 return 0;
1219 return 1;
1220}
1221
1222int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1223{
1224 STACK_OF(X509_EXTENSION) *exts = NULL;
1225 X509_EXTENSION *ext, *tmpext;
1226 ASN1_OBJECT *obj;
1227 int i, idx, ret = 0;
1228 if (!x || !req || (copy_type == EXT_COPY_NONE))
1229 return 1;
1230 exts = X509_REQ_get_extensions(req);
1231
1232 for(i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1233 ext = sk_X509_EXTENSION_value(exts, i);
1234 obj = X509_EXTENSION_get_object(ext);
1235 idx = X509_get_ext_by_OBJ(x, obj, -1);
1236 /* Does extension exist? */
1237 if (idx != -1) {
1238 /* If normal copy don't override existing extension */
1239 if (copy_type == EXT_COPY_ADD)
1240 continue;
1241 /* Delete all extensions of same type */
1242 do {
1243 tmpext = X509_get_ext(x, idx);
1244 X509_delete_ext(x, idx);
1245 X509_EXTENSION_free(tmpext);
1246 idx = X509_get_ext_by_OBJ(x, obj, -1);
1247 } while (idx != -1);
1248 }
1249 if (!X509_add_ext(x, ext, -1))
1250 goto end;
1251 }
1252
1253 ret = 1;
1254
1255 end:
1256
1257 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1258
1259 return ret;
1260}
1261
1262
1263
1264
535d79da
DSH
1265static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl)
1266{
1267 STACK_OF(CONF_VALUE) *vals;
1268 CONF_VALUE *val;
1269 int i, ret = 1;
1270 if(!arg) return 0;
1271 vals = X509V3_parse_list(arg);
1272 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1273 val = sk_CONF_VALUE_value(vals, i);
1274 if (!set_table_opts(flags, val->name, in_tbl))
1275 ret = 0;
1276 }
1277 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1278 return ret;
8ca533e3 1279}
a657546f 1280
8ca533e3
DSH
1281static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl)
1282{
1283 char c;
1284 const NAME_EX_TBL *ptbl;
a657546f
DSH
1285 c = arg[0];
1286
1287 if(c == '-') {
1288 c = 0;
1289 arg++;
1290 } else if (c == '+') {
1291 c = 1;
1292 arg++;
1293 } else c = 1;
1294
8ca533e3 1295 for(ptbl = in_tbl; ptbl->name; ptbl++) {
c15e0363 1296 if(!strcasecmp(arg, ptbl->name)) {
a657546f
DSH
1297 *flags &= ~ptbl->mask;
1298 if(c) *flags |= ptbl->flag;
1299 else *flags &= ~ptbl->flag;
1300 return 1;
1301 }
1302 }
1303 return 0;
1304}
1305
7d727231 1306void print_name(BIO *out, const char *title, X509_NAME *nm, unsigned long lflags)
a657546f 1307{
402bcde8 1308 char *buf;
a657546f
DSH
1309 char mline = 0;
1310 int indent = 0;
54a656ef 1311
a657546f
DSH
1312 if(title) BIO_puts(out, title);
1313 if((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1314 mline = 1;
1315 indent = 4;
1316 }
1317 if(lflags == XN_FLAG_COMPAT) {
402bcde8
RL
1318 buf = X509_NAME_oneline(nm, 0, 0);
1319 BIO_puts(out, buf);
a657546f 1320 BIO_puts(out, "\n");
402bcde8 1321 OPENSSL_free(buf);
a657546f
DSH
1322 } else {
1323 if(mline) BIO_puts(out, "\n");
1324 X509_NAME_print_ex(out, nm, indent, lflags);
1325 BIO_puts(out, "\n");
1326 }
1327}
1328
81f169e9
DSH
1329X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath)
1330{
1331 X509_STORE *store;
1332 X509_LOOKUP *lookup;
1333 if(!(store = X509_STORE_new())) goto end;
1334 lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file());
1335 if (lookup == NULL) goto end;
1336 if (CAfile) {
1337 if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) {
1338 BIO_printf(bp, "Error loading file %s\n", CAfile);
1339 goto end;
1340 }
1341 } else X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
1342
1343 lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
1344 if (lookup == NULL) goto end;
1345 if (CApath) {
1346 if(!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) {
1347 BIO_printf(bp, "Error loading directory %s\n", CApath);
1348 goto end;
1349 }
1350 } else X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
1351
1352 ERR_clear_error();
1353 return store;
1354 end:
1355 X509_STORE_free(store);
1356 return NULL;
1357}
531d630b 1358
0b13e9f0 1359#ifndef OPENSSL_NO_ENGINE
e1a00d7d 1360/* Try to load an engine in a shareable library */
40889b9c 1361static ENGINE *try_load_engine(BIO *err, const char *engine, int debug)
e1a00d7d
RL
1362 {
1363 ENGINE *e = ENGINE_by_id("dynamic");
1364 if (e)
1365 {
1366 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1367 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
1368 {
1369 ENGINE_free(e);
1370 e = NULL;
1371 }
1372 }
1373 return e;
1374 }
1375
531d630b
RL
1376ENGINE *setup_engine(BIO *err, const char *engine, int debug)
1377 {
1378 ENGINE *e = NULL;
1379
1380 if (engine)
1381 {
34c66925
GT
1382 if(strcmp(engine, "auto") == 0)
1383 {
1384 BIO_printf(err,"enabling auto ENGINE support\n");
1385 ENGINE_register_all_complete();
1386 return NULL;
1387 }
e1a00d7d
RL
1388 if((e = ENGINE_by_id(engine)) == NULL
1389 && (e = try_load_engine(err, engine, debug)) == NULL)
531d630b
RL
1390 {
1391 BIO_printf(err,"invalid engine \"%s\"\n", engine);
e1a00d7d 1392 ERR_print_errors(err);
531d630b
RL
1393 return NULL;
1394 }
1395 if (debug)
1396 {
1397 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM,
1398 0, err, 0);
1399 }
2fe5adc3 1400 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
531d630b
RL
1401 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL))
1402 {
1403 BIO_printf(err,"can't use that engine\n");
e1a00d7d 1404 ERR_print_errors(err);
308f028e 1405 ENGINE_free(e);
531d630b
RL
1406 return NULL;
1407 }
354c3ace 1408
e1a00d7d 1409 BIO_printf(err,"engine \"%s\" set.\n", ENGINE_get_id(e));
354c3ace 1410
531d630b
RL
1411 /* Free our "structural" reference. */
1412 ENGINE_free(e);
1413 }
1414 return e;
1415 }
0b13e9f0 1416#endif
3647bee2
DSH
1417
1418int load_config(BIO *err, CONF *cnf)
1419 {
1420 if (!cnf)
1421 cnf = config;
1422 if (!cnf)
1423 return 1;
1424
1425 OPENSSL_load_builtin_modules();
1426
1427 if (CONF_modules_load(cnf, NULL, 0) <= 0)
1428 {
1429 BIO_printf(err, "Error configuring OpenSSL\n");
1430 ERR_print_errors(err);
1431 return 0;
1432 }
1433 return 1;
1434 }
54a656ef
BL
1435
1436char *make_config_name()
1437 {
1438 const char *t=X509_get_default_cert_area();
d420ac2c 1439 size_t len;
54a656ef
BL
1440 char *p;
1441
d420ac2c
RL
1442 len=strlen(t)+strlen(OPENSSL_CONF)+2;
1443 p=OPENSSL_malloc(len);
1444 BUF_strlcpy(p,t,len);
54a656ef 1445#ifndef OPENSSL_SYS_VMS
d420ac2c 1446 BUF_strlcat(p,"/",len);
54a656ef 1447#endif
d420ac2c 1448 BUF_strlcat(p,OPENSSL_CONF,len);
54a656ef
BL
1449
1450 return p;
1451 }
f85b68cd
RL
1452
1453static unsigned long index_serial_hash(const char **a)
1454 {
1455 const char *n;
1456
1457 n=a[DB_serial];
1458 while (*n == '0') n++;
1459 return(lh_strhash(n));
1460 }
1461
1462static int index_serial_cmp(const char **a, const char **b)
1463 {
1464 const char *aa,*bb;
1465
1466 for (aa=a[DB_serial]; *aa == '0'; aa++);
1467 for (bb=b[DB_serial]; *bb == '0'; bb++);
1468 return(strcmp(aa,bb));
1469 }
1470
1471static int index_name_qual(char **a)
1472 { return(a[0][0] == 'V'); }
1473
1474static unsigned long index_name_hash(const char **a)
1475 { return(lh_strhash(a[DB_name])); }
1476
1477int index_name_cmp(const char **a, const char **b)
1478 { return(strcmp(a[DB_name],
1479 b[DB_name])); }
1480
1481static IMPLEMENT_LHASH_HASH_FN(index_serial_hash,const char **)
1482static IMPLEMENT_LHASH_COMP_FN(index_serial_cmp,const char **)
1483static IMPLEMENT_LHASH_HASH_FN(index_name_hash,const char **)
1484static IMPLEMENT_LHASH_COMP_FN(index_name_cmp,const char **)
1485
1486#undef BSIZE
1487#define BSIZE 256
1488
1489BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1490 {
1491 BIO *in=NULL;
1492 BIGNUM *ret=NULL;
1493 MS_STATIC char buf[1024];
1494 ASN1_INTEGER *ai=NULL;
1495
1496 ai=ASN1_INTEGER_new();
1497 if (ai == NULL) goto err;
1498
1499 if ((in=BIO_new(BIO_s_file())) == NULL)
1500 {
1501 ERR_print_errors(bio_err);
1502 goto err;
1503 }
1504
1505 if (BIO_read_filename(in,serialfile) <= 0)
1506 {
1507 if (!create)
1508 {
1509 perror(serialfile);
1510 goto err;
1511 }
1512 else
1513 {
f85b68cd 1514 ret=BN_new();
64674bcc 1515 if (ret == NULL || !rand_serial(ret, ai))
f85b68cd 1516 BIO_printf(bio_err, "Out of memory\n");
f85b68cd
RL
1517 }
1518 }
1519 else
1520 {
1521 if (!a2i_ASN1_INTEGER(in,ai,buf,1024))
1522 {
1523 BIO_printf(bio_err,"unable to load number from %s\n",
1524 serialfile);
1525 goto err;
1526 }
1527 ret=ASN1_INTEGER_to_BN(ai,NULL);
1528 if (ret == NULL)
1529 {
1530 BIO_printf(bio_err,"error converting number from bin to BIGNUM\n");
1531 goto err;
1532 }
1533 }
1534
1535 if (ret && retai)
1536 {
1537 *retai = ai;
1538 ai = NULL;
1539 }
1540 err:
1541 if (in != NULL) BIO_free(in);
1542 if (ai != NULL) ASN1_INTEGER_free(ai);
1543 return(ret);
1544 }
1545
4c771796 1546int save_serial(char *serialfile, char *suffix, BIGNUM *serial, ASN1_INTEGER **retai)
f85b68cd 1547 {
4c771796
RL
1548 char buf[1][BSIZE];
1549 BIO *out = NULL;
f85b68cd
RL
1550 int ret=0;
1551 ASN1_INTEGER *ai=NULL;
4c771796
RL
1552 int j;
1553
1554 if (suffix == NULL)
1555 j = strlen(serialfile);
1556 else
1557 j = strlen(serialfile) + strlen(suffix) + 1;
1558 if (j >= BSIZE)
1559 {
1560 BIO_printf(bio_err,"file name too long\n");
1561 goto err;
1562 }
f85b68cd 1563
4c771796
RL
1564 if (suffix == NULL)
1565 BUF_strlcpy(buf[0], serialfile, BSIZE);
1566 else
1567 {
1568#ifndef OPENSSL_SYS_VMS
1569 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1570#else
1571 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1572#endif
1573 }
1574#ifdef RL_DEBUG
1575 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1576#endif
f85b68cd
RL
1577 out=BIO_new(BIO_s_file());
1578 if (out == NULL)
1579 {
1580 ERR_print_errors(bio_err);
1581 goto err;
1582 }
4c771796 1583 if (BIO_write_filename(out,buf[0]) <= 0)
f85b68cd
RL
1584 {
1585 perror(serialfile);
1586 goto err;
1587 }
1588
1589 if ((ai=BN_to_ASN1_INTEGER(serial,NULL)) == NULL)
1590 {
1591 BIO_printf(bio_err,"error converting serial to ASN.1 format\n");
1592 goto err;
1593 }
1594 i2a_ASN1_INTEGER(out,ai);
1595 BIO_puts(out,"\n");
1596 ret=1;
1597 if (retai)
1598 {
1599 *retai = ai;
1600 ai = NULL;
1601 }
1602err:
1603 if (out != NULL) BIO_free_all(out);
1604 if (ai != NULL) ASN1_INTEGER_free(ai);
1605 return(ret);
1606 }
1607
4c771796
RL
1608int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1609 {
1610 char buf[5][BSIZE];
1611 int i,j;
1612 struct stat sb;
1613
1614 i = strlen(serialfile) + strlen(old_suffix);
1615 j = strlen(serialfile) + strlen(new_suffix);
1616 if (i > j) j = i;
1617 if (j + 1 >= BSIZE)
1618 {
1619 BIO_printf(bio_err,"file name too long\n");
1620 goto err;
1621 }
1622
1623#ifndef OPENSSL_SYS_VMS
1624 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1625 serialfile, new_suffix);
1626#else
1627 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1628 serialfile, new_suffix);
1629#endif
1630#ifndef OPENSSL_SYS_VMS
1631 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1632 serialfile, old_suffix);
1633#else
1634 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1635 serialfile, old_suffix);
1636#endif
1637 if (stat(serialfile,&sb) < 0)
1638 {
1639 if (errno != ENOENT
1640#ifdef ENOTDIR
53bb3bee 1641 && errno != ENOTDIR
4c771796 1642#endif
53bb3bee 1643 )
4c771796
RL
1644 goto err;
1645 }
1646 else
1647 {
1648#ifdef RL_DEBUG
1649 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1650 serialfile, buf[1]);
1651#endif
1652 if (rename(serialfile,buf[1]) < 0)
1653 {
1654 BIO_printf(bio_err,
1655 "unable to rename %s to %s\n",
1656 serialfile, buf[1]);
1657 perror("reason");
1658 goto err;
1659 }
1660 }
1661#ifdef RL_DEBUG
1662 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1663 buf[0],serialfile);
1664#endif
1665 if (rename(buf[0],serialfile) < 0)
1666 {
1667 BIO_printf(bio_err,
1668 "unable to rename %s to %s\n",
1669 buf[0],serialfile);
1670 perror("reason");
1671 rename(buf[1],serialfile);
1672 goto err;
1673 }
1674 return 1;
1675 err:
1676 return 0;
1677 }
1678
64674bcc
DSH
1679int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1680 {
1681 BIGNUM *btmp;
1682 int ret = 0;
1683 if (b)
1684 btmp = b;
1685 else
1686 btmp = BN_new();
1687
1688 if (!btmp)
1689 return 0;
1690
1691 if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1692 goto error;
1693 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1694 goto error;
1695
1696 ret = 1;
1697
1698 error:
1699
1700 if (!b)
1701 BN_free(btmp);
1702
1703 return ret;
1704 }
1705
f85b68cd
RL
1706CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1707 {
1708 CA_DB *retdb = NULL;
1709 TXT_DB *tmpdb = NULL;
1710 BIO *in = BIO_new(BIO_s_file());
1711 CONF *dbattr_conf = NULL;
1712 char buf[1][BSIZE];
1713 long errorline= -1;
1714
1715 if (in == NULL)
1716 {
1717 ERR_print_errors(bio_err);
1718 goto err;
1719 }
1720 if (BIO_read_filename(in,dbfile) <= 0)
1721 {
1722 perror(dbfile);
1723 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
1724 goto err;
1725 }
1726 if ((tmpdb = TXT_DB_read(in,DB_NUMBER)) == NULL)
1727 {
1728 if (tmpdb != NULL) TXT_DB_free(tmpdb);
1729 goto err;
1730 }
1731
1732#ifndef OPENSSL_SYS_VMS
1733 BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1734#else
1735 BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1736#endif
1737 dbattr_conf = NCONF_new(NULL);
1738 if (NCONF_load(dbattr_conf,buf[0],&errorline) <= 0)
1739 {
1740 if (errorline > 0)
1741 {
1742 BIO_printf(bio_err,
1743 "error on line %ld of db attribute file '%s'\n"
1744 ,errorline,buf[0]);
1745 goto err;
1746 }
1747 else
1748 {
1749 NCONF_free(dbattr_conf);
1750 dbattr_conf = NULL;
1751 }
1752 }
1753
1754 if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL)
1755 {
1756 fprintf(stderr, "Out of memory\n");
1757 goto err;
1758 }
1759
1760 retdb->db = tmpdb;
1761 tmpdb = NULL;
1762 if (db_attr)
1763 retdb->attributes = *db_attr;
1764 else
1765 {
1766 retdb->attributes.unique_subject = 1;
1767 }
1768
1769 if (dbattr_conf)
1770 {
1771 char *p = NCONF_get_string(dbattr_conf,NULL,"unique_subject");
1772 if (p)
1773 {
83b23ed9 1774#ifdef RL_DEBUG
f85b68cd 1775 BIO_printf(bio_err, "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
83b23ed9 1776#endif
03ddbdd9 1777 retdb->attributes.unique_subject = parse_yesno(p,1);
f85b68cd
RL
1778 }
1779 }
1780
1781 err:
1782 if (dbattr_conf) NCONF_free(dbattr_conf);
1783 if (tmpdb) TXT_DB_free(tmpdb);
1784 if (in) BIO_free_all(in);
1785 return retdb;
1786 }
1787
1788int index_index(CA_DB *db)
1789 {
1790 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1791 LHASH_HASH_FN(index_serial_hash),
1792 LHASH_COMP_FN(index_serial_cmp)))
1793 {
1794 BIO_printf(bio_err,
1795 "error creating serial number index:(%ld,%ld,%ld)\n",
1796 db->db->error,db->db->arg1,db->db->arg2);
1797 return 0;
1798 }
1799
1800 if (db->attributes.unique_subject
1801 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1802 LHASH_HASH_FN(index_name_hash),
1803 LHASH_COMP_FN(index_name_cmp)))
1804 {
1805 BIO_printf(bio_err,"error creating name index:(%ld,%ld,%ld)\n",
1806 db->db->error,db->db->arg1,db->db->arg2);
1807 return 0;
1808 }
1809 return 1;
1810 }
1811
7d727231 1812int save_index(const char *dbfile, const char *suffix, CA_DB *db)
f85b68cd
RL
1813 {
1814 char buf[3][BSIZE];
1815 BIO *out = BIO_new(BIO_s_file());
1816 int j;
1817
1818 if (out == NULL)
1819 {
1820 ERR_print_errors(bio_err);
1821 goto err;
1822 }
1823
1824 j = strlen(dbfile) + strlen(suffix);
1825 if (j + 6 >= BSIZE)
1826 {
1827 BIO_printf(bio_err,"file name too long\n");
1828 goto err;
1829 }
1830
1831#ifndef OPENSSL_SYS_VMS
1832 j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1833#else
1834 j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1835#endif
1836#ifndef OPENSSL_SYS_VMS
1837 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1838#else
1839 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1840#endif
1841#ifndef OPENSSL_SYS_VMS
1842 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1843#else
1844 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1845#endif
63b6fe2b 1846#ifdef RL_DEBUG
f85b68cd 1847 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
63b6fe2b 1848#endif
f85b68cd
RL
1849 if (BIO_write_filename(out,buf[0]) <= 0)
1850 {
1851 perror(dbfile);
1852 BIO_printf(bio_err,"unable to open '%s'\n", dbfile);
1853 goto err;
1854 }
1855 j=TXT_DB_write(out,db->db);
1856 if (j <= 0) goto err;
1857
1858 BIO_free(out);
1859
1860 out = BIO_new(BIO_s_file());
63b6fe2b 1861#ifdef RL_DEBUG
f85b68cd 1862 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
63b6fe2b 1863#endif
f85b68cd
RL
1864 if (BIO_write_filename(out,buf[1]) <= 0)
1865 {
1866 perror(buf[2]);
1867 BIO_printf(bio_err,"unable to open '%s'\n", buf[2]);
1868 goto err;
1869 }
1870 BIO_printf(out,"unique_subject = %s\n",
1871 db->attributes.unique_subject ? "yes" : "no");
1872 BIO_free(out);
1873
1874 return 1;
1875 err:
1876 return 0;
1877 }
1878
7d727231 1879int rotate_index(const char *dbfile, const char *new_suffix, const char *old_suffix)
f85b68cd
RL
1880 {
1881 char buf[5][BSIZE];
1882 int i,j;
1883 struct stat sb;
1884
1885 i = strlen(dbfile) + strlen(old_suffix);
1886 j = strlen(dbfile) + strlen(new_suffix);
1887 if (i > j) j = i;
1888 if (j + 6 >= BSIZE)
1889 {
1890 BIO_printf(bio_err,"file name too long\n");
1891 goto err;
1892 }
1893
1894#ifndef OPENSSL_SYS_VMS
1895 j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1896#else
1897 j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
1898#endif
1899#ifndef OPENSSL_SYS_VMS
1900 j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s",
1901 dbfile, new_suffix);
1902#else
1903 j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s",
1904 dbfile, new_suffix);
1905#endif
1906#ifndef OPENSSL_SYS_VMS
1907 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s",
1908 dbfile, new_suffix);
1909#else
1910 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s",
1911 dbfile, new_suffix);
1912#endif
1913#ifndef OPENSSL_SYS_VMS
1914 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s",
1915 dbfile, old_suffix);
1916#else
1917 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s",
1918 dbfile, old_suffix);
1919#endif
1920#ifndef OPENSSL_SYS_VMS
1921 j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s",
1922 dbfile, old_suffix);
1923#else
1924 j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s",
1925 dbfile, old_suffix);
1926#endif
1927 if (stat(dbfile,&sb) < 0)
1928 {
1929 if (errno != ENOENT
1930#ifdef ENOTDIR
53bb3bee 1931 && errno != ENOTDIR
f85b68cd 1932#endif
53bb3bee 1933 )
f85b68cd
RL
1934 goto err;
1935 }
1936 else
1937 {
63b6fe2b 1938#ifdef RL_DEBUG
f85b68cd
RL
1939 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1940 dbfile, buf[1]);
63b6fe2b 1941#endif
f85b68cd
RL
1942 if (rename(dbfile,buf[1]) < 0)
1943 {
1944 BIO_printf(bio_err,
1945 "unable to rename %s to %s\n",
1946 dbfile, buf[1]);
1947 perror("reason");
1948 goto err;
1949 }
1950 }
63b6fe2b 1951#ifdef RL_DEBUG
f85b68cd
RL
1952 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1953 buf[0],dbfile);
63b6fe2b 1954#endif
f85b68cd
RL
1955 if (rename(buf[0],dbfile) < 0)
1956 {
1957 BIO_printf(bio_err,
1958 "unable to rename %s to %s\n",
1959 buf[0],dbfile);
1960 perror("reason");
1961 rename(buf[1],dbfile);
1962 goto err;
1963 }
1964 if (stat(buf[4],&sb) < 0)
1965 {
1966 if (errno != ENOENT
1967#ifdef ENOTDIR
53bb3bee 1968 && errno != ENOTDIR
f85b68cd 1969#endif
53bb3bee 1970 )
f85b68cd
RL
1971 goto err;
1972 }
1973 else
1974 {
63b6fe2b 1975#ifdef RL_DEBUG
f85b68cd
RL
1976 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1977 buf[4],buf[3]);
63b6fe2b 1978#endif
f85b68cd
RL
1979 if (rename(buf[4],buf[3]) < 0)
1980 {
1981 BIO_printf(bio_err,
1982 "unable to rename %s to %s\n",
1983 buf[4], buf[3]);
1984 perror("reason");
1985 rename(dbfile,buf[0]);
1986 rename(buf[1],dbfile);
1987 goto err;
1988 }
1989 }
63b6fe2b 1990#ifdef RL_DEBUG
f85b68cd
RL
1991 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1992 buf[2],buf[4]);
63b6fe2b 1993#endif
f85b68cd
RL
1994 if (rename(buf[2],buf[4]) < 0)
1995 {
1996 BIO_printf(bio_err,
1997 "unable to rename %s to %s\n",
1998 buf[2],buf[4]);
1999 perror("reason");
2000 rename(buf[3],buf[4]);
2001 rename(dbfile,buf[0]);
2002 rename(buf[1],dbfile);
2003 goto err;
2004 }
2005 return 1;
2006 err:
2007 return 0;
2008 }
2009
2010void free_index(CA_DB *db)
2011 {
db598fbc
RL
2012 if (db)
2013 {
2014 if (db->db) TXT_DB_free(db->db);
2015 OPENSSL_free(db);
2016 }
f85b68cd 2017 }
6d5ffb59 2018
ff990440 2019int parse_yesno(const char *str, int def)
03ddbdd9
RL
2020 {
2021 int ret = def;
2022 if (str)
2023 {
2024 switch (*str)
2025 {
2026 case 'f': /* false */
2027 case 'F': /* FALSE */
2028 case 'n': /* no */
2029 case 'N': /* NO */
2030 case '0': /* 0 */
2031 ret = 0;
2032 break;
2033 case 't': /* true */
2034 case 'T': /* TRUE */
2035 case 'y': /* yes */
2036 case 'Y': /* YES */
2037 case '1': /* 1 */
2038 ret = 0;
2039 break;
2040 default:
2041 ret = def;
2042 break;
2043 }
2044 }
2045 return ret;
2046 }
2047
6d5ffb59
RL
2048/*
2049 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
2050 * where characters may be escaped by \
2051 */
2052X509_NAME *parse_name(char *subject, long chtype, int multirdn)
2053 {
2054 size_t buflen = strlen(subject)+1; /* to copy the types and values into. due to escaping, the copy can only become shorter */
2055 char *buf = OPENSSL_malloc(buflen);
2056 size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
2057 char **ne_types = OPENSSL_malloc(max_ne * sizeof (char *));
2058 char **ne_values = OPENSSL_malloc(max_ne * sizeof (char *));
2059 int *mval = OPENSSL_malloc (max_ne * sizeof (int));
2060
2061 char *sp = subject, *bp = buf;
2062 int i, ne_num = 0;
2063
2064 X509_NAME *n = NULL;
2065 int nid;
2066
2067 if (!buf || !ne_types || !ne_values)
2068 {
2069 BIO_printf(bio_err, "malloc error\n");
2070 goto error;
2071 }
2072
2073 if (*subject != '/')
2074 {
2075 BIO_printf(bio_err, "Subject does not start with '/'.\n");
2076 goto error;
2077 }
2078 sp++; /* skip leading / */
2079
2080 /* no multivalued RDN by default */
2081 mval[ne_num] = 0;
2082
2083 while (*sp)
2084 {
2085 /* collect type */
2086 ne_types[ne_num] = bp;
2087 while (*sp)
2088 {
2089 if (*sp == '\\') /* is there anything to escape in the type...? */
2090 {
2091 if (*++sp)
2092 *bp++ = *sp++;
2093 else
2094 {
2095 BIO_printf(bio_err, "escape character at end of string\n");
2096 goto error;
2097 }
2098 }
2099 else if (*sp == '=')
2100 {
2101 sp++;
2102 *bp++ = '\0';
2103 break;
2104 }
2105 else
2106 *bp++ = *sp++;
2107 }
2108 if (!*sp)
2109 {
2110 BIO_printf(bio_err, "end of string encountered while processing type of subject name element #%d\n", ne_num);
2111 goto error;
2112 }
2113 ne_values[ne_num] = bp;
2114 while (*sp)
2115 {
2116 if (*sp == '\\')
2117 {
2118 if (*++sp)
2119 *bp++ = *sp++;
2120 else
2121 {
2122 BIO_printf(bio_err, "escape character at end of string\n");
2123 goto error;
2124 }
2125 }
2126 else if (*sp == '/')
2127 {
2128 sp++;
2129 /* no multivalued RDN by default */
2130 mval[ne_num+1] = 0;
2131 break;
2132 }
2133 else if (*sp == '+' && multirdn)
2134 {
2135 /* a not escaped + signals a mutlivalued RDN */
2136 sp++;
2137 mval[ne_num+1] = -1;
2138 break;
2139 }
2140 else
2141 *bp++ = *sp++;
2142 }
2143 *bp++ = '\0';
2144 ne_num++;
2145 }
2146
2147 if (!(n = X509_NAME_new()))
2148 goto error;
2149
2150 for (i = 0; i < ne_num; i++)
2151 {
2152 if ((nid=OBJ_txt2nid(ne_types[i])) == NID_undef)
2153 {
2154 BIO_printf(bio_err, "Subject Attribute %s has no known NID, skipped\n", ne_types[i]);
2155 continue;
2156 }
2157
2158 if (!*ne_values[i])
2159 {
2160 BIO_printf(bio_err, "No value provided for Subject Attribute %s, skipped\n", ne_types[i]);
2161 continue;
2162 }
2163
2164 if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char*)ne_values[i], -1,-1,mval[i]))
2165 goto error;
2166 }
2167
2168 OPENSSL_free(ne_values);
2169 OPENSSL_free(ne_types);
2170 OPENSSL_free(buf);
2171 return n;
2172
2173error:
2174 X509_NAME_free(n);
2175 if (ne_values)
2176 OPENSSL_free(ne_values);
2177 if (ne_types)
2178 OPENSSL_free(ne_types);
2179 if (buf)
2180 OPENSSL_free(buf);
2181 return NULL;
2182}
2183
d530017c
RL
2184/* This code MUST COME AFTER anything that uses rename() */
2185#ifdef OPENSSL_SYS_WIN32
f68854b4 2186int WIN32_rename(const char *from, const char *to)
d530017c
RL
2187 {
2188#ifndef OPENSSL_SYS_WINCE
2189 /* Windows rename gives an error if 'to' exists, so delete it
2190 * first and ignore file not found errror
2191 */
2192 if((remove(to) != 0) && (errno != ENOENT))
2193 return -1;
2194#undef rename
2195 return rename(from, to);
2196#else
2197 /* convert strings to UNICODE */
2198 {
2199 BOOL result = FALSE;
2200 WCHAR* wfrom;
2201 WCHAR* wto;
2202 int i;
2203 wfrom = malloc((strlen(from)+1)*2);
2204 wto = malloc((strlen(to)+1)*2);
2205 if (wfrom != NULL && wto != NULL)
2206 {
2207 for (i=0; i<(int)strlen(from)+1; i++)
2208 wfrom[i] = (short)from[i];
2209 for (i=0; i<(int)strlen(to)+1; i++)
2210 wto[i] = (short)to[i];
2211 result = MoveFile(wfrom, wto);
2212 }
2213 if (wfrom != NULL)
2214 free(wfrom);
2215 if (wto != NULL)
2216 free(wto);
2217 return result;
2218 }
2219#endif
2220 }
2221#endif
5d7c222d 2222
c431798e
DSH
2223int args_verify(char ***pargs, int *pargc,
2224 int *badarg, BIO *err, X509_VERIFY_PARAM **pm)
5d7c222d
DSH
2225 {
2226 ASN1_OBJECT *otmp = NULL;
2227 unsigned long flags = 0;
c431798e
DSH
2228 int i;
2229 int purpose = 0;
2230 char **oldargs = *pargs;
5d7c222d
DSH
2231 char *arg = **pargs, *argn = (*pargs)[1];
2232 if (!strcmp(arg, "-policy"))
2233 {
2234 if (!argn)
2235 *badarg = 1;
2236 else
2237 {
2238 otmp = OBJ_txt2obj(argn, 0);
2239 if (!otmp)
2240 {
2241 BIO_printf(err, "Invalid Policy \"%s\"\n",
2242 argn);
2243 *badarg = 1;
2244 }
2245 }
2246 (*pargs)++;
2247 }
c431798e
DSH
2248 else if (strcmp(arg,"-purpose") == 0)
2249 {
2250 X509_PURPOSE *xptmp;
2251 if (!argn)
2252 *badarg = 1;
2253 else
2254 {
2255 i = X509_PURPOSE_get_by_sname(argn);
2256 if(i < 0)
2257 {
2258 BIO_printf(err, "unrecognized purpose\n");
2259 *badarg = 1;
2260 }
2261 else
2262 {
2263 xptmp = X509_PURPOSE_get0(i);
2264 purpose = X509_PURPOSE_get_id(xptmp);
2265 }
2266 }
2267 (*pargs)++;
2268 }
5d7c222d
DSH
2269 else if (!strcmp(arg, "-ignore_critical"))
2270 flags |= X509_V_FLAG_IGNORE_CRITICAL;
2271 else if (!strcmp(arg, "-issuer_checks"))
2272 flags |= X509_V_FLAG_CB_ISSUER_CHECK;
2273 else if (!strcmp(arg, "-crl_check"))
2274 flags |= X509_V_FLAG_CRL_CHECK;
2275 else if (!strcmp(arg, "-crl_check_all"))
2276 flags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
2277 else if (!strcmp(arg, "-policy_check"))
2278 flags |= X509_V_FLAG_POLICY_CHECK;
2279 else if (!strcmp(arg, "-explicit_policy"))
2280 flags |= X509_V_FLAG_EXPLICIT_POLICY;
2281 else if (!strcmp(arg, "-x509_strict"))
2282 flags |= X509_V_FLAG_X509_STRICT;
2283 else if (!strcmp(arg, "-policy_print"))
2284 flags |= X509_V_FLAG_NOTIFY_POLICY;
2285 else
2286 return 0;
2287
2288 if (*badarg)
2289 {
2290 if (*pm)
2291 X509_VERIFY_PARAM_free(*pm);
2292 *pm = NULL;
c431798e 2293 goto end;
5d7c222d
DSH
2294 }
2295
2296 if (!*pm && !(*pm = X509_VERIFY_PARAM_new()))
2297 {
2298 *badarg = 1;
c431798e 2299 goto end;
5d7c222d
DSH
2300 }
2301
2302 if (otmp)
2303 X509_VERIFY_PARAM_add0_policy(*pm, otmp);
2304 if (flags)
2305 X509_VERIFY_PARAM_set_flags(*pm, flags);
2306
c431798e
DSH
2307 if (purpose)
2308 X509_VERIFY_PARAM_set_purpose(*pm, purpose);
2309
2310 end:
2311
5d7c222d
DSH
2312 (*pargs)++;
2313
c431798e
DSH
2314 if (pargc)
2315 *pargc -= *pargs - oldargs;
2316
5d7c222d
DSH
2317 return 1;
2318
2319 }
c431798e 2320
7d727231
NL
2321static void nodes_print(BIO *out, const char *name,
2322 STACK_OF(X509_POLICY_NODE) *nodes)
c431798e
DSH
2323 {
2324 X509_POLICY_NODE *node;
2325 int i;
2326 BIO_printf(out, "%s Policies:", name);
2327 if (nodes)
2328 {
2329 BIO_puts(out, "\n");
2330 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++)
2331 {
2332 node = sk_X509_POLICY_NODE_value(nodes, i);
2333 X509_POLICY_NODE_print(out, node, 2);
2334 }
2335 }
2336 else
2337 BIO_puts(out, " <empty>\n");
2338 }
2339
2340void policies_print(BIO *out, X509_STORE_CTX *ctx)
2341 {
2342 X509_POLICY_TREE *tree;
2343 int explicit_policy;
2344 int free_out = 0;
2345 if (out == NULL)
2346 {
2347 out = BIO_new_fp(stderr, BIO_NOCLOSE);
2348 free_out = 1;
2349 }
2350 tree = X509_STORE_CTX_get0_policy_tree(ctx);
2351 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2352
2353 BIO_printf(out, "Require explicit Policy: %s\n",
2354 explicit_policy ? "True" : "False");
2355
2356 nodes_print(out, "Authority", X509_policy_tree_get0_policies(tree));
2357 nodes_print(out, "User", X509_policy_tree_get0_user_policies(tree));
2358 if (free_out)
2359 BIO_free(out);
2360 }