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