7b602d995d3deccaba5e2e6ab76f4dec5570c95b
[paraslash.git] / crypt.c
1 /*
2 * Copyright (C) 2005-2011 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 <stdbool.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <openssl/rand.h>
14 #include <openssl/err.h>
15 #include <openssl/rc4.h>
16 #include <openssl/pem.h>
17 #include <openssl/sha.h>
18 #include <openssl/bn.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 /**
32 * Fill a buffer with random content.
33 *
34 * \param buf The buffer to fill.
35 * \param num The size of \a buf in bytes.
36 *
37 * This function puts \a num cryptographically strong pseudo-random bytes into
38 * buf. If libssl can not guarantee an unpredictable byte sequence (for example
39 * because the PRNG has not been seeded with enough randomness) the function
40 * logs an error message and calls exit().
41 */
42 void get_random_bytes_or_die(unsigned char *buf, int num)
43 {
44 unsigned long err;
45
46 /* RAND_bytes() returns 1 on success, 0 otherwise. */
47 if (RAND_bytes(buf, num) == 1)
48 return;
49 err = ERR_get_error();
50 PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
51 exit(EXIT_FAILURE);
52 }
53
54 /**
55 * Seed pseudo random number generators.
56 *
57 * This function reads 64 bytes from /dev/urandom and adds them to the SSL
58 * PRNG. It also seeds the PRNG used by random() with a random seed obtained
59 * from SSL. If /dev/random could not be read, an error message is logged and
60 * the function calls exit().
61 *
62 * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
63 * random(3), \ref para_random().
64 */
65 void init_random_seed_or_die(void)
66 {
67 int seed, ret = RAND_load_file("/dev/urandom", 64);
68
69 if (ret != 64) {
70 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
71 exit(EXIT_FAILURE);
72 }
73 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
74 srandom(seed);
75 }
76
77 static EVP_PKEY *load_key(const char *file, int private)
78 {
79 BIO *key;
80 EVP_PKEY *pkey = NULL;
81 int ret = check_key_file(file, private);
82
83 if (ret < 0) {
84 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
85 return NULL;
86 }
87 key = BIO_new(BIO_s_file());
88 if (!key)
89 return NULL;
90 if (BIO_read_filename(key, file) > 0) {
91 if (private == LOAD_PRIVATE_KEY)
92 pkey = PEM_read_bio_PrivateKey(key, NULL, NULL, NULL);
93 else
94 pkey = PEM_read_bio_PUBKEY(key, NULL, NULL, NULL);
95 }
96 BIO_free(key);
97 return pkey;
98 }
99
100 static int get_openssl_key(const char *key_file, RSA **rsa, int private)
101 {
102 EVP_PKEY *key = load_key(key_file, private);
103
104 if (!key)
105 return (private == LOAD_PRIVATE_KEY)? -E_PRIVATE_KEY
106 : -E_PUBLIC_KEY;
107 *rsa = EVP_PKEY_get1_RSA(key);
108 EVP_PKEY_free(key);
109 if (!*rsa)
110 return -E_RSA;
111 return RSA_size(*rsa);
112 }
113
114 /*
115 * The public key loading functions below were inspired by corresponding code
116 * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
117 * Finland. However, not much of the original code remains.
118 */
119
120 static int read_bignum(const unsigned char *buf, size_t len, BIGNUM **result)
121 {
122 const unsigned char *p = buf, *end = buf + len;
123 uint32_t bnsize;
124 BIGNUM *bn;
125
126 if (p + 4 < p)
127 return -E_BIGNUM;
128 if (p + 4 > end)
129 return -E_BIGNUM;
130 bnsize = read_ssh_u32(p);
131 PARA_DEBUG_LOG("bnsize: %u\n", bnsize);
132 p += 4;
133 if (p + bnsize < p)
134 return -E_BIGNUM;
135 if (p + bnsize > end)
136 return -E_BIGNUM;
137 if (bnsize > 8192)
138 return -E_BIGNUM;
139 bn = BN_bin2bn(p, bnsize, NULL);
140 if (!bn)
141 return -E_BIGNUM;
142 *result = bn;
143 return bnsize + 4;
144 }
145
146 static int read_rsa_bignums(const unsigned char *blob, int blen, RSA **result)
147 {
148 int ret;
149 RSA *rsa;
150 const unsigned char *p = blob, *end = blob + blen;
151
152 rsa = RSA_new();
153 if (!rsa)
154 return -E_BIGNUM;
155 ret = read_bignum(p, end - p, &rsa->e);
156 if (ret < 0)
157 goto fail;
158 p += ret;
159 ret = read_bignum(p, end - p, &rsa->n);
160 if (ret < 0)
161 goto fail;
162 *result = rsa;
163 return 1;
164 fail:
165 if (rsa)
166 RSA_free(rsa);
167 return ret;
168 }
169
170 /**
171 * Read an asymmetric key from a file.
172 *
173 * \param key_file The file containing the key.
174 * \param private if non-zero, read the private key, otherwise the public key.
175 * \param result The key structure is returned here.
176 *
177 * \return The size of the key on success, negative on errors.
178 *
179 * \sa openssl(1), rsa(1).
180 */
181 int get_asymmetric_key(const char *key_file, int private,
182 struct asymmetric_key **result)
183 {
184 struct asymmetric_key *key = NULL;
185 void *map = NULL;
186 unsigned char *blob = NULL;
187 size_t map_size, blob_size, decoded_size;
188 int ret, ret2;
189 char *cp;
190
191 key = para_malloc(sizeof(*key));
192 if (private) {
193 ret = get_openssl_key(key_file, &key->rsa, LOAD_PRIVATE_KEY);
194 goto out;
195 }
196 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
197 if (ret < 0)
198 goto out;
199 ret = is_ssh_rsa_key(map, map_size);
200 if (!ret) {
201 ret = para_munmap(map, map_size);
202 map = NULL;
203 if (ret < 0)
204 goto out;
205 ret = get_openssl_key(key_file, &key->rsa, LOAD_PUBLIC_KEY);
206 goto out;
207 }
208 cp = map + ret;
209 PARA_INFO_LOG("decoding public rsa-ssh key %s\n", key_file);
210 ret = -ERRNO_TO_PARA_ERROR(EOVERFLOW);
211 if (map_size > INT_MAX / 4)
212 goto out;
213 blob_size = 2 * map_size;
214 blob = para_malloc(blob_size);
215 ret = uudecode(cp, blob, blob_size);
216 if (ret < 0)
217 goto out;
218 decoded_size = ret;
219 ret = check_ssh_key_header(blob, decoded_size);
220 if (ret < 0)
221 goto out;
222 ret = read_rsa_bignums(blob + ret, decoded_size - ret, &key->rsa);
223 if (ret < 0)
224 goto out;
225 ret = RSA_size(key->rsa);
226 out:
227 ret2 = para_munmap(map, map_size);
228 if (ret >= 0 && ret2 < 0)
229 ret = ret2;
230 if (ret < 0) {
231 free(key);
232 result = NULL;
233 PARA_ERROR_LOG("key %s: %s\n", key_file, para_strerror(-ret));
234 } else
235 *result = key;
236 free(blob);
237 return ret;
238 }
239
240 /**
241 * Deallocate an asymmetric key structure.
242 *
243 * \param key Pointer to the key structure to free.
244 *
245 * This must be called for any key obtained by get_asymmetric_key().
246 */
247 void free_asymmetric_key(struct asymmetric_key *key)
248 {
249 if (!key)
250 return;
251 RSA_free(key->rsa);
252 free(key);
253 }
254
255 /**
256 * Decrypt a buffer using a private key.
257 *
258 * \param key_file Full path of the key.
259 * \param outbuf The output buffer.
260 * \param inbuf The encrypted input buffer.
261 * \param inlen The length of \a inbuf in bytes.
262 *
263 * The \a outbuf must be large enough to hold at least \a rsa_inlen bytes.
264 *
265 * \return The size of the recovered plaintext on success, negative on errors.
266 *
267 * \sa RSA_private_decrypt(3)
268 **/
269 int priv_decrypt(const char *key_file, unsigned char *outbuf,
270 unsigned char *inbuf, int inlen)
271 {
272 struct asymmetric_key *priv;
273 int ret;
274
275 if (inlen < 0)
276 return -E_RSA;
277 ret = get_asymmetric_key(key_file, LOAD_PRIVATE_KEY, &priv);
278 if (ret < 0)
279 return ret;
280 /*
281 * RSA is vulnerable to timing attacks. Generate a random blinding
282 * factor to protect against this kind of attack.
283 */
284 ret = -E_BLINDING;
285 if (RSA_blinding_on(priv->rsa, NULL) == 0)
286 goto out;
287 ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
288 RSA_PKCS1_OAEP_PADDING);
289 RSA_blinding_off(priv->rsa);
290 if (ret <= 0)
291 ret = -E_DECRYPT;
292 out:
293 free_asymmetric_key(priv);
294 return ret;
295 }
296
297 /**
298 * Encrypt a buffer using an RSA key
299 *
300 * \param pub: The public key.
301 * \param inbuf The input buffer.
302 * \param len The length of \a inbuf.
303 * \param outbuf The output buffer.
304 *
305 * \return The size of the encrypted data on success, negative on errors.
306 *
307 * \sa RSA_public_encrypt(3)
308 */
309 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
310 unsigned len, unsigned char *outbuf)
311 {
312 int ret, flen = len; /* RSA_public_encrypt expects a signed int */
313
314 if (flen < 0)
315 return -E_ENCRYPT;
316 ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
317 RSA_PKCS1_OAEP_PADDING);
318 return ret < 0? -E_ENCRYPT : ret;
319 }
320
321 struct stream_cipher {
322 RC4_KEY key;
323 };
324
325 /**
326 * Allocate and initialize a stream cipher structure.
327 *
328 * \param data The key.
329 * \param len The size of the key.
330 *
331 * \return A new stream cipher structure.
332 */
333 struct stream_cipher *sc_new(const unsigned char *data, int len)
334 {
335 struct stream_cipher *sc = para_malloc(sizeof(*sc));
336 RC4_set_key(&sc->key, len, data);
337 return sc;
338 }
339
340 /**
341 * Deallocate a stream cipher structure.
342 *
343 * \param sc A stream cipher previously obtained by sc_new().
344 */
345 void sc_free(struct stream_cipher *sc)
346 {
347 free(sc);
348 }
349
350 /**
351 * The RC4() implementation of openssl apparently reads and writes data in
352 * blocks of 8 bytes. So we have to make sure our buffer sizes are a multiple
353 * of this.
354 */
355 #define RC4_ALIGN 8
356
357 /**
358 * Encrypt and send a buffer.
359 *
360 * \param scc The context.
361 * \param buf The buffer to send.
362 * \param len The size of \a buf in bytes.
363 *
364 * \return The return value of the underyling call to write_all().
365 *
366 * \sa \ref write_all(), RC4(3).
367 */
368 int sc_send_bin_buffer(struct stream_cipher_context *scc, const char *buf,
369 size_t len)
370 {
371 int ret;
372 unsigned char *tmp;
373 static unsigned char remainder[RC4_ALIGN];
374 size_t l1 = ROUND_DOWN(len, RC4_ALIGN), l2 = ROUND_UP(len, RC4_ALIGN);
375
376 assert(len);
377 tmp = para_malloc(l2);
378 RC4(&scc->send->key, l1, (const unsigned char *)buf, tmp);
379 if (len > l1) {
380 memcpy(remainder, buf + l1, len - l1);
381 RC4(&scc->send->key, len - l1, remainder, tmp + l1);
382 }
383 ret = write_all(scc->fd, (char *)tmp, &len);
384 free(tmp);
385 return ret;
386 }
387
388 /**
389 * Receive a buffer and decrypt it.
390 *
391 * \param scc The context.
392 * \param buf The buffer to write the decrypted data to.
393 * \param size The size of \a buf.
394 *
395 * \return The number of bytes received on success, negative on errors, zero if
396 * the peer has performed an orderly shutdown.
397 *
398 * \sa recv(2), RC4(3).
399 */
400 int sc_recv_bin_buffer(struct stream_cipher_context *scc, char *buf,
401 size_t size)
402 {
403 unsigned char *tmp = para_malloc(size);
404 ssize_t ret = recv(scc->fd, tmp, size, 0);
405
406 if (ret > 0)
407 RC4(&scc->recv->key, ret, tmp, (unsigned char *)buf);
408 else if (ret < 0)
409 ret = -ERRNO_TO_PARA_ERROR(errno);
410 free(tmp);
411 return ret;
412 }
413
414 /**
415 * Compute the hash of the given input data.
416 *
417 * \param data Pointer to the data to compute the hash value from.
418 * \param len The length of \a data in bytes.
419 * \param hash Result pointer.
420 *
421 * \a hash must point to an area at least \p HASH_SIZE bytes large.
422 *
423 * \sa sha(3), openssl(1).
424 * */
425 void hash_function(const char *data, unsigned long len, unsigned char *hash)
426 {
427 SHA_CTX c;
428 SHA1_Init(&c);
429 SHA1_Update(&c, data, len);
430 SHA1_Final(hash, &c);
431 }