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