]> git.tuebingen.mpg.de Git - paraslash.git/blob - crypt.c
222bece7249add6aa01639419d63a42426ca9c84
[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         const unsigned char *p = blob, *end = blob + blen;
138
139         rsa = RSA_new();
140         if (!rsa)
141                 return -E_BIGNUM;
142         ret = read_bignum(p, end - p, &rsa->e);
143         if (ret < 0)
144                 goto fail;
145         p += ret;
146         ret = read_bignum(p, end - p, &rsa->n);
147         if (ret < 0)
148                 goto fail;
149         *result = rsa;
150         return 1;
151 fail:
152         RSA_free(rsa);
153         return ret;
154 }
155
156 int get_asymmetric_key(const char *key_file, int private,
157                 struct asymmetric_key **result)
158 {
159         struct asymmetric_key *key = NULL;
160         void *map = NULL;
161         unsigned char *blob = NULL;
162         size_t map_size, blob_size, decoded_size;
163         int ret, ret2;
164         char *cp;
165
166         key = para_malloc(sizeof(*key));
167         if (private) {
168                 ret = get_openssl_key(key_file, &key->rsa, LOAD_PRIVATE_KEY);
169                 goto out;
170         }
171         ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
172         if (ret < 0)
173                 goto out;
174         ret = is_ssh_rsa_key(map, map_size);
175         if (!ret) {
176                 ret = para_munmap(map, map_size);
177                 map = NULL;
178                 if (ret < 0)
179                         goto out;
180                 ret = get_openssl_key(key_file, &key->rsa, LOAD_PUBLIC_KEY);
181                 goto out;
182         }
183         cp = map + ret;
184         PARA_INFO_LOG("decoding public rsa-ssh key %s\n", key_file);
185         ret = -ERRNO_TO_PARA_ERROR(EOVERFLOW);
186         if (map_size > INT_MAX / 4)
187                 goto out_unmap;
188         blob_size = 2 * map_size;
189         blob = para_malloc(blob_size);
190         ret = uudecode(cp, blob, blob_size);
191         if (ret < 0)
192                 goto out_unmap;
193         decoded_size = ret;
194         ret = check_ssh_key_header(blob, decoded_size);
195         if (ret < 0)
196                 goto out_unmap;
197         ret = read_rsa_bignums(blob + ret, decoded_size - ret, &key->rsa);
198         if (ret < 0)
199                 goto out_unmap;
200         ret = RSA_size(key->rsa);
201 out_unmap:
202         ret2 = para_munmap(map, map_size);
203         if (ret >= 0 && ret2 < 0)
204                 ret = ret2;
205 out:
206         if (ret < 0) {
207                 free(key);
208                 *result = NULL;
209                 PARA_ERROR_LOG("key %s: %s\n", key_file, para_strerror(-ret));
210         } else
211                 *result = key;
212         free(blob);
213         return ret;
214 }
215
216 void free_asymmetric_key(struct asymmetric_key *key)
217 {
218         if (!key)
219                 return;
220         RSA_free(key->rsa);
221         free(key);
222 }
223
224 int priv_decrypt(const char *key_file, unsigned char *outbuf,
225                 unsigned char *inbuf, int inlen)
226 {
227         struct asymmetric_key *priv;
228         int ret;
229
230         if (inlen < 0)
231                 return -E_RSA;
232         ret = get_asymmetric_key(key_file, LOAD_PRIVATE_KEY, &priv);
233         if (ret < 0)
234                 return ret;
235         /*
236          * RSA is vulnerable to timing attacks. Generate a random blinding
237          * factor to protect against this kind of attack.
238          */
239         ret = -E_BLINDING;
240         if (RSA_blinding_on(priv->rsa, NULL) == 0)
241                 goto out;
242         ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
243                 RSA_PKCS1_OAEP_PADDING);
244         RSA_blinding_off(priv->rsa);
245         if (ret <= 0)
246                 ret = -E_DECRYPT;
247 out:
248         free_asymmetric_key(priv);
249         return ret;
250 }
251
252 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
253                 unsigned len, unsigned char *outbuf)
254 {
255         int ret, flen = len; /* RSA_public_encrypt expects a signed int */
256
257         if (flen < 0)
258                 return -E_ENCRYPT;
259         ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
260                 RSA_PKCS1_OAEP_PADDING);
261         return ret < 0? -E_ENCRYPT : ret;
262 }
263
264 struct aes_ctr_128_context {
265         AES_KEY key;
266         unsigned char ivec[AES_CRT128_BLOCK_SIZE];
267         unsigned char ecount[AES_CRT128_BLOCK_SIZE];
268         unsigned int num;
269 };
270
271 struct stream_cipher {
272         bool use_aes;
273         union {
274                 RC4_KEY rc4_key;
275                 struct aes_ctr_128_context aes;
276         } context;
277 };
278
279 struct stream_cipher *sc_new(const unsigned char *data, int len,
280                 bool use_aes)
281 {
282         int ret;
283         struct stream_cipher *sc = para_malloc(sizeof(*sc));
284         struct aes_ctr_128_context *aes;
285
286         sc->use_aes = use_aes;
287         if (!use_aes) {
288                 RC4_set_key(&sc->context.rc4_key, len, data);
289                 return sc;
290         }
291         assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
292         aes = &sc->context.aes;
293         ret = AES_set_encrypt_key(data, AES_CRT128_BLOCK_SIZE * 8 /* bits */,
294                 &aes->key);
295         assert(ret == 0);
296         memcpy(aes->ivec, data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
297         aes->num = 0;
298         return sc;
299 }
300
301 void sc_free(struct stream_cipher *sc)
302 {
303         free(sc);
304 }
305
306 /**
307  * The RC4() implementation of openssl apparently reads and writes data in
308  * blocks of 8 bytes. So we have to make sure our buffer sizes are a multiple
309  * of this.
310  */
311 #define RC4_ALIGN 8
312
313 static void rc4_crypt(RC4_KEY *key, struct iovec *src, struct iovec *dst)
314 {
315         size_t len = src->iov_len, l1, l2;
316
317         assert(len > 0);
318         assert(len < ((typeof(src->iov_len))-1) / 2);
319         l1 = ROUND_DOWN(len, RC4_ALIGN);
320         l2 = ROUND_UP(len, RC4_ALIGN);
321
322         *dst = (typeof(*dst)) {
323                 /* Add one for the terminating zero byte. */
324                 .iov_base = para_malloc(l2 + 1),
325                 .iov_len = len
326         };
327         RC4(key, l1, src->iov_base, dst->iov_base);
328         if (len > l1) {
329                 unsigned char remainder[RC4_ALIGN] = "";
330                 memcpy(remainder, src->iov_base + l1, len - l1);
331                 RC4(key, len - l1, remainder, dst->iov_base + l1);
332         }
333         ((char *)dst->iov_base)[len] = '\0';
334 }
335
336 static void aes_ctr128_crypt(struct aes_ctr_128_context *aes, struct iovec *src,
337                 struct iovec *dst)
338 {
339         size_t len = src->iov_len;
340
341         *dst = (typeof(*dst)) {
342                 /* Add one for the terminating zero byte. */
343                 .iov_base = para_malloc(len + 1),
344                 .iov_len = len
345         };
346         AES_ctr128_encrypt(src->iov_base, dst->iov_base, len,
347                 &aes->key, aes->ivec, aes->ecount, &aes->num);
348         ((char *)dst->iov_base)[len] = '\0';
349 }
350
351 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
352 {
353         if (sc->use_aes)
354                 return aes_ctr128_crypt(&sc->context.aes, src, dst);
355         return rc4_crypt(&sc->context.rc4_key, src, dst);
356 }
357
358 void hash_function(const char *data, unsigned long len, unsigned char *hash)
359 {
360         SHA_CTX c;
361         SHA1_Init(&c);
362         SHA1_Update(&c, data, len);
363         SHA1_Final(hash, &c);
364 }