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