1 /* $NetBSD: crypto_openssl.c,v 1.11.6.1 2006/12/18 10:18:10 vanhu Exp $ */
3 /* Id: crypto_openssl.c,v 1.47 2006/05/06 20:42:09 manubsd Exp */
6 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the project nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 #define COMMON_DIGEST_FOR_OPENSSL 1
38 #include <sys/types.h>
39 #include <sys/param.h>
47 /* get openssl/ssleay version number */
48 #include <openssl/opensslv.h>
50 #if !defined(OPENSSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x0090602fL)
51 #error OpenSSL version 0.9.6 or later required.
53 #include <openssl/pem.h>
54 #include <openssl/evp.h>
55 #include <openssl/x509.h>
56 #include <openssl/x509v3.h>
57 #include <openssl/x509_vfy.h>
58 #include <openssl/bn.h>
59 #include <openssl/dh.h>
60 #include <openssl/des.h>
61 #include <openssl/crypto.h>
62 #ifdef HAVE_OPENSSL_ENGINE_H
63 #include <openssl/engine.h>
65 #include <openssl/blowfish.h>
66 #include <openssl/cast.h>
67 #include <openssl/err.h>
68 #else /* HAVE_OPENSSL */
69 #include <Security/SecDH.h>
70 #include <Security/SecRandom.h>
71 #endif /* HAVE_OPENSSL */
73 #include <CommonCrypto/CommonDigest.h>
74 #include <CommonCrypto/CommonHMAC.h>
75 #include <CommonCrypto/CommonCryptor.h>
79 #if OPENSSL_VERSION_NUMBER < 0x0090700fL
80 typedef STACK_OF(GENERAL_NAME
) GENERAL_NAMES
;
82 #define USE_NEW_DES_API
85 #define OpenSSL_BUG() do { plog(LLV_ERROR, LOCATION, NULL, "OpenSSL function failed\n"); } while(0)
88 #include "crypto_openssl.h"
98 * I hate to cast every parameter to des_xx into void *, but it is
99 * necessary for SSLeay/OpenSSL portability. It sucks.
103 static int cb_check_cert_local
__P((int, X509_STORE_CTX
*));
104 static int cb_check_cert_remote
__P((int, X509_STORE_CTX
*));
105 static X509
*mem2x509
__P((vchar_t
*));
107 static caddr_t eay_hmac_init
__P((vchar_t
*, CCHmacAlgorithm
));
111 /* X509 Certificate */
113 * convert the string of the subject name into DER
114 * e.g. str = "C=JP, ST=Kanagawa";
117 eay_str2asn1dn(str
, len
)
131 buf
= racoon_malloc(len
+ 1);
133 plog(LLV_WARNING
, LOCATION
, NULL
,"failed to allocate buffer\n");
136 memcpy(buf
, str
, len
);
138 name
= X509_NAME_new();
142 for (i
= 0; i
< len
; i
++) {
143 if (!value
&& buf
[i
] == '=') {
147 } else if (buf
[i
] == ',' || buf
[i
] == '/') {
150 plog(LLV_DEBUG
, LOCATION
, NULL
, "DN: %s=%s\n",
153 if (!value
) goto err
;
154 if (!X509_NAME_add_entry_by_txt(name
, field
,
155 (value
[0] == '*' && value
[1] == 0) ?
156 V_ASN1_PRINTABLESTRING
: MBSTRING_ASC
,
157 (unsigned char *) value
, -1, -1, 0)) {
158 plog(LLV_ERROR
, LOCATION
, NULL
,
159 "Invalid DN field: %s=%s\n",
161 plog(LLV_ERROR
, LOCATION
, NULL
,
162 "%s\n", eay_strerror());
165 for (j
= i
+ 1; j
< len
; j
++) {
176 plog(LLV_DEBUG
, LOCATION
, NULL
, "DN: %s=%s\n",
179 if (!value
) goto err
;
180 if (!X509_NAME_add_entry_by_txt(name
, field
,
181 (value
[0] == '*' && value
[1] == 0) ?
182 V_ASN1_PRINTABLESTRING
: MBSTRING_ASC
,
183 (unsigned char *) value
, -1, -1, 0)) {
184 plog(LLV_ERROR
, LOCATION
, NULL
,
185 "Invalid DN field: %s=%s\n",
187 plog(LLV_ERROR
, LOCATION
, NULL
,
188 "%s\n", eay_strerror());
192 i
= i2d_X509_NAME(name
, NULL
);
199 i
= i2d_X509_NAME(name
, (void *)&p
);
209 X509_NAME_free(name
);
216 * convert the hex string of the subject name into DER
219 eay_hex2asn1dn(const char *hex
, int len
)
221 BIGNUM
*bn
= BN_new();
229 if (BN_hex2bn(&bn
, hex
) != len
) {
230 plog(LLV_ERROR
, LOCATION
, NULL
,
231 "conversion of Hex-encoded ASN1 string to binary failed: %s\n",
236 binlen
= BN_num_bytes(bn
);
237 ret
= vmalloc(binlen
);
239 plog(LLV_WARNING
, LOCATION
, NULL
,"failed to allocate buffer\n");
244 BN_bn2bin(bn
, (unsigned char *) binbuf
);
253 * The following are derived from code in crypto/x509/x509_cmp.c
255 * X509_NAME_wildcmp() adds wildcard matching to the original
256 * X509_NAME_cmp(), nocase_cmp() and nocase_spacenorm_cmp() are as is.
259 /* Case insensitive string comparision */
260 static int nocase_cmp(const ASN1_STRING
*a
, const ASN1_STRING
*b
)
264 if (a
->length
!= b
->length
)
265 return (a
->length
- b
->length
);
267 for (i
=0; i
<a
->length
; i
++)
271 ca
= tolower(a
->data
[i
]);
272 cb
= tolower(b
->data
[i
]);
280 /* Case insensitive string comparision with space normalization
281 * Space normalization - ignore leading, trailing spaces,
282 * multiple spaces between characters are replaced by single space
284 static int nocase_spacenorm_cmp(const ASN1_STRING
*a
, const ASN1_STRING
*b
)
286 unsigned char *pa
= NULL
, *pb
= NULL
;
294 /* skip leading spaces */
295 while (la
> 0 && isspace(*pa
))
300 while (lb
> 0 && isspace(*pb
))
306 /* skip trailing spaces */
307 while (la
> 0 && isspace(pa
[la
-1]))
309 while (lb
> 0 && isspace(pb
[lb
-1]))
312 /* compare strings with space normalization */
313 while (la
> 0 && lb
> 0)
317 /* compare character */
326 if (la
<= 0 || lb
<= 0)
329 /* is white space next character ? */
330 if (isspace(*pa
) && isspace(*pb
))
332 /* skip remaining white spaces */
333 while (la
> 0 && isspace(*pa
))
338 while (lb
> 0 && isspace(*pb
))
345 if (la
> 0 || lb
> 0)
351 static int X509_NAME_wildcmp(const X509_NAME
*a
, const X509_NAME
*b
)
354 X509_NAME_ENTRY
*na
,*nb
;
356 if (sk_X509_NAME_ENTRY_num(a
->entries
)
357 != sk_X509_NAME_ENTRY_num(b
->entries
))
358 return sk_X509_NAME_ENTRY_num(a
->entries
)
359 -sk_X509_NAME_ENTRY_num(b
->entries
);
360 for (i
=sk_X509_NAME_ENTRY_num(a
->entries
)-1; i
>=0; i
--)
362 na
=sk_X509_NAME_ENTRY_value(a
->entries
,i
);
363 nb
=sk_X509_NAME_ENTRY_value(b
->entries
,i
);
364 j
=OBJ_cmp(na
->object
,nb
->object
);
366 if ((na
->value
->length
== 1 && na
->value
->data
[0] == '*')
367 || (nb
->value
->length
== 1 && nb
->value
->data
[0] == '*'))
369 j
=na
->value
->type
-nb
->value
->type
;
371 if (na
->value
->type
== V_ASN1_PRINTABLESTRING
)
372 j
=nocase_spacenorm_cmp(na
->value
, nb
->value
);
373 else if (na
->value
->type
== V_ASN1_IA5STRING
374 && OBJ_obj2nid(na
->object
) == NID_pkcs9_emailAddress
)
375 j
=nocase_cmp(na
->value
, nb
->value
);
378 j
=na
->value
->length
-nb
->value
->length
;
380 j
=memcmp(na
->value
->data
,nb
->value
->data
,
392 * compare two subjectNames.
398 eay_cmp_asn1dn(n1
, n2
)
401 X509_NAME
*a
= NULL
, *b
= NULL
;
406 if (!d2i_X509_NAME(&a
, (void *)&p
, n1
->l
))
409 if (!d2i_X509_NAME(&b
, (void *)&p
, n2
->l
))
412 i
= X509_NAME_wildcmp(a
, b
);
423 * this functions is derived from apps/verify.c in OpenSSL0.9.5
426 eay_check_x509cert(cert
, CApath
, CAfile
, local
)
432 X509_STORE
*cert_ctx
= NULL
;
433 X509_LOOKUP
*lookup
= NULL
;
438 cert_ctx
= X509_STORE_new();
439 if (cert_ctx
== NULL
)
443 X509_STORE_set_verify_cb_func(cert_ctx
, cb_check_cert_local
);
445 X509_STORE_set_verify_cb_func(cert_ctx
, cb_check_cert_remote
);
447 lookup
= X509_STORE_add_lookup(cert_ctx
, X509_LOOKUP_file());
451 X509_LOOKUP_load_file(lookup
, CAfile
,
452 (CAfile
== NULL
) ? X509_FILETYPE_DEFAULT
: X509_FILETYPE_PEM
);
454 lookup
= X509_STORE_add_lookup(cert_ctx
, X509_LOOKUP_hash_dir());
457 error
= X509_LOOKUP_add_dir(lookup
, CApath
, X509_FILETYPE_PEM
);
462 error
= -1; /* initialized */
464 /* read the certificate to be verified */
465 x509
= mem2x509(cert
);
469 csc
= X509_STORE_CTX_new();
472 X509_STORE_CTX_init(csc
, cert_ctx
, x509
, NULL
);
473 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
474 X509_STORE_CTX_set_flags (csc
, X509_V_FLAG_CRL_CHECK
);
475 X509_STORE_CTX_set_flags (csc
, X509_V_FLAG_CRL_CHECK_ALL
);
477 error
= X509_verify_cert(csc
);
478 X509_STORE_CTX_free(csc
);
481 * if x509_verify_cert() is successful then the value of error is
484 error
= error
? 0 : -1;
488 plog(LLV_WARNING
, LOCATION
, NULL
,"%s\n", eay_strerror());
489 if (cert_ctx
!= NULL
)
490 X509_STORE_free(cert_ctx
);
498 * callback function for verifing certificate.
499 * this function is derived from cb() in openssl/apps/s_server.c
502 cb_check_cert_local(ok
, ctx
)
511 X509_get_subject_name(ctx
->current_cert
),
515 * since we are just checking the certificates, it is
516 * ok if they are self signed. But we should still warn
519 switch (ctx
->error
) {
520 case X509_V_ERR_CERT_HAS_EXPIRED
:
521 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
:
522 case X509_V_ERR_INVALID_CA
:
523 case X509_V_ERR_PATH_LENGTH_EXCEEDED
:
524 case X509_V_ERR_INVALID_PURPOSE
:
525 case X509_V_ERR_UNABLE_TO_GET_CRL
:
527 log_tag
= LLV_WARNING
;
532 plog(log_tag
, LOCATION
, NULL
,
533 "%s(%d) at depth:%d SubjectName:%s\n",
534 X509_verify_cert_error_string(ctx
->error
),
545 * callback function for verifing remote certificates.
546 * this function is derived from cb() in openssl/apps/s_server.c
549 cb_check_cert_remote(ok
, ctx
)
558 X509_get_subject_name(ctx
->current_cert
),
561 switch (ctx
->error
) {
562 case X509_V_ERR_UNABLE_TO_GET_CRL
:
564 log_tag
= LLV_WARNING
;
569 plog(log_tag
, LOCATION
, NULL
,
570 "%s(%d) at depth:%d SubjectName:%s\n",
571 X509_verify_cert_error_string(ctx
->error
),
582 * get a subjectAltName from X509 certificate.
585 eay_get_x509asn1subjectname(cert
)
590 vchar_t
*name
= NULL
;
593 bp
= (unsigned char *) cert
->v
;
595 x509
= mem2x509(cert
);
599 /* get the length of the name */
600 len
= i2d_X509_NAME(x509
->cert_info
->subject
, NULL
);
605 bp
= (unsigned char *) name
->v
;
606 len
= i2d_X509_NAME(x509
->cert_info
->subject
, &bp
);
613 plog(LLV_ERROR
, LOCATION
, NULL
, "%s\n", eay_strerror());
625 * Get the common name from a cert
627 #define EAY_MAX_CN_LEN 256
629 eay_get_x509_common_name(cert
)
634 vchar_t
*commonName
= NULL
;
636 commonName
= vmalloc(EAY_MAX_CN_LEN
);
637 if (commonName
== NULL
) {
638 plog(LLV_ERROR
, LOCATION
, NULL
, "no memory\n");
642 x509
= mem2x509(cert
);
648 name
= X509_get_subject_name(x509
);
649 X509_NAME_get_text_by_NID(name
, NID_commonName
, commonName
->v
, EAY_MAX_CN_LEN
);
651 commonName
->l
= strlen(commonName
->v
);
659 * get the subjectAltName from X509 certificate.
660 * the name must be terminated by '\0'.
663 eay_get_x509subjectaltname(cert
, altname
, type
, pos
, len
)
672 GENERAL_NAMES
*gens
= NULL
;
677 *type
= GENT_OTHERNAME
;
679 x509
= mem2x509(cert
);
683 gens
= X509_get_ext_d2i(x509
, NID_subject_alt_name
, NULL
, NULL
);
687 for (i
= 0; i
< sk_GENERAL_NAME_num(gens
); i
++) {
693 /* there is no data at "pos" */
694 if (i
== sk_GENERAL_NAME_num(gens
))
697 gen
= sk_GENERAL_NAME_value(gens
, i
);
699 /* make sure the data is terminated by '\0'. */
700 if (gen
->d
.ia5
->data
[gen
->d
.ia5
->length
] != '\0') {
701 plog(LLV_ERROR
, LOCATION
, NULL
,
702 "data is not terminated by 0.");
703 hexdump(gen
->d
.ia5
->data
, gen
->d
.ia5
->length
+ 1);
707 /* read DNSName / Email */
708 if (gen
->type
== GEN_DNS
||
709 gen
->type
== GEN_EMAIL
||
710 gen
->type
== GEN_URI
) {
712 *len
= gen
->d
.ia5
->length
+ 1;
713 *altname
= racoon_malloc(*len
);
717 strlcpy(*altname
, (const char *)gen
->d
.ia5
->data
, *len
);
721 } else if (gen
->type
== GEN_IPADD
) {
723 *len
= gen
->d
.ia5
->length
+ 1;
724 *altname
= racoon_malloc(*len
);
728 memcpy(*altname
, (const char *)gen
->d
.ia5
->data
, *len
);
737 racoon_free(*altname
);
741 plog(LLV_ERROR
, LOCATION
, NULL
, "%s\n", eay_strerror());
743 printf("%s\n", eay_strerror());
747 /* free the whole stack. */
748 sk_GENERAL_NAME_pop_free(gens
, GENERAL_NAME_free
);
756 * decode a X509 certificate and make a readable text terminated '\n'.
757 * return the buffer allocated, so must free it later.
760 eay_get_x509text(cert
)
770 x509
= mem2x509(cert
);
774 bio
= BIO_new(BIO_s_mem());
778 error
= X509_print(bio
, x509
);
784 len
= BIO_get_mem_data(bio
, &bp
);
785 text
= racoon_malloc(len
+ 1);
788 memcpy(text
, bp
, len
);
799 plog(LLV_ERROR
, LOCATION
, NULL
, "%s\n", eay_strerror());
809 /* get X509 structure from buffer. */
820 bp
= (unsigned char *) cert
->v
;
822 x509
= d2i_X509(NULL
, (void *)&bp
, cert
->l
);
829 bio
= BIO_new(BIO_s_mem());
832 len
= BIO_write(bio
, cert
->v
, cert
->l
);
835 x509
= PEM_read_bio_X509(bio
, NULL
, NULL
, NULL
);
843 * get a X509 certificate from local file.
844 * a certificate must be PEM format.
846 * path to a certificate.
848 * NULL if error occured
852 eay_get_x509cert(path
)
862 /* Read private key */
863 fp
= fopen(path
, "r");
866 x509
= PEM_read_X509(fp
, NULL
, NULL
, NULL
);
872 len
= i2d_X509(x509
, NULL
);
878 bp
= (unsigned char *) cert
->v
;
879 error
= i2d_X509(x509
, &bp
);
891 * check a X509 signature
892 * XXX: to be get hash type from my cert ?
893 * to be handled EVP_dss().
894 * OUT: return -1 when error.
898 eay_check_x509sign(source
, sig
, cert
)
908 bp
= (unsigned char *) cert
->v
;
910 x509
= d2i_X509(NULL
, (void *)&bp
, cert
->l
);
912 plog(LLV_ERROR
, LOCATION
, NULL
, "d2i_X509(): %s\n", eay_strerror());
916 evp
= X509_get_pubkey(x509
);
918 plog(LLV_ERROR
, LOCATION
, NULL
, "X509_get_pubkey(): %s\n", eay_strerror());
923 res
= eay_rsa_verify(source
, sig
, evp
->pkey
.rsa
);
932 * check RSA signature
933 * OUT: return -1 when error.
937 eay_check_rsasign(source
, sig
, rsa
)
942 return eay_rsa_verify(source
, sig
, rsa
);
946 * get PKCS#1 Private Key of PEM format from local file.
949 eay_get_pkcs1privkey(path
)
953 EVP_PKEY
*evp
= NULL
;
954 vchar_t
*pkey
= NULL
;
959 /* Read private key */
960 fp
= fopen(path
, "r");
964 evp
= PEM_read_PrivateKey(fp
, NULL
, NULL
, NULL
);
971 pkeylen
= i2d_PrivateKey(evp
, NULL
);
974 pkey
= vmalloc(pkeylen
);
977 bp
= (unsigned char *) pkey
->v
;
978 pkeylen
= i2d_PrivateKey(evp
, &bp
);
987 if (error
!= 0 && pkey
!= NULL
) {
996 * get PKCS#1 Public Key of PEM format from local file.
999 eay_get_pkcs1pubkey(path
)
1003 EVP_PKEY
*evp
= NULL
;
1004 vchar_t
*pkey
= NULL
;
1010 /* Read private key */
1011 fp
= fopen(path
, "r");
1015 x509
= PEM_read_X509(fp
, NULL
, NULL
, NULL
);
1022 /* Get public key - eay */
1023 evp
= X509_get_pubkey(x509
);
1027 pkeylen
= i2d_PublicKey(evp
, NULL
);
1030 pkey
= vmalloc(pkeylen
);
1033 bp
= (unsigned char *) pkey
->v
;
1034 pkeylen
= i2d_PublicKey(evp
, &bp
);
1042 if (error
!= 0 && pkey
!= NULL
) {
1051 eay_get_x509sign(src
, privkey
)
1052 vchar_t
*src
, *privkey
;
1055 u_char
*bp
= (unsigned char *) privkey
->v
;
1056 vchar_t
*sig
= NULL
;
1058 int pad
= RSA_PKCS1_PADDING
;
1060 /* XXX to be handled EVP_PKEY_DSA */
1061 evp
= d2i_PrivateKey(EVP_PKEY_RSA
, NULL
, (void *)&bp
, privkey
->l
);
1065 sig
= eay_rsa_sign(src
, evp
->pkey
.rsa
);
1073 eay_get_rsasign(src
, rsa
)
1077 return eay_rsa_sign(src
, rsa
);
1081 eay_rsa_sign(vchar_t
*src
, RSA
*rsa
)
1084 vchar_t
*sig
= NULL
;
1085 int pad
= RSA_PKCS1_PADDING
;
1087 len
= RSA_size(rsa
);
1093 len
= RSA_private_encrypt(src
->l
, (unsigned char *) src
->v
,
1094 (unsigned char *) sig
->v
, rsa
, pad
);
1096 if (len
== 0 || len
!= sig
->l
) {
1105 eay_rsa_verify(src
, sig
, rsa
)
1109 vchar_t
*xbuf
= NULL
;
1110 int pad
= RSA_PKCS1_PADDING
;
1114 len
= RSA_size(rsa
);
1115 xbuf
= vmalloc(len
);
1117 plog(LLV_ERROR
, LOCATION
, NULL
, "%s\n", eay_strerror());
1121 len
= RSA_public_decrypt(sig
->l
, (unsigned char *) sig
->v
,
1122 (unsigned char *) xbuf
->v
, rsa
, pad
);
1123 if (len
== 0 || len
!= src
->l
) {
1124 plog(LLV_ERROR
, LOCATION
, NULL
, "%s\n", eay_strerror());
1129 error
= memcmp(src
->v
, xbuf
->v
, src
->l
);
1139 * MUST load ERR_load_crypto_strings() first.
1144 static char ebuf
[512];
1148 const char *file
, *data
;
1152 es
= CRYPTO_thread_id();
1154 while ((l
= ERR_get_error_line_data(&file
, &line
, &data
, &flags
)) != 0){
1155 n
= snprintf(ebuf
+ len
, sizeof(ebuf
) - len
,
1157 es
, ERR_error_string(l
, buf
), file
, line
,
1158 (flags
& ERR_TXT_STRING
) ? data
: "");
1159 if (n
< 0 || n
>= sizeof(ebuf
) - len
)
1162 if (sizeof(ebuf
) < len
)
1170 evp_crypt(vchar_t
*data
, vchar_t
*key
, vchar_t
*iv
, const EVP_CIPHER
*e
, int enc
)
1178 if (data
->l
% EVP_CIPHER_block_size(e
))
1181 if ((res
= vmalloc(data
->l
)) == NULL
)
1184 EVP_CIPHER_CTX_init(&ctx
);
1186 switch(EVP_CIPHER_nid(e
)){
1193 case NID_cast5_cfb64
:
1194 case NID_cast5_ofb64
:
1195 /* XXX: can we do that also for algos with a fixed key size ?
1197 /* init context without key/iv
1199 if (!EVP_CipherInit(&ctx
, e
, NULL
, NULL
, enc
))
1208 if (!EVP_CIPHER_CTX_set_key_length(&ctx
, key
->l
))
1215 /* finalize context init with desired key size
1217 if (!EVP_CipherInit(&ctx
, NULL
, (u_char
*) key
->v
,
1218 (u_char
*) iv
->v
, enc
))
1226 if (!EVP_CipherInit(&ctx
, e
, (u_char
*) key
->v
,
1227 (u_char
*) iv
->v
, enc
)) {
1234 /* disable openssl padding */
1235 EVP_CIPHER_CTX_set_padding(&ctx
, 0);
1237 if (!EVP_Cipher(&ctx
, (u_char
*) res
->v
, (u_char
*) data
->v
, data
->l
)) {
1243 EVP_CIPHER_CTX_cleanup(&ctx
);
1249 evp_weakkey(vchar_t
*key
, const EVP_CIPHER
*e
)
1255 evp_keylen(int len
, const EVP_CIPHER
*e
)
1259 /* EVP functions return lengths in bytes, ipsec-tools
1260 * uses lengths in bits, therefore conversion is required. --AK
1262 if (len
!= 0 && len
!= (EVP_CIPHER_key_length(e
) << 3))
1265 return EVP_CIPHER_key_length(e
) << 3;
1267 #endif /* HAVE_OPENSSL */
1270 eay_CCCrypt(CCOperation oper
,
1279 CCCryptorStatus status
;
1281 /* allocate buffer for result */
1282 if ((res
= vmalloc(data
->l
)) == NULL
)
1285 status
= CCCrypt(oper
,
1291 res
->v
, res
->l
, &res_len
);
1292 if (status
== kCCSuccess
) {
1293 if (res
->l
!= res_len
) {
1294 plog(LLV_ERROR
, LOCATION
, NULL
,
1295 "crypt %d %d length mismatch. expected: %zd. got: %zd.\n",
1296 oper
, algo
, res
->l
, res_len
);
1300 plog(LLV_ERROR
, LOCATION
, NULL
,
1301 "crypt %d %d error. status %d.\n",
1302 oper
, algo
, (int)status
);
1312 eay_des_encrypt(data
, key
, iv
)
1313 vchar_t
*data
, *key
, *iv
;
1315 return(eay_CCCrypt(kCCEncrypt
, kCCAlgorithmDES
, 0 /* CBC */, data
, key
, iv
));
1319 eay_des_decrypt(data
, key
, iv
)
1320 vchar_t
*data
, *key
, *iv
;
1322 return(eay_CCCrypt(kCCDecrypt
, kCCAlgorithmDES
, 0 /* CBC */, data
, key
, iv
));
1326 eay_des_weakkey(key
)
1330 #ifdef USE_NEW_DES_API
1331 return DES_is_weak_key((void *)key
->v
);
1333 return des_is_weak_key((void *)key
->v
);
1344 /* CommonCrypto return lengths in bytes, ipsec-tools
1345 * uses lengths in bits, therefore conversion is required.
1347 if (len
!= 0 && len
!= (kCCKeySizeDES
<< 3))
1350 return kCCKeySizeDES
<< 3;
1357 eay_3des_encrypt(data
, key
, iv
)
1358 vchar_t
*data
, *key
, *iv
;
1360 return(eay_CCCrypt(kCCEncrypt
, kCCAlgorithm3DES
, 0 /* CBC */, data
, key
, iv
));
1364 eay_3des_decrypt(data
, key
, iv
)
1365 vchar_t
*data
, *key
, *iv
;
1367 return(eay_CCCrypt(kCCDecrypt
, kCCAlgorithm3DES
, 0 /* CBC */, data
, key
, iv
));
1371 eay_3des_weakkey(key
)
1378 eay_3des_keylen(len
)
1381 /* CommonCrypto return lengths in bytes, ipsec-tools
1382 * uses lengths in bits, therefore conversion is required.
1384 if (len
!= 0 && len
!= (kCCKeySize3DES
<< 3))
1387 return kCCKeySize3DES
<< 3;
1394 eay_aes_encrypt(data
, key
, iv
)
1395 vchar_t
*data
, *key
, *iv
;
1397 return(eay_CCCrypt(kCCEncrypt
, kCCAlgorithmAES128
/* adapts to AES-192, or AES-256 depending on the key size*/, 0 /* CBC */, data
, key
, iv
));
1401 eay_aes_decrypt(data
, key
, iv
)
1402 vchar_t
*data
, *key
, *iv
;
1404 return(eay_CCCrypt(kCCDecrypt
, kCCAlgorithmAES128
/* adapts to AES-192, or AES-256 depending on the key size*/, 0 /* CBC */, data
, key
, iv
));
1411 /* CommonCrypto return lengths in bytes, ipsec-tools
1412 * uses lengths in bits, therefore conversion is required.
1415 if (len
!= (kCCKeySizeAES128
<< 3) &&
1416 len
!= (kCCKeySizeAES192
<< 3) &&
1417 len
!= (kCCKeySizeAES256
<< 3))
1420 return kCCKeySizeAES128
<< 3;
1427 eay_aes_weakkey(key
)
1433 /* for ipsec part */
1441 eay_null_keylen(len
)
1451 eay_hmac_init(key
, algorithm
)
1453 CCHmacAlgorithm algorithm
;
1455 CCHmacContext
*c
= racoon_malloc(sizeof(*c
));
1457 CCHmacInit(c
, algorithm
, key
->v
, key
->l
);
1467 eay_hmacsha2_512_one(key
, data
)
1468 vchar_t
*key
, *data
;
1473 ctx
= eay_hmacsha2_512_init(key
);
1474 eay_hmacsha2_512_update(ctx
, data
);
1475 res
= eay_hmacsha2_512_final(ctx
);
1481 eay_hmacsha2_512_init(key
)
1484 return eay_hmac_init(key
, kCCHmacAlgSHA512
);
1488 eay_hmacsha2_512_update(c
, data
)
1492 CCHmacUpdate(ALIGNED_CAST(CCHmacContext
*)c
, data
->v
, data
->l
);
1496 eay_hmacsha2_512_final(c
)
1501 if ((res
= vmalloc(CC_SHA512_DIGEST_LENGTH
)) == 0)
1504 CCHmacFinal(ALIGNED_CAST(CCHmacContext
*)c
, res
->v
);
1505 res
->l
= CC_SHA512_DIGEST_LENGTH
;
1507 (void)racoon_free(c
);
1515 eay_hmacsha2_384_one(key
, data
)
1516 vchar_t
*key
, *data
;
1521 ctx
= eay_hmacsha2_384_init(key
);
1522 eay_hmacsha2_384_update(ctx
, data
);
1523 res
= eay_hmacsha2_384_final(ctx
);
1529 eay_hmacsha2_384_init(key
)
1532 return eay_hmac_init(key
, kCCHmacAlgSHA384
);
1536 eay_hmacsha2_384_update(c
, data
)
1540 CCHmacUpdate(ALIGNED_CAST(CCHmacContext
*)c
, data
->v
, data
->l
);
1544 eay_hmacsha2_384_final(c
)
1549 if ((res
= vmalloc(CC_SHA384_DIGEST_LENGTH
)) == 0)
1552 CCHmacFinal(ALIGNED_CAST(CCHmacContext
*)c
, res
->v
);
1553 res
->l
= CC_SHA384_DIGEST_LENGTH
;
1555 (void)racoon_free(c
);
1563 eay_hmacsha2_256_one(key
, data
)
1564 vchar_t
*key
, *data
;
1569 ctx
= eay_hmacsha2_256_init(key
);
1570 eay_hmacsha2_256_update(ctx
, data
);
1571 res
= eay_hmacsha2_256_final(ctx
);
1577 eay_hmacsha2_256_init(key
)
1580 return eay_hmac_init(key
, kCCHmacAlgSHA256
);
1584 eay_hmacsha2_256_update(c
, data
)
1588 CCHmacUpdate(ALIGNED_CAST(CCHmacContext
*)c
, data
->v
, data
->l
);
1592 eay_hmacsha2_256_final(c
)
1597 if ((res
= vmalloc(CC_SHA256_DIGEST_LENGTH
)) == 0)
1600 CCHmacFinal(ALIGNED_CAST(CCHmacContext
*)c
, res
->v
);
1601 res
->l
= CC_SHA256_DIGEST_LENGTH
;
1603 (void)racoon_free(c
);
1606 #endif /* WITH_SHA2 */
1612 eay_hmacsha1_one(key
, data
)
1613 vchar_t
*key
, *data
;
1618 ctx
= eay_hmacsha1_init(key
);
1619 eay_hmacsha1_update(ctx
, data
);
1620 res
= eay_hmacsha1_final(ctx
);
1626 eay_hmacsha1_init(key
)
1629 return eay_hmac_init(key
, kCCHmacAlgSHA1
);
1633 eay_hmacsha1_update(c
, data
)
1637 CCHmacUpdate(ALIGNED_CAST(CCHmacContext
*)c
, data
->v
, data
->l
);
1641 eay_hmacsha1_final(c
)
1646 if ((res
= vmalloc(CC_SHA1_DIGEST_LENGTH
)) == 0)
1649 CCHmacFinal(ALIGNED_CAST(CCHmacContext
*)c
, res
->v
);
1650 res
->l
= CC_SHA1_DIGEST_LENGTH
;
1652 (void)racoon_free(c
);
1660 eay_hmacmd5_one(key
, data
)
1661 vchar_t
*key
, *data
;
1666 ctx
= eay_hmacmd5_init(key
);
1667 eay_hmacmd5_update(ctx
, data
);
1668 res
= eay_hmacmd5_final(ctx
);
1674 eay_hmacmd5_init(key
)
1677 return eay_hmac_init(key
, kCCHmacAlgMD5
);
1681 eay_hmacmd5_update(c
, data
)
1685 CCHmacUpdate(ALIGNED_CAST(CCHmacContext
*)c
, data
->v
, data
->l
);
1689 eay_hmacmd5_final(c
)
1694 if ((res
= vmalloc(CC_MD5_DIGEST_LENGTH
)) == 0)
1697 CCHmacFinal(ALIGNED_CAST(CCHmacContext
*)c
, res
->v
);
1698 res
->l
= CC_MD5_DIGEST_LENGTH
;
1699 (void)racoon_free(c
);
1707 * SHA2-512 functions
1712 SHA512_CTX
*c
= racoon_malloc(sizeof(*c
));
1720 eay_sha2_512_update(c
, data
)
1724 SHA512_Update(ALIGNED_CAST(SHA512_CTX
*)c
, (unsigned char *) data
->v
, data
->l
);
1730 eay_sha2_512_final(c
)
1735 if ((res
= vmalloc(SHA512_DIGEST_LENGTH
)) == 0)
1738 SHA512_Final((unsigned char *) res
->v
, ALIGNED_CAST(SHA512_CTX
*)c
);
1739 (void)racoon_free(c
);
1745 eay_sha2_512_one(data
)
1751 ctx
= eay_sha2_512_init();
1752 eay_sha2_512_update(ctx
, data
);
1753 res
= eay_sha2_512_final(ctx
);
1759 eay_sha2_512_hashlen()
1761 return SHA512_DIGEST_LENGTH
<< 3;
1767 * SHA2-384 functions
1770 typedef SHA512_CTX SHA384_CTX
;
1775 SHA384_CTX
*c
= racoon_malloc(sizeof(*c
));
1783 eay_sha2_384_update(c
, data
)
1787 SHA384_Update(ALIGNED_CAST(SHA384_CTX
*)c
, (unsigned char *) data
->v
, data
->l
);
1793 eay_sha2_384_final(c
)
1798 if ((res
= vmalloc(SHA384_DIGEST_LENGTH
)) == 0)
1801 SHA384_Final((unsigned char *) res
->v
, ALIGNED_CAST(SHA384_CTX
*)c
);
1802 (void)racoon_free(c
);
1808 eay_sha2_384_one(data
)
1814 ctx
= eay_sha2_384_init();
1815 eay_sha2_384_update(ctx
, data
);
1816 res
= eay_sha2_384_final(ctx
);
1822 eay_sha2_384_hashlen()
1824 return SHA384_DIGEST_LENGTH
<< 3;
1830 * SHA2-256 functions
1835 SHA256_CTX
*c
= racoon_malloc(sizeof(*c
));
1843 eay_sha2_256_update(c
, data
)
1847 SHA256_Update(ALIGNED_CAST(SHA256_CTX
*)c
, (unsigned char *) data
->v
, data
->l
);
1853 eay_sha2_256_final(c
)
1858 if ((res
= vmalloc(SHA256_DIGEST_LENGTH
)) == 0)
1861 SHA256_Final((unsigned char *) res
->v
, ALIGNED_CAST(SHA256_CTX
*)c
);
1862 (void)racoon_free(c
);
1868 eay_sha2_256_one(data
)
1874 ctx
= eay_sha2_256_init();
1875 eay_sha2_256_update(ctx
, data
);
1876 res
= eay_sha2_256_final(ctx
);
1882 eay_sha2_256_hashlen()
1884 return SHA256_DIGEST_LENGTH
<< 3;
1894 SHA_CTX
*c
= racoon_malloc(sizeof(*c
));
1902 eay_sha1_update(c
, data
)
1906 SHA1_Update(ALIGNED_CAST(SHA_CTX
*)c
, data
->v
, data
->l
);
1917 if ((res
= vmalloc(SHA_DIGEST_LENGTH
)) == 0)
1920 SHA1_Final((unsigned char *) res
->v
, ALIGNED_CAST(SHA_CTX
*)c
);
1921 (void)racoon_free(c
);
1933 ctx
= eay_sha1_init();
1934 eay_sha1_update(ctx
, data
);
1935 res
= eay_sha1_final(ctx
);
1943 return SHA_DIGEST_LENGTH
<< 3;
1952 MD5_CTX
*c
= racoon_malloc(sizeof(*c
));
1960 eay_md5_update(c
, data
)
1964 MD5_Update(ALIGNED_CAST(MD5_CTX
*)c
, data
->v
, data
->l
);
1975 if ((res
= vmalloc(MD5_DIGEST_LENGTH
)) == 0)
1978 MD5_Final((unsigned char *) res
->v
, ALIGNED_CAST(MD5_CTX
*)c
);
1979 (void)racoon_free(c
);
1991 ctx
= eay_md5_init();
1992 eay_md5_update(ctx
, data
);
1993 res
= eay_md5_final(ctx
);
2001 return MD5_DIGEST_LENGTH
<< 3;
2008 * size: number of bytes.
2011 eay_set_random(size
)
2017 if ((r
= BN_new()) == NULL
)
2019 BN_rand(r
, size
* 8, 0, 0);
2029 eay_set_random(u_int32_t size
)
2031 vchar_t
*res
= vmalloc(size
);
2036 if (SecRandomCopyBytes(kSecRandomDefault
, size
, res
->v
)) {
2048 eay_dh_generate(prime
, g
, publen
, pub
, priv
)
2049 vchar_t
*prime
, **pub
, **priv
;
2058 /* pre-process to generate number */
2059 if (eay_v2bn(&p
, prime
) < 0)
2062 if ((dh
= DH_new()) == NULL
)
2065 p
= NULL
; /* p is now part of dh structure */
2067 if ((dh
->g
= BN_new()) == NULL
)
2069 if (!BN_set_word(dh
->g
, g
))
2073 dh
->length
= publen
;
2075 /* generate public and private number */
2076 if (!DH_generate_key(dh
))
2079 /* copy results to buffers */
2080 if (eay_bn2v(pub
, dh
->pub_key
) < 0)
2082 if (eay_bn2v(priv
, dh
->priv_key
) < 0) {
2098 eay_dh_compute(prime
, g
, pub
, priv
, pub2
, key
)
2099 vchar_t
*prime
, *pub
, *priv
, *pub2
, **key
;
2102 BIGNUM
*dh_pub
= NULL
;
2105 unsigned char *v
= NULL
;
2108 /* make public number to compute */
2109 if (eay_v2bn(&dh_pub
, pub2
) < 0)
2112 /* make DH structure */
2113 if ((dh
= DH_new()) == NULL
)
2115 if (eay_v2bn(&dh
->p
, prime
) < 0)
2117 if (eay_v2bn(&dh
->pub_key
, pub
) < 0)
2119 if (eay_v2bn(&dh
->priv_key
, priv
) < 0)
2121 dh
->length
= pub2
->l
* 8;
2124 if ((dh
->g
= BN_new()) == NULL
)
2126 if (!BN_set_word(dh
->g
, g
))
2129 if ((v
= racoon_calloc(prime
->l
, sizeof(u_char
))) == NULL
)
2131 if ((l
= DH_compute_key(v
, dh_pub
, dh
)) == -1)
2133 memcpy((*key
)->v
+ (prime
->l
- l
), v
, l
);
2148 * convert vchar_t <-> BIGNUM.
2150 * vchar_t: unit is u_char, network endian, most significant byte first.
2151 * BIGNUM: unit is BN_ULONG, each of BN_ULONG is in host endian,
2152 * least significant BN_ULONG must come first.
2154 * hex value of "0x3ffe050104" is represented as follows:
2155 * vchar_t: 3f fe 05 01 04
2156 * BIGNUM (BN_ULONG = u_int8_t): 04 01 05 fe 3f
2157 * BIGNUM (BN_ULONG = u_int16_t): 0x0104 0xfe05 0x003f
2158 * BIGNUM (BN_ULONG = u_int32_t_t): 0xfe050104 0x0000003f
2165 if ((*bn
= BN_bin2bn((unsigned char *) var
->v
, var
->l
, NULL
)) == NULL
)
2176 *var
= vmalloc(bn
->top
* BN_BYTES
);
2180 (*var
)->l
= BN_bn2bin(bn
, (unsigned char *) (*var
)->v
);
2188 OpenSSL_add_all_algorithms();
2189 ERR_load_crypto_strings();
2190 #ifdef HAVE_OPENSSL_ENGINE_H
2191 ENGINE_load_builtin_engines();
2192 ENGINE_register_all_complete();
2197 base64_decode(char *in
, long inlen
)
2199 BIO
*bio
=NULL
, *b64
=NULL
;
2200 vchar_t
*res
= NULL
;
2204 outb
= malloc(inlen
* 2);
2207 bio
= BIO_new_mem_buf(in
, inlen
);
2208 b64
= BIO_new(BIO_f_base64());
2209 BIO_set_flags(b64
, BIO_FLAGS_BASE64_NO_NL
);
2210 bio
= BIO_push(b64
, bio
);
2212 outlen
= BIO_read(bio
, outb
, inlen
* 2);
2214 plog(LLV_ERROR
, LOCATION
, NULL
, "%s\n", eay_strerror());
2218 res
= vmalloc(outlen
);
2222 memcpy(res
->v
, outb
, outlen
);
2234 base64_encode(char *in
, long inlen
)
2236 BIO
*bio
=NULL
, *b64
=NULL
;
2239 vchar_t
*res
= NULL
;
2241 bio
= BIO_new(BIO_s_mem());
2242 b64
= BIO_new(BIO_f_base64());
2243 BIO_set_flags(b64
, BIO_FLAGS_BASE64_NO_NL
);
2244 bio
= BIO_push(b64
, bio
);
2246 BIO_write(bio
, in
, inlen
);
2249 plen
= BIO_get_mem_data(bio
, &ptr
);
2250 res
= vmalloc(plen
+1);
2254 memcpy (res
->v
, ptr
, plen
);
2255 res
->v
[plen
] = '\0';
2265 binbuf_pubkey2rsa(vchar_t
*binbuf
)
2268 RSA
*rsa_pub
= NULL
;
2270 if (binbuf
->v
[0] > binbuf
->l
- 1) {
2271 plog(LLV_ERROR
, LOCATION
, NULL
, "Plain RSA pubkey format error: decoded string doesn't make sense.\n");
2275 exp
= BN_bin2bn((unsigned char *) (binbuf
->v
+ 1), binbuf
->v
[0], NULL
);
2276 mod
= BN_bin2bn((unsigned char *) (binbuf
->v
+ binbuf
->v
[0] + 1),
2277 binbuf
->l
- binbuf
->v
[0] - 1, NULL
);
2278 rsa_pub
= RSA_new();
2280 if (!exp
|| !mod
|| !rsa_pub
) {
2281 plog(LLV_ERROR
, LOCATION
, NULL
, "Plain RSA pubkey parsing error: %s\n", eay_strerror());
2300 base64_pubkey2rsa(char *in
)
2303 RSA
*rsa_pub
= NULL
;
2306 if (strncmp(in
, "0s", 2) != 0) {
2307 plog(LLV_ERROR
, LOCATION
, NULL
, "Plain RSA pubkey format error: doesn't start with '0s'\n");
2311 binbuf
= base64_decode(in
+ 2, strlen(in
+ 2));
2313 plog(LLV_ERROR
, LOCATION
, NULL
, "Plain RSA pubkey format error: Base64 decoding failed.\n");
2317 if (binbuf
->v
[0] > binbuf
->l
- 1) {
2318 plog(LLV_ERROR
, LOCATION
, NULL
, "Plain RSA pubkey format error: decoded string doesn't make sense.\n");
2322 rsa_pub
= binbuf_pubkey2rsa(binbuf
);
2332 bignum_pubkey2rsa(BIGNUM
*in
)
2334 RSA
*rsa_pub
= NULL
;
2337 binbuf
= vmalloc(BN_num_bytes(in
));
2339 plog(LLV_ERROR
, LOCATION
, NULL
, "Plain RSA pubkey conversion: memory allocation failed..\n");
2343 BN_bn2bin(in
, (unsigned char *) binbuf
->v
);
2345 rsa_pub
= binbuf_pubkey2rsa(binbuf
);
2353 #endif /* HAVE_OPENSSL */
2361 vrand
= eay_set_random(sizeof(result
));
2362 memcpy(&result
, vrand
->v
, sizeof(result
));
2372 return SSLeay_version(SSLEAY_VERSION
);