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_OPENSSL_THREAD_STOP /* openssl-1.1 or later */
66 OPENSSL_thread_stop();
67 #else /* openssl-1.0 */
68 ERR_remove_thread_state(NULL);
74 * The public key loading functions below were inspired by corresponding code
75 * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
76 * Finland. However, not much of the original code remains.
79 static int read_bignum(const unsigned char *buf, size_t len, BIGNUM **result)
81 const unsigned char *p = buf, *end = buf + len;
89 bnsize = read_u32_be(p);
90 PARA_DEBUG_LOG("bnsize: %u\n", bnsize);
98 bn = BN_bin2bn(p, bnsize, NULL);
105 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
107 static int generate_private_pkey(struct asymmetric_key *priv,
108 const BIGNUM *n, const BIGNUM *e, const BIGNUM *d,
109 const BIGNUM *p, const BIGNUM *q)
111 const BIGNUM *bignums[] = {n, e, d, p, q};
112 const char *strings[] = {"n", "e", "d", "p", "q"};
113 int ret, bytes[ARRAY_SIZE(bignums)];
114 unsigned char *bufs[ARRAY_SIZE(bignums)];
115 OSSL_PARAM params[ARRAY_SIZE(bignums) + 1];
117 * Convert bignums to buffers for OSSL_PARAM_construct_BN() and init
120 for (int i = 0; i < ARRAY_SIZE(bignums); i++) {
121 bytes[i] = BN_num_bytes(bignums[i]);
122 PARA_DEBUG_LOG("%s: %d bits\n", strings[i], bytes[i] * 8);
123 bufs[i] = alloc(bytes[i]);
124 assert(BN_bn2nativepad(bignums[i], bufs[i], bytes[i]) > 0);
125 params[i] = OSSL_PARAM_construct_BN(strings[i], bufs[i],
128 params[ARRAY_SIZE(bignums)] = OSSL_PARAM_construct_end();
129 /* Transfer buffers to openssl to create the pkey from it */
130 priv->ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL);
132 assert(EVP_PKEY_fromdata_init(priv->ctx) > 0);
133 ret = EVP_PKEY_fromdata(priv->ctx, &priv->pkey,
134 EVP_PKEY_KEYPAIR, params);
135 for (int i = 0; i < ARRAY_SIZE(bignums); i++)
138 EVP_PKEY_CTX_free(priv->ctx);
139 return openssl_perror("EVP_PKEY_fromdata()");
142 return BN_num_bytes(n) * 8;
146 * Convert bignumns e and n to a pkey and context.
148 static int generate_public_pkey(struct asymmetric_key *pub,
149 const BIGNUM *e, const BIGNUM *n)
151 unsigned char *ebuf, *nbuf;
152 int ret, ebytes = BN_num_bytes(e), nbytes = BN_num_bytes(n);
153 OSSL_PARAM params[3];
155 /* Convert e and n to a buffer for OSSL_PARAM_construct_BN() */
156 ebuf = alloc(ebytes);
157 assert(BN_bn2nativepad(e, ebuf, ebytes) > 0);
158 nbuf = alloc(nbytes);
159 assert(BN_bn2nativepad(n, nbuf, nbytes) > 0);
160 /* Init params[] with {e,n}buf and create the pkey from it */
161 params[0] = OSSL_PARAM_construct_BN("e", ebuf, ebytes);
162 params[1] = OSSL_PARAM_construct_BN("n", nbuf, nbytes);
163 params[2] = OSSL_PARAM_construct_end();
164 pub->ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL);
166 assert(EVP_PKEY_fromdata_init(pub->ctx) > 0);
167 ret = EVP_PKEY_fromdata(pub->ctx, &pub->pkey, EVP_PKEY_PUBLIC_KEY,
172 EVP_PKEY_CTX_free(pub->ctx);
173 return openssl_perror("EVP_PKEY_fromdata()");
179 #endif /* HAVE_OSSL_PARAM */
181 static int read_public_key(const unsigned char *blob, size_t blen,
182 struct asymmetric_key *pub)
185 const unsigned char *p = blob, *end = blob + blen;
188 ret = read_bignum(p, end - p, &e);
192 ret = read_bignum(p, end - p, &n);
197 bits = BN_num_bytes(n) * 8;
198 PARA_DEBUG_LOG("modulus: %d bits\n", bits);
199 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
200 ret = generate_public_pkey(pub, e, n);
205 #else /* openssl < 3.0 */
206 pub->rsa = RSA_new();
208 #if HAVE_RSA_SET0_KEY /* openssl-1.1 */
209 RSA_set0_key(pub->rsa, n, e, NULL);
210 #else /* openssl-1.0 */
214 /* e and n are now owned by openssl */
215 #endif /* HAVE_OSSL_PARAM */
219 static int read_pem_private_key(const char *path, struct asymmetric_key *priv)
224 assert((bio = BIO_new(BIO_s_file())));
225 ret = BIO_read_filename(bio, path);
228 ret = openssl_perror("BIO_read_filename");
231 priv->pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
233 ret = openssl_perror("PEM_read_bio_PrivateKey");
236 #ifndef HAVE_OSSL_PARAM /* openssl-1 */
237 priv->rsa = EVP_PKEY_get1_RSA(priv->pkey);
244 static int read_openssh_private_key(const unsigned char *blob,
245 const unsigned char *end, struct asymmetric_key *priv)
248 BIGNUM *n, *e, *d, *iqmp, *p, *q; /* stored in the key file */
249 const unsigned char *cp = blob;
251 ret = read_bignum(cp, end - cp, &n);
255 ret = read_bignum(cp, end - cp, &e);
259 ret = read_bignum(cp, end - cp, &d);
263 ret = read_bignum(cp, end - cp, &iqmp);
267 ret = read_bignum(cp, end - cp, &p);
271 ret = read_bignum(cp, end - cp, &q);
274 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
276 * Ignore iqmp, the coefficient for Chinese remainder theorem. It is
277 * dispensable because it can be derived from the other values. Passing
278 * it to the EVP API results in a memory leak.
280 ret = generate_private_pkey(priv, n, e, d, p, q);
282 assert((priv->rsa = RSA_new()));
283 #ifdef HAVE_RSA_SET0_KEY
284 RSA_set0_key(priv->rsa, n, e, d);
285 RSA_set0_factors(priv->rsa, p, q);
286 RSA_set0_crt_params(priv->rsa, NULL, NULL, iqmp);
291 priv->rsa->iqmp = iqmp;
296 #endif /* HAVE_OSSL_PARAM */
311 static int get_private_key(const char *path, struct asymmetric_key *priv)
314 unsigned char *blob, *end;
317 ret = decode_private_key(path, &blob, &blob_size);
320 end = blob + blob_size;
321 if (ret == PKT_OPENSSH) {
322 ret = find_openssh_bignum_offset(blob, blob_size);
325 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
326 ret = read_openssh_private_key(blob + ret, end, priv);
328 ret = read_pem_private_key(path, priv);
334 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
339 struct asymmetric_key *pub;
341 ret = decode_public_key(key_file, &blob, &decoded_size);
344 pub = zalloc(sizeof(*pub)); /* ->pkey needs to start out zeroed */
345 ret = read_public_key(blob + ret, decoded_size - ret, pub);
350 PARA_ERROR_LOG("can not load key %s\n", key_file);
353 PARA_NOTICE_LOG("loaded %d bit key from %s\n", ret, key_file);
358 void apc_free_pubkey(struct asymmetric_key *pub)
362 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
363 EVP_PKEY_CTX_free(pub->ctx);
364 EVP_PKEY_free(pub->pkey);
371 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
372 static int pkey_priv_decrypt(const struct asymmetric_key *priv,
373 unsigned char **outbuf, unsigned char *inbuf, int inlen)
378 assert((ctx = EVP_PKEY_CTX_new(priv->pkey, NULL)));
379 assert((EVP_PKEY_decrypt_init(ctx) > 0));
380 assert(EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) > 0);
381 if (EVP_PKEY_decrypt(ctx, NULL, &outlen, inbuf, inlen) <= 0) {
383 EVP_PKEY_CTX_free(ctx);
384 return openssl_perror("EVP_PKEY_encrypt()");
386 *outbuf = alloc(outlen);
387 assert((EVP_PKEY_decrypt(ctx, *outbuf, &outlen, inbuf, inlen) > 0));
388 EVP_PKEY_CTX_free(ctx);
389 PARA_INFO_LOG("wrote %zu decrypted data bytes\n", outlen);
392 #endif /* HAVE_OSSL_PARAM */
394 int apc_priv_decrypt(const char *key_file, unsigned char **outbuf,
395 unsigned char *inbuf, int inlen)
397 struct asymmetric_key *priv;
401 ret = check_private_key_file(key_file);
406 priv = zalloc(sizeof(*priv)); /* ->pkey needs to start out zeroed */
407 ret = get_private_key(key_file, priv);
412 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
413 ret = pkey_priv_decrypt(priv, outbuf, inbuf, inlen);
414 EVP_PKEY_CTX_free(priv->ctx);
415 EVP_PKEY_free(priv->pkey);
418 * RSA is vulnerable to timing attacks. Generate a random blinding
419 * factor to protect against this kind of attack.
422 if (RSA_blinding_on(priv->rsa, NULL) == 0)
424 *outbuf = alloc(RSA_size(priv->rsa));
425 ret = RSA_private_decrypt(inlen, inbuf, *outbuf, priv->rsa,
426 RSA_PKCS1_OAEP_PADDING);
427 RSA_blinding_off(priv->rsa);
440 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
441 unsigned len, unsigned char **outbuf)
444 #ifdef HAVE_OSSL_PARAM /* openssl-3 */
449 assert((ctx = EVP_PKEY_CTX_new(pub->pkey, NULL)));
450 assert((EVP_PKEY_encrypt_init(ctx) > 0));
451 assert((EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) > 0));
452 if (EVP_PKEY_encrypt(ctx, NULL, &outlen, inbuf, len) <= 0) {
453 ret = openssl_perror("EVP_PKEY_encrypt()");
456 *outbuf = alloc(outlen);
457 assert((EVP_PKEY_encrypt(ctx, *outbuf, &outlen, inbuf, len) > 0));
458 PARA_INFO_LOG("wrote %zu encrypted data bytes\n", outlen);
461 EVP_PKEY_CTX_free(ctx);
463 #else /* openssl < 3.0 */
464 *outbuf = alloc(RSA_size(pub->rsa));
465 ret = RSA_public_encrypt((int)len, inbuf, *outbuf, pub->rsa,
466 RSA_PKCS1_OAEP_PADDING);
473 #endif /* HAVE_OSSL_PARAM */
476 struct stream_cipher {
480 struct stream_cipher *sc_new(const unsigned char *data, int len)
482 struct stream_cipher *sc = alloc(sizeof(*sc));
484 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
485 assert((sc->aes = EVP_CIPHER_CTX_new()));
486 EVP_EncryptInit_ex(sc->aes, EVP_aes_128_ctr(), NULL, data,
487 data + AES_CRT128_BLOCK_SIZE);
491 void sc_free(struct stream_cipher *sc)
495 EVP_CIPHER_CTX_free(sc->aes);
499 static void aes_ctr128_crypt(EVP_CIPHER_CTX *ctx, struct iovec *src,
502 int ret, inlen = src->iov_len, outlen, tmplen;
504 *dst = (typeof(*dst)) {
505 /* Add one for the terminating zero byte. */
506 .iov_base = alloc(inlen + 1),
509 ret = EVP_EncryptUpdate(ctx, dst->iov_base, &outlen, src->iov_base, inlen);
511 ret = EVP_EncryptFinal_ex(ctx, dst->iov_base + outlen, &tmplen);
514 ((char *)dst->iov_base)[outlen] = '\0';
515 dst->iov_len = outlen;
518 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
520 return aes_ctr128_crypt(sc->aes, src, dst);
523 void hash_function(const char *data, unsigned long len, unsigned char *hash)
528 assert((c = EVP_MD_CTX_new()));
529 ret = EVP_DigestInit_ex(c, EVP_sha1(), NULL);
531 ret = EVP_DigestUpdate(c, data, len);
533 ret = EVP_DigestFinal_ex(c, hash, NULL);
538 void hash2_function(const char *data, unsigned long len, unsigned char *hash)
543 assert((c = EVP_MD_CTX_new()));
544 ret = EVP_DigestInit_ex(c, EVP_sha256(), NULL);
546 ret = EVP_DigestUpdate(c, data, len);
548 ret = EVP_DigestFinal_ex(c, hash, NULL);