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