crypto: Rename check_key_file() -> check_private_key_file().
[paraslash.git] / crypt.c
1 /*
2 * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
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 #include <openssl/bn.h>
18 #include <openssl/aes.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 #include "base64.h"
27
28 struct asymmetric_key {
29 RSA *rsa;
30 };
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 * Read 64 bytes from /dev/urandom and adds them to the SSL PRNG. Seed the PRNG
46 * used by random() with a random seed obtained from SSL. If /dev/random is not
47 * readable the function calls exit().
48 *
49 * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
50 * random(3), \ref para_random().
51 */
52 void init_random_seed_or_die(void)
53 {
54 int seed, ret = RAND_load_file("/dev/urandom", 64);
55
56 if (ret != 64) {
57 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
58 exit(EXIT_FAILURE);
59 }
60 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
61 srandom(seed);
62 }
63
64 static EVP_PKEY *load_key(const char *file, int private)
65 {
66 BIO *key;
67 EVP_PKEY *pkey = NULL;
68
69 key = BIO_new(BIO_s_file());
70 if (!key)
71 return NULL;
72 if (BIO_read_filename(key, file) > 0) {
73 if (private == LOAD_PRIVATE_KEY)
74 pkey = PEM_read_bio_PrivateKey(key, NULL, NULL, NULL);
75 else
76 pkey = PEM_read_bio_PUBKEY(key, NULL, NULL, NULL);
77 }
78 BIO_free(key);
79 return pkey;
80 }
81
82 static int get_openssl_key(const char *key_file, RSA **rsa, int private)
83 {
84 EVP_PKEY *key = load_key(key_file, private);
85
86 if (!key)
87 return (private == LOAD_PRIVATE_KEY)? -E_PRIVATE_KEY
88 : -E_PUBLIC_KEY;
89 *rsa = EVP_PKEY_get1_RSA(key);
90 EVP_PKEY_free(key);
91 if (!*rsa)
92 return -E_RSA;
93 return RSA_size(*rsa);
94 }
95
96 /*
97 * The public key loading functions below were inspired by corresponding code
98 * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
99 * Finland. However, not much of the original code remains.
100 */
101
102 static int read_bignum(const unsigned char *buf, size_t len, BIGNUM **result)
103 {
104 const unsigned char *p = buf, *end = buf + len;
105 uint32_t bnsize;
106 BIGNUM *bn;
107
108 if (p + 4 < p)
109 return -E_BIGNUM;
110 if (p + 4 > end)
111 return -E_BIGNUM;
112 bnsize = read_ssh_u32(p);
113 PARA_DEBUG_LOG("bnsize: %u\n", bnsize);
114 p += 4;
115 if (p + bnsize < p)
116 return -E_BIGNUM;
117 if (p + bnsize > end)
118 return -E_BIGNUM;
119 if (bnsize > 8192)
120 return -E_BIGNUM;
121 bn = BN_bin2bn(p, bnsize, NULL);
122 if (!bn)
123 return -E_BIGNUM;
124 *result = bn;
125 return bnsize + 4;
126 }
127
128 static int read_rsa_bignums(const unsigned char *blob, int blen, RSA **result)
129 {
130 int ret;
131 RSA *rsa;
132 BIGNUM *n, *e;
133 const unsigned char *p = blob, *end = blob + blen;
134
135 rsa = RSA_new();
136 if (!rsa)
137 return -E_BIGNUM;
138 ret = read_bignum(p, end - p, &e);
139 if (ret < 0)
140 goto fail;
141 p += ret;
142 ret = read_bignum(p, end - p, &n);
143 if (ret < 0)
144 goto fail;
145 #ifdef HAVE_RSA_SET0_KEY
146 RSA_set0_key(rsa, n, e, NULL);
147 #else
148 rsa->n = n;
149 rsa->e = e;
150 #endif
151 *result = rsa;
152 return 1;
153 fail:
154 RSA_free(rsa);
155 return ret;
156 }
157
158 int get_asymmetric_key(const char *key_file, int private,
159 struct asymmetric_key **result)
160 {
161 struct asymmetric_key *key = NULL;
162 void *map = NULL;
163 unsigned char *blob = NULL;
164 size_t map_size, encoded_size, decoded_size;
165 int ret, ret2;
166 char *cp;
167
168 key = para_malloc(sizeof(*key));
169 if (private) {
170 ret = get_openssl_key(key_file, &key->rsa, LOAD_PRIVATE_KEY);
171 goto out;
172 }
173 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
174 if (ret < 0)
175 goto out;
176 ret = is_ssh_rsa_key(map, map_size);
177 if (!ret) {
178 ret = para_munmap(map, map_size);
179 map = NULL;
180 if (ret < 0)
181 goto out;
182 ret = get_openssl_key(key_file, &key->rsa, LOAD_PUBLIC_KEY);
183 goto out;
184 }
185 cp = map + ret;
186 encoded_size = map_size - ret;
187 PARA_INFO_LOG("decoding public rsa-ssh key %s\n", key_file);
188 ret = uudecode(cp, encoded_size, (char **)&blob, &decoded_size);
189 if (ret < 0)
190 goto out_unmap;
191 ret = check_ssh_key_header(blob, decoded_size);
192 if (ret < 0)
193 goto out_unmap;
194 ret = read_rsa_bignums(blob + ret, decoded_size - ret, &key->rsa);
195 if (ret < 0)
196 goto out_unmap;
197 ret = RSA_size(key->rsa);
198 out_unmap:
199 ret2 = para_munmap(map, map_size);
200 if (ret >= 0 && ret2 < 0)
201 ret = ret2;
202 out:
203 if (ret < 0) {
204 free(key);
205 *result = NULL;
206 PARA_ERROR_LOG("key %s: %s\n", key_file, para_strerror(-ret));
207 } else
208 *result = key;
209 free(blob);
210 return ret;
211 }
212
213 void free_asymmetric_key(struct asymmetric_key *key)
214 {
215 if (!key)
216 return;
217 RSA_free(key->rsa);
218 free(key);
219 }
220
221 int priv_decrypt(const char *key_file, unsigned char *outbuf,
222 unsigned char *inbuf, int inlen)
223 {
224 struct asymmetric_key *priv;
225 int ret;
226
227 ret = check_private_key_file(key_file);
228 if (ret < 0)
229 return ret;
230 if (inlen < 0)
231 return -E_RSA;
232 ret = get_asymmetric_key(key_file, LOAD_PRIVATE_KEY, &priv);
233 if (ret < 0)
234 return ret;
235 /*
236 * RSA is vulnerable to timing attacks. Generate a random blinding
237 * factor to protect against this kind of attack.
238 */
239 ret = -E_BLINDING;
240 if (RSA_blinding_on(priv->rsa, NULL) == 0)
241 goto out;
242 ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
243 RSA_PKCS1_OAEP_PADDING);
244 RSA_blinding_off(priv->rsa);
245 if (ret <= 0)
246 ret = -E_DECRYPT;
247 out:
248 free_asymmetric_key(priv);
249 return ret;
250 }
251
252 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
253 unsigned len, unsigned char *outbuf)
254 {
255 int ret, flen = len; /* RSA_public_encrypt expects a signed int */
256
257 if (flen < 0)
258 return -E_ENCRYPT;
259 ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
260 RSA_PKCS1_OAEP_PADDING);
261 return ret < 0? -E_ENCRYPT : ret;
262 }
263
264 struct stream_cipher {
265 bool use_aes;
266 union {
267 RC4_KEY rc4_key;
268 EVP_CIPHER_CTX *aes;
269 } context;
270 };
271
272 struct stream_cipher *sc_new(const unsigned char *data, int len,
273 bool use_aes)
274 {
275 struct stream_cipher *sc = para_malloc(sizeof(*sc));
276
277 sc->use_aes = use_aes;
278 if (!use_aes) {
279 RC4_set_key(&sc->context.rc4_key, len, data);
280 return sc;
281 }
282 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
283 sc->context.aes = EVP_CIPHER_CTX_new();
284 EVP_EncryptInit_ex(sc->context.aes, EVP_aes_128_ctr(), NULL, data,
285 data + AES_CRT128_BLOCK_SIZE);
286 return sc;
287 }
288
289 void sc_free(struct stream_cipher *sc)
290 {
291 if (!sc)
292 return;
293 EVP_CIPHER_CTX_free(sc->context.aes);
294 free(sc);
295 }
296
297 /**
298 * The RC4() implementation of openssl apparently reads and writes data in
299 * blocks of 8 bytes. So we have to make sure our buffer sizes are a multiple
300 * of this.
301 */
302 #define RC4_ALIGN 8
303
304 static void rc4_crypt(RC4_KEY *key, struct iovec *src, struct iovec *dst)
305 {
306 size_t len = src->iov_len, l1, l2;
307
308 assert(len > 0);
309 assert(len < ((typeof(src->iov_len))-1) / 2);
310 l1 = ROUND_DOWN(len, RC4_ALIGN);
311 l2 = ROUND_UP(len, RC4_ALIGN);
312
313 *dst = (typeof(*dst)) {
314 /* Add one for the terminating zero byte. */
315 .iov_base = para_malloc(l2 + 1),
316 .iov_len = len
317 };
318 RC4(key, l1, src->iov_base, dst->iov_base);
319 if (len > l1) {
320 unsigned char remainder[RC4_ALIGN] = "";
321 memcpy(remainder, src->iov_base + l1, len - l1);
322 RC4(key, len - l1, remainder, dst->iov_base + l1);
323 }
324 ((char *)dst->iov_base)[len] = '\0';
325 }
326
327 static void aes_ctr128_crypt(EVP_CIPHER_CTX *ctx, struct iovec *src,
328 struct iovec *dst)
329 {
330 int ret, inlen = src->iov_len, outlen, tmplen;
331
332 *dst = (typeof(*dst)) {
333 /* Add one for the terminating zero byte. */
334 .iov_base = para_malloc(inlen + 1),
335 .iov_len = inlen
336 };
337 ret = EVP_EncryptUpdate(ctx, dst->iov_base, &outlen, src->iov_base, inlen);
338 assert(ret != 0);
339 ret = EVP_EncryptFinal_ex(ctx, dst->iov_base + outlen, &tmplen);
340 assert(ret != 0);
341 outlen += tmplen;
342 ((char *)dst->iov_base)[outlen] = '\0';
343 dst->iov_len = outlen;
344 }
345
346 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
347 {
348 if (sc->use_aes)
349 return aes_ctr128_crypt(sc->context.aes, src, dst);
350 return rc4_crypt(&sc->context.rc4_key, src, dst);
351 }
352
353 void hash_function(const char *data, unsigned long len, unsigned char *hash)
354 {
355 SHA_CTX c;
356 SHA1_Init(&c);
357 SHA1_Update(&c, data, len);
358 SHA1_Final(hash, &c);
359 }