a2642929114b7c1bf790c81a0cbbacf180a2411c
[paraslash.git] / crypt.c
1 /*
2  * Copyright (C) 2005-2009 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 RSA encryption/decryption routines */
8
9 #include <dirent.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
16 #include "para.h"
17 #include "error.h"
18 #include "string.h"
19 #include "crypt.h"
20 #include "fd.h"
21 /**
22  * Fill a buffer with random content.
23  *
24  * \param buf The buffer to fill.
25  * \param num The size of \a buf in bytes.
26  *
27  * This function puts \a num cryptographically strong pseudo-random bytes into
28  * buf. If libssl can not guarantee an unpredictable byte sequence (for example
29  * because the PRNG has not been seeded with enough randomness) the function
30  * logs an error message and calls exit().
31  */
32 void get_random_bytes_or_die(unsigned char *buf, int num)
33 {
34         unsigned long err;
35
36         /* RAND_bytes() returns 1 on success, 0 otherwise. */
37         if (RAND_bytes(buf, num) == 1)
38                 return;
39         err = ERR_get_error();
40         PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
41         exit(EXIT_FAILURE);
42 }
43
44 /**
45  * Seed pseudo random number generators.
46  *
47  * This function reads 64 bytes from /dev/urandom and adds them to the SSL
48  * PRNG. It also seeds the PRNG used by random() with a random seed obtained
49  * from SSL. If /dev/random could not be read, an error message is logged and
50  * the function calls exit().
51  *
52  * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
53  * random(3), \ref para_random().
54  */
55 void init_random_seed_or_die(void)
56 {
57         int seed, ret = RAND_load_file("/dev/urandom", 64);
58
59         if (ret != 64) {
60                 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
61                 exit(EXIT_FAILURE);
62         }
63         get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
64         srandom(seed);
65 }
66
67 static EVP_PKEY *load_key(const char *file, int private)
68 {
69         BIO *key;
70         EVP_PKEY *pkey = 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 /**
86  * read an RSA key from a file
87  *
88  * \param key_file the file containing the key
89  * \param rsa RSA structure is returned here
90  * \param private if non-zero, read the private key, otherwise the public key
91  *
92  * \return The size of the RSA key on success, negative on errors.
93  *
94  * \sa openssl(1), rsa(1).
95  */
96 int get_rsa_key(char *key_file, RSA **rsa, int private)
97 {
98         EVP_PKEY *key = load_key(key_file, private);
99
100         if (!key)
101                 return (private == LOAD_PRIVATE_KEY)? -E_PRIVATE_KEY
102                         : -E_PUBLIC_KEY;
103         *rsa = EVP_PKEY_get1_RSA(key);
104         EVP_PKEY_free(key);
105         if (!*rsa)
106                 return -E_RSA;
107         return RSA_size(*rsa);
108 }
109
110 /**
111  * free an RSA structure
112  *
113  * \param rsa pointer to the RSA struct to free
114  *
115  * This must be called for any key obtained by get_rsa_key().
116  */
117 void rsa_free(RSA *rsa)
118 {
119         if (rsa)
120                 RSA_free(rsa);
121 }
122
123 /**
124  * decrypt a buffer using an RSA key
125  *
126  * \param key_file full path of the rsa key
127  * \param outbuf the output buffer
128  * \param inbuf the encrypted input buffer
129  * \param rsa_inlen the length of \a inbuf
130  *
131  * The \a outbuf must be large enough to hold at least \a rsa_inlen bytes.
132  *
133  * \return The size of the recovered plaintext on success, negative on errors.
134  *
135  * \sa RSA_private_decrypt(3)
136  **/
137 int para_decrypt_buffer(char *key_file, unsigned char *outbuf, unsigned char *inbuf,
138                         unsigned rsa_inlen)
139 {
140         RSA *rsa;
141         int ret, inlen = rsa_inlen;
142
143         if (inlen < 0)
144                 return -E_RSA;
145         ret = get_rsa_key(key_file, &rsa, LOAD_PRIVATE_KEY);
146         if (ret < 0)
147                 return ret;
148         ret = RSA_private_decrypt(inlen, inbuf, outbuf, rsa, RSA_PKCS1_OAEP_PADDING);
149         rsa_free(rsa);
150         return (ret > 0)? ret : -E_DECRYPT;
151 }
152
153 /**
154  * encrypt a buffer using an RSA key
155  *
156  * \param rsa: public rsa key
157  * \param inbuf the input buffer
158  * \param len the length of \a inbuf
159  * \param outbuf the output buffer
160  *
161  * \return The size of the encrypted data on success, negative on errors
162  *
163  * \sa RSA_public_encrypt(3)
164  */
165 int para_encrypt_buffer(RSA *rsa, unsigned char *inbuf,
166                 unsigned len, unsigned char *outbuf)
167 {
168         int ret, flen = len; /* RSA_public_encrypt expects a signed int */
169
170         if (flen < 0)
171                 return -E_ENCRYPT;
172         ret = RSA_public_encrypt(flen, inbuf, outbuf, rsa, RSA_PKCS1_OAEP_PADDING);
173         return ret < 0? -E_ENCRYPT : ret;
174 }
175
176 /**
177  * Encrypt and send a buffer.
178  *
179  * \param rc4c The rc4 crypt context.
180  * \param buf The buffer to send.
181  * \param len The size of \a buf in bytes.
182  *
183  * \return The return value of the underyling call to write_all().
184  *
185  * \sa \ref write_all(), RC4(3).
186  */
187 int rc4_send_bin_buffer(struct rc4_context *rc4c, const char *buf, size_t len)
188 {
189         int ret;
190         unsigned char *tmp;
191
192         assert(len);
193         tmp = para_malloc(len);
194         RC4(&rc4c->send_key, len, (const unsigned char *)buf, tmp);
195         ret = write_all(rc4c->fd, (char *)tmp, &len);
196         free(tmp);
197         return ret;
198 }
199
200 /**
201  * Encrypt and send a \p NULL-terminated buffer.
202  *
203  * \param rc4c The rc4 crypt context.
204  * \param buf The buffer to send.
205  *
206  * \return The return value of the underyling call to rc4_send_bin_buffer().
207  */
208 int rc4_send_buffer(struct rc4_context *rc4c, const char *buf)
209 {
210         return rc4_send_bin_buffer(rc4c, buf, strlen(buf));
211 }
212
213 /**
214  * Format, encrypt and send a buffer.
215  *
216  * \param rc4c The rc4 crypt context.
217  * \param fmt A format string.
218  *
219  * \return The return value of the underyling call to rc4_send_buffer().
220  */
221 __printf_2_3 int rc4_send_va_buffer(struct rc4_context *rc4c, const char *fmt, ...)
222 {
223         char *msg;
224         int ret;
225
226         PARA_VSPRINTF(fmt, msg);
227         ret = rc4_send_buffer(rc4c, msg);
228         free(msg);
229         return ret;
230 }
231
232 /**
233  * Receive a buffer and decrypt it.
234  *
235  * \param rc4c The rc4 crypt context.
236  * \param buf The buffer to write the decrypted data to.
237  * \param size The size of \a buf.
238  *
239  * \return The number of bytes received on success, negative on errors, zero if
240  * the peer has performed an orderly shutdown.
241  *
242  * \sa recv(2), RC4(3).
243  */
244 int rc4_recv_bin_buffer(struct rc4_context *rc4c, char *buf, size_t size)
245 {
246         unsigned char *tmp = para_malloc(size);
247         ssize_t ret = recv(rc4c->fd, tmp, size, 0);
248
249         if (ret > 0)
250                 RC4(&rc4c->recv_key, ret, tmp, (unsigned char *)buf);
251         else if (ret < 0)
252                 ret = -ERRNO_TO_PARA_ERROR(errno);
253         free(tmp);
254         return ret;
255 }
256
257 /**
258  * Receive a buffer, decrypt it and write terminating NULL byte.
259  *
260  * \param rc4c The rc4 crypt context.
261  * \param buf The buffer to write the decrypted data to.
262  * \param size The size of \a buf.
263  *
264  * Read at most \a size - 1 bytes from file descriptor given by \a rc4c,
265  * decrypt the received data and write a NULL byte at the end of the decrypted
266  * data.
267  *
268  * \return The return value of the underlying call to \ref
269  * rc4_recv_bin_buffer().
270  */
271 int rc4_recv_buffer(struct rc4_context *rc4c, char *buf, size_t size)
272 {
273         int n;
274
275         assert(size);
276         n = rc4_recv_bin_buffer(rc4c, buf, size - 1);
277         if (n >= 0)
278                 buf[n] = '\0';
279         else
280                 *buf = '\0';
281         return n;
282 }