1 /* $Id: crypto_openssl.c,v 1.40 2004/12/29 14:23:08 vanhu Exp $ */
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
34 #include <sys/types.h>
35 #include <sys/param.h>
42 /* get openssl/ssleay version number */
43 #include <openssl/opensslv.h>
45 #if !defined(OPENSSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x0090602fL)
46 #error OpenSSL version 0.9.6 or later required.
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>
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>
72 #include "crypto/rijndael/rijndael-api-fst.h"
75 #ifdef HAVE_OPENSSL_SHA2_H
76 #include <openssl/sha2.h>
78 #include "crypto/sha2/sha2.h"
83 #if OPENSSL_VERSION_NUMBER < 0x0090700fL
84 typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES;
86 #define USE_NEW_DES_API
89 #define OpenSSL_BUG() do { plog(LLV_ERROR, LOCATION, NULL, "OpenSSL function failed\n"); } while(0)
95 #include "crypto_openssl.h"
100 * I hate to cast every parameter to des_xx into void *, but it is
101 * necessary for SSLeay/OpenSSL portability. It sucks.
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 *));
108 static caddr_t eay_hmac_init __P((vchar_t *, const EVP_MD *));
110 /* X509 Certificate */
112 * convert the string of the subject name into DER
113 * e.g. str = "C=JP, ST=Kanagawa";
116 eay_str2asn1dn(str, len)
130 buf = racoon_malloc(len + 1);
132 printf("failed to allocate buffer\n");
135 memcpy(buf, str, len);
137 name = X509_NAME_new();
141 for (i = 0; i < len; i++) {
142 if (!value && buf[i] == '=') {
146 } else if (buf[i] == ',' || buf[i] == '/') {
149 plog(LLV_DEBUG, LOCATION, NULL, "DN: %s=%s\n",
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,
157 plog(LLV_ERROR, LOCATION, NULL,
158 "Invalid DN field: %s=%s\n",
160 plog(LLV_ERROR, LOCATION, NULL,
161 "%s\n", eay_strerror());
164 for (j = i + 1; j < len; j++) {
175 plog(LLV_DEBUG, LOCATION, NULL, "DN: %s=%s\n",
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,
183 plog(LLV_ERROR, LOCATION, NULL,
184 "Invalid DN field: %s=%s\n",
186 plog(LLV_ERROR, LOCATION, NULL,
187 "%s\n", eay_strerror());
191 i = i2d_X509_NAME(name, NULL);
198 i = i2d_X509_NAME(name, (void *)&p);
208 X509_NAME_free(name);
213 * convert the hex string of the subject name into DER
216 eay_hex2asn1dn(const char *hex, int len)
218 BIGNUM *bn = BN_new();
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",
233 binlen = BN_num_bytes(bn);
234 ret = vmalloc(binlen);
236 printf("failed to allocate buffer\n");
241 BN_bn2bin(bn, binbuf);
250 * The following are derived from code in crypto/x509/x509_cmp.c
252 * X509_NAME_wildcmp() adds wildcard matching to the original
253 * X509_NAME_cmp(), nocase_cmp() and nocase_spacenorm_cmp() are as is.
256 /* Case insensitive string comparision */
257 static int nocase_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
261 if (a->length != b->length)
262 return (a->length - b->length);
264 for (i=0; i<a->length; i++)
268 ca = tolower(a->data[i]);
269 cb = tolower(b->data[i]);
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
281 static int nocase_spacenorm_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
283 unsigned char *pa = NULL, *pb = NULL;
291 /* skip leading spaces */
292 while (la > 0 && isspace(*pa))
297 while (lb > 0 && isspace(*pb))
303 /* skip trailing spaces */
304 while (la > 0 && isspace(pa[la-1]))
306 while (lb > 0 && isspace(pb[lb-1]))
309 /* compare strings with space normalization */
310 while (la > 0 && lb > 0)
314 /* compare character */
323 if (la <= 0 || lb <= 0)
326 /* is white space next character ? */
327 if (isspace(*pa) && isspace(*pb))
329 /* skip remaining white spaces */
330 while (la > 0 && isspace(*pa))
335 while (lb > 0 && isspace(*pb))
342 if (la > 0 || lb > 0)
348 static int X509_NAME_wildcmp(const X509_NAME *a, const X509_NAME *b)
351 X509_NAME_ENTRY *na,*nb;
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--)
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);
363 if ((na->value->length == 1 && na->value->data[0] == '*')
364 || (nb->value->length == 1 && nb->value->data[0] == '*'))
366 j=na->value->type-nb->value->type;
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);
375 j=na->value->length-nb->value->length;
377 j=memcmp(na->value->data,nb->value->data,
389 * compare two subjectNames.
395 eay_cmp_asn1dn(n1, n2)
398 X509_NAME *a = NULL, *b = NULL;
403 if (!d2i_X509_NAME(&a, (void *)&p, n1->l))
406 if (!d2i_X509_NAME(&b, (void *)&p, n2->l))
409 i = X509_NAME_wildcmp(a, b);
420 * this functions is derived from apps/verify.c in OpenSSL0.9.5
423 eay_check_x509cert(cert, CApath, CAfile, local)
429 X509_STORE *cert_ctx = NULL;
430 X509_LOOKUP *lookup = NULL;
435 cert_ctx = X509_STORE_new();
436 if (cert_ctx == NULL)
440 X509_STORE_set_verify_cb_func(cert_ctx, cb_check_cert_local);
442 X509_STORE_set_verify_cb_func(cert_ctx, cb_check_cert_remote);
444 lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
448 X509_LOOKUP_load_file(lookup, CAfile,
449 (CAfile == NULL) ? X509_FILETYPE_DEFAULT : X509_FILETYPE_PEM);
451 lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
454 error = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
459 error = -1; /* initialized */
461 /* read the certificate to be verified */
462 x509 = mem2x509(cert);
466 csc = X509_STORE_CTX_new();
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);
474 error = X509_verify_cert(csc);
475 X509_STORE_CTX_cleanup(csc);
478 * if x509_verify_cert() is successful then the value of error is
481 error = error ? 0 : -1;
485 printf("%s\n", eay_strerror());
486 if (cert_ctx != NULL)
487 X509_STORE_free(cert_ctx);
495 * callback function for verifing certificate.
496 * this function is derived from cb() in openssl/apps/s_server.c
499 cb_check_cert_local(ok, ctx)
508 X509_get_subject_name(ctx->current_cert),
512 * since we are just checking the certificates, it is
513 * ok if they are self signed. But we should still warn
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:
524 log_tag = LLV_WARNING;
529 plog(log_tag, LOCATION, NULL,
530 "%s(%d) at depth:%d SubjectName:%s\n",
531 X509_verify_cert_error_string(ctx->error),
542 * callback function for verifing remote certificates.
543 * this function is derived from cb() in openssl/apps/s_server.c
546 cb_check_cert_remote(ok, ctx)
555 X509_get_subject_name(ctx->current_cert),
558 switch (ctx->error) {
559 case X509_V_ERR_UNABLE_TO_GET_CRL:
561 log_tag = LLV_WARNING;
566 plog(log_tag, LOCATION, NULL,
567 "%s(%d) at depth:%d SubjectName:%s\n",
568 X509_verify_cert_error_string(ctx->error),
579 * get a subjectAltName from X509 certificate.
582 eay_get_x509asn1subjectname(cert)
587 vchar_t *name = NULL;
593 x509 = mem2x509(cert);
597 /* get the length of the name */
598 len = i2d_X509_NAME(x509->cert_info->subject, NULL);
604 len = i2d_X509_NAME(x509->cert_info->subject, &bp);
610 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
623 * get the subjectAltName from X509 certificate.
624 * the name must be terminated by '\0'.
627 eay_get_x509subjectaltname(cert, altname, type, pos)
634 GENERAL_NAMES *gens = NULL;
640 *type = GENT_OTHERNAME;
642 x509 = mem2x509(cert);
646 gens = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL);
650 /* there is no data at "pos" */
651 if (pos > sk_GENERAL_NAME_num(gens))
654 gen = sk_GENERAL_NAME_value(gens, pos - 1);
656 /* read DNSName / Email */
657 if (gen->type == GEN_DNS ||
658 gen->type == GEN_EMAIL ||
659 gen->type == GEN_URI )
661 /* make sure if the data is terminated by '\0'. */
662 if (gen->d.ia5->data[gen->d.ia5->length] != '\0')
664 plog(LLV_ERROR, LOCATION, NULL,
665 "data is not terminated by NUL.");
666 hexdump(gen->d.ia5->data, gen->d.ia5->length + 1);
670 len = gen->d.ia5->length + 1;
671 *altname = racoon_malloc(len);
675 strlcpy(*altname, gen->d.ia5->data, len);
679 /* read IP address */
680 else if (gen->type == GEN_IPADD)
682 unsigned char p[5], *ip;
685 /* only support IPv4 */
686 if (gen->d.ip->length != 4)
689 /* convert Octet String to String
692 /*i2d_ASN1_OCTET_STRING(gen->d.ip,&ip);*/
693 ip = gen->d.ip->data;
695 /* XXX Magic, enough for an IPv4 address
697 *altname = racoon_malloc(20);
701 sprintf(*altname, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
705 /* XXX other possible types ?
706 * For now, error will be -1 if unsupported type
712 racoon_free(*altname);
715 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
720 /* free the whole stack. */
721 sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
728 * decode a X509 certificate and make a readable text terminated '\n'.
729 * return the buffer allocated, so must free it later.
732 eay_get_x509text(cert)
742 x509 = mem2x509(cert);
746 bio = BIO_new(BIO_s_mem());
750 error = X509_print(bio, x509);
756 len = BIO_get_mem_data(bio, &bp);
757 text = racoon_malloc(len + 1);
760 memcpy(text, bp, len);
771 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
781 /* get X509 structure from buffer. */
794 x509 = d2i_X509(NULL, &bp, cert->l);
801 bio = BIO_new(BIO_s_mem());
804 len = BIO_write(bio, cert->v, cert->l);
807 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
815 * get a X509 certificate from local file.
816 * a certificate must be PEM format.
818 * path to a certificate.
820 * NULL if error occured
824 eay_get_x509cert(path)
834 /* Read private key */
835 fp = fopen(path, "r");
838 x509 = PEM_read_X509(fp, NULL, NULL, NULL);
844 len = i2d_X509(x509, NULL);
851 error = i2d_X509(x509, &bp);
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.
870 eay_check_x509sign(source, sig, cert)
882 x509 = d2i_X509(NULL, &bp, cert->l);
884 plog(LLV_ERROR, LOCATION, NULL, "d2i_X509(): %s\n", eay_strerror());
888 evp = X509_get_pubkey(x509);
890 plog(LLV_ERROR, LOCATION, NULL, "X509_get_pubkey(): %s\n", eay_strerror());
894 res = eay_rsa_verify(source, sig, evp->pkey.rsa);
902 * check RSA signature
903 * OUT: return -1 when error.
907 eay_check_rsasign(source, sig, rsa)
912 return eay_rsa_verify(source, sig, rsa);
916 * get PKCS#1 Private Key of PEM format from local file.
919 eay_get_pkcs1privkey(path)
923 EVP_PKEY *evp = NULL;
924 vchar_t *pkey = NULL;
929 /* Read private key */
930 fp = fopen(path, "r");
934 evp = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
941 pkeylen = i2d_PrivateKey(evp, NULL);
944 pkey = vmalloc(pkeylen);
948 pkeylen = i2d_PrivateKey(evp, &bp);
957 if (error != 0 && pkey != NULL) {
966 * get PKCS#1 Public Key of PEM format from local file.
969 eay_get_pkcs1pubkey(path)
973 EVP_PKEY *evp = NULL;
974 vchar_t *pkey = NULL;
980 /* Read private key */
981 fp = fopen(path, "r");
985 x509 = PEM_read_X509(fp, NULL, NULL, NULL);
992 /* Get public key - eay */
993 evp = X509_get_pubkey(x509);
997 pkeylen = i2d_PublicKey(evp, NULL);
1000 pkey = vmalloc(pkeylen);
1004 pkeylen = i2d_PublicKey(evp, &bp);
1012 if (error != 0 && pkey != NULL) {
1021 eay_get_x509sign(src, privkey)
1022 vchar_t *src, *privkey;
1025 u_char *bp = privkey->v;
1026 vchar_t *sig = NULL;
1028 int pad = RSA_PKCS1_PADDING;
1030 /* XXX to be handled EVP_PKEY_DSA */
1031 evp = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &bp, privkey->l);
1035 sig = eay_rsa_sign(src, evp->pkey.rsa);
1043 eay_get_rsasign(src, rsa)
1047 return eay_rsa_sign(src, rsa);
1051 eay_rsa_sign(vchar_t *src, RSA *rsa)
1054 vchar_t *sig = NULL;
1055 int pad = RSA_PKCS1_PADDING;
1057 len = RSA_size(rsa);
1063 len = RSA_private_encrypt(src->l, src->v, sig->v, rsa, pad);
1065 if (len == 0 || len != sig->l) {
1074 eay_rsa_verify(src, sig, rsa)
1078 vchar_t *xbuf = NULL;
1079 int pad = RSA_PKCS1_PADDING;
1083 len = RSA_size(rsa);
1084 xbuf = vmalloc(len);
1086 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
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());
1097 error = memcmp(src->v, xbuf->v, src->l);
1107 * MUST load ERR_load_crypto_strings() first.
1112 static char ebuf[512];
1116 const char *file, *data;
1120 es = CRYPTO_thread_id();
1122 while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0){
1123 n = snprintf(ebuf + len, sizeof(ebuf) - len,
1125 es, ERR_error_string(l, buf), file, line,
1126 (flags & ERR_TXT_STRING) ? data : "");
1127 if (n < 0 || n >= sizeof(ebuf) - len)
1130 if (sizeof(ebuf) < len)
1138 evp_crypt(vchar_t *data, vchar_t *key, vchar_t *iv, const EVP_CIPHER *e, int enc)
1146 if (data->l % EVP_CIPHER_block_size(e))
1149 if ((res = vmalloc(data->l)) == NULL)
1152 EVP_CIPHER_CTX_init(&ctx);
1154 if (!EVP_CipherInit(&ctx, e, key->v, iv->v, enc)) {
1160 if (!EVP_Cipher(&ctx, res->v, data->v, data->l)) {
1166 EVP_CIPHER_CTX_cleanup(&ctx);
1172 evp_weakkey(vchar_t *key, const EVP_CIPHER *e)
1178 evp_keylen(int len, const EVP_CIPHER *e)
1182 if (len != 0 && len != EVP_CIPHER_key_length(e))
1185 return EVP_CIPHER_key_length(e);
1192 eay_des_encrypt(data, key, iv)
1193 vchar_t *data, *key, *iv;
1195 return evp_crypt(data, key, iv, EVP_des_cbc(), 1);
1199 eay_des_decrypt(data, key, iv)
1200 vchar_t *data, *key, *iv;
1202 return evp_crypt(data, key, iv, EVP_des_cbc(), 0);
1206 eay_des_weakkey(key)
1209 #ifdef USE_NEW_DES_API
1210 return DES_is_weak_key((void *)key->v);
1212 return des_is_weak_key((void *)key->v);
1220 return evp_keylen(len, EVP_des_cbc());
1227 eay_bf_encrypt(data, key, iv)
1228 vchar_t *data, *key, *iv;
1230 return evp_crypt(data, key, iv, EVP_bf_cbc(), 1);
1234 eay_bf_decrypt(data, key, iv)
1235 vchar_t *data, *key, *iv;
1237 return evp_crypt(data, key, iv, EVP_bf_cbc(), 0);
1244 return 0; /* XXX to be done. refer to RFC 2451 */
1253 if (len < 40 || len > 448)
1262 eay_3des_encrypt(data, key, iv)
1263 vchar_t *data, *key, *iv;
1265 return evp_crypt(data, key, iv, EVP_des_ede3_cbc(), 1);
1269 eay_3des_decrypt(data, key, iv)
1270 vchar_t *data, *key, *iv;
1272 return evp_crypt(data, key, iv, EVP_des_ede3_cbc(), 0);
1276 eay_3des_weakkey(key)
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)));
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)));
1294 eay_3des_keylen(len)
1297 if (len != 0 && len != 192)
1306 eay_cast_encrypt(data, key, iv)
1307 vchar_t *data, *key, *iv;
1309 return evp_crypt(data, key, iv, EVP_cast5_cbc(), 1);
1313 eay_cast_decrypt(data, key, iv)
1314 vchar_t *data, *key, *iv;
1316 return evp_crypt(data, key, iv, EVP_cast5_cbc(), 0);
1320 eay_cast_weakkey(key)
1323 return 0; /* No known weak keys. */
1327 eay_cast_keylen(len)
1332 if (len < 40 || len > 128)
1340 #ifndef HAVE_OPENSSL_AES_H
1342 eay_aes_encrypt(data, key, iv)
1343 vchar_t *data, *key, *iv;
1349 memset(&k, 0, sizeof(k));
1350 if (rijndael_makeKey(&k, DIR_ENCRYPT, key->l << 3, key->v) < 0)
1353 /* allocate buffer for result */
1354 if ((res = vmalloc(data->l)) == NULL)
1357 /* encryption data */
1358 memset(&c, 0, sizeof(c));
1359 if (rijndael_cipherInit(&c, MODE_CBC, iv->v) < 0){
1363 if (rijndael_blockEncrypt(&c, &k, data->v, data->l << 3, res->v) < 0){
1372 eay_aes_decrypt(data, key, iv)
1373 vchar_t *data, *key, *iv;
1379 memset(&k, 0, sizeof(k));
1380 if (rijndael_makeKey(&k, DIR_DECRYPT, key->l << 3, key->v) < 0)
1383 /* allocate buffer for result */
1384 if ((res = vmalloc(data->l)) == NULL)
1387 /* decryption data */
1388 memset(&c, 0, sizeof(c));
1389 if (rijndael_cipherInit(&c, MODE_CBC, iv->v) < 0){
1393 if (rijndael_blockDecrypt(&c, &k, data->v, data->l << 3, res->v) < 0){
1401 static inline const EVP_CIPHER *
1402 aes_evp_by_keylen(int keylen)
1407 return EVP_aes_128_cbc();
1410 return EVP_aes_192_cbc();
1413 return EVP_aes_256_cbc();
1420 eay_aes_encrypt(data, key, iv)
1421 vchar_t *data, *key, *iv;
1423 return evp_crypt(data, key, iv, aes_evp_by_keylen(key->l), 1);
1427 eay_aes_decrypt(data, key, iv)
1428 vchar_t *data, *key, *iv;
1430 return evp_crypt(data, key, iv, aes_evp_by_keylen(key->l), 0);
1435 eay_aes_weakkey(key)
1447 if (len != 128 && len != 192 && len != 256)
1452 /* for ipsec part */
1466 eay_twofish_keylen(len)
1469 if (len < 0 || len > 256)
1475 eay_null_keylen(len)
1485 eay_hmac_init(key, md)
1489 HMAC_CTX *c = racoon_malloc(sizeof(*c));
1491 HMAC_Init(c, key->v, key->l, md);
1501 eay_hmacsha2_512_one(key, data)
1502 vchar_t *key, *data;
1507 ctx = eay_hmacsha2_512_init(key);
1508 eay_hmacsha2_512_update(ctx, data);
1509 res = eay_hmacsha2_512_final(ctx);
1515 eay_hmacsha2_512_init(key)
1518 return eay_hmac_init(key, EVP_sha2_512());
1522 eay_hmacsha2_512_update(c, data)
1526 HMAC_Update((HMAC_CTX *)c, data->v, data->l);
1530 eay_hmacsha2_512_final(c)
1536 if ((res = vmalloc(SHA512_DIGEST_LENGTH)) == 0)
1539 HMAC_Final((HMAC_CTX *)c, res->v, &l);
1541 HMAC_cleanup((HMAC_CTX *)c);
1542 (void)racoon_free(c);
1544 if (SHA512_DIGEST_LENGTH != res->l) {
1545 plog(LLV_ERROR, LOCATION, NULL,
1546 "hmac sha2_512 length mismatch %zd.\n", res->l);
1558 eay_hmacsha2_384_one(key, data)
1559 vchar_t *key, *data;
1564 ctx = eay_hmacsha2_384_init(key);
1565 eay_hmacsha2_384_update(ctx, data);
1566 res = eay_hmacsha2_384_final(ctx);
1572 eay_hmacsha2_384_init(key)
1575 return eay_hmac_init(key, EVP_sha2_384());
1579 eay_hmacsha2_384_update(c, data)
1583 HMAC_Update((HMAC_CTX *)c, data->v, data->l);
1587 eay_hmacsha2_384_final(c)
1593 if ((res = vmalloc(SHA384_DIGEST_LENGTH)) == 0)
1596 HMAC_Final((HMAC_CTX *)c, res->v, &l);
1598 HMAC_cleanup((HMAC_CTX *)c);
1599 (void)racoon_free(c);
1601 if (SHA384_DIGEST_LENGTH != res->l) {
1602 plog(LLV_ERROR, LOCATION, NULL,
1603 "hmac sha2_384 length mismatch %zd.\n", res->l);
1615 eay_hmacsha2_256_one(key, data)
1616 vchar_t *key, *data;
1621 ctx = eay_hmacsha2_256_init(key);
1622 eay_hmacsha2_256_update(ctx, data);
1623 res = eay_hmacsha2_256_final(ctx);
1629 eay_hmacsha2_256_init(key)
1632 return eay_hmac_init(key, EVP_sha2_256());
1636 eay_hmacsha2_256_update(c, data)
1640 HMAC_Update((HMAC_CTX *)c, data->v, data->l);
1644 eay_hmacsha2_256_final(c)
1650 if ((res = vmalloc(SHA256_DIGEST_LENGTH)) == 0)
1653 HMAC_Final((HMAC_CTX *)c, res->v, &l);
1655 HMAC_cleanup((HMAC_CTX *)c);
1656 (void)racoon_free(c);
1658 if (SHA256_DIGEST_LENGTH != res->l) {
1659 plog(LLV_ERROR, LOCATION, NULL,
1660 "hmac sha2_256 length mismatch %zd.\n", res->l);
1667 #endif /* WITH_SHA2 */
1673 eay_hmacsha1_one(key, data)
1674 vchar_t *key, *data;
1679 ctx = eay_hmacsha1_init(key);
1680 eay_hmacsha1_update(ctx, data);
1681 res = eay_hmacsha1_final(ctx);
1687 eay_hmacsha1_init(key)
1690 return eay_hmac_init(key, EVP_sha1());
1694 eay_hmacsha1_update(c, data)
1698 HMAC_Update((HMAC_CTX *)c, data->v, data->l);
1702 eay_hmacsha1_final(c)
1708 if ((res = vmalloc(SHA_DIGEST_LENGTH)) == 0)
1711 HMAC_Final((HMAC_CTX *)c, res->v, &l);
1713 HMAC_cleanup((HMAC_CTX *)c);
1714 (void)racoon_free(c);
1716 if (SHA_DIGEST_LENGTH != res->l) {
1717 plog(LLV_ERROR, LOCATION, NULL,
1718 "hmac sha1 length mismatch %zd.\n", res->l);
1730 eay_hmacmd5_one(key, data)
1731 vchar_t *key, *data;
1736 ctx = eay_hmacmd5_init(key);
1737 eay_hmacmd5_update(ctx, data);
1738 res = eay_hmacmd5_final(ctx);
1744 eay_hmacmd5_init(key)
1747 return eay_hmac_init(key, EVP_md5());
1751 eay_hmacmd5_update(c, data)
1755 HMAC_Update((HMAC_CTX *)c, data->v, data->l);
1759 eay_hmacmd5_final(c)
1765 if ((res = vmalloc(MD5_DIGEST_LENGTH)) == 0)
1768 HMAC_Final((HMAC_CTX *)c, res->v, &l);
1770 HMAC_cleanup((HMAC_CTX *)c);
1771 (void)racoon_free(c);
1773 if (MD5_DIGEST_LENGTH != res->l) {
1774 plog(LLV_ERROR, LOCATION, NULL,
1775 "hmac md5 length mismatch %zd.\n", res->l);
1785 * SHA2-512 functions
1790 SHA512_CTX *c = racoon_malloc(sizeof(*c));
1798 eay_sha2_512_update(c, data)
1802 SHA512_Update((SHA512_CTX *)c, data->v, data->l);
1808 eay_sha2_512_final(c)
1813 if ((res = vmalloc(SHA512_DIGEST_LENGTH)) == 0)
1816 SHA512_Final(res->v, (SHA512_CTX *)c);
1817 (void)racoon_free(c);
1823 eay_sha2_512_one(data)
1829 ctx = eay_sha2_512_init();
1830 eay_sha2_512_update(ctx, data);
1831 res = eay_sha2_512_final(ctx);
1837 eay_sha2_512_hashlen()
1839 return SHA512_DIGEST_LENGTH << 3;
1845 * SHA2-384 functions
1850 SHA384_CTX *c = racoon_malloc(sizeof(*c));
1858 eay_sha2_384_update(c, data)
1862 SHA384_Update((SHA384_CTX *)c, data->v, data->l);
1868 eay_sha2_384_final(c)
1873 if ((res = vmalloc(SHA384_DIGEST_LENGTH)) == 0)
1876 SHA384_Final(res->v, (SHA384_CTX *)c);
1877 (void)racoon_free(c);
1883 eay_sha2_384_one(data)
1889 ctx = eay_sha2_384_init();
1890 eay_sha2_384_update(ctx, data);
1891 res = eay_sha2_384_final(ctx);
1897 eay_sha2_384_hashlen()
1899 return SHA384_DIGEST_LENGTH << 3;
1905 * SHA2-256 functions
1910 SHA256_CTX *c = racoon_malloc(sizeof(*c));
1918 eay_sha2_256_update(c, data)
1922 SHA256_Update((SHA256_CTX *)c, data->v, data->l);
1928 eay_sha2_256_final(c)
1933 if ((res = vmalloc(SHA256_DIGEST_LENGTH)) == 0)
1936 SHA256_Final(res->v, (SHA256_CTX *)c);
1937 (void)racoon_free(c);
1943 eay_sha2_256_one(data)
1949 ctx = eay_sha2_256_init();
1950 eay_sha2_256_update(ctx, data);
1951 res = eay_sha2_256_final(ctx);
1957 eay_sha2_256_hashlen()
1959 return SHA256_DIGEST_LENGTH << 3;
1969 SHA_CTX *c = racoon_malloc(sizeof(*c));
1977 eay_sha1_update(c, data)
1981 SHA1_Update((SHA_CTX *)c, data->v, data->l);
1992 if ((res = vmalloc(SHA_DIGEST_LENGTH)) == 0)
1995 SHA1_Final(res->v, (SHA_CTX *)c);
1996 (void)racoon_free(c);
2008 ctx = eay_sha1_init();
2009 eay_sha1_update(ctx, data);
2010 res = eay_sha1_final(ctx);
2018 return SHA_DIGEST_LENGTH << 3;
2027 MD5_CTX *c = racoon_malloc(sizeof(*c));
2035 eay_md5_update(c, data)
2039 MD5_Update((MD5_CTX *)c, data->v, data->l);
2050 if ((res = vmalloc(MD5_DIGEST_LENGTH)) == 0)
2053 MD5_Final(res->v, (MD5_CTX *)c);
2054 (void)racoon_free(c);
2066 ctx = eay_md5_init();
2067 eay_md5_update(ctx, data);
2068 res = eay_md5_final(ctx);
2076 return MD5_DIGEST_LENGTH << 3;
2081 * size: number of bytes.
2084 eay_set_random(size)
2090 if ((r = BN_new()) == NULL)
2092 BN_rand(r, size * 8, 0, 0);
2103 eay_dh_generate(prime, g, publen, pub, priv)
2104 vchar_t *prime, **pub, **priv;
2113 /* pre-process to generate number */
2114 if (eay_v2bn(&p, prime) < 0)
2117 if ((dh = DH_new()) == NULL)
2120 p = NULL; /* p is now part of dh structure */
2122 if ((dh->g = BN_new()) == NULL)
2124 if (!BN_set_word(dh->g, g))
2128 dh->length = publen;
2130 /* generate public and private number */
2131 if (!DH_generate_key(dh))
2134 /* copy results to buffers */
2135 if (eay_bn2v(pub, dh->pub_key) < 0)
2137 if (eay_bn2v(priv, dh->priv_key) < 0) {
2153 eay_dh_compute(prime, g, pub, priv, pub2, key)
2154 vchar_t *prime, *pub, *priv, *pub2, **key;
2157 BIGNUM *dh_pub = NULL;
2163 /* make public number to compute */
2164 if (eay_v2bn(&dh_pub, pub2) < 0)
2167 /* make DH structure */
2168 if ((dh = DH_new()) == NULL)
2170 if (eay_v2bn(&dh->p, prime) < 0)
2172 if (eay_v2bn(&dh->pub_key, pub) < 0)
2174 if (eay_v2bn(&dh->priv_key, priv) < 0)
2176 dh->length = pub2->l * 8;
2179 if ((dh->g = BN_new()) == NULL)
2181 if (!BN_set_word(dh->g, g))
2184 if ((v = (caddr_t)racoon_calloc(prime->l, sizeof(u_char))) == NULL)
2186 if ((l = DH_compute_key(v, dh_pub, dh)) == -1)
2188 memcpy((*key)->v + (prime->l - l), v, l);
2203 * convert vchar_t <-> BIGNUM.
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.
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
2220 if ((*bn = BN_bin2bn(var->v, var->l, NULL)) == NULL)
2231 *var = vmalloc(bn->top * BN_BYTES);
2235 (*var)->l = BN_bn2bin(bn, (*var)->v);
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();
2252 base64_decode(char *in, long inlen)
2254 BIO *bio=NULL, *b64=NULL;
2255 vchar_t *res = NULL;
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);
2264 outlen = BIO_read(bio, out, inlen * 2);
2266 plog(LLV_ERROR, LOCATION, NULL, "%s\n", eay_strerror());
2270 res = vmalloc(outlen);
2274 memcpy(res->v, out, outlen);
2284 base64_encode(char *in, long inlen)
2286 BIO *bio=NULL, *b64=NULL;
2289 vchar_t *res = NULL;
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);
2296 BIO_write(bio, in, inlen);
2299 plen = BIO_get_mem_data(bio, &ptr);
2300 res = vmalloc(plen+1);
2304 memcpy (res->v, ptr, plen);
2305 res->v[plen] = '\0';
2315 binbuf_pubkey2rsa(vchar_t *binbuf)
2318 RSA *rsa_pub = NULL;
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");
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();
2329 if (!exp || !mod || !rsa_pub) {
2330 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey parsing error: %s\n", eay_strerror());
2349 base64_pubkey2rsa(char *in)
2352 RSA *rsa_pub = NULL;
2355 if (strncmp(in, "0s", 2) != 0) {
2356 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: doesn't start with '0s'\n");
2360 binbuf = base64_decode(in + 2, strlen(in + 2));
2362 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey format error: Base64 decoding failed.\n");
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");
2371 rsa_pub = binbuf_pubkey2rsa(binbuf);
2381 bignum_pubkey2rsa(BIGNUM *in)
2383 RSA *rsa_pub = NULL;
2386 binbuf = vmalloc(BN_num_bytes(in));
2388 plog(LLV_ERROR, LOCATION, NULL, "Plain RSA pubkey conversion: memory allocation failed..\n");
2392 BN_bn2bin(in, binbuf->v);
2394 rsa_pub = binbuf_pubkey2rsa(binbuf);
2409 vrand = eay_set_random(sizeof(result));
2410 memcpy(&result, vrand->v, sizeof(result));
2419 return SSLeay_version(SSLEAY_VERSION);