xref: /netbsd-src/crypto/dist/ipsec-tools/src/racoon/crypto_openssl.c (revision 1ad9454efb13a65cd7535ccf867508cb14d9d30e)
1 /*	$NetBSD: crypto_openssl.c,v 1.9 2006/09/19 07:51:27 vanhu Exp $	*/
2 
3 /* Id: crypto_openssl.c,v 1.47 2006/05/06 20:42:09 manubsd Exp */
4 
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include "config.h"
35 
36 #include <sys/types.h>
37 #include <sys/param.h>
38 
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <limits.h>
42 #include <string.h>
43 
44 /* get openssl/ssleay version number */
45 #include <openssl/opensslv.h>
46 
47 #if !defined(OPENSSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x0090602fL)
48 #error OpenSSL version 0.9.6 or later required.
49 #endif
50 
51 #include <openssl/pem.h>
52 #include <openssl/evp.h>
53 #include <openssl/x509.h>
54 #include <openssl/x509v3.h>
55 #include <openssl/x509_vfy.h>
56 #include <openssl/bn.h>
57 #include <openssl/dh.h>
58 #include <openssl/md5.h>
59 #include <openssl/sha.h>
60 #include <openssl/hmac.h>
61 #include <openssl/des.h>
62 #include <openssl/crypto.h>
63 #ifdef HAVE_OPENSSL_ENGINE_H
64 #include <openssl/engine.h>
65 #endif
66 #include <openssl/blowfish.h>
67 #include <openssl/cast.h>
68 #include <openssl/err.h>
69 #ifdef HAVE_OPENSSL_RC5_H
70 #include <openssl/rc5.h>
71 #endif
72 #ifdef HAVE_OPENSSL_IDEA_H
73 #include <openssl/idea.h>
74 #endif
75 #if defined(HAVE_OPENSSL_AES_H)
76 #include <openssl/aes.h>
77 #elif defined(HAVE_OPENSSL_RIJNDAEL_H)
78 #include <openssl/rijndael.h>
79 #else
80 #include "crypto/rijndael/rijndael-api-fst.h"
81 #endif
82 #ifdef WITH_SHA2
83 #ifdef HAVE_OPENSSL_SHA2_H
84 #include <openssl/sha2.h>
85 #else
86 #include "crypto/sha2/sha2.h"
87 #endif
88 #endif
89 
90 /* 0.9.7 stuff? */
91 #if OPENSSL_VERSION_NUMBER < 0x0090700fL
92 typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES;
93 #else
94 #define USE_NEW_DES_API
95 #endif
96 
97 #define OpenSSL_BUG()	do { plog(LLV_ERROR, LOCATION, NULL, "OpenSSL function failed\n"); } while(0)
98 
99 #include "var.h"
100 #include "misc.h"
101 #include "vmbuf.h"
102 #include "plog.h"
103 #include "crypto_openssl.h"
104 #include "debug.h"
105 #include "gcmalloc.h"
106 
107 /*
108  * I hate to cast every parameter to des_xx into void *, but it is
109  * necessary for SSLeay/OpenSSL portability.  It sucks.
110  */
111 
112 static int cb_check_cert_local __P((int, X509_STORE_CTX *));
113 static int cb_check_cert_remote __P((int, X509_STORE_CTX *));
114 static X509 *mem2x509 __P((vchar_t *));
115 
116 static caddr_t eay_hmac_init __P((vchar_t *, const EVP_MD *));
117 
118 /* X509 Certificate */
119 /*
120  * convert the string of the subject name into DER
121  * e.g. str = "C=JP, ST=Kanagawa";
122  */
123 vchar_t *
124 eay_str2asn1dn(str, len)
125 	const char *str;
126 	int len;
127 {
128 	X509_NAME *name;
129 	char *buf;
130 	char *field, *value;
131 	int i, j;
132 	vchar_t *ret;
133 	caddr_t p;
134 
135 	if (len == -1)
136 		len = strlen(str);
137 
138 	buf = racoon_malloc(len + 1);
139 	if (!buf) {
140 		plog(LLV_WARNING, LOCATION, NULL,"failed to allocate buffer\n");
141 		return NULL;
142 	}
143 	memcpy(buf, str, len);
144 
145 	name = X509_NAME_new();
146 
147 	field = &buf[0];
148 	value = NULL;
149 	for (i = 0; i < len; i++) {
150 		if (!value && buf[i] == '=') {
151 			buf[i] = '\0';
152 			value = &buf[i + 1];
153 			continue;
154 		} else if (buf[i] == ',' || buf[i] == '/') {
155 			buf[i] = '\0';
156 
157 			plog(LLV_DEBUG, LOCATION, NULL, "DN: %s=%s\n",
158 			     field, value);
159 
160 			if (!value) goto err;
161 			if (!X509_NAME_add_entry_by_txt(name, field,
162 					(value[0] == '*' && value[1] == 0) ?
163 						V_ASN1_PRINTABLESTRING : MBSTRING_ASC,
164 					(unsigned char *) value, -1, -1, 0)) {
165 				plog(LLV_ERROR, LOCATION, NULL,
166 				     "Invalid DN field: %s=%s\n",
167 				     field, value);
168 				plog(LLV_ERROR, LOCATION, NULL,
169 				     "%s\n", eay_strerror());
170 				goto err;
171 			}
172 			for (j = i + 1; j < len; j++) {
173 				if (buf[j] != ' ')
174 					break;
175 			}
176 			field = &buf[j];
177 			value = NULL;
178 			continue;
179 		}
180 	}
181 	buf[len] = '\0';
182 
183 	plog(LLV_DEBUG, LOCATION, NULL, "DN: %s=%s\n",
184 	     field, value);
185 
186 	if (!value) goto err;
187 	if (!X509_NAME_add_entry_by_txt(name, field,
188 			(value[0] == '*' && value[1] == 0) ?
189 				V_ASN1_PRINTABLESTRING : MBSTRING_ASC,
190 			(unsigned char *) value, -1, -1, 0)) {
191 		plog(LLV_ERROR, LOCATION, NULL,
192 		     "Invalid DN field: %s=%s\n",
193 		     field, value);
194 		plog(LLV_ERROR, LOCATION, NULL,
195 		     "%s\n", eay_strerror());
196 		goto err;
197 	}
198 
199 	i = i2d_X509_NAME(name, NULL);
200 	if (!i)
201 		goto err;
202 	ret = vmalloc(i);
203 	if (!ret)
204 		goto err;
205 	p = ret->v;
206 	i = i2d_X509_NAME(name, (void *)&p);
207 	if (!i)
208 		goto err;
209 
210 	return ret;
211 
212     err:
213 	if (buf)
214 		racoon_free(buf);
215 	if (name)
216 		X509_NAME_free(name);
217 	return NULL;
218 }
219 
220 /*
221  * convert the hex string of the subject name into DER
222  */
223 vchar_t *
224 eay_hex2asn1dn(const char *hex, int len)
225 {
226 	BIGNUM *bn = BN_new();
227 	char *binbuf;
228 	size_t binlen;
229 	vchar_t *ret = NULL;
230 
231 	if (len == -1)
232 		len = strlen(hex);
233 
234 	if (BN_hex2bn(&bn, hex) != len) {
235 		plog(LLV_ERROR, LOCATION, NULL,
236 		     "conversion of Hex-encoded ASN1 string to binary failed: %s\n",
237 		     eay_strerror());
238 		goto out;
239 	}
240 
241 	binlen = BN_num_bytes(bn);
242 	ret = vmalloc(binlen);
243 	if (!ret) {
244 		plog(LLV_WARNING, LOCATION, NULL,"failed to allocate buffer\n");
245 		return NULL;
246 	}
247 	binbuf = ret->v;
248 
249 	BN_bn2bin(bn, (unsigned char *) binbuf);
250 
251 out:
252 	BN_free(bn);
253 
254 	return ret;
255 }
256 
257 /*
258  * The following are derived from code in crypto/x509/x509_cmp.c
259  * in OpenSSL0.9.7c:
260  * X509_NAME_wildcmp() adds wildcard matching to the original
261  * X509_NAME_cmp(), nocase_cmp() and nocase_spacenorm_cmp() are as is.
262  */
263 #include <ctype.h>
264 /* Case insensitive string comparision */
265 static int nocase_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
266 {
267 	int i;
268 
269 	if (a->length != b->length)
270 		return (a->length - b->length);
271 
272 	for (i=0; i<a->length; i++)
273 	{
274 		int ca, cb;
275 
276 		ca = tolower(a->data[i]);
277 		cb = tolower(b->data[i]);
278 
279 		if (ca != cb)
280 			return(ca-cb);
281 	}
282 	return 0;
283 }
284 
285 /* Case insensitive string comparision with space normalization
286  * Space normalization - ignore leading, trailing spaces,
287  *       multiple spaces between characters are replaced by single space
288  */
289 static int nocase_spacenorm_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
290 {
291 	unsigned char *pa = NULL, *pb = NULL;
292 	int la, lb;
293 
294 	la = a->length;
295 	lb = b->length;
296 	pa = a->data;
297 	pb = b->data;
298 
299 	/* skip leading spaces */
300 	while (la > 0 && isspace(*pa))
301 	{
302 		la--;
303 		pa++;
304 	}
305 	while (lb > 0 && isspace(*pb))
306 	{
307 		lb--;
308 		pb++;
309 	}
310 
311 	/* skip trailing spaces */
312 	while (la > 0 && isspace(pa[la-1]))
313 		la--;
314 	while (lb > 0 && isspace(pb[lb-1]))
315 		lb--;
316 
317 	/* compare strings with space normalization */
318 	while (la > 0 && lb > 0)
319 	{
320 		int ca, cb;
321 
322 		/* compare character */
323 		ca = tolower(*pa);
324 		cb = tolower(*pb);
325 		if (ca != cb)
326 			return (ca - cb);
327 
328 		pa++; pb++;
329 		la--; lb--;
330 
331 		if (la <= 0 || lb <= 0)
332 			break;
333 
334 		/* is white space next character ? */
335 		if (isspace(*pa) && isspace(*pb))
336 		{
337 			/* skip remaining white spaces */
338 			while (la > 0 && isspace(*pa))
339 			{
340 				la--;
341 				pa++;
342 			}
343 			while (lb > 0 && isspace(*pb))
344 			{
345 				lb--;
346 				pb++;
347 			}
348 		}
349 	}
350 	if (la > 0 || lb > 0)
351 		return la - lb;
352 
353 	return 0;
354 }
355 
356 static int X509_NAME_wildcmp(const X509_NAME *a, const X509_NAME *b)
357 {
358     int i,j;
359     X509_NAME_ENTRY *na,*nb;
360 
361     if (sk_X509_NAME_ENTRY_num(a->entries)
362 	!= sk_X509_NAME_ENTRY_num(b->entries))
363 	    return sk_X509_NAME_ENTRY_num(a->entries)
364 	      -sk_X509_NAME_ENTRY_num(b->entries);
365     for (i=sk_X509_NAME_ENTRY_num(a->entries)-1; i>=0; i--)
366     {
367 	    na=sk_X509_NAME_ENTRY_value(a->entries,i);
368 	    nb=sk_X509_NAME_ENTRY_value(b->entries,i);
369 	    j=OBJ_cmp(na->object,nb->object);
370 	    if (j) return(j);
371 	    if ((na->value->length == 1 && na->value->data[0] == '*')
372 	     || (nb->value->length == 1 && nb->value->data[0] == '*'))
373 		    continue;
374 	    j=na->value->type-nb->value->type;
375 	    if (j) return(j);
376 	    if (na->value->type == V_ASN1_PRINTABLESTRING)
377 		    j=nocase_spacenorm_cmp(na->value, nb->value);
378 	    else if (na->value->type == V_ASN1_IA5STRING
379 		    && OBJ_obj2nid(na->object) == NID_pkcs9_emailAddress)
380 		    j=nocase_cmp(na->value, nb->value);
381 	    else
382 		    {
383 		    j=na->value->length-nb->value->length;
384 		    if (j) return(j);
385 		    j=memcmp(na->value->data,nb->value->data,
386 			    na->value->length);
387 		    }
388 	    if (j) return(j);
389 	    j=na->set-nb->set;
390 	    if (j) return(j);
391     }
392 
393     return(0);
394 }
395 
396 /*
397  * compare two subjectNames.
398  * OUT:        0: equal
399  *	positive:
400  *	      -1: other error.
401  */
402 int
403 eay_cmp_asn1dn(n1, n2)
404 	vchar_t *n1, *n2;
405 {
406 	X509_NAME *a = NULL, *b = NULL;
407 	caddr_t p;
408 	int i = -1;
409 
410 	p = n1->v;
411 	if (!d2i_X509_NAME(&a, (void *)&p, n1->l))
412 		goto end;
413 	p = n2->v;
414 	if (!d2i_X509_NAME(&b, (void *)&p, n2->l))
415 		goto end;
416 
417 	i = X509_NAME_wildcmp(a, b);
418 
419     end:
420 	if (a)
421 		X509_NAME_free(a);
422 	if (b)
423 		X509_NAME_free(b);
424 	return i;
425 }
426 
427 /*
428  * this functions is derived from apps/verify.c in OpenSSL0.9.5
429  */
430 int
431 eay_check_x509cert(cert, CApath, CAfile, local)
432 	vchar_t *cert;
433 	char *CApath;
434 	char *CAfile;
435 	int local;
436 {
437 	X509_STORE *cert_ctx = NULL;
438 	X509_LOOKUP *lookup = NULL;
439 	X509 *x509 = NULL;
440 	X509_STORE_CTX *csc;
441 	int error = -1;
442 
443 	cert_ctx = X509_STORE_new();
444 	if (cert_ctx == NULL)
445 		goto end;
446 
447 	if (local)
448 		X509_STORE_set_verify_cb_func(cert_ctx, cb_check_cert_local);
449 	else
450 		X509_STORE_set_verify_cb_func(cert_ctx, cb_check_cert_remote);
451 
452 	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
453 	if (lookup == NULL)
454 		goto end;
455 
456 	X509_LOOKUP_load_file(lookup, CAfile,
457 	    (CAfile == NULL) ? X509_FILETYPE_DEFAULT : X509_FILETYPE_PEM);
458 
459 	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
460 	if (lookup == NULL)
461 		goto end;
462 	error = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
463 	if(!error) {
464 		error = -1;
465 		goto end;
466 	}
467 	error = -1;	/* initialized */
468 
469 	/* read the certificate to be verified */
470 	x509 = mem2x509(cert);
471 	if (x509 == NULL)
472 		goto end;
473 
474 	csc = X509_STORE_CTX_new();
475 	if (csc == NULL)
476 		goto end;
477 	X509_STORE_CTX_init(csc, cert_ctx, x509, NULL);
478 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
479 	X509_STORE_CTX_set_flags (csc, X509_V_FLAG_CRL_CHECK);
480 	X509_STORE_CTX_set_flags (csc, X509_V_FLAG_CRL_CHECK_ALL);
481 #endif
482 	error = X509_verify_cert(csc);
483 	X509_STORE_CTX_cleanup(csc);
484 
485 	/*
486 	 * if x509_verify_cert() is successful then the value of error is
487 	 * set non-zero.
488 	 */
489 	error = error ? 0 : -1;
490 
491 end:
492 	if (error)
493 		plog(LLV_WARNING, LOCATION, NULL,"%s\n", eay_strerror());
494 	if (cert_ctx != NULL)
495 		X509_STORE_free(cert_ctx);
496 	if (x509 != NULL)
497 		X509_free(x509);
498 
499 	return(error);
500 }
501 
502 /*
503  * callback function for verifing certificate.
504  * this function is derived from cb() in openssl/apps/s_server.c
505  */
506 static int
507 cb_check_cert_local(ok, ctx)
508 	int ok;
509 	X509_STORE_CTX *ctx;
510 {
511 	char buf[256];
512 	int log_tag;
513 
514 	if (!ok) {
515 		X509_NAME_oneline(
516 				X509_get_subject_name(ctx->current_cert),
517 				buf,
518 				256);
519 		/*
520 		 * since we are just checking the certificates, it is
521 		 * ok if they are self signed. But we should still warn
522 		 * the user.
523  		 */
524 		switch (ctx->error) {
525 		case X509_V_ERR_CERT_HAS_EXPIRED:
526 		case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
527 		case X509_V_ERR_INVALID_CA:
528 		case X509_V_ERR_PATH_LENGTH_EXCEEDED:
529 		case X509_V_ERR_INVALID_PURPOSE:
530 		case X509_V_ERR_UNABLE_TO_GET_CRL:
531 			ok = 1;
532 			log_tag = LLV_WARNING;
533 			break;
534 		default:
535 			log_tag = LLV_ERROR;
536 		}
537 		plog(log_tag, LOCATION, NULL,
538 			"%s(%d) at depth:%d SubjectName:%s\n",
539 			X509_verify_cert_error_string(ctx->error),
540 			ctx->error,
541 			ctx->error_depth,
542 			buf);
543 	}
544 	ERR_clear_error();
545 
546 	return ok;
547 }
548 
549 /*
550  * callback function for verifing remote certificates.
551  * this function is derived from cb() in openssl/apps/s_server.c
552  */
553 static int
554 cb_check_cert_remote(ok, ctx)
555 	int ok;
556 	X509_STORE_CTX *ctx;
557 {
558 	char buf[256];
559 	int log_tag;
560 
561 	if (!ok) {
562 		X509_NAME_oneline(
563 				X509_get_subject_name(ctx->current_cert),
564 				buf,
565 				256);
566 		switch (ctx->error) {
567 		case X509_V_ERR_UNABLE_TO_GET_CRL:
568 			ok = 1;
569 			log_tag = LLV_WARNING;
570 			break;
571 		default:
572 			log_tag = LLV_ERROR;
573 		}
574 		plog(log_tag, LOCATION, NULL,
575 			"%s(%d) at depth:%d SubjectName:%s\n",
576 			X509_verify_cert_error_string(ctx->error),
577 			ctx->error,
578 			ctx->error_depth,
579 			buf);
580 	}
581 	ERR_clear_error();
582 
583 	return ok;
584 }
585 
586 /*
587  * get a subjectAltName from X509 certificate.
588  */
589 vchar_t *
590 eay_get_x509asn1subjectname(cert)
591 	vchar_t *cert;
592 {
593 	X509 *x509 = NULL;
594 	u_char *bp;
595 	vchar_t *name = NULL;
596 	int len;
597 
598 	bp = (unsigned char *) cert->v;
599 
600 	x509 = mem2x509(cert);
601 	if (x509 == NULL)
602 		goto error;
603 
604 	/* get the length of the name */
605 	len = i2d_X509_NAME(x509->cert_info->subject, NULL);
606 	name = vmalloc(len);
607 	if (!name)
608 		goto error;
609 	/* get the name */
610 	bp = (unsigned char *) name->v;
611 	len = i2d_X509_NAME(x509->cert_info->subject, &bp);
612 
613 	X509_free(x509);
614 
615 	return name;
616 
617 error:
618 	plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
619 
620 	if (name != NULL)
621 		vfree(name);
622 
623 	if (x509 != NULL)
624 		X509_free(x509);
625 
626 	return NULL;
627 }
628 
629 /*
630  * get the subjectAltName from X509 certificate.
631  * the name must be terminated by '\0'.
632  */
633 int
634 eay_get_x509subjectaltname(cert, altname, type, pos)
635 	vchar_t *cert;
636 	char **altname;
637 	int *type;
638 	int pos;
639 {
640 	X509 *x509 = NULL;
641 	GENERAL_NAMES *gens = NULL;
642 	GENERAL_NAME *gen;
643 	int len;
644 	int error = -1;
645 
646 	*altname = NULL;
647 	*type = GENT_OTHERNAME;
648 
649 	x509 = mem2x509(cert);
650 	if (x509 == NULL)
651 		goto end;
652 
653 	gens = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL);
654 	if (gens == NULL)
655 		goto end;
656 
657 	/* there is no data at "pos" */
658 	if (pos > sk_GENERAL_NAME_num(gens))
659 		goto end;
660 
661 	gen = sk_GENERAL_NAME_value(gens, pos - 1);
662 
663 	/* read DNSName / Email */
664 	if (gen->type == GEN_DNS	||
665 		gen->type == GEN_EMAIL	||
666 		gen->type == GEN_URI )
667 	{
668 		/* make sure if the data is terminated by '\0'. */
669 		if (gen->d.ia5->data[gen->d.ia5->length] != '\0')
670 		{
671 			plog(LLV_ERROR, LOCATION, NULL,
672 				 "data is not terminated by NUL.");
673 			hexdump(gen->d.ia5->data, gen->d.ia5->length + 1);
674 			goto end;
675 		}
676 
677 		len = gen->d.ia5->length + 1;
678 		*altname = racoon_malloc(len);
679 		if (!*altname)
680 			goto end;
681 
682 		strlcpy(*altname, (char *) gen->d.ia5->data, len);
683 		*type = gen->type;
684 		error = 0;
685 	}
686 	/* read IP address */
687 	else if (gen->type == GEN_IPADD)
688 	{
689 		unsigned char p[5], *ip;
690 		ip = p;
691 
692 		/* only support IPv4 */
693 		if (gen->d.ip->length != 4)
694 			goto end;
695 
696 		/* convert Octet String to String
697 		 * XXX ???????
698 		 */
699 		/*i2d_ASN1_OCTET_STRING(gen->d.ip,&ip);*/
700 		ip = gen->d.ip->data;
701 
702 		/* XXX Magic, enough for an IPv4 address
703 		 */
704 		*altname = racoon_malloc(20);
705 		if (!*altname)
706 			goto end;
707 
708 		sprintf(*altname, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
709 		*type = gen->type;
710 		error = 0;
711 	}
712 	/* XXX other possible types ?
713 	 * For now, error will be -1 if unsupported type
714 	 */
715 
716 end:
717 	if (error) {
718 		if (*altname) {
719 			racoon_free(*altname);
720 			*altname = NULL;
721 		}
722 		plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
723 	}
724 	if (x509)
725 		X509_free(x509);
726 	if (gens)
727 		/* free the whole stack. */
728 		sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
729 
730 	return error;
731 }
732 
733 
734 /*
735  * decode a X509 certificate and make a readable text terminated '\n'.
736  * return the buffer allocated, so must free it later.
737  */
738 char *
739 eay_get_x509text(cert)
740 	vchar_t *cert;
741 {
742 	X509 *x509 = NULL;
743 	BIO *bio = NULL;
744 	char *text = NULL;
745 	u_char *bp = NULL;
746 	int len = 0;
747 	int error = -1;
748 
749 	x509 = mem2x509(cert);
750 	if (x509 == NULL)
751 		goto end;
752 
753 	bio = BIO_new(BIO_s_mem());
754 	if (bio == NULL)
755 		goto end;
756 
757 	error = X509_print(bio, x509);
758 	if (error != 1) {
759 		error = -1;
760 		goto end;
761 	}
762 
763 	len = BIO_get_mem_data(bio, &bp);
764 	text = racoon_malloc(len + 1);
765 	if (text == NULL)
766 		goto end;
767 	memcpy(text, bp, len);
768 	text[len] = '\0';
769 
770 	error = 0;
771 
772     end:
773 	if (error) {
774 		if (text) {
775 			racoon_free(text);
776 			text = NULL;
777 		}
778 		plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
779 	}
780 	if (bio)
781 		BIO_free(bio);
782 	if (x509)
783 		X509_free(x509);
784 
785 	return text;
786 }
787 
788 /* get X509 structure from buffer. */
789 static X509 *
790 mem2x509(cert)
791 	vchar_t *cert;
792 {
793 	X509 *x509;
794 
795 #ifndef EAYDEBUG
796     {
797 	u_char *bp;
798 
799 	bp = (unsigned char *) cert->v;
800 
801 	x509 = d2i_X509(NULL, (void *)&bp, cert->l);
802     }
803 #else
804     {
805 	BIO *bio;
806 	int len;
807 
808 	bio = BIO_new(BIO_s_mem());
809 	if (bio == NULL)
810 		return NULL;
811 	len = BIO_write(bio, cert->v, cert->l);
812 	if (len == -1)
813 		return NULL;
814 	x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
815 	BIO_free(bio);
816     }
817 #endif
818 	return x509;
819 }
820 
821 /*
822  * get a X509 certificate from local file.
823  * a certificate must be PEM format.
824  * Input:
825  *	path to a certificate.
826  * Output:
827  *	NULL if error occured
828  *	other is the cert.
829  */
830 vchar_t *
831 eay_get_x509cert(path)
832 	char *path;
833 {
834 	FILE *fp;
835 	X509 *x509;
836 	vchar_t *cert;
837 	u_char *bp;
838 	int len;
839 	int error;
840 
841 	/* Read private key */
842 	fp = fopen(path, "r");
843 	if (fp == NULL)
844 		return NULL;
845 	x509 = PEM_read_X509(fp, NULL, NULL, NULL);
846 	fclose (fp);
847 
848 	if (x509 == NULL)
849 		return NULL;
850 
851 	len = i2d_X509(x509, NULL);
852 	cert = vmalloc(len);
853 	if (cert == NULL) {
854 		X509_free(x509);
855 		return NULL;
856 	}
857 	bp = (unsigned char *) cert->v;
858 	error = i2d_X509(x509, &bp);
859 	X509_free(x509);
860 
861 	if (error == 0) {
862 		vfree(cert);
863 		return NULL;
864 	}
865 
866 	return cert;
867 }
868 
869 /*
870  * check a X509 signature
871  *	XXX: to be get hash type from my cert ?
872  *		to be handled EVP_dss().
873  * OUT: return -1 when error.
874  *	0
875  */
876 int
877 eay_check_x509sign(source, sig, cert)
878 	vchar_t *source;
879 	vchar_t *sig;
880 	vchar_t *cert;
881 {
882 	X509 *x509;
883 	u_char *bp;
884 	EVP_PKEY *evp;
885 	int res;
886 
887 	bp = (unsigned char *) cert->v;
888 
889 	x509 = d2i_X509(NULL, (void *)&bp, cert->l);
890 	if (x509 == NULL) {
891 		plog(LLV_ERROR, LOCATION, NULL, "d2i_X509(): %s\n", eay_strerror());
892 		return -1;
893 	}
894 
895 	evp = X509_get_pubkey(x509);
896 	if (! evp) {
897 		plog(LLV_ERROR, LOCATION, NULL, "X509_get_pubkey(): %s\n", eay_strerror());
898 		return -1;
899 	}
900 
901 	res = eay_rsa_verify(source, sig, evp->pkey.rsa);
902 
903 	EVP_PKEY_free(evp);
904 
905 	return res;
906 }
907 
908 /*
909  * check RSA signature
910  * OUT: return -1 when error.
911  *	0 on success
912  */
913 int
914 eay_check_rsasign(source, sig, rsa)
915 	vchar_t *source;
916 	vchar_t *sig;
917 	RSA *rsa;
918 {
919 	return eay_rsa_verify(source, sig, rsa);
920 }
921 
922 /*
923  * get PKCS#1 Private Key of PEM format from local file.
924  */
925 vchar_t *
926 eay_get_pkcs1privkey(path)
927 	char *path;
928 {
929 	FILE *fp;
930 	EVP_PKEY *evp = NULL;
931 	vchar_t *pkey = NULL;
932 	u_char *bp;
933 	int pkeylen;
934 	int error = -1;
935 
936 	/* Read private key */
937 	fp = fopen(path, "r");
938 	if (fp == NULL)
939 		return NULL;
940 
941 	evp = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
942 
943 	fclose (fp);
944 
945 	if (evp == NULL)
946 		return NULL;
947 
948 	pkeylen = i2d_PrivateKey(evp, NULL);
949 	if (pkeylen == 0)
950 		goto end;
951 	pkey = vmalloc(pkeylen);
952 	if (pkey == NULL)
953 		goto end;
954 	bp = (unsigned char *) pkey->v;
955 	pkeylen = i2d_PrivateKey(evp, &bp);
956 	if (pkeylen == 0)
957 		goto end;
958 
959 	error = 0;
960 
961 end:
962 	if (evp != NULL)
963 		EVP_PKEY_free(evp);
964 	if (error != 0 && pkey != NULL) {
965 		vfree(pkey);
966 		pkey = NULL;
967 	}
968 
969 	return pkey;
970 }
971 
972 /*
973  * get PKCS#1 Public Key of PEM format from local file.
974  */
975 vchar_t *
976 eay_get_pkcs1pubkey(path)
977 	char *path;
978 {
979 	FILE *fp;
980 	EVP_PKEY *evp = NULL;
981 	vchar_t *pkey = NULL;
982 	X509 *x509 = NULL;
983 	u_char *bp;
984 	int pkeylen;
985 	int error = -1;
986 
987 	/* Read private key */
988 	fp = fopen(path, "r");
989 	if (fp == NULL)
990 		return NULL;
991 
992 	x509 = PEM_read_X509(fp, NULL, NULL, NULL);
993 
994 	fclose (fp);
995 
996 	if (x509 == NULL)
997 		return NULL;
998 
999 	/* Get public key - eay */
1000 	evp = X509_get_pubkey(x509);
1001 	if (evp == NULL)
1002 		return NULL;
1003 
1004 	pkeylen = i2d_PublicKey(evp, NULL);
1005 	if (pkeylen == 0)
1006 		goto end;
1007 	pkey = vmalloc(pkeylen);
1008 	if (pkey == NULL)
1009 		goto end;
1010 	bp = (unsigned char *) pkey->v;
1011 	pkeylen = i2d_PublicKey(evp, &bp);
1012 	if (pkeylen == 0)
1013 		goto end;
1014 
1015 	error = 0;
1016 end:
1017 	if (evp != NULL)
1018 		EVP_PKEY_free(evp);
1019 	if (error != 0 && pkey != NULL) {
1020 		vfree(pkey);
1021 		pkey = NULL;
1022 	}
1023 
1024 	return pkey;
1025 }
1026 
1027 vchar_t *
1028 eay_get_x509sign(src, privkey)
1029 	vchar_t *src, *privkey;
1030 {
1031 	EVP_PKEY *evp;
1032 	u_char *bp = (unsigned char *) privkey->v;
1033 	vchar_t *sig = NULL;
1034 	int len;
1035 	int pad = RSA_PKCS1_PADDING;
1036 
1037 	/* XXX to be handled EVP_PKEY_DSA */
1038 	evp = d2i_PrivateKey(EVP_PKEY_RSA, NULL, (void *)&bp, privkey->l);
1039 	if (evp == NULL)
1040 		return NULL;
1041 
1042 	sig = eay_rsa_sign(src, evp->pkey.rsa);
1043 
1044 	EVP_PKEY_free(evp);
1045 
1046 	return sig;
1047 }
1048 
1049 vchar_t *
1050 eay_get_rsasign(src, rsa)
1051 	vchar_t *src;
1052 	RSA *rsa;
1053 {
1054 	return eay_rsa_sign(src, rsa);
1055 }
1056 
1057 vchar_t *
1058 eay_rsa_sign(vchar_t *src, RSA *rsa)
1059 {
1060 	int len;
1061 	vchar_t *sig = NULL;
1062 	int pad = RSA_PKCS1_PADDING;
1063 
1064 	len = RSA_size(rsa);
1065 
1066 	sig = vmalloc(len);
1067 	if (sig == NULL)
1068 		return NULL;
1069 
1070 	len = RSA_private_encrypt(src->l, (unsigned char *) src->v,
1071 			(unsigned char *) sig->v, rsa, pad);
1072 
1073 	if (len == 0 || len != sig->l) {
1074 		vfree(sig);
1075 		sig = NULL;
1076 	}
1077 
1078 	return sig;
1079 }
1080 
1081 int
1082 eay_rsa_verify(src, sig, rsa)
1083 	vchar_t *src, *sig;
1084 	RSA *rsa;
1085 {
1086 	vchar_t *xbuf = NULL;
1087 	int pad = RSA_PKCS1_PADDING;
1088 	int len = 0;
1089 	int error;
1090 
1091 	len = RSA_size(rsa);
1092 	xbuf = vmalloc(len);
1093 	if (xbuf == NULL) {
1094 		plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
1095 		return -1;
1096 	}
1097 
1098 	len = RSA_public_decrypt(sig->l, (unsigned char *) sig->v,
1099 			(unsigned char *) xbuf->v, rsa, pad);
1100 	if (len == 0 || len != src->l) {
1101 		plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
1102 		vfree(xbuf);
1103 		return -1;
1104 	}
1105 
1106 	error = memcmp(src->v, xbuf->v, src->l);
1107 	vfree(xbuf);
1108 	if (error != 0)
1109 		return -1;
1110 
1111 	return 0;
1112 }
1113 
1114 /*
1115  * get error string
1116  * MUST load ERR_load_crypto_strings() first.
1117  */
1118 char *
1119 eay_strerror()
1120 {
1121 	static char ebuf[512];
1122 	int len = 0, n;
1123 	unsigned long l;
1124 	char buf[200];
1125 	const char *file, *data;
1126 	int line, flags;
1127 	unsigned long es;
1128 
1129 	es = CRYPTO_thread_id();
1130 
1131 	while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0){
1132 		n = snprintf(ebuf + len, sizeof(ebuf) - len,
1133 				"%lu:%s:%s:%d:%s ",
1134 				es, ERR_error_string(l, buf), file, line,
1135 				(flags & ERR_TXT_STRING) ? data : "");
1136 		if (n < 0 || n >= sizeof(ebuf) - len)
1137 			break;
1138 		len += n;
1139 		if (sizeof(ebuf) < len)
1140 			break;
1141 	}
1142 
1143 	return ebuf;
1144 }
1145 
1146 vchar_t *
1147 evp_crypt(vchar_t *data, vchar_t *key, vchar_t *iv, const EVP_CIPHER *e, int enc)
1148 {
1149 	vchar_t *res;
1150 	EVP_CIPHER_CTX ctx;
1151 
1152 	if (!e)
1153 		return NULL;
1154 
1155 	if (data->l % EVP_CIPHER_block_size(e))
1156 		return NULL;
1157 
1158 	if ((res = vmalloc(data->l)) == NULL)
1159 		return NULL;
1160 
1161 	EVP_CIPHER_CTX_init(&ctx);
1162 
1163 	switch(EVP_CIPHER_nid(e)){
1164 	case NID_bf_cbc:
1165 	case NID_bf_ecb:
1166 	case NID_bf_cfb64:
1167 	case NID_bf_ofb64:
1168 	case NID_cast5_cbc:
1169 	case NID_cast5_ecb:
1170 	case NID_cast5_cfb64:
1171 	case NID_cast5_ofb64:
1172 		/* XXX: can we do that also for algos with a fixed key size ?
1173 		 */
1174 		/* init context without key/iv
1175          */
1176         if (!EVP_CipherInit(&ctx, e, NULL, NULL, enc))
1177         {
1178             OpenSSL_BUG();
1179             vfree(res);
1180             return NULL;
1181         }
1182 
1183         /* update key size
1184          */
1185         if (!EVP_CIPHER_CTX_set_key_length(&ctx, key->l))
1186         {
1187             OpenSSL_BUG();
1188             vfree(res);
1189             return NULL;
1190         }
1191 
1192         /* finalize context init with desired key size
1193          */
1194         if (!EVP_CipherInit(&ctx, NULL, (u_char *) key->v,
1195 							(u_char *) iv->v, enc))
1196         {
1197             OpenSSL_BUG();
1198             vfree(res);
1199             return NULL;
1200 		}
1201 		break;
1202 	default:
1203 		if (!EVP_CipherInit(&ctx, e, (u_char *) key->v,
1204 							(u_char *) iv->v, enc)) {
1205 			OpenSSL_BUG();
1206 			vfree(res);
1207 			return NULL;
1208 		}
1209 	}
1210 
1211 	/* disable openssl padding */
1212 	EVP_CIPHER_CTX_set_padding(&ctx, 0);
1213 
1214 	if (!EVP_Cipher(&ctx, (u_char *) res->v, (u_char *) data->v, data->l)) {
1215 		OpenSSL_BUG();
1216 		vfree(res);
1217 		return NULL;
1218 	}
1219 
1220 	EVP_CIPHER_CTX_cleanup(&ctx);
1221 
1222 	return res;
1223 }
1224 
1225 int
1226 evp_weakkey(vchar_t *key, const EVP_CIPHER *e)
1227 {
1228 	return 0;
1229 }
1230 
1231 int
1232 evp_keylen(int len, const EVP_CIPHER *e)
1233 {
1234 	if (!e)
1235 		return -1;
1236 	/* EVP functions return lengths in bytes, ipsec-tools
1237 	 * uses lengths in bits, therefore conversion is required. --AK
1238 	 */
1239 	if (len != 0 && len != (EVP_CIPHER_key_length(e) << 3))
1240 		return -1;
1241 
1242 	return EVP_CIPHER_key_length(e) << 3;
1243 }
1244 
1245 /*
1246  * DES-CBC
1247  */
1248 vchar_t *
1249 eay_des_encrypt(data, key, iv)
1250 	vchar_t *data, *key, *iv;
1251 {
1252 	return evp_crypt(data, key, iv, EVP_des_cbc(), 1);
1253 }
1254 
1255 vchar_t *
1256 eay_des_decrypt(data, key, iv)
1257 	vchar_t *data, *key, *iv;
1258 {
1259 	return evp_crypt(data, key, iv, EVP_des_cbc(), 0);
1260 }
1261 
1262 int
1263 eay_des_weakkey(key)
1264 	vchar_t *key;
1265 {
1266 #ifdef USE_NEW_DES_API
1267 	return DES_is_weak_key((void *)key->v);
1268 #else
1269 	return des_is_weak_key((void *)key->v);
1270 #endif
1271 }
1272 
1273 int
1274 eay_des_keylen(len)
1275 	int len;
1276 {
1277 	return evp_keylen(len, EVP_des_cbc());
1278 }
1279 
1280 #ifdef HAVE_OPENSSL_IDEA_H
1281 /*
1282  * IDEA-CBC
1283  */
1284 vchar_t *
1285 eay_idea_encrypt(data, key, iv)
1286 	vchar_t *data, *key, *iv;
1287 {
1288 	vchar_t *res;
1289 	IDEA_KEY_SCHEDULE ks;
1290 
1291 	idea_set_encrypt_key(key->v, &ks);
1292 
1293 	/* allocate buffer for result */
1294 	if ((res = vmalloc(data->l)) == NULL)
1295 		return NULL;
1296 
1297 	/* decryption data */
1298 	idea_cbc_encrypt(data->v, res->v, data->l,
1299 			&ks, iv->v, IDEA_ENCRYPT);
1300 
1301 	return res;
1302 }
1303 
1304 vchar_t *
1305 eay_idea_decrypt(data, key, iv)
1306 	vchar_t *data, *key, *iv;
1307 {
1308 	vchar_t *res;
1309 	IDEA_KEY_SCHEDULE ks, dks;
1310 
1311 	idea_set_encrypt_key(key->v, &ks);
1312 	idea_set_decrypt_key(&ks, &dks);
1313 
1314 	/* allocate buffer for result */
1315 	if ((res = vmalloc(data->l)) == NULL)
1316 		return NULL;
1317 
1318 	/* decryption data */
1319 	idea_cbc_encrypt(data->v, res->v, data->l,
1320 			&dks, iv->v, IDEA_DECRYPT);
1321 
1322 	return res;
1323 }
1324 
1325 int
1326 eay_idea_weakkey(key)
1327 	vchar_t *key;
1328 {
1329 	return 0;       /* XXX */
1330 }
1331 
1332 int
1333 eay_idea_keylen(len)
1334 	int len;
1335 {
1336 	if (len != 0 && len != 128)
1337 		return -1;
1338 	return 128;
1339 }
1340 #endif
1341 
1342 /*
1343  * BLOWFISH-CBC
1344  */
1345 vchar_t *
1346 eay_bf_encrypt(data, key, iv)
1347 	vchar_t *data, *key, *iv;
1348 {
1349 	return evp_crypt(data, key, iv, EVP_bf_cbc(), 1);
1350 }
1351 
1352 vchar_t *
1353 eay_bf_decrypt(data, key, iv)
1354 	vchar_t *data, *key, *iv;
1355 {
1356 	return evp_crypt(data, key, iv, EVP_bf_cbc(), 0);
1357 }
1358 
1359 int
1360 eay_bf_weakkey(key)
1361 	vchar_t *key;
1362 {
1363 	return 0;	/* XXX to be done. refer to RFC 2451 */
1364 }
1365 
1366 int
1367 eay_bf_keylen(len)
1368 	int len;
1369 {
1370 	if (len == 0)
1371 		return 448;
1372 	if (len < 40 || len > 448)
1373 		return -1;
1374 	return len;
1375 }
1376 
1377 #ifdef HAVE_OPENSSL_RC5_H
1378 /*
1379  * RC5-CBC
1380  */
1381 vchar_t *
1382 eay_rc5_encrypt(data, key, iv)
1383 	vchar_t *data, *key, *iv;
1384 {
1385 	vchar_t *res;
1386 	RC5_32_KEY ks;
1387 
1388 	/* in RFC 2451, there is information about the number of round. */
1389 	RC5_32_set_key(&ks, key->l, key->v, 16);
1390 
1391 	/* allocate buffer for result */
1392 	if ((res = vmalloc(data->l)) == NULL)
1393 		return NULL;
1394 
1395 	/* decryption data */
1396 	RC5_32_cbc_encrypt(data->v, res->v, data->l,
1397 		&ks, iv->v, RC5_ENCRYPT);
1398 
1399 	return res;
1400 }
1401 
1402 vchar_t *
1403 eay_rc5_decrypt(data, key, iv)
1404 	vchar_t *data, *key, *iv;
1405 {
1406 	vchar_t *res;
1407 	RC5_32_KEY ks;
1408 
1409 	/* in RFC 2451, there is information about the number of round. */
1410 	RC5_32_set_key(&ks, key->l, key->v, 16);
1411 
1412 	/* allocate buffer for result */
1413 	if ((res = vmalloc(data->l)) == NULL)
1414 		return NULL;
1415 
1416 	/* decryption data */
1417 	RC5_32_cbc_encrypt(data->v, res->v, data->l,
1418 		&ks, iv->v, RC5_DECRYPT);
1419 
1420 	return res;
1421 }
1422 
1423 int
1424 eay_rc5_weakkey(key)
1425 	vchar_t *key;
1426 {
1427 	return 0;       /* No known weak keys when used with 16 rounds. */
1428 
1429 }
1430 
1431 int
1432 eay_rc5_keylen(len)
1433 	int len;
1434 {
1435 	if (len == 0)
1436 		return 128;
1437 	if (len < 40 || len > 2040)
1438 		return -1;
1439 	return len;
1440 }
1441 #endif
1442 
1443 /*
1444  * 3DES-CBC
1445  */
1446 vchar_t *
1447 eay_3des_encrypt(data, key, iv)
1448 	vchar_t *data, *key, *iv;
1449 {
1450 	return evp_crypt(data, key, iv, EVP_des_ede3_cbc(), 1);
1451 }
1452 
1453 vchar_t *
1454 eay_3des_decrypt(data, key, iv)
1455 	vchar_t *data, *key, *iv;
1456 {
1457 	return evp_crypt(data, key, iv, EVP_des_ede3_cbc(), 0);
1458 }
1459 
1460 int
1461 eay_3des_weakkey(key)
1462 	vchar_t *key;
1463 {
1464 #ifdef USE_NEW_DES_API
1465 	return (DES_is_weak_key((void *)key->v) ||
1466 	    DES_is_weak_key((void *)(key->v + 8)) ||
1467 	    DES_is_weak_key((void *)(key->v + 16)));
1468 #else
1469 	if (key->l < 24)
1470 		return 0;
1471 
1472 	return (des_is_weak_key((void *)key->v) ||
1473 	    des_is_weak_key((void *)(key->v + 8)) ||
1474 	    des_is_weak_key((void *)(key->v + 16)));
1475 #endif
1476 }
1477 
1478 int
1479 eay_3des_keylen(len)
1480 	int len;
1481 {
1482 	if (len != 0 && len != 192)
1483 		return -1;
1484 	return 192;
1485 }
1486 
1487 /*
1488  * CAST-CBC
1489  */
1490 vchar_t *
1491 eay_cast_encrypt(data, key, iv)
1492 	vchar_t *data, *key, *iv;
1493 {
1494 	return evp_crypt(data, key, iv, EVP_cast5_cbc(), 1);
1495 }
1496 
1497 vchar_t *
1498 eay_cast_decrypt(data, key, iv)
1499 	vchar_t *data, *key, *iv;
1500 {
1501 	return evp_crypt(data, key, iv, EVP_cast5_cbc(), 0);
1502 }
1503 
1504 int
1505 eay_cast_weakkey(key)
1506 	vchar_t *key;
1507 {
1508 	return 0;	/* No known weak keys. */
1509 }
1510 
1511 int
1512 eay_cast_keylen(len)
1513 	int len;
1514 {
1515 	if (len == 0)
1516 		return 128;
1517 	if (len < 40 || len > 128)
1518 		return -1;
1519 	return len;
1520 }
1521 
1522 /*
1523  * AES(RIJNDAEL)-CBC
1524  */
1525 #ifndef HAVE_OPENSSL_AES_H
1526 vchar_t *
1527 eay_aes_encrypt(data, key, iv)
1528 	vchar_t *data, *key, *iv;
1529 {
1530 	vchar_t *res;
1531 	keyInstance k;
1532 	cipherInstance c;
1533 
1534 	memset(&k, 0, sizeof(k));
1535 	if (rijndael_makeKey(&k, DIR_ENCRYPT, key->l << 3, key->v) < 0)
1536 		return NULL;
1537 
1538 	/* allocate buffer for result */
1539 	if ((res = vmalloc(data->l)) == NULL)
1540 		return NULL;
1541 
1542 	/* encryption data */
1543 	memset(&c, 0, sizeof(c));
1544 	if (rijndael_cipherInit(&c, MODE_CBC, iv->v) < 0){
1545 		vfree(res);
1546 		return NULL;
1547 	}
1548 	if (rijndael_blockEncrypt(&c, &k, data->v, data->l << 3, res->v) < 0){
1549 		vfree(res);
1550 		return NULL;
1551 	}
1552 
1553 	return res;
1554 }
1555 
1556 vchar_t *
1557 eay_aes_decrypt(data, key, iv)
1558 	vchar_t *data, *key, *iv;
1559 {
1560 	vchar_t *res;
1561 	keyInstance k;
1562 	cipherInstance c;
1563 
1564 	memset(&k, 0, sizeof(k));
1565 	if (rijndael_makeKey(&k, DIR_DECRYPT, key->l << 3, key->v) < 0)
1566 		return NULL;
1567 
1568 	/* allocate buffer for result */
1569 	if ((res = vmalloc(data->l)) == NULL)
1570 		return NULL;
1571 
1572 	/* decryption data */
1573 	memset(&c, 0, sizeof(c));
1574 	if (rijndael_cipherInit(&c, MODE_CBC, iv->v) < 0){
1575 		vfree(res);
1576 		return NULL;
1577 	}
1578 	if (rijndael_blockDecrypt(&c, &k, data->v, data->l << 3, res->v) < 0){
1579 		vfree(res);
1580 		return NULL;
1581 	}
1582 
1583 	return res;
1584 }
1585 #else
1586 static inline const EVP_CIPHER *
1587 aes_evp_by_keylen(int keylen)
1588 {
1589 	switch(keylen) {
1590 		case 16:
1591 		case 128:
1592 			return EVP_aes_128_cbc();
1593 		case 24:
1594 		case 192:
1595 			return EVP_aes_192_cbc();
1596 		case 32:
1597 		case 256:
1598 			return EVP_aes_256_cbc();
1599 		default:
1600 			return NULL;
1601 	}
1602 }
1603 
1604 vchar_t *
1605 eay_aes_encrypt(data, key, iv)
1606        vchar_t *data, *key, *iv;
1607 {
1608 	return evp_crypt(data, key, iv, aes_evp_by_keylen(key->l), 1);
1609 }
1610 
1611 vchar_t *
1612 eay_aes_decrypt(data, key, iv)
1613        vchar_t *data, *key, *iv;
1614 {
1615 	return evp_crypt(data, key, iv, aes_evp_by_keylen(key->l), 0);
1616 }
1617 #endif
1618 
1619 int
1620 eay_aes_weakkey(key)
1621 	vchar_t *key;
1622 {
1623 	return 0;
1624 }
1625 
1626 int
1627 eay_aes_keylen(len)
1628 	int len;
1629 {
1630 	if (len == 0)
1631 		return 128;
1632 	if (len != 128 && len != 192 && len != 256)
1633 		return -1;
1634 	return len;
1635 }
1636 
1637 /* for ipsec part */
1638 int
1639 eay_null_hashlen()
1640 {
1641 	return 0;
1642 }
1643 
1644 int
1645 eay_kpdk_hashlen()
1646 {
1647 	return 0;
1648 }
1649 
1650 int
1651 eay_twofish_keylen(len)
1652 	int len;
1653 {
1654 	if (len < 0 || len > 256)
1655 		return -1;
1656 	return len;
1657 }
1658 
1659 int
1660 eay_null_keylen(len)
1661 	int len;
1662 {
1663 	return 0;
1664 }
1665 
1666 /*
1667  * HMAC functions
1668  */
1669 static caddr_t
1670 eay_hmac_init(key, md)
1671 	vchar_t *key;
1672 	const EVP_MD *md;
1673 {
1674 	HMAC_CTX *c = racoon_malloc(sizeof(*c));
1675 
1676 	HMAC_Init(c, key->v, key->l, md);
1677 
1678 	return (caddr_t)c;
1679 }
1680 
1681 #ifdef WITH_SHA2
1682 /*
1683  * HMAC SHA2-512
1684  */
1685 vchar_t *
1686 eay_hmacsha2_512_one(key, data)
1687 	vchar_t *key, *data;
1688 {
1689 	vchar_t *res;
1690 	caddr_t ctx;
1691 
1692 	ctx = eay_hmacsha2_512_init(key);
1693 	eay_hmacsha2_512_update(ctx, data);
1694 	res = eay_hmacsha2_512_final(ctx);
1695 
1696 	return(res);
1697 }
1698 
1699 caddr_t
1700 eay_hmacsha2_512_init(key)
1701 	vchar_t *key;
1702 {
1703 	return eay_hmac_init(key, EVP_sha2_512());
1704 }
1705 
1706 void
1707 eay_hmacsha2_512_update(c, data)
1708 	caddr_t c;
1709 	vchar_t *data;
1710 {
1711 	HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
1712 }
1713 
1714 vchar_t *
1715 eay_hmacsha2_512_final(c)
1716 	caddr_t c;
1717 {
1718 	vchar_t *res;
1719 	unsigned int l;
1720 
1721 	if ((res = vmalloc(SHA512_DIGEST_LENGTH)) == 0)
1722 		return NULL;
1723 
1724 	HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
1725 	res->l = l;
1726 	HMAC_cleanup((HMAC_CTX *)c);
1727 	(void)racoon_free(c);
1728 
1729 	if (SHA512_DIGEST_LENGTH != res->l) {
1730 		plog(LLV_ERROR, LOCATION, NULL,
1731 			"hmac sha2_512 length mismatch %zd.\n", res->l);
1732 		vfree(res);
1733 		return NULL;
1734 	}
1735 
1736 	return(res);
1737 }
1738 
1739 /*
1740  * HMAC SHA2-384
1741  */
1742 vchar_t *
1743 eay_hmacsha2_384_one(key, data)
1744 	vchar_t *key, *data;
1745 {
1746 	vchar_t *res;
1747 	caddr_t ctx;
1748 
1749 	ctx = eay_hmacsha2_384_init(key);
1750 	eay_hmacsha2_384_update(ctx, data);
1751 	res = eay_hmacsha2_384_final(ctx);
1752 
1753 	return(res);
1754 }
1755 
1756 caddr_t
1757 eay_hmacsha2_384_init(key)
1758 	vchar_t *key;
1759 {
1760 	return eay_hmac_init(key, EVP_sha2_384());
1761 }
1762 
1763 void
1764 eay_hmacsha2_384_update(c, data)
1765 	caddr_t c;
1766 	vchar_t *data;
1767 {
1768 	HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
1769 }
1770 
1771 vchar_t *
1772 eay_hmacsha2_384_final(c)
1773 	caddr_t c;
1774 {
1775 	vchar_t *res;
1776 	unsigned int l;
1777 
1778 	if ((res = vmalloc(SHA384_DIGEST_LENGTH)) == 0)
1779 		return NULL;
1780 
1781 	HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
1782 	res->l = l;
1783 	HMAC_cleanup((HMAC_CTX *)c);
1784 	(void)racoon_free(c);
1785 
1786 	if (SHA384_DIGEST_LENGTH != res->l) {
1787 		plog(LLV_ERROR, LOCATION, NULL,
1788 			"hmac sha2_384 length mismatch %zd.\n", res->l);
1789 		vfree(res);
1790 		return NULL;
1791 	}
1792 
1793 	return(res);
1794 }
1795 
1796 /*
1797  * HMAC SHA2-256
1798  */
1799 vchar_t *
1800 eay_hmacsha2_256_one(key, data)
1801 	vchar_t *key, *data;
1802 {
1803 	vchar_t *res;
1804 	caddr_t ctx;
1805 
1806 	ctx = eay_hmacsha2_256_init(key);
1807 	eay_hmacsha2_256_update(ctx, data);
1808 	res = eay_hmacsha2_256_final(ctx);
1809 
1810 	return(res);
1811 }
1812 
1813 caddr_t
1814 eay_hmacsha2_256_init(key)
1815 	vchar_t *key;
1816 {
1817 	return eay_hmac_init(key, EVP_sha2_256());
1818 }
1819 
1820 void
1821 eay_hmacsha2_256_update(c, data)
1822 	caddr_t c;
1823 	vchar_t *data;
1824 {
1825 	HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
1826 }
1827 
1828 vchar_t *
1829 eay_hmacsha2_256_final(c)
1830 	caddr_t c;
1831 {
1832 	vchar_t *res;
1833 	unsigned int l;
1834 
1835 	if ((res = vmalloc(SHA256_DIGEST_LENGTH)) == 0)
1836 		return NULL;
1837 
1838 	HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
1839 	res->l = l;
1840 	HMAC_cleanup((HMAC_CTX *)c);
1841 	(void)racoon_free(c);
1842 
1843 	if (SHA256_DIGEST_LENGTH != res->l) {
1844 		plog(LLV_ERROR, LOCATION, NULL,
1845 			"hmac sha2_256 length mismatch %zd.\n", res->l);
1846 		vfree(res);
1847 		return NULL;
1848 	}
1849 
1850 	return(res);
1851 }
1852 #endif	/* WITH_SHA2 */
1853 
1854 /*
1855  * HMAC SHA1
1856  */
1857 vchar_t *
1858 eay_hmacsha1_one(key, data)
1859 	vchar_t *key, *data;
1860 {
1861 	vchar_t *res;
1862 	caddr_t ctx;
1863 
1864 	ctx = eay_hmacsha1_init(key);
1865 	eay_hmacsha1_update(ctx, data);
1866 	res = eay_hmacsha1_final(ctx);
1867 
1868 	return(res);
1869 }
1870 
1871 caddr_t
1872 eay_hmacsha1_init(key)
1873 	vchar_t *key;
1874 {
1875 	return eay_hmac_init(key, EVP_sha1());
1876 }
1877 
1878 void
1879 eay_hmacsha1_update(c, data)
1880 	caddr_t c;
1881 	vchar_t *data;
1882 {
1883 	HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
1884 }
1885 
1886 vchar_t *
1887 eay_hmacsha1_final(c)
1888 	caddr_t c;
1889 {
1890 	vchar_t *res;
1891 	unsigned int l;
1892 
1893 	if ((res = vmalloc(SHA_DIGEST_LENGTH)) == 0)
1894 		return NULL;
1895 
1896 	HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
1897 	res->l = l;
1898 	HMAC_cleanup((HMAC_CTX *)c);
1899 	(void)racoon_free(c);
1900 
1901 	if (SHA_DIGEST_LENGTH != res->l) {
1902 		plog(LLV_ERROR, LOCATION, NULL,
1903 			"hmac sha1 length mismatch %zd.\n", res->l);
1904 		vfree(res);
1905 		return NULL;
1906 	}
1907 
1908 	return(res);
1909 }
1910 
1911 /*
1912  * HMAC MD5
1913  */
1914 vchar_t *
1915 eay_hmacmd5_one(key, data)
1916 	vchar_t *key, *data;
1917 {
1918 	vchar_t *res;
1919 	caddr_t ctx;
1920 
1921 	ctx = eay_hmacmd5_init(key);
1922 	eay_hmacmd5_update(ctx, data);
1923 	res = eay_hmacmd5_final(ctx);
1924 
1925 	return(res);
1926 }
1927 
1928 caddr_t
1929 eay_hmacmd5_init(key)
1930 	vchar_t *key;
1931 {
1932 	return eay_hmac_init(key, EVP_md5());
1933 }
1934 
1935 void
1936 eay_hmacmd5_update(c, data)
1937 	caddr_t c;
1938 	vchar_t *data;
1939 {
1940 	HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
1941 }
1942 
1943 vchar_t *
1944 eay_hmacmd5_final(c)
1945 	caddr_t c;
1946 {
1947 	vchar_t *res;
1948 	unsigned int l;
1949 
1950 	if ((res = vmalloc(MD5_DIGEST_LENGTH)) == 0)
1951 		return NULL;
1952 
1953 	HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
1954 	res->l = l;
1955 	HMAC_cleanup((HMAC_CTX *)c);
1956 	(void)racoon_free(c);
1957 
1958 	if (MD5_DIGEST_LENGTH != res->l) {
1959 		plog(LLV_ERROR, LOCATION, NULL,
1960 			"hmac md5 length mismatch %zd.\n", res->l);
1961 		vfree(res);
1962 		return NULL;
1963 	}
1964 
1965 	return(res);
1966 }
1967 
1968 #ifdef WITH_SHA2
1969 /*
1970  * SHA2-512 functions
1971  */
1972 caddr_t
1973 eay_sha2_512_init()
1974 {
1975 	SHA512_CTX *c = racoon_malloc(sizeof(*c));
1976 
1977 	SHA512_Init(c);
1978 
1979 	return((caddr_t)c);
1980 }
1981 
1982 void
1983 eay_sha2_512_update(c, data)
1984 	caddr_t c;
1985 	vchar_t *data;
1986 {
1987 	SHA512_Update((SHA512_CTX *)c, (unsigned char *) data->v, data->l);
1988 
1989 	return;
1990 }
1991 
1992 vchar_t *
1993 eay_sha2_512_final(c)
1994 	caddr_t c;
1995 {
1996 	vchar_t *res;
1997 
1998 	if ((res = vmalloc(SHA512_DIGEST_LENGTH)) == 0)
1999 		return(0);
2000 
2001 	SHA512_Final((unsigned char *) res->v, (SHA512_CTX *)c);
2002 	(void)racoon_free(c);
2003 
2004 	return(res);
2005 }
2006 
2007 vchar_t *
2008 eay_sha2_512_one(data)
2009 	vchar_t *data;
2010 {
2011 	caddr_t ctx;
2012 	vchar_t *res;
2013 
2014 	ctx = eay_sha2_512_init();
2015 	eay_sha2_512_update(ctx, data);
2016 	res = eay_sha2_512_final(ctx);
2017 
2018 	return(res);
2019 }
2020 
2021 int
2022 eay_sha2_512_hashlen()
2023 {
2024 	return SHA512_DIGEST_LENGTH << 3;
2025 }
2026 #endif
2027 
2028 #ifdef WITH_SHA2
2029 /*
2030  * SHA2-384 functions
2031  */
2032 caddr_t
2033 eay_sha2_384_init()
2034 {
2035 	SHA384_CTX *c = racoon_malloc(sizeof(*c));
2036 
2037 	SHA384_Init(c);
2038 
2039 	return((caddr_t)c);
2040 }
2041 
2042 void
2043 eay_sha2_384_update(c, data)
2044 	caddr_t c;
2045 	vchar_t *data;
2046 {
2047 	SHA384_Update((SHA384_CTX *)c, (unsigned char *) data->v, data->l);
2048 
2049 	return;
2050 }
2051 
2052 vchar_t *
2053 eay_sha2_384_final(c)
2054 	caddr_t c;
2055 {
2056 	vchar_t *res;
2057 
2058 	if ((res = vmalloc(SHA384_DIGEST_LENGTH)) == 0)
2059 		return(0);
2060 
2061 	SHA384_Final((unsigned char *) res->v, (SHA384_CTX *)c);
2062 	(void)racoon_free(c);
2063 
2064 	return(res);
2065 }
2066 
2067 vchar_t *
2068 eay_sha2_384_one(data)
2069 	vchar_t *data;
2070 {
2071 	caddr_t ctx;
2072 	vchar_t *res;
2073 
2074 	ctx = eay_sha2_384_init();
2075 	eay_sha2_384_update(ctx, data);
2076 	res = eay_sha2_384_final(ctx);
2077 
2078 	return(res);
2079 }
2080 
2081 int
2082 eay_sha2_384_hashlen()
2083 {
2084 	return SHA384_DIGEST_LENGTH << 3;
2085 }
2086 #endif
2087 
2088 #ifdef WITH_SHA2
2089 /*
2090  * SHA2-256 functions
2091  */
2092 caddr_t
2093 eay_sha2_256_init()
2094 {
2095 	SHA256_CTX *c = racoon_malloc(sizeof(*c));
2096 
2097 	SHA256_Init(c);
2098 
2099 	return((caddr_t)c);
2100 }
2101 
2102 void
2103 eay_sha2_256_update(c, data)
2104 	caddr_t c;
2105 	vchar_t *data;
2106 {
2107 	SHA256_Update((SHA256_CTX *)c, (unsigned char *) data->v, data->l);
2108 
2109 	return;
2110 }
2111 
2112 vchar_t *
2113 eay_sha2_256_final(c)
2114 	caddr_t c;
2115 {
2116 	vchar_t *res;
2117 
2118 	if ((res = vmalloc(SHA256_DIGEST_LENGTH)) == 0)
2119 		return(0);
2120 
2121 	SHA256_Final((unsigned char *) res->v, (SHA256_CTX *)c);
2122 	(void)racoon_free(c);
2123 
2124 	return(res);
2125 }
2126 
2127 vchar_t *
2128 eay_sha2_256_one(data)
2129 	vchar_t *data;
2130 {
2131 	caddr_t ctx;
2132 	vchar_t *res;
2133 
2134 	ctx = eay_sha2_256_init();
2135 	eay_sha2_256_update(ctx, data);
2136 	res = eay_sha2_256_final(ctx);
2137 
2138 	return(res);
2139 }
2140 
2141 int
2142 eay_sha2_256_hashlen()
2143 {
2144 	return SHA256_DIGEST_LENGTH << 3;
2145 }
2146 #endif
2147 
2148 /*
2149  * SHA functions
2150  */
2151 caddr_t
2152 eay_sha1_init()
2153 {
2154 	SHA_CTX *c = racoon_malloc(sizeof(*c));
2155 
2156 	SHA1_Init(c);
2157 
2158 	return((caddr_t)c);
2159 }
2160 
2161 void
2162 eay_sha1_update(c, data)
2163 	caddr_t c;
2164 	vchar_t *data;
2165 {
2166 	SHA1_Update((SHA_CTX *)c, data->v, data->l);
2167 
2168 	return;
2169 }
2170 
2171 vchar_t *
2172 eay_sha1_final(c)
2173 	caddr_t c;
2174 {
2175 	vchar_t *res;
2176 
2177 	if ((res = vmalloc(SHA_DIGEST_LENGTH)) == 0)
2178 		return(0);
2179 
2180 	SHA1_Final((unsigned char *) res->v, (SHA_CTX *)c);
2181 	(void)racoon_free(c);
2182 
2183 	return(res);
2184 }
2185 
2186 vchar_t *
2187 eay_sha1_one(data)
2188 	vchar_t *data;
2189 {
2190 	caddr_t ctx;
2191 	vchar_t *res;
2192 
2193 	ctx = eay_sha1_init();
2194 	eay_sha1_update(ctx, data);
2195 	res = eay_sha1_final(ctx);
2196 
2197 	return(res);
2198 }
2199 
2200 int
2201 eay_sha1_hashlen()
2202 {
2203 	return SHA_DIGEST_LENGTH << 3;
2204 }
2205 
2206 /*
2207  * MD5 functions
2208  */
2209 caddr_t
2210 eay_md5_init()
2211 {
2212 	MD5_CTX *c = racoon_malloc(sizeof(*c));
2213 
2214 	MD5_Init(c);
2215 
2216 	return((caddr_t)c);
2217 }
2218 
2219 void
2220 eay_md5_update(c, data)
2221 	caddr_t c;
2222 	vchar_t *data;
2223 {
2224 	MD5_Update((MD5_CTX *)c, data->v, data->l);
2225 
2226 	return;
2227 }
2228 
2229 vchar_t *
2230 eay_md5_final(c)
2231 	caddr_t c;
2232 {
2233 	vchar_t *res;
2234 
2235 	if ((res = vmalloc(MD5_DIGEST_LENGTH)) == 0)
2236 		return(0);
2237 
2238 	MD5_Final((unsigned char *) res->v, (MD5_CTX *)c);
2239 	(void)racoon_free(c);
2240 
2241 	return(res);
2242 }
2243 
2244 vchar_t *
2245 eay_md5_one(data)
2246 	vchar_t *data;
2247 {
2248 	caddr_t ctx;
2249 	vchar_t *res;
2250 
2251 	ctx = eay_md5_init();
2252 	eay_md5_update(ctx, data);
2253 	res = eay_md5_final(ctx);
2254 
2255 	return(res);
2256 }
2257 
2258 int
2259 eay_md5_hashlen()
2260 {
2261 	return MD5_DIGEST_LENGTH << 3;
2262 }
2263 
2264 /*
2265  * eay_set_random
2266  *   size: number of bytes.
2267  */
2268 vchar_t *
2269 eay_set_random(size)
2270 	u_int32_t size;
2271 {
2272 	BIGNUM *r = NULL;
2273 	vchar_t *res = 0;
2274 
2275 	if ((r = BN_new()) == NULL)
2276 		goto end;
2277 	BN_rand(r, size * 8, 0, 0);
2278 	eay_bn2v(&res, r);
2279 
2280 end:
2281 	if (r)
2282 		BN_free(r);
2283 	return(res);
2284 }
2285 
2286 /* DH */
2287 int
2288 eay_dh_generate(prime, g, publen, pub, priv)
2289 	vchar_t *prime, **pub, **priv;
2290 	u_int publen;
2291 	u_int32_t g;
2292 {
2293 	BIGNUM *p = NULL;
2294 	DH *dh = NULL;
2295 	int error = -1;
2296 
2297 	/* initialize */
2298 	/* pre-process to generate number */
2299 	if (eay_v2bn(&p, prime) < 0)
2300 		goto end;
2301 
2302 	if ((dh = DH_new()) == NULL)
2303 		goto end;
2304 	dh->p = p;
2305 	p = NULL;	/* p is now part of dh structure */
2306 	dh->g = NULL;
2307 	if ((dh->g = BN_new()) == NULL)
2308 		goto end;
2309 	if (!BN_set_word(dh->g, g))
2310 		goto end;
2311 
2312 	if (publen != 0)
2313 		dh->length = publen;
2314 
2315 	/* generate public and private number */
2316 	if (!DH_generate_key(dh))
2317 		goto end;
2318 
2319 	/* copy results to buffers */
2320 	if (eay_bn2v(pub, dh->pub_key) < 0)
2321 		goto end;
2322 	if (eay_bn2v(priv, dh->priv_key) < 0) {
2323 		vfree(*pub);
2324 		goto end;
2325 	}
2326 
2327 	error = 0;
2328 
2329 end:
2330 	if (dh != NULL)
2331 		DH_free(dh);
2332 	if (p != 0)
2333 		BN_free(p);
2334 	return(error);
2335 }
2336 
2337 int
2338 eay_dh_compute(prime, g, pub, priv, pub2, key)
2339 	vchar_t *prime, *pub, *priv, *pub2, **key;
2340 	u_int32_t g;
2341 {
2342 	BIGNUM *dh_pub = NULL;
2343 	DH *dh = NULL;
2344 	int l;
2345 	unsigned char *v = NULL;
2346 	int error = -1;
2347 
2348 	/* make public number to compute */
2349 	if (eay_v2bn(&dh_pub, pub2) < 0)
2350 		goto end;
2351 
2352 	/* make DH structure */
2353 	if ((dh = DH_new()) == NULL)
2354 		goto end;
2355 	if (eay_v2bn(&dh->p, prime) < 0)
2356 		goto end;
2357 	if (eay_v2bn(&dh->pub_key, pub) < 0)
2358 		goto end;
2359 	if (eay_v2bn(&dh->priv_key, priv) < 0)
2360 		goto end;
2361 	dh->length = pub2->l * 8;
2362 
2363 	dh->g = NULL;
2364 	if ((dh->g = BN_new()) == NULL)
2365 		goto end;
2366 	if (!BN_set_word(dh->g, g))
2367 		goto end;
2368 
2369 	if ((v = racoon_calloc(prime->l, sizeof(u_char))) == NULL)
2370 		goto end;
2371 	if ((l = DH_compute_key(v, dh_pub, dh)) == -1)
2372 		goto end;
2373 	memcpy((*key)->v + (prime->l - l), v, l);
2374 
2375 	error = 0;
2376 
2377 end:
2378 	if (dh_pub != NULL)
2379 		BN_free(dh_pub);
2380 	if (dh != NULL)
2381 		DH_free(dh);
2382 	if (v != NULL)
2383 		racoon_free(v);
2384 	return(error);
2385 }
2386 
2387 /*
2388  * convert vchar_t <-> BIGNUM.
2389  *
2390  * vchar_t: unit is u_char, network endian, most significant byte first.
2391  * BIGNUM: unit is BN_ULONG, each of BN_ULONG is in host endian,
2392  *	least significant BN_ULONG must come first.
2393  *
2394  * hex value of "0x3ffe050104" is represented as follows:
2395  *	vchar_t: 3f fe 05 01 04
2396  *	BIGNUM (BN_ULONG = u_int8_t): 04 01 05 fe 3f
2397  *	BIGNUM (BN_ULONG = u_int16_t): 0x0104 0xfe05 0x003f
2398  *	BIGNUM (BN_ULONG = u_int32_t_t): 0xfe050104 0x0000003f
2399  */
2400 int
2401 eay_v2bn(bn, var)
2402 	BIGNUM **bn;
2403 	vchar_t *var;
2404 {
2405 	if ((*bn = BN_bin2bn((unsigned char *) var->v, var->l, NULL)) == NULL)
2406 		return -1;
2407 
2408 	return 0;
2409 }
2410 
2411 int
2412 eay_bn2v(var, bn)
2413 	vchar_t **var;
2414 	BIGNUM *bn;
2415 {
2416 	*var = vmalloc(bn->top * BN_BYTES);
2417 	if (*var == NULL)
2418 		return(-1);
2419 
2420 	(*var)->l = BN_bn2bin(bn, (unsigned char *) (*var)->v);
2421 
2422 	return 0;
2423 }
2424 
2425 void
2426 eay_init()
2427 {
2428 	OpenSSL_add_all_algorithms();
2429 	ERR_load_crypto_strings();
2430 #ifdef HAVE_OPENSSL_ENGINE_H
2431 	ENGINE_load_builtin_engines();
2432 	ENGINE_register_all_complete();
2433 #endif
2434 }
2435 
2436 vchar_t *
2437 base64_decode(char *in, long inlen)
2438 {
2439 	BIO *bio=NULL, *b64=NULL;
2440 	vchar_t *res = NULL;
2441 	char out[inlen*2];
2442 	long outlen;
2443 
2444 	bio = BIO_new_mem_buf(in, inlen);
2445 	b64 = BIO_new(BIO_f_base64());
2446 	BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
2447 	bio = BIO_push(b64, bio);
2448 
2449 	outlen = BIO_read(bio, out, inlen * 2);
2450 	if (outlen <= 0) {
2451 		plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
2452 		goto out;
2453 	}
2454 
2455 	res = vmalloc(outlen);
2456 	if (!res)
2457 		goto out;
2458 
2459 	memcpy(res->v, out, outlen);
2460 
2461 out:
2462 	if (bio)
2463 		BIO_free_all(bio);
2464 
2465 	return res;
2466 }
2467 
2468 vchar_t *
2469 base64_encode(char *in, long inlen)
2470 {
2471 	BIO *bio=NULL, *b64=NULL;
2472 	char *ptr;
2473 	long plen = -1;
2474 	vchar_t *res = NULL;
2475 
2476 	bio = BIO_new(BIO_s_mem());
2477 	b64 = BIO_new(BIO_f_base64());
2478 	BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
2479 	bio = BIO_push(b64, bio);
2480 
2481 	BIO_write(bio, in, inlen);
2482 	BIO_flush(bio);
2483 
2484 	plen = BIO_get_mem_data(bio, &ptr);
2485 	res = vmalloc(plen+1);
2486 	if (!res)
2487 		goto out;
2488 
2489 	memcpy (res->v, ptr, plen);
2490 	res->v[plen] = '\0';
2491 
2492 out:
2493 	if (bio)
2494 		BIO_free_all(bio);
2495 
2496 	return res;
2497 }
2498 
2499 static RSA *
2500 binbuf_pubkey2rsa(vchar_t *binbuf)
2501 {
2502 	BIGNUM *exp, *mod;
2503 	RSA *rsa_pub = NULL;
2504 
2505 	if (binbuf->v[0] > binbuf->l - 1) {
2506 		plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: decoded string doesn't make sense.\n");
2507 		goto out;
2508 	}
2509 
2510 	exp = BN_bin2bn((unsigned char *) (binbuf->v + 1), binbuf->v[0], NULL);
2511 	mod = BN_bin2bn((unsigned char *) (binbuf->v + binbuf->v[0] + 1),
2512 			binbuf->l - binbuf->v[0] - 1, NULL);
2513 	rsa_pub = RSA_new();
2514 
2515 	if (!exp || !mod || !rsa_pub) {
2516 		plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey parsing error: %s\n", eay_strerror());
2517 		if (exp)
2518 			BN_free(exp);
2519 		if (mod)
2520 			BN_free(exp);
2521 		if (rsa_pub)
2522 			RSA_free(rsa_pub);
2523 		rsa_pub = NULL;
2524 		goto out;
2525 	}
2526 
2527 	rsa_pub->n = mod;
2528 	rsa_pub->e = exp;
2529 
2530 out:
2531 	return rsa_pub;
2532 }
2533 
2534 RSA *
2535 base64_pubkey2rsa(char *in)
2536 {
2537 	BIGNUM *exp, *mod;
2538 	RSA *rsa_pub = NULL;
2539 	vchar_t *binbuf;
2540 
2541 	if (strncmp(in, "0s", 2) != 0) {
2542 		plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: doesn't start with '0s'\n");
2543 		return NULL;
2544 	}
2545 
2546 	binbuf = base64_decode(in + 2, strlen(in + 2));
2547 	if (!binbuf) {
2548 		plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: Base64 decoding failed.\n");
2549 		return NULL;
2550 	}
2551 
2552 	if (binbuf->v[0] > binbuf->l - 1) {
2553 		plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: decoded string doesn't make sense.\n");
2554 		goto out;
2555 	}
2556 
2557 	rsa_pub = binbuf_pubkey2rsa(binbuf);
2558 
2559 out:
2560 	if (binbuf)
2561 		vfree(binbuf);
2562 
2563 	return rsa_pub;
2564 }
2565 
2566 RSA *
2567 bignum_pubkey2rsa(BIGNUM *in)
2568 {
2569 	RSA *rsa_pub = NULL;
2570 	vchar_t *binbuf;
2571 
2572 	binbuf = vmalloc(BN_num_bytes(in));
2573 	if (!binbuf) {
2574 		plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey conversion: memory allocation failed..\n");
2575 		return NULL;
2576 	}
2577 
2578 	BN_bn2bin(in, (unsigned char *) binbuf->v);
2579 
2580 	rsa_pub = binbuf_pubkey2rsa(binbuf);
2581 
2582 out:
2583 	if (binbuf)
2584 		vfree(binbuf);
2585 
2586 	return rsa_pub;
2587 }
2588 
2589 u_int32_t
2590 eay_random()
2591 {
2592 	u_int32_t result;
2593 	vchar_t *vrand;
2594 
2595 	vrand = eay_set_random(sizeof(result));
2596 	memcpy(&result, vrand->v, sizeof(result));
2597 	vfree(vrand);
2598 
2599 	return result;
2600 }
2601 
2602 const char *
2603 eay_version()
2604 {
2605 	return SSLeay_version(SSLEAY_VERSION);
2606 }
2607