Merge branch 'refs/heads/t/duration-keyword' into pu
[paraslash.git] / openssl.c
1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file openssl.c Openssl-based encryption/decryption routines. */
4
5 #include <regex.h>
6 #include <sys/types.h>
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
15 #include "para.h"
16 #include "error.h"
17 #include "string.h"
18 #include "crypt.h"
19 #include "crypt_backend.h"
20 #include "portable_io.h"
21
22 struct asymmetric_key {
23 RSA *rsa;
24 };
25
26 void get_random_bytes_or_die(unsigned char *buf, int num)
27 {
28 unsigned long err;
29
30 /* RAND_bytes() returns 1 on success, 0 otherwise. */
31 if (RAND_bytes(buf, num) == 1)
32 return;
33 err = ERR_get_error();
34 PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
35 exit(EXIT_FAILURE);
36 }
37
38 /*
39 * Read 64 bytes from /dev/urandom and add them to the SSL PRNG. Seed the PRNG
40 * used by random(3) with a random seed obtained from SSL. If /dev/urandom is
41 * not readable, the function calls exit().
42 *
43 * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
44 * random(3), \ref para_random().
45 */
46 void crypt_init(void)
47 {
48 int seed, ret = RAND_load_file("/dev/urandom", 64);
49
50 if (ret != 64) {
51 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
52 exit(EXIT_FAILURE);
53 }
54 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
55 srandom(seed);
56 }
57
58 void crypt_shutdown(void)
59 {
60 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
61 CRYPTO_cleanup_all_ex_data();
62 #endif
63 #ifdef HAVE_OPENSSL_THREAD_STOP /* openssl-1.1 or later */
64 OPENSSL_thread_stop();
65 #else /* openssl-1.0 */
66 ERR_remove_thread_state(NULL);
67 #endif
68 EVP_cleanup();
69 }
70
71 /*
72 * The public key loading functions below were inspired by corresponding code
73 * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
74 * Finland. However, not much of the original code remains.
75 */
76
77 static int read_bignum(const unsigned char *buf, size_t len, BIGNUM **result)
78 {
79 const unsigned char *p = buf, *end = buf + len;
80 uint32_t bnsize;
81 BIGNUM *bn;
82
83 if (p + 4 < p)
84 return -E_BIGNUM;
85 if (p + 4 > end)
86 return -E_BIGNUM;
87 bnsize = read_u32_be(p);
88 PARA_DEBUG_LOG("bnsize: %u\n", bnsize);
89 p += 4;
90 if (p + bnsize < p)
91 return -E_BIGNUM;
92 if (p + bnsize > end)
93 return -E_BIGNUM;
94 if (bnsize > 8192)
95 return -E_BIGNUM;
96 bn = BN_bin2bn(p, bnsize, NULL);
97 if (!bn)
98 return -E_BIGNUM;
99 *result = bn;
100 return bnsize + 4;
101 }
102
103 static int read_rsa_bignums(const unsigned char *blob, int blen, RSA **result)
104 {
105 int ret;
106 RSA *rsa;
107 BIGNUM *n, *e;
108 const unsigned char *p = blob, *end = blob + blen;
109
110 rsa = RSA_new();
111 if (!rsa)
112 return -E_BIGNUM;
113 ret = read_bignum(p, end - p, &e);
114 if (ret < 0)
115 goto free_rsa;
116 p += ret;
117 ret = read_bignum(p, end - p, &n);
118 if (ret < 0)
119 goto free_e;
120 #ifdef HAVE_RSA_SET0_KEY
121 RSA_set0_key(rsa, n, e, NULL);
122 #else
123 rsa->n = n;
124 rsa->e = e;
125 #endif
126 *result = rsa;
127 return 1;
128 free_e:
129 BN_free(e);
130 free_rsa:
131 RSA_free(rsa);
132 return ret;
133 }
134
135 static int read_pem_private_key(const char *path, RSA **rsa)
136 {
137 EVP_PKEY *pkey;
138 BIO *bio = BIO_new(BIO_s_file());
139
140 *rsa = NULL;
141 if (!bio)
142 return -E_PRIVATE_KEY;
143 if (BIO_read_filename(bio, path) <= 0)
144 goto bio_free;
145 pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
146 if (!pkey)
147 goto bio_free;
148 *rsa = EVP_PKEY_get1_RSA(pkey);
149 EVP_PKEY_free(pkey);
150 bio_free:
151 BIO_free(bio);
152 return *rsa? RSA_size(*rsa) : -E_PRIVATE_KEY;
153 }
154
155 static int read_private_rsa_params(const unsigned char *blob,
156 const unsigned char *end, RSA **result)
157 {
158 int ret;
159 RSA *rsa;
160 BN_CTX *ctx;
161 BIGNUM *n, *e, *d, *iqmp, *p, *q; /* stored in the key file */
162 BIGNUM *dmp1, *dmq1; /* these will be computed */
163 BIGNUM *tmp;
164 const unsigned char *cp = blob;
165
166 rsa = RSA_new();
167 if (!rsa)
168 return -E_BIGNUM;
169 ret = -E_BIGNUM;
170 tmp = BN_new();
171 if (!tmp)
172 goto free_rsa;
173 ctx = BN_CTX_new();
174 if (!ctx)
175 goto free_tmp;
176 dmp1 = BN_new();
177 if (!dmp1)
178 goto free_ctx;
179 dmq1 = BN_new();
180 if (!dmq1)
181 goto free_dmp1;
182 ret = read_bignum(cp, end - cp, &n);
183 if (ret < 0)
184 goto free_dmq1;
185 cp += ret;
186 ret = read_bignum(cp, end - cp, &e);
187 if (ret < 0)
188 goto free_n;
189 cp += ret;
190 ret = read_bignum(cp, end - cp, &d);
191 if (ret < 0)
192 goto free_e;
193 cp += ret;
194 ret = read_bignum(cp, end - cp, &iqmp);
195 if (ret < 0)
196 goto free_d;
197 cp += ret;
198 ret = read_bignum(cp, end - cp, &p);
199 if (ret < 0)
200 goto free_iqmp;
201 cp += ret;
202 ret = read_bignum(cp, end - cp, &q);
203 if (ret < 0)
204 goto free_p;
205 ret = -E_BIGNUM;
206 if (!BN_sub(tmp, q, BN_value_one()))
207 goto free_q;
208 if (!BN_mod(dmp1, d, tmp, ctx))
209 goto free_q;
210 if (!BN_sub(tmp, q, BN_value_one()))
211 goto free_q;
212 if (!BN_mod(dmq1, d, tmp, ctx))
213 goto free_q;
214 #ifdef HAVE_RSA_SET0_KEY
215 RSA_set0_key(rsa, n, e, d);
216 RSA_set0_factors(rsa, p, q);
217 RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp);
218 #else
219 rsa->n = n;
220 rsa->e = e;
221 rsa->d = d;
222 rsa->p = p;
223 rsa->q = q;
224 rsa->dmp1 = dmp1;
225 rsa->dmq1 = dmq1;
226 rsa->iqmp = iqmp;
227 #endif
228 *result = rsa;
229 ret = 1;
230 goto free_ctx;
231 free_q:
232 BN_clear_free(q);
233 free_p:
234 BN_clear_free(p);
235 free_iqmp:
236 BN_clear_free(iqmp);
237 free_d:
238 BN_clear_free(d);
239 free_e:
240 BN_free(e);
241 free_n:
242 BN_free(n);
243 free_dmq1:
244 BN_clear_free(dmq1);
245 free_dmp1:
246 BN_clear_free(dmp1);
247 free_ctx:
248 BN_CTX_free(ctx);
249 free_tmp:
250 BN_clear_free(tmp);
251 free_rsa:
252 if (ret < 0)
253 RSA_free(rsa);
254 return ret;
255 }
256
257 static int get_private_key(const char *path, RSA **rsa)
258 {
259 int ret;
260 unsigned char *blob, *end;
261 size_t blob_size;
262
263 *rsa = NULL;
264 ret = decode_private_key(path, &blob, &blob_size);
265 if (ret < 0)
266 return ret;
267 end = blob + blob_size;
268 if (ret == PKT_OPENSSH) {
269 ret = find_openssh_bignum_offset(blob, blob_size);
270 if (ret < 0)
271 goto free_blob;
272 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
273 ret = read_private_rsa_params(blob + ret, end, rsa);
274 } else
275 ret = read_pem_private_key(path, rsa);
276 free_blob:
277 free(blob);
278 return ret;
279 }
280
281 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
282 {
283 unsigned char *blob;
284 size_t decoded_size;
285 int ret;
286 struct asymmetric_key *key = para_malloc(sizeof(*key));
287
288 ret = decode_public_key(key_file, &blob, &decoded_size);
289 if (ret < 0)
290 goto out;
291 ret = read_rsa_bignums(blob + ret, decoded_size - ret, &key->rsa);
292 if (ret < 0)
293 goto free_blob;
294 ret = RSA_size(key->rsa);
295 assert(ret > 0);
296 *result = key;
297 free_blob:
298 free(blob);
299 out:
300 if (ret < 0) {
301 free(key);
302 *result = NULL;
303 PARA_ERROR_LOG("can not load key %s\n", key_file);
304 }
305 return ret;
306 }
307
308 void apc_free_pubkey(struct asymmetric_key *key)
309 {
310 if (!key)
311 return;
312 RSA_free(key->rsa);
313 free(key);
314 }
315
316 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
317 unsigned char *inbuf, int inlen)
318 {
319 struct asymmetric_key *priv;
320 int ret;
321
322 ret = check_private_key_file(key_file);
323 if (ret < 0)
324 return ret;
325 if (inlen < 0)
326 return -E_RSA;
327 priv = para_malloc(sizeof(*priv));
328 ret = get_private_key(key_file, &priv->rsa);
329 if (ret < 0) {
330 free(priv);
331 return ret;
332 }
333 /*
334 * RSA is vulnerable to timing attacks. Generate a random blinding
335 * factor to protect against this kind of attack.
336 */
337 ret = -E_BLINDING;
338 if (RSA_blinding_on(priv->rsa, NULL) == 0)
339 goto out;
340 ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
341 RSA_PKCS1_OAEP_PADDING);
342 RSA_blinding_off(priv->rsa);
343 if (ret <= 0)
344 ret = -E_DECRYPT;
345 out:
346 RSA_free(priv->rsa);
347 free(priv);
348 return ret;
349 }
350
351 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
352 unsigned len, unsigned char *outbuf)
353 {
354 int ret, flen = len; /* RSA_public_encrypt expects a signed int */
355
356 if (flen < 0)
357 return -E_ENCRYPT;
358 ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
359 RSA_PKCS1_OAEP_PADDING);
360 return ret < 0? -E_ENCRYPT : ret;
361 }
362
363 struct stream_cipher {
364 EVP_CIPHER_CTX *aes;
365 };
366
367 struct stream_cipher *sc_new(const unsigned char *data, int len)
368 {
369 struct stream_cipher *sc = para_malloc(sizeof(*sc));
370
371 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
372 sc->aes = EVP_CIPHER_CTX_new();
373 EVP_EncryptInit_ex(sc->aes, EVP_aes_128_ctr(), NULL, data,
374 data + AES_CRT128_BLOCK_SIZE);
375 return sc;
376 }
377
378 void sc_free(struct stream_cipher *sc)
379 {
380 if (!sc)
381 return;
382 EVP_CIPHER_CTX_free(sc->aes);
383 free(sc);
384 }
385
386 static void aes_ctr128_crypt(EVP_CIPHER_CTX *ctx, struct iovec *src,
387 struct iovec *dst)
388 {
389 int ret, inlen = src->iov_len, outlen, tmplen;
390
391 *dst = (typeof(*dst)) {
392 /* Add one for the terminating zero byte. */
393 .iov_base = para_malloc(inlen + 1),
394 .iov_len = inlen
395 };
396 ret = EVP_EncryptUpdate(ctx, dst->iov_base, &outlen, src->iov_base, inlen);
397 assert(ret != 0);
398 ret = EVP_EncryptFinal_ex(ctx, dst->iov_base + outlen, &tmplen);
399 assert(ret != 0);
400 outlen += tmplen;
401 ((char *)dst->iov_base)[outlen] = '\0';
402 dst->iov_len = outlen;
403 }
404
405 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
406 {
407 return aes_ctr128_crypt(sc->aes, src, dst);
408 }
409
410 void hash_function(const char *data, unsigned long len, unsigned char *hash)
411 {
412 SHA_CTX c;
413 SHA1_Init(&c);
414 SHA1_Update(&c, data, len);
415 SHA1_Final(hash, &c);
416 }