1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file openssl.c Openssl-based encryption/decryption routines. */
7 #include <sys/socket.h>
8 #include <openssl/rand.h>
9 #include <openssl/err.h>
10 #include <openssl/pem.h>
11 #include <openssl/sha.h>
12 #include <openssl/bn.h>
13 #include <openssl/aes.h>
14 #include <openssl/evp.h>
20 #include "crypt_backend.h"
21 #include "portable_io.h"
23 struct asymmetric_key {
29 static int openssl_perror(const char *pfx)
31 unsigned long err = ERR_get_error();
32 PARA_ERROR_LOG("%s: \"%s\"\n", pfx, ERR_reason_error_string(err));
36 void get_random_bytes_or_die(unsigned char *buf, int num)
40 if (RAND_bytes(buf, num) == 1) /* success */
42 ret = openssl_perror("RAND_bytes");
43 PARA_EMERG_LOG("%s\n", strerror(-ret));
48 * Read 64 bytes from /dev/urandom and add them to the SSL PRNG. Then seed the
49 * PRNG used by random(3) with a random seed obtained from SSL.
53 int seed, ret = RAND_load_file("/dev/urandom", 64);
56 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
59 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
63 void crypt_shutdown(void)
65 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
66 CRYPTO_cleanup_all_ex_data();
68 #ifdef HAVE_OPENSSL_THREAD_STOP /* openssl-1.1 or later */
69 OPENSSL_thread_stop();
70 #else /* openssl-1.0 */
71 ERR_remove_thread_state(NULL);
77 * The public key loading functions below were inspired by corresponding code
78 * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
79 * Finland. However, not much of the original code remains.
82 static int read_bignum(const unsigned char *buf, size_t len, BIGNUM **result)
84 const unsigned char *p = buf, *end = buf + len;
92 bnsize = read_u32_be(p);
93 PARA_DEBUG_LOG("bnsize: %u\n", bnsize);
101 bn = BN_bin2bn(p, bnsize, NULL);
108 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
110 static int generate_private_pkey(struct asymmetric_key *priv,
111 const BIGNUM *n, const BIGNUM *e, const BIGNUM *d,
112 const BIGNUM *p, const BIGNUM *q)
114 const BIGNUM *bignums[] = {n, e, d, p, q};
115 const char *strings[] = {"n", "e", "d", "p", "q"};
116 int ret, bytes[ARRAY_SIZE(bignums)];
117 unsigned char *bufs[ARRAY_SIZE(bignums)];
118 OSSL_PARAM params[ARRAY_SIZE(bignums) + 1];
120 * Convert bignums to buffers for OSSL_PARAM_construct_BN() and init
123 for (int i = 0; i < ARRAY_SIZE(bignums); i++) {
124 bytes[i] = BN_num_bytes(bignums[i]);
125 PARA_DEBUG_LOG("%s: %d bits\n", strings[i], bytes[i] * 8);
126 bufs[i] = alloc(bytes[i]);
127 assert(BN_bn2nativepad(bignums[i], bufs[i], bytes[i]) > 0);
128 params[i] = OSSL_PARAM_construct_BN(strings[i], bufs[i],
131 params[ARRAY_SIZE(bignums)] = OSSL_PARAM_construct_end();
132 /* Transfer buffers to openssl to create the pkey from it */
133 priv->ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL);
135 assert(EVP_PKEY_fromdata_init(priv->ctx) > 0);
136 ret = EVP_PKEY_fromdata(priv->ctx, &priv->pkey,
137 EVP_PKEY_KEYPAIR, params);
138 for (int i = 0; i < ARRAY_SIZE(bignums); i++)
141 EVP_PKEY_CTX_free(priv->ctx);
142 return openssl_perror("EVP_PKEY_fromdata()");
145 return BN_num_bytes(n) * 8;
149 * Convert bignumns e and n to a pkey and context.
151 static int generate_public_pkey(struct asymmetric_key *pub,
152 const BIGNUM *e, const BIGNUM *n)
154 unsigned char *ebuf, *nbuf;
155 int ret, ebytes = BN_num_bytes(e), nbytes = BN_num_bytes(n);
156 OSSL_PARAM params[3];
158 /* Convert e and n to a buffer for OSSL_PARAM_construct_BN() */
159 ebuf = alloc(ebytes);
160 assert(BN_bn2nativepad(e, ebuf, ebytes) > 0);
161 nbuf = alloc(nbytes);
162 assert(BN_bn2nativepad(n, nbuf, nbytes) > 0);
163 /* Init params[] with {e,n}buf and create the pkey from it */
164 params[0] = OSSL_PARAM_construct_BN("e", ebuf, ebytes);
165 params[1] = OSSL_PARAM_construct_BN("n", nbuf, nbytes);
166 params[2] = OSSL_PARAM_construct_end();
167 pub->ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL);
169 assert(EVP_PKEY_fromdata_init(pub->ctx) > 0);
170 ret = EVP_PKEY_fromdata(pub->ctx, &pub->pkey, EVP_PKEY_PUBLIC_KEY,
175 EVP_PKEY_CTX_free(pub->ctx);
176 return openssl_perror("EVP_PKEY_fromdata()");
182 #endif /* HAVE_OSSL_PARAM */
184 static int read_public_key(const unsigned char *blob, size_t blen,
185 struct asymmetric_key *pub)
188 const unsigned char *p = blob, *end = blob + blen;
191 ret = read_bignum(p, end - p, &e);
195 ret = read_bignum(p, end - p, &n);
200 bits = BN_num_bytes(n) * 8;
201 PARA_DEBUG_LOG("modulus: %d bits\n", bits);
202 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
203 ret = generate_public_pkey(pub, e, n);
208 #else /* openssl < 3.0 */
209 pub->rsa = RSA_new();
211 #if HAVE_RSA_SET0_KEY /* openssl-1.1 */
212 RSA_set0_key(pub->rsa, n, e, NULL);
213 #else /* openssl-1.0 */
217 /* e and n are now owned by openssl */
218 #endif /* HAVE_OSSL_PARAM */
222 static int read_pem_private_key(const char *path, struct asymmetric_key *priv)
227 assert((bio = BIO_new(BIO_s_file())));
228 ret = BIO_read_filename(bio, path);
231 ret = openssl_perror("BIO_read_filename");
234 priv->pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
236 ret = openssl_perror("PEM_read_bio_PrivateKey");
239 #ifndef HAVE_OSSL_PARAM /* openssl-1 */
240 priv->rsa = EVP_PKEY_get1_RSA(priv->pkey);
247 static int read_openssh_private_key(const unsigned char *blob,
248 const unsigned char *end, struct asymmetric_key *priv)
251 BIGNUM *n, *e, *d, *iqmp, *p, *q; /* stored in the key file */
252 const unsigned char *cp = blob;
254 ret = read_bignum(cp, end - cp, &n);
258 ret = read_bignum(cp, end - cp, &e);
262 ret = read_bignum(cp, end - cp, &d);
266 ret = read_bignum(cp, end - cp, &iqmp);
270 ret = read_bignum(cp, end - cp, &p);
274 ret = read_bignum(cp, end - cp, &q);
277 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
279 * Ignore iqmp, the coefficient for Chinese remainder theorem. It is
280 * dispensable because it can be derived from the other values. Passing
281 * it to the EVP API results in a memory leak.
283 ret = generate_private_pkey(priv, n, e, d, p, q);
285 assert((priv->rsa = RSA_new()));
286 #ifdef HAVE_RSA_SET0_KEY
287 RSA_set0_key(priv->rsa, n, e, d);
288 RSA_set0_factors(priv->rsa, p, q);
289 RSA_set0_crt_params(priv->rsa, NULL, NULL, iqmp);
294 priv->rsa->iqmp = iqmp;
299 #endif /* HAVE_OSSL_PARAM */
314 static int get_private_key(const char *path, struct asymmetric_key *priv)
317 unsigned char *blob, *end;
320 ret = decode_private_key(path, &blob, &blob_size);
323 end = blob + blob_size;
324 if (ret == PKT_OPENSSH) {
325 ret = find_openssh_bignum_offset(blob, blob_size);
328 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
329 ret = read_openssh_private_key(blob + ret, end, priv);
331 ret = read_pem_private_key(path, priv);
337 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
342 struct asymmetric_key *pub;
344 ret = decode_public_key(key_file, &blob, &decoded_size);
347 pub = zalloc(sizeof(*pub)); /* ->pkey needs to start out zeroed */
348 ret = read_public_key(blob + ret, decoded_size - ret, pub);
353 PARA_ERROR_LOG("can not load key %s\n", key_file);
356 PARA_NOTICE_LOG("loaded %d bit key from %s\n", ret, key_file);
361 void apc_free_pubkey(struct asymmetric_key *pub)
365 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
366 EVP_PKEY_CTX_free(pub->ctx);
367 EVP_PKEY_free(pub->pkey);
374 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
375 static int pkey_priv_decrypt(const struct asymmetric_key *priv,
376 unsigned char **outbuf, unsigned char *inbuf, int inlen)
381 assert((ctx = EVP_PKEY_CTX_new(priv->pkey, NULL)));
382 assert((EVP_PKEY_decrypt_init(ctx) > 0));
383 assert(EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) > 0);
384 if (EVP_PKEY_decrypt(ctx, NULL, &outlen, inbuf, inlen) <= 0) {
386 EVP_PKEY_CTX_free(ctx);
387 return openssl_perror("EVP_PKEY_encrypt()");
389 *outbuf = alloc(outlen);
390 assert((EVP_PKEY_decrypt(ctx, *outbuf, &outlen, inbuf, inlen) > 0));
391 EVP_PKEY_CTX_free(ctx);
392 PARA_INFO_LOG("wrote %zu decrypted data bytes\n", outlen);
395 #endif /* HAVE_OSSL_PARAM */
397 int apc_priv_decrypt(const char *key_file, unsigned char **outbuf,
398 unsigned char *inbuf, int inlen)
400 struct asymmetric_key *priv;
404 ret = check_private_key_file(key_file);
409 priv = zalloc(sizeof(*priv)); /* ->pkey needs to start out zeroed */
410 ret = get_private_key(key_file, priv);
415 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
416 ret = pkey_priv_decrypt(priv, outbuf, inbuf, inlen);
417 EVP_PKEY_CTX_free(priv->ctx);
418 EVP_PKEY_free(priv->pkey);
421 * RSA is vulnerable to timing attacks. Generate a random blinding
422 * factor to protect against this kind of attack.
425 if (RSA_blinding_on(priv->rsa, NULL) == 0)
427 *outbuf = alloc(RSA_size(priv->rsa));
428 ret = RSA_private_decrypt(inlen, inbuf, *outbuf, priv->rsa,
429 RSA_PKCS1_OAEP_PADDING);
430 RSA_blinding_off(priv->rsa);
443 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
444 unsigned len, unsigned char **outbuf)
447 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
452 assert((ctx = EVP_PKEY_CTX_new(pub->pkey, NULL)));
453 assert((EVP_PKEY_encrypt_init(ctx) > 0));
454 assert((EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) > 0));
455 if (EVP_PKEY_encrypt(ctx, NULL, &outlen, inbuf, len) <= 0) {
456 ret = openssl_perror("EVP_PKEY_encrypt()");
459 *outbuf = alloc(outlen);
460 assert((EVP_PKEY_encrypt(ctx, *outbuf, &outlen, inbuf, len) > 0));
461 PARA_INFO_LOG("wrote %zu encrypted data bytes\n", outlen);
464 EVP_PKEY_CTX_free(ctx);
466 #else /* openssl < 3.0 */
467 *outbuf = alloc(RSA_size(pub->rsa));
468 ret = RSA_public_encrypt((int)len, inbuf, *outbuf, pub->rsa,
469 RSA_PKCS1_OAEP_PADDING);
476 #endif /* HAVE_OSSL_PARAM */
479 struct stream_cipher {
483 struct stream_cipher *sc_new(const unsigned char *data, int len)
485 struct stream_cipher *sc = alloc(sizeof(*sc));
487 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
488 assert((sc->aes = EVP_CIPHER_CTX_new()));
489 EVP_EncryptInit_ex(sc->aes, EVP_aes_128_ctr(), NULL, data,
490 data + AES_CRT128_BLOCK_SIZE);
494 void sc_free(struct stream_cipher *sc)
498 EVP_CIPHER_CTX_free(sc->aes);
502 static void aes_ctr128_crypt(EVP_CIPHER_CTX *ctx, struct iovec *src,
505 int ret, inlen = src->iov_len, outlen, tmplen;
507 *dst = (typeof(*dst)) {
508 /* Add one for the terminating zero byte. */
509 .iov_base = alloc(inlen + 1),
512 ret = EVP_EncryptUpdate(ctx, dst->iov_base, &outlen, src->iov_base, inlen);
514 ret = EVP_EncryptFinal_ex(ctx, dst->iov_base + outlen, &tmplen);
517 ((char *)dst->iov_base)[outlen] = '\0';
518 dst->iov_len = outlen;
521 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
523 return aes_ctr128_crypt(sc->aes, src, dst);
526 void hash_function(const char *data, unsigned long len, unsigned char *hash)
531 assert((c = EVP_MD_CTX_new()));
532 ret = EVP_DigestInit_ex(c, EVP_sha1(), NULL);
534 ret = EVP_DigestUpdate(c, data, len);
536 ret = EVP_DigestFinal_ex(c, hash, NULL);
541 void hash2_function(const char *data, unsigned long len, unsigned char *hash)
546 assert((c = EVP_MD_CTX_new()));
547 ret = EVP_DigestInit_ex(c, EVP_sha256(), NULL);
549 ret = EVP_DigestUpdate(c, data, len);
551 ret = EVP_DigestFinal_ex(c, hash, NULL);