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