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