f3bfed3be755ccce6ba9ec1d89c40934babedc35
[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 <dirent.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
19 #include "para.h"
20 #include "error.h"
21 #include "string.h"
22 #include "crypt.h"
23 #include "fd.h"
24
25 struct asymmetric_key {
26         RSA *rsa;
27 };
28
29 /**
30  * Fill a buffer with random content.
31  *
32  * \param buf The buffer to fill.
33  * \param num The size of \a buf in bytes.
34  *
35  * This function puts \a num cryptographically strong pseudo-random bytes into
36  * buf. If libssl can not guarantee an unpredictable byte sequence (for example
37  * because the PRNG has not been seeded with enough randomness) the function
38  * logs an error message and calls exit().
39  */
40 void get_random_bytes_or_die(unsigned char *buf, int num)
41 {
42         unsigned long err;
43
44         /* RAND_bytes() returns 1 on success, 0 otherwise. */
45         if (RAND_bytes(buf, num) == 1)
46                 return;
47         err = ERR_get_error();
48         PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
49         exit(EXIT_FAILURE);
50 }
51
52 /**
53  * Seed pseudo random number generators.
54  *
55  * This function reads 64 bytes from /dev/urandom and adds them to the SSL
56  * PRNG. It also seeds the PRNG used by random() with a random seed obtained
57  * from SSL. If /dev/random could not be read, an error message is logged and
58  * the function calls exit().
59  *
60  * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
61  * random(3), \ref para_random().
62  */
63 void init_random_seed_or_die(void)
64 {
65         int seed, ret = RAND_load_file("/dev/urandom", 64);
66
67         if (ret != 64) {
68                 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
69                 exit(EXIT_FAILURE);
70         }
71         get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
72         srandom(seed);
73 }
74
75 static int check_key_file(const char *file, int private)
76 {
77         struct stat st;
78
79         if (stat(file, &st) != 0)
80                 return -ERRNO_TO_PARA_ERROR(errno);
81         if (private != LOAD_PRIVATE_KEY)
82                 return 0;
83         if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0)
84                 return -E_KEY_PERM;
85         return 1;
86 }
87
88 static EVP_PKEY *load_key(const char *file, int private)
89 {
90         BIO *key;
91         EVP_PKEY *pkey = NULL;
92         int ret = check_key_file(file, private);
93
94         if (ret < 0) {
95                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
96                 return NULL;
97         }
98         key = BIO_new(BIO_s_file());
99         if (!key)
100                 return NULL;
101         if (BIO_read_filename(key, file) > 0) {
102                 if (private == LOAD_PRIVATE_KEY)
103                         pkey = PEM_read_bio_PrivateKey(key, NULL, NULL, NULL);
104                 else
105                         pkey = PEM_read_bio_PUBKEY(key, NULL, NULL, NULL);
106         }
107         BIO_free(key);
108         return pkey;
109 }
110
111 /**
112  * Read an asymmetric key from a file.
113  *
114  * \param key_file The file containing the key.
115  * \param private if non-zero, read the private key, otherwise the public key.
116  * \param result The key structure is returned here.
117  *
118  * \return The size of the key on success, negative on errors.
119  *
120  * \sa openssl(1), rsa(1).
121  */
122 int get_asymmetric_key(const char *key_file, int private,
123                 struct asymmetric_key **result)
124 {
125         struct asymmetric_key *key;
126         RSA *rsa;
127         EVP_PKEY *pkey = load_key(key_file, private);
128
129         if (!pkey)
130                 return (private == LOAD_PRIVATE_KEY)? -E_PRIVATE_KEY
131                         : -E_PUBLIC_KEY;
132         rsa = EVP_PKEY_get1_RSA(pkey);
133         EVP_PKEY_free(pkey);
134         if (!rsa)
135                 return -E_RSA;
136         key = para_malloc(sizeof(*key));
137         key->rsa = rsa;
138         *result = key;
139         return RSA_size(rsa);
140 }
141
142 /**
143  * Deallocate an asymmetric key structure.
144  *
145  * \param key Pointer to the key structure to free.
146  *
147  * This must be called for any key obtained by get_asymmetric_key().
148  */
149 void free_asymmetric_key(struct asymmetric_key *key)
150 {
151         if (!key)
152                 return;
153         RSA_free(key->rsa);
154         free(key);
155 }
156
157 /**
158  * Decrypt a buffer using a private key.
159  *
160  * \param key_file Full path of the key.
161  * \param outbuf The output buffer.
162  * \param inbuf The encrypted input buffer.
163  * \param inlen The length of \a inbuf in bytes.
164  *
165  * The \a outbuf must be large enough to hold at least \a rsa_inlen bytes.
166  *
167  * \return The size of the recovered plaintext on success, negative on errors.
168  *
169  * \sa RSA_private_decrypt(3)
170  **/
171 int priv_decrypt(const char *key_file, unsigned char *outbuf,
172                 unsigned char *inbuf, int inlen)
173 {
174         struct asymmetric_key *priv;
175         int ret;
176
177         if (inlen < 0)
178                 return -E_RSA;
179         ret = get_asymmetric_key(key_file, LOAD_PRIVATE_KEY, &priv);
180         if (ret < 0)
181                 return ret;
182         /*
183          * RSA is vulnerable to timing attacks. Generate a random blinding
184          * factor to protect against this kind of attack.
185          */
186         ret = -E_BLINDING;
187         if (RSA_blinding_on(priv->rsa, NULL) == 0)
188                 goto out;
189         ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
190                 RSA_PKCS1_OAEP_PADDING);
191         RSA_blinding_off(priv->rsa);
192         if (ret <= 0)
193                 ret = -E_DECRYPT;
194 out:
195         free_asymmetric_key(priv);
196         return ret;
197 }
198
199 /**
200  * Encrypt a buffer using an RSA key
201  *
202  * \param pub: The public key.
203  * \param inbuf The input buffer.
204  * \param len The length of \a inbuf.
205  * \param outbuf The output buffer.
206  *
207  * \return The size of the encrypted data on success, negative on errors.
208  *
209  * \sa RSA_public_encrypt(3)
210  */
211 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
212                 unsigned len, unsigned char *outbuf)
213 {
214         int ret, flen = len; /* RSA_public_encrypt expects a signed int */
215
216         if (flen < 0)
217                 return -E_ENCRYPT;
218         ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
219                 RSA_PKCS1_OAEP_PADDING);
220         return ret < 0? -E_ENCRYPT : ret;
221 }
222
223 #define RC4_ALIGN 8
224 struct stream_cipher {
225         RC4_KEY key;
226 };
227
228 /**
229  * Allocate and initialize a stream cipher structure.
230  *
231  * \param data The key.
232  * \param len The size of the key.
233  *
234  * \return A new stream cipher structure.
235  */
236 struct stream_cipher *sc_new(const unsigned char *data, int len)
237 {
238         struct stream_cipher *sc = para_malloc(sizeof(*sc));
239         RC4_set_key(&sc->key, len, data);
240         return sc;
241 }
242
243 /**
244  * Deallocate a stream cipher structure.
245  *
246  * \param sc A stream cipher previously obtained by sc_new().
247  */
248 void sc_free(struct stream_cipher *sc)
249 {
250         free(sc);
251 }
252
253 /**
254  * Encrypt and send a buffer.
255  *
256  * \param scc The context.
257  * \param buf The buffer to send.
258  * \param len The size of \a buf in bytes.
259  *
260  * \return The return value of the underyling call to write_all().
261  *
262  * \sa \ref write_all(), RC4(3).
263  */
264 int sc_send_bin_buffer(struct stream_cipher_context *scc, const char *buf,
265                 size_t len)
266 {
267         int ret;
268         unsigned char *tmp;
269         static unsigned char remainder[RC4_ALIGN];
270         size_t l1 = ROUND_DOWN(len, RC4_ALIGN), l2 = ROUND_UP(len, RC4_ALIGN);
271
272         assert(len);
273         tmp = para_malloc(l2);
274         RC4(&scc->send->key, l1, (const unsigned char *)buf, tmp);
275         if (len > l1) {
276                 memcpy(remainder, buf + l1, len - l1);
277                 RC4(&scc->send->key, len - l1, remainder, tmp + l1);
278         }
279         ret = write_all(scc->fd, (char *)tmp, &len);
280         free(tmp);
281         return ret;
282 }
283
284 /**
285  * Encrypt and send a \p NULL-terminated buffer.
286  *
287  * \param scc The context.
288  * \param buf The buffer to send.
289  *
290  * \return The return value of the underyling call to sc_send_bin_buffer().
291  */
292 int sc_send_buffer(struct stream_cipher_context *scc, const char *buf)
293 {
294         return sc_send_bin_buffer(scc, buf, strlen(buf));
295 }
296
297 /**
298  * Format, encrypt and send a buffer.
299  *
300  * \param scc The context.
301  * \param fmt A format string.
302  *
303  * \return The return value of the underyling call to sc_send_buffer().
304  */
305 __printf_2_3 int sc_send_va_buffer(struct stream_cipher_context *scc,
306                 const char *fmt, ...)
307 {
308         char *msg;
309         int ret;
310
311         PARA_VSPRINTF(fmt, msg);
312         ret = sc_send_buffer(scc, msg);
313         free(msg);
314         return ret;
315 }
316
317 /**
318  * Receive a buffer and decrypt it.
319  *
320  * \param scc The context.
321  * \param buf The buffer to write the decrypted data to.
322  * \param size The size of \a buf.
323  *
324  * \return The number of bytes received on success, negative on errors, zero if
325  * the peer has performed an orderly shutdown.
326  *
327  * \sa recv(2), RC4(3).
328  */
329 int sc_recv_bin_buffer(struct stream_cipher_context *scc, char *buf,
330                 size_t size)
331 {
332         unsigned char *tmp = para_malloc(size);
333         ssize_t ret = recv(scc->fd, tmp, size, 0);
334
335         if (ret > 0)
336                 RC4(&scc->recv->key, ret, tmp, (unsigned char *)buf);
337         else if (ret < 0)
338                 ret = -ERRNO_TO_PARA_ERROR(errno);
339         free(tmp);
340         return ret;
341 }
342
343 /**
344  * Receive a buffer, decrypt it and write terminating NULL byte.
345  *
346  * \param scc The context.
347  * \param buf The buffer to write the decrypted data to.
348  * \param size The size of \a buf.
349  *
350  * Read at most \a size - 1 bytes from file descriptor given by \a scc, decrypt
351  * the received data and write a NULL byte at the end of the decrypted data.
352  *
353  * \return The return value of the underlying call to \ref
354  * sc_recv_bin_buffer().
355  */
356 int sc_recv_buffer(struct stream_cipher_context *scc, char *buf, size_t size)
357 {
358         int n;
359
360         assert(size);
361         n = sc_recv_bin_buffer(scc, buf, size - 1);
362         if (n >= 0)
363                 buf[n] = '\0';
364         else
365                 *buf = '\0';
366         return n;
367 }
368
369 /**
370  * Compute the hash of the given input data.
371  *
372  * \param data Pointer to the data to compute the hash value from.
373  * \param len The length of \a data in bytes.
374  * \param hash Result pointer.
375  *
376  * \a hash must point to an area at least \p HASH_SIZE bytes large.
377  *
378  * \sa sha(3), openssl(1).
379  * */
380 void hash_function(const char *data, unsigned long len, unsigned char *hash)
381 {
382         SHA_CTX c;
383         SHA1_Init(&c);
384         SHA1_Update(&c, data, len);
385         SHA1_Final(hash, &c);
386 }