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