ogg_afh_common.c: Check return value of ogg_page_granulepos().
[paraslash.git] / openssl.c
1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file openssl.c Openssl-based encryption/decryption routines. */
4
5 #include <regex.h>
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <openssl/rand.h>
9 #include <openssl/err.h>
10 #include <openssl/pem.h>
11 #include <openssl/sha.h>
12 #include <openssl/bn.h>
13 #include <openssl/aes.h>
14
15 #include "para.h"
16 #include "error.h"
17 #include "string.h"
18 #include "crypt.h"
19 #include "crypt_backend.h"
20 #include "portable_io.h"
21
22 struct asymmetric_key {
23         RSA *rsa;
24 };
25
26 void get_random_bytes_or_die(unsigned char *buf, int num)
27 {
28         unsigned long err;
29
30         /* RAND_bytes() returns 1 on success, 0 otherwise. */
31         if (RAND_bytes(buf, num) == 1)
32                 return;
33         err = ERR_get_error();
34         PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
35         exit(EXIT_FAILURE);
36 }
37
38 /*
39  * Read 64 bytes from /dev/urandom and add them to the SSL PRNG. Seed the PRNG
40  * used by random(3) with a random seed obtained from SSL. If /dev/urandom is
41  * not readable, the function calls exit().
42  *
43  * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
44  * random(3), \ref para_random().
45  */
46 void crypt_init(void)
47 {
48         int seed, ret = RAND_load_file("/dev/urandom", 64);
49
50         if (ret != 64) {
51                 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
52                 exit(EXIT_FAILURE);
53         }
54         get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
55         srandom(seed);
56 }
57
58 void crypt_shutdown(void)
59 {
60         CRYPTO_cleanup_all_ex_data();
61 }
62
63 static int get_private_key(const char *path, RSA **rsa)
64 {
65         EVP_PKEY *pkey;
66         BIO *bio = BIO_new(BIO_s_file());
67
68         *rsa = NULL;
69         if (!bio)
70                 return -E_PRIVATE_KEY;
71         if (BIO_read_filename(bio, path) <= 0)
72                 goto bio_free;
73         pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
74         if (!pkey)
75                 goto bio_free;
76         *rsa = EVP_PKEY_get1_RSA(pkey);
77         EVP_PKEY_free(pkey);
78 bio_free:
79         BIO_free(bio);
80         return *rsa? RSA_size(*rsa) : -E_PRIVATE_KEY;
81 }
82
83 /*
84  * The public key loading functions below were inspired by corresponding code
85  * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
86  * Finland. However, not much of the original code remains.
87  */
88
89 static int read_bignum(const unsigned char *buf, size_t len, BIGNUM **result)
90 {
91         const unsigned char *p = buf, *end = buf + len;
92         uint32_t bnsize;
93         BIGNUM *bn;
94
95         if (p + 4 < p)
96                 return -E_BIGNUM;
97         if (p + 4 > end)
98                 return -E_BIGNUM;
99         bnsize = read_u32_be(p);
100         PARA_DEBUG_LOG("bnsize: %u\n", bnsize);
101         p += 4;
102         if (p + bnsize < p)
103                 return -E_BIGNUM;
104         if (p + bnsize > end)
105                 return -E_BIGNUM;
106         if (bnsize > 8192)
107                 return -E_BIGNUM;
108         bn = BN_bin2bn(p, bnsize, NULL);
109         if (!bn)
110                 return -E_BIGNUM;
111         *result = bn;
112         return bnsize + 4;
113 }
114
115 static int read_rsa_bignums(const unsigned char *blob, int blen, RSA **result)
116 {
117         int ret;
118         RSA *rsa;
119         BIGNUM *n, *e;
120         const unsigned char *p = blob, *end = blob + blen;
121
122         rsa = RSA_new();
123         if (!rsa)
124                 return -E_BIGNUM;
125         ret = read_bignum(p, end - p, &e);
126         if (ret < 0)
127                 goto free_rsa;
128         p += ret;
129         ret = read_bignum(p, end - p, &n);
130         if (ret < 0)
131                 goto free_e;
132 #ifdef HAVE_RSA_SET0_KEY
133         RSA_set0_key(rsa, n, e, NULL);
134 #else
135         rsa->n = n;
136         rsa->e = e;
137 #endif
138         *result = rsa;
139         return 1;
140 free_e:
141         BN_free(e);
142 free_rsa:
143         RSA_free(rsa);
144         return ret;
145 }
146
147 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
148 {
149         unsigned char *blob;
150         size_t decoded_size;
151         int ret;
152         struct asymmetric_key *key = para_malloc(sizeof(*key));
153
154         ret = decode_ssh_key(key_file, &blob, &decoded_size);
155         if (ret < 0)
156                 goto out;
157         ret = read_rsa_bignums(blob + ret, decoded_size - ret, &key->rsa);
158         if (ret < 0)
159                 goto free_blob;
160         ret = RSA_size(key->rsa);
161         assert(ret > 0);
162         *result = key;
163 free_blob:
164         free(blob);
165 out:
166         if (ret < 0) {
167                 free(key);
168                 *result = NULL;
169                 PARA_ERROR_LOG("can not load key %s\n", key_file);
170         }
171         return ret;
172 }
173
174 void apc_free_pubkey(struct asymmetric_key *key)
175 {
176         if (!key)
177                 return;
178         RSA_free(key->rsa);
179         free(key);
180 }
181
182 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
183                 unsigned char *inbuf, int inlen)
184 {
185         struct asymmetric_key *priv;
186         int ret;
187
188         ret = check_private_key_file(key_file);
189         if (ret < 0)
190                 return ret;
191         if (inlen < 0)
192                 return -E_RSA;
193         priv = para_malloc(sizeof(*priv));
194         ret = get_private_key(key_file, &priv->rsa);
195         if (ret < 0) {
196                 free(priv);
197                 return ret;
198         }
199         /*
200          * RSA is vulnerable to timing attacks. Generate a random blinding
201          * factor to protect against this kind of attack.
202          */
203         ret = -E_BLINDING;
204         if (RSA_blinding_on(priv->rsa, NULL) == 0)
205                 goto out;
206         ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
207                 RSA_PKCS1_OAEP_PADDING);
208         RSA_blinding_off(priv->rsa);
209         if (ret <= 0)
210                 ret = -E_DECRYPT;
211 out:
212         RSA_free(priv->rsa);
213         free(priv);
214         return ret;
215 }
216
217 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
218                 unsigned len, unsigned char *outbuf)
219 {
220         int ret, flen = len; /* RSA_public_encrypt expects a signed int */
221
222         if (flen < 0)
223                 return -E_ENCRYPT;
224         ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
225                 RSA_PKCS1_OAEP_PADDING);
226         return ret < 0? -E_ENCRYPT : ret;
227 }
228
229 struct stream_cipher {
230         EVP_CIPHER_CTX *aes;
231 };
232
233 struct stream_cipher *sc_new(const unsigned char *data, int len)
234 {
235         struct stream_cipher *sc = para_malloc(sizeof(*sc));
236
237         assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
238         sc->aes = EVP_CIPHER_CTX_new();
239         EVP_EncryptInit_ex(sc->aes, EVP_aes_128_ctr(), NULL, data,
240                 data + AES_CRT128_BLOCK_SIZE);
241         return sc;
242 }
243
244 void sc_free(struct stream_cipher *sc)
245 {
246         if (!sc)
247                 return;
248         EVP_CIPHER_CTX_free(sc->aes);
249         free(sc);
250 }
251
252 static void aes_ctr128_crypt(EVP_CIPHER_CTX *ctx, struct iovec *src,
253                 struct iovec *dst)
254 {
255         int ret, inlen = src->iov_len, outlen, tmplen;
256
257         *dst = (typeof(*dst)) {
258                 /* Add one for the terminating zero byte. */
259                 .iov_base = para_malloc(inlen + 1),
260                 .iov_len = inlen
261         };
262         ret = EVP_EncryptUpdate(ctx, dst->iov_base, &outlen, src->iov_base, inlen);
263         assert(ret != 0);
264         ret = EVP_EncryptFinal_ex(ctx, dst->iov_base + outlen, &tmplen);
265         assert(ret != 0);
266         outlen += tmplen;
267         ((char *)dst->iov_base)[outlen] = '\0';
268         dst->iov_len = outlen;
269 }
270
271 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
272 {
273         return aes_ctr128_crypt(sc->aes, src, dst);
274 }
275
276 void hash_function(const char *data, unsigned long len, unsigned char *hash)
277 {
278         SHA_CTX c;
279         SHA1_Init(&c);
280         SHA1_Update(&c, data, len);
281         SHA1_Final(hash, &c);
282 }