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