resample filter: Don't discard const.
[paraslash.git] / crypt.c
1 /*
2  * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file crypt.c Openssl-based encryption/decryption routines. */
8
9 #include <regex.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <openssl/rand.h>
13 #include <openssl/err.h>
14 #include <openssl/rc4.h>
15 #include <openssl/pem.h>
16 #include <openssl/sha.h>
17 #include <openssl/bn.h>
18 #include <openssl/aes.h>
19
20 #include "para.h"
21 #include "error.h"
22 #include "string.h"
23 #include "crypt.h"
24 #include "fd.h"
25 #include "crypt_backend.h"
26 #include "base64.h"
27
28 struct asymmetric_key {
29         RSA *rsa;
30 };
31
32 void get_random_bytes_or_die(unsigned char *buf, int num)
33 {
34         unsigned long err;
35
36         /* RAND_bytes() returns 1 on success, 0 otherwise. */
37         if (RAND_bytes(buf, num) == 1)
38                 return;
39         err = ERR_get_error();
40         PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
41         exit(EXIT_FAILURE);
42 }
43
44 /*
45  * Read 64 bytes from /dev/urandom and adds them to the SSL PRNG. Seed the PRNG
46  * used by random() with a random seed obtained from SSL. If /dev/random is not
47  * readable the function calls exit().
48  *
49  * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
50  * random(3), \ref para_random().
51  */
52 void init_random_seed_or_die(void)
53 {
54         int seed, ret = RAND_load_file("/dev/urandom", 64);
55
56         if (ret != 64) {
57                 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
58                 exit(EXIT_FAILURE);
59         }
60         get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
61         srandom(seed);
62 }
63
64 static EVP_PKEY *load_key(const char *file, int private)
65 {
66         BIO *key;
67         EVP_PKEY *pkey = NULL;
68         int ret = check_key_file(file, private);
69
70         if (ret < 0) {
71                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
72                 return NULL;
73         }
74         key = BIO_new(BIO_s_file());
75         if (!key)
76                 return NULL;
77         if (BIO_read_filename(key, file) > 0) {
78                 if (private == LOAD_PRIVATE_KEY)
79                         pkey = PEM_read_bio_PrivateKey(key, NULL, NULL, NULL);
80                 else
81                         pkey = PEM_read_bio_PUBKEY(key, NULL, NULL, NULL);
82         }
83         BIO_free(key);
84         return pkey;
85 }
86
87 static int get_openssl_key(const char *key_file, RSA **rsa, int private)
88 {
89         EVP_PKEY *key = load_key(key_file, private);
90
91         if (!key)
92                 return (private == LOAD_PRIVATE_KEY)? -E_PRIVATE_KEY
93                         : -E_PUBLIC_KEY;
94         *rsa = EVP_PKEY_get1_RSA(key);
95         EVP_PKEY_free(key);
96         if (!*rsa)
97                 return -E_RSA;
98         return RSA_size(*rsa);
99 }
100
101 /*
102  * The public key loading functions below were inspired by corresponding code
103  * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
104  * Finland. However, not much of the original code remains.
105  */
106
107 static int read_bignum(const unsigned char *buf, size_t len, BIGNUM **result)
108 {
109         const unsigned char *p = buf, *end = buf + len;
110         uint32_t bnsize;
111         BIGNUM *bn;
112
113         if (p + 4 < p)
114                 return -E_BIGNUM;
115         if (p + 4 > end)
116                 return -E_BIGNUM;
117         bnsize = read_ssh_u32(p);
118         PARA_DEBUG_LOG("bnsize: %u\n", bnsize);
119         p += 4;
120         if (p + bnsize < p)
121                 return -E_BIGNUM;
122         if (p + bnsize > end)
123                 return -E_BIGNUM;
124         if (bnsize > 8192)
125                 return -E_BIGNUM;
126         bn = BN_bin2bn(p, bnsize, NULL);
127         if (!bn)
128                 return -E_BIGNUM;
129         *result = bn;
130         return bnsize + 4;
131 }
132
133 static int read_rsa_bignums(const unsigned char *blob, int blen, RSA **result)
134 {
135         int ret;
136         RSA *rsa;
137         BIGNUM *n, *e;
138         const unsigned char *p = blob, *end = blob + blen;
139
140         rsa = RSA_new();
141         if (!rsa)
142                 return -E_BIGNUM;
143         ret = read_bignum(p, end - p, &e);
144         if (ret < 0)
145                 goto fail;
146         p += ret;
147         ret = read_bignum(p, end - p, &n);
148         if (ret < 0)
149                 goto fail;
150 #ifdef HAVE_RSA_SET0_KEY
151         RSA_set0_key(rsa, n, e, NULL);
152 #else
153         rsa->n = n;
154         rsa->e = e;
155 #endif
156         *result = rsa;
157         return 1;
158 fail:
159         RSA_free(rsa);
160         return ret;
161 }
162
163 int get_asymmetric_key(const char *key_file, int private,
164                 struct asymmetric_key **result)
165 {
166         struct asymmetric_key *key = NULL;
167         void *map = NULL;
168         unsigned char *blob = NULL;
169         size_t map_size, encoded_size, decoded_size;
170         int ret, ret2;
171         char *cp;
172
173         key = para_malloc(sizeof(*key));
174         if (private) {
175                 ret = get_openssl_key(key_file, &key->rsa, LOAD_PRIVATE_KEY);
176                 goto out;
177         }
178         ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
179         if (ret < 0)
180                 goto out;
181         ret = is_ssh_rsa_key(map, map_size);
182         if (!ret) {
183                 ret = para_munmap(map, map_size);
184                 map = NULL;
185                 if (ret < 0)
186                         goto out;
187                 ret = get_openssl_key(key_file, &key->rsa, LOAD_PUBLIC_KEY);
188                 goto out;
189         }
190         cp = map + ret;
191         encoded_size = map_size - ret;
192         PARA_INFO_LOG("decoding public rsa-ssh key %s\n", key_file);
193         ret = uudecode(cp, encoded_size, (char **)&blob, &decoded_size);
194         if (ret < 0)
195                 goto out_unmap;
196         ret = check_ssh_key_header(blob, decoded_size);
197         if (ret < 0)
198                 goto out_unmap;
199         ret = read_rsa_bignums(blob + ret, decoded_size - ret, &key->rsa);
200         if (ret < 0)
201                 goto out_unmap;
202         ret = RSA_size(key->rsa);
203 out_unmap:
204         ret2 = para_munmap(map, map_size);
205         if (ret >= 0 && ret2 < 0)
206                 ret = ret2;
207 out:
208         if (ret < 0) {
209                 free(key);
210                 *result = NULL;
211                 PARA_ERROR_LOG("key %s: %s\n", key_file, para_strerror(-ret));
212         } else
213                 *result = key;
214         free(blob);
215         return ret;
216 }
217
218 void free_asymmetric_key(struct asymmetric_key *key)
219 {
220         if (!key)
221                 return;
222         RSA_free(key->rsa);
223         free(key);
224 }
225
226 int priv_decrypt(const char *key_file, unsigned char *outbuf,
227                 unsigned char *inbuf, int inlen)
228 {
229         struct asymmetric_key *priv;
230         int ret;
231
232         if (inlen < 0)
233                 return -E_RSA;
234         ret = get_asymmetric_key(key_file, LOAD_PRIVATE_KEY, &priv);
235         if (ret < 0)
236                 return ret;
237         /*
238          * RSA is vulnerable to timing attacks. Generate a random blinding
239          * factor to protect against this kind of attack.
240          */
241         ret = -E_BLINDING;
242         if (RSA_blinding_on(priv->rsa, NULL) == 0)
243                 goto out;
244         ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
245                 RSA_PKCS1_OAEP_PADDING);
246         RSA_blinding_off(priv->rsa);
247         if (ret <= 0)
248                 ret = -E_DECRYPT;
249 out:
250         free_asymmetric_key(priv);
251         return ret;
252 }
253
254 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
255                 unsigned len, unsigned char *outbuf)
256 {
257         int ret, flen = len; /* RSA_public_encrypt expects a signed int */
258
259         if (flen < 0)
260                 return -E_ENCRYPT;
261         ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
262                 RSA_PKCS1_OAEP_PADDING);
263         return ret < 0? -E_ENCRYPT : ret;
264 }
265
266 struct stream_cipher {
267         bool use_aes;
268         union {
269                 RC4_KEY rc4_key;
270                 EVP_CIPHER_CTX *aes;
271         } context;
272 };
273
274 struct stream_cipher *sc_new(const unsigned char *data, int len,
275                 bool use_aes)
276 {
277         struct stream_cipher *sc = para_malloc(sizeof(*sc));
278
279         sc->use_aes = use_aes;
280         if (!use_aes) {
281                 RC4_set_key(&sc->context.rc4_key, len, data);
282                 return sc;
283         }
284         assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
285         sc->context.aes = EVP_CIPHER_CTX_new();
286         EVP_EncryptInit_ex(sc->context.aes, EVP_aes_128_ctr(), NULL, data,
287                 data + AES_CRT128_BLOCK_SIZE);
288         return sc;
289 }
290
291 void sc_free(struct stream_cipher *sc)
292 {
293         if (!sc)
294                 return;
295         EVP_CIPHER_CTX_free(sc->context.aes);
296         free(sc);
297 }
298
299 /**
300  * The RC4() implementation of openssl apparently reads and writes data in
301  * blocks of 8 bytes. So we have to make sure our buffer sizes are a multiple
302  * of this.
303  */
304 #define RC4_ALIGN 8
305
306 static void rc4_crypt(RC4_KEY *key, struct iovec *src, struct iovec *dst)
307 {
308         size_t len = src->iov_len, l1, l2;
309
310         assert(len > 0);
311         assert(len < ((typeof(src->iov_len))-1) / 2);
312         l1 = ROUND_DOWN(len, RC4_ALIGN);
313         l2 = ROUND_UP(len, RC4_ALIGN);
314
315         *dst = (typeof(*dst)) {
316                 /* Add one for the terminating zero byte. */
317                 .iov_base = para_malloc(l2 + 1),
318                 .iov_len = len
319         };
320         RC4(key, l1, src->iov_base, dst->iov_base);
321         if (len > l1) {
322                 unsigned char remainder[RC4_ALIGN] = "";
323                 memcpy(remainder, src->iov_base + l1, len - l1);
324                 RC4(key, len - l1, remainder, dst->iov_base + l1);
325         }
326         ((char *)dst->iov_base)[len] = '\0';
327 }
328
329 static void aes_ctr128_crypt(EVP_CIPHER_CTX *ctx, struct iovec *src,
330                 struct iovec *dst)
331 {
332         int ret, inlen = src->iov_len, outlen, tmplen;
333
334         *dst = (typeof(*dst)) {
335                 /* Add one for the terminating zero byte. */
336                 .iov_base = para_malloc(inlen + 1),
337                 .iov_len = inlen
338         };
339         ret = EVP_EncryptUpdate(ctx, dst->iov_base, &outlen, src->iov_base, inlen);
340         assert(ret != 0);
341         ret = EVP_EncryptFinal_ex(ctx, dst->iov_base + outlen, &tmplen);
342         assert(ret != 0);
343         outlen += tmplen;
344         ((char *)dst->iov_base)[outlen] = '\0';
345         dst->iov_len = outlen;
346 }
347
348 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
349 {
350         if (sc->use_aes)
351                 return aes_ctr128_crypt(sc->context.aes, src, dst);
352         return rc4_crypt(&sc->context.rc4_key, src, dst);
353 }
354
355 void hash_function(const char *data, unsigned long len, unsigned char *hash)
356 {
357         SHA_CTX c;
358         SHA1_Init(&c);
359         SHA1_Update(&c, data, len);
360         SHA1_Final(hash, &c);
361 }