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