No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / dist / ipsec-tools / src / racoon / crypto_openssl.c
blob7abf45afdcabdf183709cae22baafc1cf9ab335f
1 /* $NetBSD: crypto_openssl.c,v 1.18 2009/04/20 13:22:41 tteras Exp $ */
3 /* Id: crypto_openssl.c,v 1.47 2006/05/06 20:42:09 manubsd Exp */
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.
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.
34 #include "config.h"
36 #include <sys/types.h>
37 #include <sys/param.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <limits.h>
42 #include <string.h>
44 /* get openssl/ssleay version number */
45 #include <openssl/opensslv.h>
47 #if !defined(OPENSSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x0090602fL)
48 #error OpenSSL version 0.9.6 or later required.
49 #endif
51 #include <openssl/pem.h>
52 #include <openssl/evp.h>
53 #include <openssl/x509.h>
54 #include <openssl/x509v3.h>
55 #include <openssl/x509_vfy.h>
56 #include <openssl/bn.h>
57 #include <openssl/dh.h>
58 #include <openssl/md5.h>
59 #include <openssl/sha.h>
60 #include <openssl/hmac.h>
61 #include <openssl/des.h>
62 #include <openssl/crypto.h>
63 #ifdef HAVE_OPENSSL_ENGINE_H
64 #include <openssl/engine.h>
65 #endif
66 #include <openssl/blowfish.h>
67 #include <openssl/cast.h>
68 #include <openssl/err.h>
69 #ifdef HAVE_OPENSSL_RC5_H
70 #include <openssl/rc5.h>
71 #endif
72 #ifdef HAVE_OPENSSL_IDEA_H
73 #include <openssl/idea.h>
74 #endif
75 #if defined(HAVE_OPENSSL_AES_H)
76 #include <openssl/aes.h>
77 #elif defined(HAVE_OPENSSL_RIJNDAEL_H)
78 #include <openssl/rijndael.h>
79 #else
80 #include "crypto/rijndael/rijndael-api-fst.h"
81 #endif
82 #if defined(HAVE_OPENSSL_CAMELLIA_H)
83 #include <openssl/camellia.h>
84 #endif
85 #ifdef WITH_SHA2
86 #ifdef HAVE_OPENSSL_SHA2_H
87 #include <openssl/sha2.h>
88 #else
89 #include "crypto/sha2/sha2.h"
90 #endif
91 #endif
92 #include "plog.h"
94 /* 0.9.7 stuff? */
95 #if OPENSSL_VERSION_NUMBER < 0x0090700fL
96 typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES;
97 #else
98 #define USE_NEW_DES_API
99 #endif
101 #define OpenSSL_BUG() do { plog(LLV_ERROR, LOCATION, NULL, "OpenSSL function failed\n"); } while(0)
103 #include "var.h"
104 #include "misc.h"
105 #include "vmbuf.h"
106 #include "plog.h"
107 #include "crypto_openssl.h"
108 #include "debug.h"
109 #include "gcmalloc.h"
110 #include "isakmp.h"
113 * I hate to cast every parameter to des_xx into void *, but it is
114 * necessary for SSLeay/OpenSSL portability. It sucks.
117 static int cb_check_cert_local __P((int, X509_STORE_CTX *));
118 static int cb_check_cert_remote __P((int, X509_STORE_CTX *));
119 static X509 *mem2x509 __P((vchar_t *));
121 static caddr_t eay_hmac_init __P((vchar_t *, const EVP_MD *));
123 /* X509 Certificate */
125 * convert the string of the subject name into DER
126 * e.g. str = "C=JP, ST=Kanagawa";
128 vchar_t *
129 eay_str2asn1dn(str, len)
130 const char *str;
131 int len;
133 X509_NAME *name;
134 char *buf, *dst;
135 char *field, *value;
136 int i;
137 vchar_t *ret = NULL;
138 caddr_t p;
140 if (len == -1)
141 len = strlen(str);
143 buf = racoon_malloc(len + 1);
144 if (!buf) {
145 plog(LLV_WARNING, LOCATION, NULL,"failed to allocate buffer\n");
146 return NULL;
148 memcpy(buf, str, len);
150 name = X509_NAME_new();
152 dst = field = &buf[0];
153 value = NULL;
154 for (i = 0; i < len; i++) {
155 if (buf[i] == '\\') {
156 /* Escape characters specified in RFC 2253 */
157 if (i < len - 1 &&
158 strchr("\\,=+<>#;", buf[i+1]) != NULL) {
159 *dst++ = buf[++i];
160 continue;
161 } else if (i < len - 2) {
162 /* RFC 2253 hexpair character escape */
163 long u;
164 char esc_str[3];
165 char *endptr;
167 esc_str[0] = buf[++i];
168 esc_str[1] = buf[++i];
169 esc_str[2] = '\0';
170 u = strtol(esc_str, &endptr, 16);
171 if (*endptr != '\0' || u < 0 || u > 255)
172 goto err;
173 *dst++ = u;
174 continue;
175 } else
176 goto err;
178 if (!value && buf[i] == '=') {
179 *dst = '\0';
180 dst = value = &buf[i + 1];
181 continue;
182 } else if (buf[i] == ',' || buf[i] == '/') {
183 *dst = '\0';
185 plog(LLV_DEBUG, LOCATION, NULL, "DN: %s=%s\n",
186 field, value);
188 if (!value) goto err;
189 if (!X509_NAME_add_entry_by_txt(name, field,
190 (value[0] == '*' && value[1] == 0) ?
191 V_ASN1_PRINTABLESTRING : MBSTRING_ASC,
192 (unsigned char *) value, -1, -1, 0)) {
193 plog(LLV_ERROR, LOCATION, NULL,
194 "Invalid DN field: %s=%s\n",
195 field, value);
196 plog(LLV_ERROR, LOCATION, NULL,
197 "%s\n", eay_strerror());
198 goto err;
201 while (i + 1 < len && buf[i + 1] == ' ') i++;
202 dst = field = &buf[i + 1];
203 value = NULL;
204 continue;
205 } else {
206 *dst++ = buf[i];
209 *dst = '\0';
211 plog(LLV_DEBUG, LOCATION, NULL, "DN: %s=%s\n",
212 field, value);
214 if (!value) goto err;
215 if (!X509_NAME_add_entry_by_txt(name, field,
216 (value[0] == '*' && value[1] == 0) ?
217 V_ASN1_PRINTABLESTRING : MBSTRING_ASC,
218 (unsigned char *) value, -1, -1, 0)) {
219 plog(LLV_ERROR, LOCATION, NULL,
220 "Invalid DN field: %s=%s\n",
221 field, value);
222 plog(LLV_ERROR, LOCATION, NULL,
223 "%s\n", eay_strerror());
224 goto err;
227 i = i2d_X509_NAME(name, NULL);
228 if (!i)
229 goto err;
230 ret = vmalloc(i);
231 if (!ret)
232 goto err;
233 p = ret->v;
234 i = i2d_X509_NAME(name, (void *)&p);
235 if (!i)
236 goto err;
238 return ret;
240 err:
241 if (buf)
242 racoon_free(buf);
243 if (name)
244 X509_NAME_free(name);
245 if (ret)
246 vfree(ret);
247 return NULL;
251 * convert the hex string of the subject name into DER
253 vchar_t *
254 eay_hex2asn1dn(const char *hex, int len)
256 BIGNUM *bn = BN_new();
257 char *binbuf;
258 size_t binlen;
259 vchar_t *ret = NULL;
261 if (len == -1)
262 len = strlen(hex);
264 if (BN_hex2bn(&bn, hex) != len) {
265 plog(LLV_ERROR, LOCATION, NULL,
266 "conversion of Hex-encoded ASN1 string to binary failed: %s\n",
267 eay_strerror());
268 goto out;
271 binlen = BN_num_bytes(bn);
272 ret = vmalloc(binlen);
273 if (!ret) {
274 plog(LLV_WARNING, LOCATION, NULL,"failed to allocate buffer\n");
275 return NULL;
277 binbuf = ret->v;
279 BN_bn2bin(bn, (unsigned char *) binbuf);
281 out:
282 BN_free(bn);
284 return ret;
288 * The following are derived from code in crypto/x509/x509_cmp.c
289 * in OpenSSL0.9.7c:
290 * X509_NAME_wildcmp() adds wildcard matching to the original
291 * X509_NAME_cmp(), nocase_cmp() and nocase_spacenorm_cmp() are as is.
293 #include <ctype.h>
294 /* Case insensitive string comparision */
295 static int nocase_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
297 int i;
299 if (a->length != b->length)
300 return (a->length - b->length);
302 for (i=0; i<a->length; i++)
304 int ca, cb;
306 ca = tolower(a->data[i]);
307 cb = tolower(b->data[i]);
309 if (ca != cb)
310 return(ca-cb);
312 return 0;
315 /* Case insensitive string comparision with space normalization
316 * Space normalization - ignore leading, trailing spaces,
317 * multiple spaces between characters are replaced by single space
319 static int nocase_spacenorm_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
321 unsigned char *pa = NULL, *pb = NULL;
322 int la, lb;
324 la = a->length;
325 lb = b->length;
326 pa = a->data;
327 pb = b->data;
329 /* skip leading spaces */
330 while (la > 0 && isspace(*pa))
332 la--;
333 pa++;
335 while (lb > 0 && isspace(*pb))
337 lb--;
338 pb++;
341 /* skip trailing spaces */
342 while (la > 0 && isspace(pa[la-1]))
343 la--;
344 while (lb > 0 && isspace(pb[lb-1]))
345 lb--;
347 /* compare strings with space normalization */
348 while (la > 0 && lb > 0)
350 int ca, cb;
352 /* compare character */
353 ca = tolower(*pa);
354 cb = tolower(*pb);
355 if (ca != cb)
356 return (ca - cb);
358 pa++; pb++;
359 la--; lb--;
361 if (la <= 0 || lb <= 0)
362 break;
364 /* is white space next character ? */
365 if (isspace(*pa) && isspace(*pb))
367 /* skip remaining white spaces */
368 while (la > 0 && isspace(*pa))
370 la--;
371 pa++;
373 while (lb > 0 && isspace(*pb))
375 lb--;
376 pb++;
380 if (la > 0 || lb > 0)
381 return la - lb;
383 return 0;
386 static int X509_NAME_wildcmp(const X509_NAME *a, const X509_NAME *b)
388 int i,j;
389 X509_NAME_ENTRY *na,*nb;
391 if (sk_X509_NAME_ENTRY_num(a->entries)
392 != sk_X509_NAME_ENTRY_num(b->entries))
393 return sk_X509_NAME_ENTRY_num(a->entries)
394 -sk_X509_NAME_ENTRY_num(b->entries);
395 for (i=sk_X509_NAME_ENTRY_num(a->entries)-1; i>=0; i--)
397 na=sk_X509_NAME_ENTRY_value(a->entries,i);
398 nb=sk_X509_NAME_ENTRY_value(b->entries,i);
399 j=OBJ_cmp(na->object,nb->object);
400 if (j) return(j);
401 if ((na->value->length == 1 && na->value->data[0] == '*')
402 || (nb->value->length == 1 && nb->value->data[0] == '*'))
403 continue;
404 j=na->value->type-nb->value->type;
405 if (j) return(j);
406 if (na->value->type == V_ASN1_PRINTABLESTRING)
407 j=nocase_spacenorm_cmp(na->value, nb->value);
408 else if (na->value->type == V_ASN1_IA5STRING
409 && OBJ_obj2nid(na->object) == NID_pkcs9_emailAddress)
410 j=nocase_cmp(na->value, nb->value);
411 else
413 j=na->value->length-nb->value->length;
414 if (j) return(j);
415 j=memcmp(na->value->data,nb->value->data,
416 na->value->length);
418 if (j) return(j);
419 j=na->set-nb->set;
420 if (j) return(j);
423 return(0);
427 * compare two subjectNames.
428 * OUT: 0: equal
429 * positive:
430 * -1: other error.
433 eay_cmp_asn1dn(n1, n2)
434 vchar_t *n1, *n2;
436 X509_NAME *a = NULL, *b = NULL;
437 caddr_t p;
438 int i = -1;
440 p = n1->v;
441 if (!d2i_X509_NAME(&a, (void *)&p, n1->l))
442 goto end;
443 p = n2->v;
444 if (!d2i_X509_NAME(&b, (void *)&p, n2->l))
445 goto end;
447 i = X509_NAME_wildcmp(a, b);
449 end:
450 if (a)
451 X509_NAME_free(a);
452 if (b)
453 X509_NAME_free(b);
454 return i;
458 * this functions is derived from apps/verify.c in OpenSSL0.9.5
461 eay_check_x509cert(cert, CApath, CAfile, local)
462 vchar_t *cert;
463 char *CApath;
464 char *CAfile;
465 int local;
467 X509_STORE *cert_ctx = NULL;
468 X509_LOOKUP *lookup = NULL;
469 X509 *x509 = NULL;
470 X509_STORE_CTX *csc;
471 int error = -1;
473 cert_ctx = X509_STORE_new();
474 if (cert_ctx == NULL)
475 goto end;
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);
482 lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
483 if (lookup == NULL)
484 goto end;
486 X509_LOOKUP_load_file(lookup, CAfile,
487 (CAfile == NULL) ? X509_FILETYPE_DEFAULT : X509_FILETYPE_PEM);
489 lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
490 if (lookup == NULL)
491 goto end;
492 error = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
493 if(!error) {
494 error = -1;
495 goto end;
497 error = -1; /* initialized */
499 /* read the certificate to be verified */
500 x509 = mem2x509(cert);
501 if (x509 == NULL)
502 goto end;
504 csc = X509_STORE_CTX_new();
505 if (csc == NULL)
506 goto end;
507 X509_STORE_CTX_init(csc, cert_ctx, x509, NULL);
508 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
509 X509_STORE_CTX_set_flags (csc, X509_V_FLAG_CRL_CHECK);
510 X509_STORE_CTX_set_flags (csc, X509_V_FLAG_CRL_CHECK_ALL);
511 #endif
512 error = X509_verify_cert(csc);
513 X509_STORE_CTX_free(csc);
516 * if x509_verify_cert() is successful then the value of error is
517 * set non-zero.
519 error = error ? 0 : -1;
521 end:
522 if (error)
523 plog(LLV_WARNING, LOCATION, NULL,"%s\n", eay_strerror());
524 if (cert_ctx != NULL)
525 X509_STORE_free(cert_ctx);
526 if (x509 != NULL)
527 X509_free(x509);
529 return(error);
533 * callback function for verifing certificate.
534 * this function is derived from cb() in openssl/apps/s_server.c
536 static int
537 cb_check_cert_local(ok, ctx)
538 int ok;
539 X509_STORE_CTX *ctx;
541 char buf[256];
542 int log_tag;
544 if (!ok) {
545 X509_NAME_oneline(
546 X509_get_subject_name(ctx->current_cert),
547 buf,
548 256);
550 * since we are just checking the certificates, it is
551 * ok if they are self signed. But we should still warn
552 * the user.
554 switch (ctx->error) {
555 case X509_V_ERR_CERT_HAS_EXPIRED:
556 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
557 case X509_V_ERR_INVALID_CA:
558 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
559 case X509_V_ERR_INVALID_PURPOSE:
560 case X509_V_ERR_UNABLE_TO_GET_CRL:
561 ok = 1;
562 log_tag = LLV_WARNING;
563 break;
564 default:
565 log_tag = LLV_ERROR;
567 plog(log_tag, LOCATION, NULL,
568 "%s(%d) at depth:%d SubjectName:%s\n",
569 X509_verify_cert_error_string(ctx->error),
570 ctx->error,
571 ctx->error_depth,
572 buf);
574 ERR_clear_error();
576 return ok;
580 * callback function for verifing remote certificates.
581 * this function is derived from cb() in openssl/apps/s_server.c
583 static int
584 cb_check_cert_remote(ok, ctx)
585 int ok;
586 X509_STORE_CTX *ctx;
588 char buf[256];
589 int log_tag;
591 if (!ok) {
592 X509_NAME_oneline(
593 X509_get_subject_name(ctx->current_cert),
594 buf,
595 256);
596 switch (ctx->error) {
597 case X509_V_ERR_UNABLE_TO_GET_CRL:
598 ok = 1;
599 log_tag = LLV_WARNING;
600 break;
601 default:
602 log_tag = LLV_ERROR;
604 plog(log_tag, LOCATION, NULL,
605 "%s(%d) at depth:%d SubjectName:%s\n",
606 X509_verify_cert_error_string(ctx->error),
607 ctx->error,
608 ctx->error_depth,
609 buf);
611 ERR_clear_error();
613 return ok;
617 * get a subjectName from X509 certificate.
619 vchar_t *
620 eay_get_x509asn1subjectname(cert)
621 vchar_t *cert;
623 X509 *x509 = NULL;
624 u_char *bp;
625 vchar_t *name = NULL;
626 int len;
628 x509 = mem2x509(cert);
629 if (x509 == NULL)
630 goto error;
632 /* get the length of the name */
633 len = i2d_X509_NAME(x509->cert_info->subject, NULL);
634 name = vmalloc(len);
635 if (!name)
636 goto error;
637 /* get the name */
638 bp = (unsigned char *) name->v;
639 len = i2d_X509_NAME(x509->cert_info->subject, &bp);
641 X509_free(x509);
643 return name;
645 error:
646 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
648 if (name != NULL)
649 vfree(name);
651 if (x509 != NULL)
652 X509_free(x509);
654 return NULL;
658 * get the subjectAltName from X509 certificate.
659 * the name must be terminated by '\0'.
662 eay_get_x509subjectaltname(cert, altname, type, pos)
663 vchar_t *cert;
664 char **altname;
665 int *type;
666 int pos;
668 X509 *x509 = NULL;
669 GENERAL_NAMES *gens = NULL;
670 GENERAL_NAME *gen;
671 int len;
672 int error = -1;
674 *altname = NULL;
675 *type = GENT_OTHERNAME;
677 x509 = mem2x509(cert);
678 if (x509 == NULL)
679 goto end;
681 gens = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL);
682 if (gens == NULL)
683 goto end;
685 /* there is no data at "pos" */
686 if (pos > sk_GENERAL_NAME_num(gens))
687 goto end;
689 gen = sk_GENERAL_NAME_value(gens, pos - 1);
691 /* read DNSName / Email */
692 if (gen->type == GEN_DNS ||
693 gen->type == GEN_EMAIL ||
694 gen->type == GEN_URI )
696 /* make sure if the data is terminated by '\0'. */
697 if (gen->d.ia5->data[gen->d.ia5->length] != '\0')
699 plog(LLV_ERROR, LOCATION, NULL,
700 "data is not terminated by NUL.");
701 racoon_hexdump(gen->d.ia5->data, gen->d.ia5->length + 1);
702 goto end;
705 len = gen->d.ia5->length + 1;
706 *altname = racoon_malloc(len);
707 if (!*altname)
708 goto end;
710 strlcpy(*altname, (char *) gen->d.ia5->data, len);
711 *type = gen->type;
712 error = 0;
714 /* read IP address */
715 else if (gen->type == GEN_IPADD)
717 unsigned char p[5], *ip;
718 ip = p;
720 /* only support IPv4 */
721 if (gen->d.ip->length != 4)
722 goto end;
724 /* convert Octet String to String
725 * XXX ???????
727 /*i2d_ASN1_OCTET_STRING(gen->d.ip,&ip);*/
728 ip = gen->d.ip->data;
730 /* XXX Magic, enough for an IPv4 address
732 *altname = racoon_malloc(20);
733 if (!*altname)
734 goto end;
736 sprintf(*altname, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
737 *type = gen->type;
738 error = 0;
740 /* XXX other possible types ?
741 * For now, error will be -1 if unsupported type
744 end:
745 if (error) {
746 if (*altname) {
747 racoon_free(*altname);
748 *altname = NULL;
750 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
752 if (x509)
753 X509_free(x509);
754 if (gens)
755 /* free the whole stack. */
756 sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
758 return error;
762 * get a issuerName from X509 certificate.
764 vchar_t *
765 eay_get_x509asn1issuername(cert)
766 vchar_t *cert;
768 X509 *x509 = NULL;
769 u_char *bp;
770 vchar_t *name = NULL;
771 int len;
773 x509 = mem2x509(cert);
774 if (x509 == NULL)
775 goto error;
777 /* get the length of the name */
778 len = i2d_X509_NAME(x509->cert_info->issuer, NULL);
779 name = vmalloc(len);
780 if (name == NULL)
781 goto error;
783 /* get the name */
784 bp = (unsigned char *) name->v;
785 len = i2d_X509_NAME(x509->cert_info->issuer, &bp);
787 X509_free(x509);
789 return name;
791 error:
792 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
794 if (name != NULL)
795 vfree(name);
796 if (x509 != NULL)
797 X509_free(x509);
799 return NULL;
803 * decode a X509 certificate and make a readable text terminated '\n'.
804 * return the buffer allocated, so must free it later.
806 char *
807 eay_get_x509text(cert)
808 vchar_t *cert;
810 X509 *x509 = NULL;
811 BIO *bio = NULL;
812 char *text = NULL;
813 u_char *bp = NULL;
814 int len = 0;
815 int error = -1;
817 x509 = mem2x509(cert);
818 if (x509 == NULL)
819 goto end;
821 bio = BIO_new(BIO_s_mem());
822 if (bio == NULL)
823 goto end;
825 error = X509_print(bio, x509);
826 if (error != 1) {
827 error = -1;
828 goto end;
831 len = BIO_get_mem_data(bio, &bp);
832 text = racoon_malloc(len + 1);
833 if (text == NULL)
834 goto end;
835 memcpy(text, bp, len);
836 text[len] = '\0';
838 error = 0;
840 end:
841 if (error) {
842 if (text) {
843 racoon_free(text);
844 text = NULL;
846 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
848 if (bio)
849 BIO_free(bio);
850 if (x509)
851 X509_free(x509);
853 return text;
856 /* get X509 structure from buffer. */
857 static X509 *
858 mem2x509(cert)
859 vchar_t *cert;
861 X509 *x509;
863 #ifndef EAYDEBUG
865 u_char *bp;
867 bp = (unsigned char *) cert->v + 1;
869 x509 = d2i_X509(NULL, (void *)&bp, cert->l - 1);
871 #else
873 BIO *bio;
874 int len;
876 bio = BIO_new(BIO_s_mem());
877 if (bio == NULL)
878 return NULL;
879 len = BIO_write(bio, cert->v + 1, cert->l - 1);
880 if (len == -1)
881 return NULL;
882 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
883 BIO_free(bio);
885 #endif
886 return x509;
890 * get a X509 certificate from local file.
891 * a certificate must be PEM format.
892 * Input:
893 * path to a certificate.
894 * Output:
895 * NULL if error occured
896 * other is the cert.
898 vchar_t *
899 eay_get_x509cert(path)
900 char *path;
902 FILE *fp;
903 X509 *x509;
904 vchar_t *cert;
905 u_char *bp;
906 int len;
907 int error;
909 /* Read private key */
910 fp = fopen(path, "r");
911 if (fp == NULL)
912 return NULL;
913 x509 = PEM_read_X509(fp, NULL, NULL, NULL);
914 fclose (fp);
916 if (x509 == NULL)
917 return NULL;
919 len = i2d_X509(x509, NULL);
920 cert = vmalloc(len + 1);
921 if (cert == NULL) {
922 X509_free(x509);
923 return NULL;
925 cert->v[0] = ISAKMP_CERT_X509SIGN;
926 bp = (unsigned char *) &cert->v[1];
927 error = i2d_X509(x509, &bp);
928 X509_free(x509);
930 if (error == 0) {
931 vfree(cert);
932 return NULL;
935 return cert;
939 * check a X509 signature
940 * XXX: to be get hash type from my cert ?
941 * to be handled EVP_dss().
942 * OUT: return -1 when error.
946 eay_check_x509sign(source, sig, cert)
947 vchar_t *source;
948 vchar_t *sig;
949 vchar_t *cert;
951 X509 *x509;
952 EVP_PKEY *evp;
953 int res;
955 x509 = mem2x509(cert);
956 if (x509 == NULL)
957 return -1;
959 evp = X509_get_pubkey(x509);
960 if (! evp) {
961 plog(LLV_ERROR, LOCATION, NULL, "X509_get_pubkey(): %s\n", eay_strerror());
962 X509_free(x509);
963 return -1;
966 res = eay_rsa_verify(source, sig, evp->pkey.rsa);
968 EVP_PKEY_free(evp);
969 X509_free(x509);
971 return res;
975 * check RSA signature
976 * OUT: return -1 when error.
977 * 0 on success
980 eay_check_rsasign(source, sig, rsa)
981 vchar_t *source;
982 vchar_t *sig;
983 RSA *rsa;
985 return eay_rsa_verify(source, sig, rsa);
989 * get PKCS#1 Private Key of PEM format from local file.
991 vchar_t *
992 eay_get_pkcs1privkey(path)
993 char *path;
995 FILE *fp;
996 EVP_PKEY *evp = NULL;
997 vchar_t *pkey = NULL;
998 u_char *bp;
999 int pkeylen;
1000 int error = -1;
1002 /* Read private key */
1003 fp = fopen(path, "r");
1004 if (fp == NULL)
1005 return NULL;
1007 evp = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
1009 fclose (fp);
1011 if (evp == NULL)
1012 return NULL;
1014 pkeylen = i2d_PrivateKey(evp, NULL);
1015 if (pkeylen == 0)
1016 goto end;
1017 pkey = vmalloc(pkeylen);
1018 if (pkey == NULL)
1019 goto end;
1020 bp = (unsigned char *) pkey->v;
1021 pkeylen = i2d_PrivateKey(evp, &bp);
1022 if (pkeylen == 0)
1023 goto end;
1025 error = 0;
1027 end:
1028 if (evp != NULL)
1029 EVP_PKEY_free(evp);
1030 if (error != 0 && pkey != NULL) {
1031 vfree(pkey);
1032 pkey = NULL;
1035 return pkey;
1039 * get PKCS#1 Public Key of PEM format from local file.
1041 vchar_t *
1042 eay_get_pkcs1pubkey(path)
1043 char *path;
1045 FILE *fp;
1046 EVP_PKEY *evp = NULL;
1047 vchar_t *pkey = NULL;
1048 X509 *x509 = NULL;
1049 u_char *bp;
1050 int pkeylen;
1051 int error = -1;
1053 /* Read private key */
1054 fp = fopen(path, "r");
1055 if (fp == NULL)
1056 return NULL;
1058 x509 = PEM_read_X509(fp, NULL, NULL, NULL);
1060 fclose (fp);
1062 if (x509 == NULL)
1063 return NULL;
1065 /* Get public key - eay */
1066 evp = X509_get_pubkey(x509);
1067 if (evp == NULL)
1068 return NULL;
1070 pkeylen = i2d_PublicKey(evp, NULL);
1071 if (pkeylen == 0)
1072 goto end;
1073 pkey = vmalloc(pkeylen);
1074 if (pkey == NULL)
1075 goto end;
1076 bp = (unsigned char *) pkey->v;
1077 pkeylen = i2d_PublicKey(evp, &bp);
1078 if (pkeylen == 0)
1079 goto end;
1081 error = 0;
1082 end:
1083 if (evp != NULL)
1084 EVP_PKEY_free(evp);
1085 if (error != 0 && pkey != NULL) {
1086 vfree(pkey);
1087 pkey = NULL;
1090 return pkey;
1093 vchar_t *
1094 eay_get_x509sign(src, privkey)
1095 vchar_t *src, *privkey;
1097 EVP_PKEY *evp;
1098 u_char *bp = (unsigned char *) privkey->v;
1099 vchar_t *sig = NULL;
1100 int len;
1101 int pad = RSA_PKCS1_PADDING;
1103 /* XXX to be handled EVP_PKEY_DSA */
1104 evp = d2i_PrivateKey(EVP_PKEY_RSA, NULL, (void *)&bp, privkey->l);
1105 if (evp == NULL)
1106 return NULL;
1108 sig = eay_rsa_sign(src, evp->pkey.rsa);
1110 EVP_PKEY_free(evp);
1112 return sig;
1115 vchar_t *
1116 eay_get_rsasign(src, rsa)
1117 vchar_t *src;
1118 RSA *rsa;
1120 return eay_rsa_sign(src, rsa);
1123 vchar_t *
1124 eay_rsa_sign(vchar_t *src, RSA *rsa)
1126 int len;
1127 vchar_t *sig = NULL;
1128 int pad = RSA_PKCS1_PADDING;
1130 len = RSA_size(rsa);
1132 sig = vmalloc(len);
1133 if (sig == NULL)
1134 return NULL;
1136 len = RSA_private_encrypt(src->l, (unsigned char *) src->v,
1137 (unsigned char *) sig->v, rsa, pad);
1139 if (len == 0 || len != sig->l) {
1140 vfree(sig);
1141 sig = NULL;
1144 return sig;
1148 eay_rsa_verify(src, sig, rsa)
1149 vchar_t *src, *sig;
1150 RSA *rsa;
1152 vchar_t *xbuf = NULL;
1153 int pad = RSA_PKCS1_PADDING;
1154 int len = 0;
1155 int error;
1157 len = RSA_size(rsa);
1158 xbuf = vmalloc(len);
1159 if (xbuf == NULL) {
1160 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
1161 return -1;
1164 len = RSA_public_decrypt(sig->l, (unsigned char *) sig->v,
1165 (unsigned char *) xbuf->v, rsa, pad);
1166 if (len == 0 || len != src->l) {
1167 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
1168 vfree(xbuf);
1169 return -1;
1172 error = memcmp(src->v, xbuf->v, src->l);
1173 vfree(xbuf);
1174 if (error != 0)
1175 return -1;
1177 return 0;
1181 * get error string
1182 * MUST load ERR_load_crypto_strings() first.
1184 char *
1185 eay_strerror()
1187 static char ebuf[512];
1188 int len = 0, n;
1189 unsigned long l;
1190 char buf[200];
1191 const char *file, *data;
1192 int line, flags;
1193 unsigned long es;
1195 es = CRYPTO_thread_id();
1197 while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0){
1198 n = snprintf(ebuf + len, sizeof(ebuf) - len,
1199 "%lu:%s:%s:%d:%s ",
1200 es, ERR_error_string(l, buf), file, line,
1201 (flags & ERR_TXT_STRING) ? data : "");
1202 if (n < 0 || n >= sizeof(ebuf) - len)
1203 break;
1204 len += n;
1205 if (sizeof(ebuf) < len)
1206 break;
1209 return ebuf;
1212 vchar_t *
1213 evp_crypt(vchar_t *data, vchar_t *key, vchar_t *iv, const EVP_CIPHER *e, int enc)
1215 vchar_t *res;
1216 EVP_CIPHER_CTX ctx;
1218 if (!e)
1219 return NULL;
1221 if (data->l % EVP_CIPHER_block_size(e))
1222 return NULL;
1224 if ((res = vmalloc(data->l)) == NULL)
1225 return NULL;
1227 EVP_CIPHER_CTX_init(&ctx);
1229 switch(EVP_CIPHER_nid(e)){
1230 case NID_bf_cbc:
1231 case NID_bf_ecb:
1232 case NID_bf_cfb64:
1233 case NID_bf_ofb64:
1234 case NID_cast5_cbc:
1235 case NID_cast5_ecb:
1236 case NID_cast5_cfb64:
1237 case NID_cast5_ofb64:
1238 /* XXX: can we do that also for algos with a fixed key size ?
1240 /* init context without key/iv
1242 if (!EVP_CipherInit(&ctx, e, NULL, NULL, enc))
1244 OpenSSL_BUG();
1245 vfree(res);
1246 return NULL;
1249 /* update key size
1251 if (!EVP_CIPHER_CTX_set_key_length(&ctx, key->l))
1253 OpenSSL_BUG();
1254 vfree(res);
1255 return NULL;
1258 /* finalize context init with desired key size
1260 if (!EVP_CipherInit(&ctx, NULL, (u_char *) key->v,
1261 (u_char *) iv->v, enc))
1263 OpenSSL_BUG();
1264 vfree(res);
1265 return NULL;
1267 break;
1268 default:
1269 if (!EVP_CipherInit(&ctx, e, (u_char *) key->v,
1270 (u_char *) iv->v, enc)) {
1271 OpenSSL_BUG();
1272 vfree(res);
1273 return NULL;
1277 /* disable openssl padding */
1278 EVP_CIPHER_CTX_set_padding(&ctx, 0);
1280 if (!EVP_Cipher(&ctx, (u_char *) res->v, (u_char *) data->v, data->l)) {
1281 OpenSSL_BUG();
1282 vfree(res);
1283 return NULL;
1286 EVP_CIPHER_CTX_cleanup(&ctx);
1288 return res;
1292 evp_weakkey(vchar_t *key, const EVP_CIPHER *e)
1294 return 0;
1298 evp_keylen(int len, const EVP_CIPHER *e)
1300 if (!e)
1301 return -1;
1302 /* EVP functions return lengths in bytes, ipsec-tools
1303 * uses lengths in bits, therefore conversion is required. --AK
1305 if (len != 0 && len != (EVP_CIPHER_key_length(e) << 3))
1306 return -1;
1308 return EVP_CIPHER_key_length(e) << 3;
1312 * DES-CBC
1314 vchar_t *
1315 eay_des_encrypt(data, key, iv)
1316 vchar_t *data, *key, *iv;
1318 return evp_crypt(data, key, iv, EVP_des_cbc(), 1);
1321 vchar_t *
1322 eay_des_decrypt(data, key, iv)
1323 vchar_t *data, *key, *iv;
1325 return evp_crypt(data, key, iv, EVP_des_cbc(), 0);
1329 eay_des_weakkey(key)
1330 vchar_t *key;
1332 #ifdef USE_NEW_DES_API
1333 return DES_is_weak_key((void *)key->v);
1334 #else
1335 return des_is_weak_key((void *)key->v);
1336 #endif
1340 eay_des_keylen(len)
1341 int len;
1343 return evp_keylen(len, EVP_des_cbc());
1346 #ifdef HAVE_OPENSSL_IDEA_H
1348 * IDEA-CBC
1350 vchar_t *
1351 eay_idea_encrypt(data, key, iv)
1352 vchar_t *data, *key, *iv;
1354 vchar_t *res;
1355 IDEA_KEY_SCHEDULE ks;
1357 idea_set_encrypt_key((unsigned char *)key->v, &ks);
1359 /* allocate buffer for result */
1360 if ((res = vmalloc(data->l)) == NULL)
1361 return NULL;
1363 /* decryption data */
1364 idea_cbc_encrypt((unsigned char *)data->v, (unsigned char *)res->v, data->l,
1365 &ks, (unsigned char *)iv->v, IDEA_ENCRYPT);
1367 return res;
1370 vchar_t *
1371 eay_idea_decrypt(data, key, iv)
1372 vchar_t *data, *key, *iv;
1374 vchar_t *res;
1375 IDEA_KEY_SCHEDULE ks, dks;
1377 idea_set_encrypt_key((unsigned char *)key->v, &ks);
1378 idea_set_decrypt_key(&ks, &dks);
1380 /* allocate buffer for result */
1381 if ((res = vmalloc(data->l)) == NULL)
1382 return NULL;
1384 /* decryption data */
1385 idea_cbc_encrypt((unsigned char *)data->v, (unsigned char *)res->v, data->l,
1386 &dks, (unsigned char *)iv->v, IDEA_DECRYPT);
1388 return res;
1392 eay_idea_weakkey(key)
1393 vchar_t *key;
1395 return 0; /* XXX */
1399 eay_idea_keylen(len)
1400 int len;
1402 if (len != 0 && len != 128)
1403 return -1;
1404 return 128;
1406 #endif
1409 * BLOWFISH-CBC
1411 vchar_t *
1412 eay_bf_encrypt(data, key, iv)
1413 vchar_t *data, *key, *iv;
1415 return evp_crypt(data, key, iv, EVP_bf_cbc(), 1);
1418 vchar_t *
1419 eay_bf_decrypt(data, key, iv)
1420 vchar_t *data, *key, *iv;
1422 return evp_crypt(data, key, iv, EVP_bf_cbc(), 0);
1426 eay_bf_weakkey(key)
1427 vchar_t *key;
1429 return 0; /* XXX to be done. refer to RFC 2451 */
1433 eay_bf_keylen(len)
1434 int len;
1436 if (len == 0)
1437 return 448;
1438 if (len < 40 || len > 448)
1439 return -1;
1440 return len;
1443 #ifdef HAVE_OPENSSL_RC5_H
1445 * RC5-CBC
1447 vchar_t *
1448 eay_rc5_encrypt(data, key, iv)
1449 vchar_t *data, *key, *iv;
1451 vchar_t *res;
1452 RC5_32_KEY ks;
1454 /* in RFC 2451, there is information about the number of round. */
1455 RC5_32_set_key(&ks, key->l, (unsigned char *)key->v, 16);
1457 /* allocate buffer for result */
1458 if ((res = vmalloc(data->l)) == NULL)
1459 return NULL;
1461 /* decryption data */
1462 RC5_32_cbc_encrypt((unsigned char *)data->v, (unsigned char *)res->v, data->l,
1463 &ks, (unsigned char *)iv->v, RC5_ENCRYPT);
1465 return res;
1468 vchar_t *
1469 eay_rc5_decrypt(data, key, iv)
1470 vchar_t *data, *key, *iv;
1472 vchar_t *res;
1473 RC5_32_KEY ks;
1475 /* in RFC 2451, there is information about the number of round. */
1476 RC5_32_set_key(&ks, key->l, (unsigned char *)key->v, 16);
1478 /* allocate buffer for result */
1479 if ((res = vmalloc(data->l)) == NULL)
1480 return NULL;
1482 /* decryption data */
1483 RC5_32_cbc_encrypt((unsigned char *)data->v, (unsigned char *)res->v, data->l,
1484 &ks, (unsigned char *)iv->v, RC5_DECRYPT);
1486 return res;
1490 eay_rc5_weakkey(key)
1491 vchar_t *key;
1493 return 0; /* No known weak keys when used with 16 rounds. */
1498 eay_rc5_keylen(len)
1499 int len;
1501 if (len == 0)
1502 return 128;
1503 if (len < 40 || len > 2040)
1504 return -1;
1505 return len;
1507 #endif
1510 * 3DES-CBC
1512 vchar_t *
1513 eay_3des_encrypt(data, key, iv)
1514 vchar_t *data, *key, *iv;
1516 return evp_crypt(data, key, iv, EVP_des_ede3_cbc(), 1);
1519 vchar_t *
1520 eay_3des_decrypt(data, key, iv)
1521 vchar_t *data, *key, *iv;
1523 return evp_crypt(data, key, iv, EVP_des_ede3_cbc(), 0);
1527 eay_3des_weakkey(key)
1528 vchar_t *key;
1530 #ifdef USE_NEW_DES_API
1531 return (DES_is_weak_key((void *)key->v) ||
1532 DES_is_weak_key((void *)(key->v + 8)) ||
1533 DES_is_weak_key((void *)(key->v + 16)));
1534 #else
1535 if (key->l < 24)
1536 return 0;
1538 return (des_is_weak_key((void *)key->v) ||
1539 des_is_weak_key((void *)(key->v + 8)) ||
1540 des_is_weak_key((void *)(key->v + 16)));
1541 #endif
1545 eay_3des_keylen(len)
1546 int len;
1548 if (len != 0 && len != 192)
1549 return -1;
1550 return 192;
1554 * CAST-CBC
1556 vchar_t *
1557 eay_cast_encrypt(data, key, iv)
1558 vchar_t *data, *key, *iv;
1560 return evp_crypt(data, key, iv, EVP_cast5_cbc(), 1);
1563 vchar_t *
1564 eay_cast_decrypt(data, key, iv)
1565 vchar_t *data, *key, *iv;
1567 return evp_crypt(data, key, iv, EVP_cast5_cbc(), 0);
1571 eay_cast_weakkey(key)
1572 vchar_t *key;
1574 return 0; /* No known weak keys. */
1578 eay_cast_keylen(len)
1579 int len;
1581 if (len == 0)
1582 return 128;
1583 if (len < 40 || len > 128)
1584 return -1;
1585 return len;
1589 * AES(RIJNDAEL)-CBC
1591 #ifndef HAVE_OPENSSL_AES_H
1592 vchar_t *
1593 eay_aes_encrypt(data, key, iv)
1594 vchar_t *data, *key, *iv;
1596 vchar_t *res;
1597 keyInstance k;
1598 cipherInstance c;
1600 memset(&k, 0, sizeof(k));
1601 if (rijndael_makeKey(&k, DIR_ENCRYPT, key->l << 3, key->v) < 0)
1602 return NULL;
1604 /* allocate buffer for result */
1605 if ((res = vmalloc(data->l)) == NULL)
1606 return NULL;
1608 /* encryption data */
1609 memset(&c, 0, sizeof(c));
1610 if (rijndael_cipherInit(&c, MODE_CBC, iv->v) < 0){
1611 vfree(res);
1612 return NULL;
1614 if (rijndael_blockEncrypt(&c, &k, data->v, data->l << 3, res->v) < 0){
1615 vfree(res);
1616 return NULL;
1619 return res;
1622 vchar_t *
1623 eay_aes_decrypt(data, key, iv)
1624 vchar_t *data, *key, *iv;
1626 vchar_t *res;
1627 keyInstance k;
1628 cipherInstance c;
1630 memset(&k, 0, sizeof(k));
1631 if (rijndael_makeKey(&k, DIR_DECRYPT, key->l << 3, key->v) < 0)
1632 return NULL;
1634 /* allocate buffer for result */
1635 if ((res = vmalloc(data->l)) == NULL)
1636 return NULL;
1638 /* decryption data */
1639 memset(&c, 0, sizeof(c));
1640 if (rijndael_cipherInit(&c, MODE_CBC, iv->v) < 0){
1641 vfree(res);
1642 return NULL;
1644 if (rijndael_blockDecrypt(&c, &k, data->v, data->l << 3, res->v) < 0){
1645 vfree(res);
1646 return NULL;
1649 return res;
1651 #else
1652 static inline const EVP_CIPHER *
1653 aes_evp_by_keylen(int keylen)
1655 switch(keylen) {
1656 case 16:
1657 case 128:
1658 return EVP_aes_128_cbc();
1659 case 24:
1660 case 192:
1661 return EVP_aes_192_cbc();
1662 case 32:
1663 case 256:
1664 return EVP_aes_256_cbc();
1665 default:
1666 return NULL;
1670 vchar_t *
1671 eay_aes_encrypt(data, key, iv)
1672 vchar_t *data, *key, *iv;
1674 return evp_crypt(data, key, iv, aes_evp_by_keylen(key->l), 1);
1677 vchar_t *
1678 eay_aes_decrypt(data, key, iv)
1679 vchar_t *data, *key, *iv;
1681 return evp_crypt(data, key, iv, aes_evp_by_keylen(key->l), 0);
1683 #endif
1686 eay_aes_weakkey(key)
1687 vchar_t *key;
1689 return 0;
1693 eay_aes_keylen(len)
1694 int len;
1696 if (len == 0)
1697 return 128;
1698 if (len != 128 && len != 192 && len != 256)
1699 return -1;
1700 return len;
1703 #if defined(HAVE_OPENSSL_CAMELLIA_H)
1705 * CAMELLIA-CBC
1707 static inline const EVP_CIPHER *
1708 camellia_evp_by_keylen(int keylen)
1710 switch(keylen) {
1711 case 16:
1712 case 128:
1713 return EVP_camellia_128_cbc();
1714 case 24:
1715 case 192:
1716 return EVP_camellia_192_cbc();
1717 case 32:
1718 case 256:
1719 return EVP_camellia_256_cbc();
1720 default:
1721 return NULL;
1725 vchar_t *
1726 eay_camellia_encrypt(data, key, iv)
1727 vchar_t *data, *key, *iv;
1729 return evp_crypt(data, key, iv, camellia_evp_by_keylen(key->l), 1);
1732 vchar_t *
1733 eay_camellia_decrypt(data, key, iv)
1734 vchar_t *data, *key, *iv;
1736 return evp_crypt(data, key, iv, camellia_evp_by_keylen(key->l), 0);
1740 eay_camellia_weakkey(key)
1741 vchar_t *key;
1743 return 0;
1747 eay_camellia_keylen(len)
1748 int len;
1750 if (len == 0)
1751 return 128;
1752 if (len != 128 && len != 192 && len != 256)
1753 return -1;
1754 return len;
1757 #endif
1759 /* for ipsec part */
1761 eay_null_hashlen()
1763 return 0;
1767 eay_kpdk_hashlen()
1769 return 0;
1773 eay_twofish_keylen(len)
1774 int len;
1776 if (len < 0 || len > 256)
1777 return -1;
1778 return len;
1782 eay_null_keylen(len)
1783 int len;
1785 return 0;
1789 * HMAC functions
1791 static caddr_t
1792 eay_hmac_init(key, md)
1793 vchar_t *key;
1794 const EVP_MD *md;
1796 HMAC_CTX *c = racoon_malloc(sizeof(*c));
1798 HMAC_Init(c, key->v, key->l, md);
1800 return (caddr_t)c;
1803 #ifdef WITH_SHA2
1805 * HMAC SHA2-512
1807 vchar_t *
1808 eay_hmacsha2_512_one(key, data)
1809 vchar_t *key, *data;
1811 vchar_t *res;
1812 caddr_t ctx;
1814 ctx = eay_hmacsha2_512_init(key);
1815 eay_hmacsha2_512_update(ctx, data);
1816 res = eay_hmacsha2_512_final(ctx);
1818 return(res);
1821 caddr_t
1822 eay_hmacsha2_512_init(key)
1823 vchar_t *key;
1825 return eay_hmac_init(key, EVP_sha2_512());
1828 void
1829 eay_hmacsha2_512_update(c, data)
1830 caddr_t c;
1831 vchar_t *data;
1833 HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
1836 vchar_t *
1837 eay_hmacsha2_512_final(c)
1838 caddr_t c;
1840 vchar_t *res;
1841 unsigned int l;
1843 if ((res = vmalloc(SHA512_DIGEST_LENGTH)) == 0)
1844 return NULL;
1846 HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
1847 res->l = l;
1848 HMAC_cleanup((HMAC_CTX *)c);
1849 (void)racoon_free(c);
1851 if (SHA512_DIGEST_LENGTH != res->l) {
1852 plog(LLV_ERROR, LOCATION, NULL,
1853 "hmac sha2_512 length mismatch %zd.\n", res->l);
1854 vfree(res);
1855 return NULL;
1858 return(res);
1862 * HMAC SHA2-384
1864 vchar_t *
1865 eay_hmacsha2_384_one(key, data)
1866 vchar_t *key, *data;
1868 vchar_t *res;
1869 caddr_t ctx;
1871 ctx = eay_hmacsha2_384_init(key);
1872 eay_hmacsha2_384_update(ctx, data);
1873 res = eay_hmacsha2_384_final(ctx);
1875 return(res);
1878 caddr_t
1879 eay_hmacsha2_384_init(key)
1880 vchar_t *key;
1882 return eay_hmac_init(key, EVP_sha2_384());
1885 void
1886 eay_hmacsha2_384_update(c, data)
1887 caddr_t c;
1888 vchar_t *data;
1890 HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
1893 vchar_t *
1894 eay_hmacsha2_384_final(c)
1895 caddr_t c;
1897 vchar_t *res;
1898 unsigned int l;
1900 if ((res = vmalloc(SHA384_DIGEST_LENGTH)) == 0)
1901 return NULL;
1903 HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
1904 res->l = l;
1905 HMAC_cleanup((HMAC_CTX *)c);
1906 (void)racoon_free(c);
1908 if (SHA384_DIGEST_LENGTH != res->l) {
1909 plog(LLV_ERROR, LOCATION, NULL,
1910 "hmac sha2_384 length mismatch %zd.\n", res->l);
1911 vfree(res);
1912 return NULL;
1915 return(res);
1919 * HMAC SHA2-256
1921 vchar_t *
1922 eay_hmacsha2_256_one(key, data)
1923 vchar_t *key, *data;
1925 vchar_t *res;
1926 caddr_t ctx;
1928 ctx = eay_hmacsha2_256_init(key);
1929 eay_hmacsha2_256_update(ctx, data);
1930 res = eay_hmacsha2_256_final(ctx);
1932 return(res);
1935 caddr_t
1936 eay_hmacsha2_256_init(key)
1937 vchar_t *key;
1939 return eay_hmac_init(key, EVP_sha2_256());
1942 void
1943 eay_hmacsha2_256_update(c, data)
1944 caddr_t c;
1945 vchar_t *data;
1947 HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
1950 vchar_t *
1951 eay_hmacsha2_256_final(c)
1952 caddr_t c;
1954 vchar_t *res;
1955 unsigned int l;
1957 if ((res = vmalloc(SHA256_DIGEST_LENGTH)) == 0)
1958 return NULL;
1960 HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
1961 res->l = l;
1962 HMAC_cleanup((HMAC_CTX *)c);
1963 (void)racoon_free(c);
1965 if (SHA256_DIGEST_LENGTH != res->l) {
1966 plog(LLV_ERROR, LOCATION, NULL,
1967 "hmac sha2_256 length mismatch %zd.\n", res->l);
1968 vfree(res);
1969 return NULL;
1972 return(res);
1974 #endif /* WITH_SHA2 */
1977 * HMAC SHA1
1979 vchar_t *
1980 eay_hmacsha1_one(key, data)
1981 vchar_t *key, *data;
1983 vchar_t *res;
1984 caddr_t ctx;
1986 ctx = eay_hmacsha1_init(key);
1987 eay_hmacsha1_update(ctx, data);
1988 res = eay_hmacsha1_final(ctx);
1990 return(res);
1993 caddr_t
1994 eay_hmacsha1_init(key)
1995 vchar_t *key;
1997 return eay_hmac_init(key, EVP_sha1());
2000 void
2001 eay_hmacsha1_update(c, data)
2002 caddr_t c;
2003 vchar_t *data;
2005 HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
2008 vchar_t *
2009 eay_hmacsha1_final(c)
2010 caddr_t c;
2012 vchar_t *res;
2013 unsigned int l;
2015 if ((res = vmalloc(SHA_DIGEST_LENGTH)) == 0)
2016 return NULL;
2018 HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
2019 res->l = l;
2020 HMAC_cleanup((HMAC_CTX *)c);
2021 (void)racoon_free(c);
2023 if (SHA_DIGEST_LENGTH != res->l) {
2024 plog(LLV_ERROR, LOCATION, NULL,
2025 "hmac sha1 length mismatch %zd.\n", res->l);
2026 vfree(res);
2027 return NULL;
2030 return(res);
2034 * HMAC MD5
2036 vchar_t *
2037 eay_hmacmd5_one(key, data)
2038 vchar_t *key, *data;
2040 vchar_t *res;
2041 caddr_t ctx;
2043 ctx = eay_hmacmd5_init(key);
2044 eay_hmacmd5_update(ctx, data);
2045 res = eay_hmacmd5_final(ctx);
2047 return(res);
2050 caddr_t
2051 eay_hmacmd5_init(key)
2052 vchar_t *key;
2054 return eay_hmac_init(key, EVP_md5());
2057 void
2058 eay_hmacmd5_update(c, data)
2059 caddr_t c;
2060 vchar_t *data;
2062 HMAC_Update((HMAC_CTX *)c, (unsigned char *) data->v, data->l);
2065 vchar_t *
2066 eay_hmacmd5_final(c)
2067 caddr_t c;
2069 vchar_t *res;
2070 unsigned int l;
2072 if ((res = vmalloc(MD5_DIGEST_LENGTH)) == 0)
2073 return NULL;
2075 HMAC_Final((HMAC_CTX *)c, (unsigned char *) res->v, &l);
2076 res->l = l;
2077 HMAC_cleanup((HMAC_CTX *)c);
2078 (void)racoon_free(c);
2080 if (MD5_DIGEST_LENGTH != res->l) {
2081 plog(LLV_ERROR, LOCATION, NULL,
2082 "hmac md5 length mismatch %zd.\n", res->l);
2083 vfree(res);
2084 return NULL;
2087 return(res);
2090 #ifdef WITH_SHA2
2092 * SHA2-512 functions
2094 caddr_t
2095 eay_sha2_512_init()
2097 SHA512_CTX *c = racoon_malloc(sizeof(*c));
2099 SHA512_Init(c);
2101 return((caddr_t)c);
2104 void
2105 eay_sha2_512_update(c, data)
2106 caddr_t c;
2107 vchar_t *data;
2109 SHA512_Update((SHA512_CTX *)c, (unsigned char *) data->v, data->l);
2111 return;
2114 vchar_t *
2115 eay_sha2_512_final(c)
2116 caddr_t c;
2118 vchar_t *res;
2120 if ((res = vmalloc(SHA512_DIGEST_LENGTH)) == 0)
2121 return(0);
2123 SHA512_Final((unsigned char *) res->v, (SHA512_CTX *)c);
2124 (void)racoon_free(c);
2126 return(res);
2129 vchar_t *
2130 eay_sha2_512_one(data)
2131 vchar_t *data;
2133 caddr_t ctx;
2134 vchar_t *res;
2136 ctx = eay_sha2_512_init();
2137 eay_sha2_512_update(ctx, data);
2138 res = eay_sha2_512_final(ctx);
2140 return(res);
2144 eay_sha2_512_hashlen()
2146 return SHA512_DIGEST_LENGTH << 3;
2148 #endif
2150 #ifdef WITH_SHA2
2152 * SHA2-384 functions
2154 caddr_t
2155 eay_sha2_384_init()
2157 SHA384_CTX *c = racoon_malloc(sizeof(*c));
2159 SHA384_Init(c);
2161 return((caddr_t)c);
2164 void
2165 eay_sha2_384_update(c, data)
2166 caddr_t c;
2167 vchar_t *data;
2169 SHA384_Update((SHA384_CTX *)c, (unsigned char *) data->v, data->l);
2171 return;
2174 vchar_t *
2175 eay_sha2_384_final(c)
2176 caddr_t c;
2178 vchar_t *res;
2180 if ((res = vmalloc(SHA384_DIGEST_LENGTH)) == 0)
2181 return(0);
2183 SHA384_Final((unsigned char *) res->v, (SHA384_CTX *)c);
2184 (void)racoon_free(c);
2186 return(res);
2189 vchar_t *
2190 eay_sha2_384_one(data)
2191 vchar_t *data;
2193 caddr_t ctx;
2194 vchar_t *res;
2196 ctx = eay_sha2_384_init();
2197 eay_sha2_384_update(ctx, data);
2198 res = eay_sha2_384_final(ctx);
2200 return(res);
2204 eay_sha2_384_hashlen()
2206 return SHA384_DIGEST_LENGTH << 3;
2208 #endif
2210 #ifdef WITH_SHA2
2212 * SHA2-256 functions
2214 caddr_t
2215 eay_sha2_256_init()
2217 SHA256_CTX *c = racoon_malloc(sizeof(*c));
2219 SHA256_Init(c);
2221 return((caddr_t)c);
2224 void
2225 eay_sha2_256_update(c, data)
2226 caddr_t c;
2227 vchar_t *data;
2229 SHA256_Update((SHA256_CTX *)c, (unsigned char *) data->v, data->l);
2231 return;
2234 vchar_t *
2235 eay_sha2_256_final(c)
2236 caddr_t c;
2238 vchar_t *res;
2240 if ((res = vmalloc(SHA256_DIGEST_LENGTH)) == 0)
2241 return(0);
2243 SHA256_Final((unsigned char *) res->v, (SHA256_CTX *)c);
2244 (void)racoon_free(c);
2246 return(res);
2249 vchar_t *
2250 eay_sha2_256_one(data)
2251 vchar_t *data;
2253 caddr_t ctx;
2254 vchar_t *res;
2256 ctx = eay_sha2_256_init();
2257 eay_sha2_256_update(ctx, data);
2258 res = eay_sha2_256_final(ctx);
2260 return(res);
2264 eay_sha2_256_hashlen()
2266 return SHA256_DIGEST_LENGTH << 3;
2268 #endif
2271 * SHA functions
2273 caddr_t
2274 eay_sha1_init()
2276 SHA_CTX *c = racoon_malloc(sizeof(*c));
2278 SHA1_Init(c);
2280 return((caddr_t)c);
2283 void
2284 eay_sha1_update(c, data)
2285 caddr_t c;
2286 vchar_t *data;
2288 SHA1_Update((SHA_CTX *)c, data->v, data->l);
2290 return;
2293 vchar_t *
2294 eay_sha1_final(c)
2295 caddr_t c;
2297 vchar_t *res;
2299 if ((res = vmalloc(SHA_DIGEST_LENGTH)) == 0)
2300 return(0);
2302 SHA1_Final((unsigned char *) res->v, (SHA_CTX *)c);
2303 (void)racoon_free(c);
2305 return(res);
2308 vchar_t *
2309 eay_sha1_one(data)
2310 vchar_t *data;
2312 caddr_t ctx;
2313 vchar_t *res;
2315 ctx = eay_sha1_init();
2316 eay_sha1_update(ctx, data);
2317 res = eay_sha1_final(ctx);
2319 return(res);
2323 eay_sha1_hashlen()
2325 return SHA_DIGEST_LENGTH << 3;
2329 * MD5 functions
2331 caddr_t
2332 eay_md5_init()
2334 MD5_CTX *c = racoon_malloc(sizeof(*c));
2336 MD5_Init(c);
2338 return((caddr_t)c);
2341 void
2342 eay_md5_update(c, data)
2343 caddr_t c;
2344 vchar_t *data;
2346 MD5_Update((MD5_CTX *)c, data->v, data->l);
2348 return;
2351 vchar_t *
2352 eay_md5_final(c)
2353 caddr_t c;
2355 vchar_t *res;
2357 if ((res = vmalloc(MD5_DIGEST_LENGTH)) == 0)
2358 return(0);
2360 MD5_Final((unsigned char *) res->v, (MD5_CTX *)c);
2361 (void)racoon_free(c);
2363 return(res);
2366 vchar_t *
2367 eay_md5_one(data)
2368 vchar_t *data;
2370 caddr_t ctx;
2371 vchar_t *res;
2373 ctx = eay_md5_init();
2374 eay_md5_update(ctx, data);
2375 res = eay_md5_final(ctx);
2377 return(res);
2381 eay_md5_hashlen()
2383 return MD5_DIGEST_LENGTH << 3;
2387 * eay_set_random
2388 * size: number of bytes.
2390 vchar_t *
2391 eay_set_random(size)
2392 u_int32_t size;
2394 BIGNUM *r = NULL;
2395 vchar_t *res = 0;
2397 if ((r = BN_new()) == NULL)
2398 goto end;
2399 BN_rand(r, size * 8, 0, 0);
2400 eay_bn2v(&res, r);
2402 end:
2403 if (r)
2404 BN_free(r);
2405 return(res);
2408 /* DH */
2410 eay_dh_generate(prime, g, publen, pub, priv)
2411 vchar_t *prime, **pub, **priv;
2412 u_int publen;
2413 u_int32_t g;
2415 BIGNUM *p = NULL;
2416 DH *dh = NULL;
2417 int error = -1;
2419 /* initialize */
2420 /* pre-process to generate number */
2421 if (eay_v2bn(&p, prime) < 0)
2422 goto end;
2424 if ((dh = DH_new()) == NULL)
2425 goto end;
2426 dh->p = p;
2427 p = NULL; /* p is now part of dh structure */
2428 dh->g = NULL;
2429 if ((dh->g = BN_new()) == NULL)
2430 goto end;
2431 if (!BN_set_word(dh->g, g))
2432 goto end;
2434 if (publen != 0)
2435 dh->length = publen;
2437 /* generate public and private number */
2438 if (!DH_generate_key(dh))
2439 goto end;
2441 /* copy results to buffers */
2442 if (eay_bn2v(pub, dh->pub_key) < 0)
2443 goto end;
2444 if (eay_bn2v(priv, dh->priv_key) < 0) {
2445 vfree(*pub);
2446 goto end;
2449 error = 0;
2451 end:
2452 if (dh != NULL)
2453 DH_free(dh);
2454 if (p != 0)
2455 BN_free(p);
2456 return(error);
2460 eay_dh_compute(prime, g, pub, priv, pub2, key)
2461 vchar_t *prime, *pub, *priv, *pub2, **key;
2462 u_int32_t g;
2464 BIGNUM *dh_pub = NULL;
2465 DH *dh = NULL;
2466 int l;
2467 unsigned char *v = NULL;
2468 int error = -1;
2470 /* make public number to compute */
2471 if (eay_v2bn(&dh_pub, pub2) < 0)
2472 goto end;
2474 /* make DH structure */
2475 if ((dh = DH_new()) == NULL)
2476 goto end;
2477 if (eay_v2bn(&dh->p, prime) < 0)
2478 goto end;
2479 if (eay_v2bn(&dh->pub_key, pub) < 0)
2480 goto end;
2481 if (eay_v2bn(&dh->priv_key, priv) < 0)
2482 goto end;
2483 dh->length = pub2->l * 8;
2485 dh->g = NULL;
2486 if ((dh->g = BN_new()) == NULL)
2487 goto end;
2488 if (!BN_set_word(dh->g, g))
2489 goto end;
2491 if ((v = racoon_calloc(prime->l, sizeof(u_char))) == NULL)
2492 goto end;
2493 if ((l = DH_compute_key(v, dh_pub, dh)) == -1)
2494 goto end;
2495 memcpy((*key)->v + (prime->l - l), v, l);
2497 error = 0;
2499 end:
2500 if (dh_pub != NULL)
2501 BN_free(dh_pub);
2502 if (dh != NULL)
2503 DH_free(dh);
2504 if (v != NULL)
2505 racoon_free(v);
2506 return(error);
2510 * convert vchar_t <-> BIGNUM.
2512 * vchar_t: unit is u_char, network endian, most significant byte first.
2513 * BIGNUM: unit is BN_ULONG, each of BN_ULONG is in host endian,
2514 * least significant BN_ULONG must come first.
2516 * hex value of "0x3ffe050104" is represented as follows:
2517 * vchar_t: 3f fe 05 01 04
2518 * BIGNUM (BN_ULONG = u_int8_t): 04 01 05 fe 3f
2519 * BIGNUM (BN_ULONG = u_int16_t): 0x0104 0xfe05 0x003f
2520 * BIGNUM (BN_ULONG = u_int32_t_t): 0xfe050104 0x0000003f
2523 eay_v2bn(bn, var)
2524 BIGNUM **bn;
2525 vchar_t *var;
2527 if ((*bn = BN_bin2bn((unsigned char *) var->v, var->l, NULL)) == NULL)
2528 return -1;
2530 return 0;
2534 eay_bn2v(var, bn)
2535 vchar_t **var;
2536 BIGNUM *bn;
2538 *var = vmalloc(bn->top * BN_BYTES);
2539 if (*var == NULL)
2540 return(-1);
2542 (*var)->l = BN_bn2bin(bn, (unsigned char *) (*var)->v);
2544 return 0;
2547 void
2548 eay_init()
2550 OpenSSL_add_all_algorithms();
2551 ERR_load_crypto_strings();
2552 #ifdef HAVE_OPENSSL_ENGINE_H
2553 ENGINE_load_builtin_engines();
2554 ENGINE_register_all_complete();
2555 #endif
2558 vchar_t *
2559 base64_decode(char *in, long inlen)
2561 BIO *bio=NULL, *b64=NULL;
2562 vchar_t *res = NULL;
2563 char *outb;
2564 long outlen;
2566 outb = malloc(inlen * 2);
2567 if (outb == NULL)
2568 goto out;
2569 bio = BIO_new_mem_buf(in, inlen);
2570 b64 = BIO_new(BIO_f_base64());
2571 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
2572 bio = BIO_push(b64, bio);
2574 outlen = BIO_read(bio, outb, inlen * 2);
2575 if (outlen <= 0) {
2576 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
2577 goto out;
2580 res = vmalloc(outlen);
2581 if (!res)
2582 goto out;
2584 memcpy(res->v, outb, outlen);
2586 out:
2587 if (outb)
2588 free(outb);
2589 if (bio)
2590 BIO_free_all(bio);
2592 return res;
2595 vchar_t *
2596 base64_encode(char *in, long inlen)
2598 BIO *bio=NULL, *b64=NULL;
2599 char *ptr;
2600 long plen = -1;
2601 vchar_t *res = NULL;
2603 bio = BIO_new(BIO_s_mem());
2604 b64 = BIO_new(BIO_f_base64());
2605 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
2606 bio = BIO_push(b64, bio);
2608 BIO_write(bio, in, inlen);
2609 BIO_flush(bio);
2611 plen = BIO_get_mem_data(bio, &ptr);
2612 res = vmalloc(plen+1);
2613 if (!res)
2614 goto out;
2616 memcpy (res->v, ptr, plen);
2617 res->v[plen] = '\0';
2619 out:
2620 if (bio)
2621 BIO_free_all(bio);
2623 return res;
2626 static RSA *
2627 binbuf_pubkey2rsa(vchar_t *binbuf)
2629 BIGNUM *exp, *mod;
2630 RSA *rsa_pub = NULL;
2632 if (binbuf->v[0] > binbuf->l - 1) {
2633 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: decoded string doesn't make sense.\n");
2634 goto out;
2637 exp = BN_bin2bn((unsigned char *) (binbuf->v + 1), binbuf->v[0], NULL);
2638 mod = BN_bin2bn((unsigned char *) (binbuf->v + binbuf->v[0] + 1),
2639 binbuf->l - binbuf->v[0] - 1, NULL);
2640 rsa_pub = RSA_new();
2642 if (!exp || !mod || !rsa_pub) {
2643 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey parsing error: %s\n", eay_strerror());
2644 if (exp)
2645 BN_free(exp);
2646 if (mod)
2647 BN_free(exp);
2648 if (rsa_pub)
2649 RSA_free(rsa_pub);
2650 rsa_pub = NULL;
2651 goto out;
2654 rsa_pub->n = mod;
2655 rsa_pub->e = exp;
2657 out:
2658 return rsa_pub;
2661 RSA *
2662 base64_pubkey2rsa(char *in)
2664 BIGNUM *exp, *mod;
2665 RSA *rsa_pub = NULL;
2666 vchar_t *binbuf;
2668 if (strncmp(in, "0s", 2) != 0) {
2669 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: doesn't start with '0s'\n");
2670 return NULL;
2673 binbuf = base64_decode(in + 2, strlen(in + 2));
2674 if (!binbuf) {
2675 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: Base64 decoding failed.\n");
2676 return NULL;
2679 if (binbuf->v[0] > binbuf->l - 1) {
2680 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: decoded string doesn't make sense.\n");
2681 goto out;
2684 rsa_pub = binbuf_pubkey2rsa(binbuf);
2686 out:
2687 if (binbuf)
2688 vfree(binbuf);
2690 return rsa_pub;
2693 RSA *
2694 bignum_pubkey2rsa(BIGNUM *in)
2696 RSA *rsa_pub = NULL;
2697 vchar_t *binbuf;
2699 binbuf = vmalloc(BN_num_bytes(in));
2700 if (!binbuf) {
2701 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey conversion: memory allocation failed..\n");
2702 return NULL;
2705 BN_bn2bin(in, (unsigned char *) binbuf->v);
2707 rsa_pub = binbuf_pubkey2rsa(binbuf);
2709 out:
2710 if (binbuf)
2711 vfree(binbuf);
2713 return rsa_pub;
2716 u_int32_t
2717 eay_random()
2719 u_int32_t result;
2720 vchar_t *vrand;
2722 vrand = eay_set_random(sizeof(result));
2723 memcpy(&result, vrand->v, sizeof(result));
2724 vfree(vrand);
2726 return result;
2729 const char *
2730 eay_version()
2732 return SSLeay_version(SSLEAY_VERSION);