2 * Copyright (C) 2005-2011 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file crypt.c Openssl-based encryption/decryption routines. */
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 #include <openssl/pem.h>
24 struct asymmetric_key {
29 * Fill a buffer with random content.
31 * \param buf The buffer to fill.
32 * \param num The size of \a buf in bytes.
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().
39 void get_random_bytes_or_die(unsigned char *buf, int num)
43 /* RAND_bytes() returns 1 on success, 0 otherwise. */
44 if (RAND_bytes(buf, num) == 1)
46 err = ERR_get_error();
47 PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
52 * Seed pseudo random number generators.
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().
59 * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
60 * random(3), \ref para_random().
62 void init_random_seed_or_die(void)
64 int seed, ret = RAND_load_file("/dev/urandom", 64);
67 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
70 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
74 static int check_key_file(const char *file, int private)
78 if (stat(file, &st) != 0)
79 return -ERRNO_TO_PARA_ERROR(errno);
80 if (private != LOAD_PRIVATE_KEY)
82 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0)
87 static EVP_PKEY *load_key(const char *file, int private)
90 EVP_PKEY *pkey = NULL;
91 int ret = check_key_file(file, private);
94 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
97 key = BIO_new(BIO_s_file());
100 if (BIO_read_filename(key, file) > 0) {
101 if (private == LOAD_PRIVATE_KEY)
102 pkey = PEM_read_bio_PrivateKey(key, NULL, NULL, NULL);
104 pkey = PEM_read_bio_PUBKEY(key, NULL, NULL, NULL);
111 * Read an asymmetric key from a file.
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.
117 * \return The size of the key on success, negative on errors.
119 * \sa openssl(1), rsa(1).
121 int get_asymmetric_key(const char *key_file, int private,
122 struct asymmetric_key **result)
124 struct asymmetric_key *key;
126 EVP_PKEY *pkey = load_key(key_file, private);
129 return (private == LOAD_PRIVATE_KEY)? -E_PRIVATE_KEY
131 rsa = EVP_PKEY_get1_RSA(pkey);
135 key = para_malloc(sizeof(*key));
138 return RSA_size(rsa);
142 * Deallocate an asymmetric key structure.
144 * \param key Pointer to the key structure to free.
146 * This must be called for any key obtained by get_asymmetric_key().
148 void free_asymmetric_key(struct asymmetric_key *key)
157 * Decrypt a buffer using a private key.
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.
164 * The \a outbuf must be large enough to hold at least \a rsa_inlen bytes.
166 * \return The size of the recovered plaintext on success, negative on errors.
168 * \sa RSA_private_decrypt(3)
170 int priv_decrypt(const char *key_file, unsigned char *outbuf,
171 unsigned char *inbuf, int inlen)
173 struct asymmetric_key *priv;
178 ret = get_asymmetric_key(key_file, LOAD_PRIVATE_KEY, &priv);
182 * RSA is vulnerable to timing attacks. Generate a random blinding
183 * factor to protect against this kind of attack.
186 if (RSA_blinding_on(priv->rsa, NULL) == 0)
188 ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
189 RSA_PKCS1_OAEP_PADDING);
190 RSA_blinding_off(priv->rsa);
194 free_asymmetric_key(priv);
199 * Encrypt a buffer using an RSA key
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.
206 * \return The size of the encrypted data on success, negative on errors.
208 * \sa RSA_public_encrypt(3)
210 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
211 unsigned len, unsigned char *outbuf)
213 int ret, flen = len; /* RSA_public_encrypt expects a signed int */
217 ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
218 RSA_PKCS1_OAEP_PADDING);
219 return ret < 0? -E_ENCRYPT : ret;
223 struct stream_cipher {
228 * Allocate and initialize a stream cipher structure.
230 * \param data The key.
231 * \param len The size of the key.
233 * \return A new stream cipher structure.
235 struct stream_cipher *stream_cipher_new(const unsigned char *data, int len)
237 struct stream_cipher *sc = para_malloc(sizeof(*sc));
238 RC4_set_key(&sc->key, len, data);
243 * Deallocate a stream cipher structure.
245 * \param sc A stream cipher previously obtained by stream_cipher_new().
247 void stream_cipher_free(struct stream_cipher *sc)
253 * Encrypt and send a buffer.
255 * \param rc4c The rc4 crypt context.
256 * \param buf The buffer to send.
257 * \param len The size of \a buf in bytes.
259 * \return The return value of the underyling call to write_all().
261 * \sa \ref write_all(), RC4(3).
263 int rc4_send_bin_buffer(struct rc4_context *rc4c, const char *buf, size_t len)
267 static unsigned char remainder[RC4_ALIGN];
268 size_t l1 = ROUND_DOWN(len, RC4_ALIGN), l2 = ROUND_UP(len, RC4_ALIGN);
271 tmp = para_malloc(l2);
272 RC4(&rc4c->send->key, l1, (const unsigned char *)buf, tmp);
274 memcpy(remainder, buf + l1, len - l1);
275 RC4(&rc4c->send->key, len - l1, remainder, tmp + l1);
277 ret = write_all(rc4c->fd, (char *)tmp, &len);
283 * Encrypt and send a \p NULL-terminated buffer.
285 * \param rc4c The rc4 crypt context.
286 * \param buf The buffer to send.
288 * \return The return value of the underyling call to rc4_send_bin_buffer().
290 int rc4_send_buffer(struct rc4_context *rc4c, const char *buf)
292 return rc4_send_bin_buffer(rc4c, buf, strlen(buf));
296 * Format, encrypt and send a buffer.
298 * \param rc4c The rc4 crypt context.
299 * \param fmt A format string.
301 * \return The return value of the underyling call to rc4_send_buffer().
303 __printf_2_3 int rc4_send_va_buffer(struct rc4_context *rc4c, const char *fmt, ...)
308 PARA_VSPRINTF(fmt, msg);
309 ret = rc4_send_buffer(rc4c, msg);
315 * Receive a buffer and decrypt it.
317 * \param rc4c The rc4 crypt context.
318 * \param buf The buffer to write the decrypted data to.
319 * \param size The size of \a buf.
321 * \return The number of bytes received on success, negative on errors, zero if
322 * the peer has performed an orderly shutdown.
324 * \sa recv(2), RC4(3).
326 int rc4_recv_bin_buffer(struct rc4_context *rc4c, char *buf, size_t size)
328 unsigned char *tmp = para_malloc(size);
329 ssize_t ret = recv(rc4c->fd, tmp, size, 0);
332 RC4(&rc4c->recv->key, ret, tmp, (unsigned char *)buf);
334 ret = -ERRNO_TO_PARA_ERROR(errno);
340 * Receive a buffer, decrypt it and write terminating NULL byte.
342 * \param rc4c The rc4 crypt context.
343 * \param buf The buffer to write the decrypted data to.
344 * \param size The size of \a buf.
346 * Read at most \a size - 1 bytes from file descriptor given by \a rc4c,
347 * decrypt the received data and write a NULL byte at the end of the decrypted
350 * \return The return value of the underlying call to \ref
351 * rc4_recv_bin_buffer().
353 int rc4_recv_buffer(struct rc4_context *rc4c, char *buf, size_t size)
358 n = rc4_recv_bin_buffer(rc4c, buf, size - 1);