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