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