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