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