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