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