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>
17 #include <openssl/sha.h>
25 struct asymmetric_key {
30 * Fill a buffer with random content.
32 * \param buf The buffer to fill.
33 * \param num The size of \a buf in bytes.
35 * This function puts \a num cryptographically strong pseudo-random bytes into
36 * buf. If libssl can not guarantee an unpredictable byte sequence (for example
37 * because the PRNG has not been seeded with enough randomness) the function
38 * logs an error message and calls exit().
40 void get_random_bytes_or_die(unsigned char *buf, int num)
44 /* RAND_bytes() returns 1 on success, 0 otherwise. */
45 if (RAND_bytes(buf, num) == 1)
47 err = ERR_get_error();
48 PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
53 * Seed pseudo random number generators.
55 * This function reads 64 bytes from /dev/urandom and adds them to the SSL
56 * PRNG. It also seeds the PRNG used by random() with a random seed obtained
57 * from SSL. If /dev/random could not be read, an error message is logged and
58 * the function calls exit().
60 * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
61 * random(3), \ref para_random().
63 void init_random_seed_or_die(void)
65 int seed, ret = RAND_load_file("/dev/urandom", 64);
68 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret);
71 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
75 static int check_key_file(const char *file, int private)
79 if (stat(file, &st) != 0)
80 return -ERRNO_TO_PARA_ERROR(errno);
81 if (private != LOAD_PRIVATE_KEY)
83 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0)
88 static EVP_PKEY *load_key(const char *file, int private)
91 EVP_PKEY *pkey = NULL;
92 int ret = check_key_file(file, private);
95 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
98 key = BIO_new(BIO_s_file());
101 if (BIO_read_filename(key, file) > 0) {
102 if (private == LOAD_PRIVATE_KEY)
103 pkey = PEM_read_bio_PrivateKey(key, NULL, NULL, NULL);
105 pkey = PEM_read_bio_PUBKEY(key, NULL, NULL, NULL);
112 * Read an asymmetric key from a file.
114 * \param key_file The file containing the key.
115 * \param private if non-zero, read the private key, otherwise the public key.
116 * \param result The key structure is returned here.
118 * \return The size of the key on success, negative on errors.
120 * \sa openssl(1), rsa(1).
122 int get_asymmetric_key(const char *key_file, int private,
123 struct asymmetric_key **result)
125 struct asymmetric_key *key;
127 EVP_PKEY *pkey = load_key(key_file, private);
130 return (private == LOAD_PRIVATE_KEY)? -E_PRIVATE_KEY
132 rsa = EVP_PKEY_get1_RSA(pkey);
136 key = para_malloc(sizeof(*key));
139 return RSA_size(rsa);
143 * Deallocate an asymmetric key structure.
145 * \param key Pointer to the key structure to free.
147 * This must be called for any key obtained by get_asymmetric_key().
149 void free_asymmetric_key(struct asymmetric_key *key)
158 * Decrypt a buffer using a private key.
160 * \param key_file Full path of the key.
161 * \param outbuf The output buffer.
162 * \param inbuf The encrypted input buffer.
163 * \param inlen The length of \a inbuf in bytes.
165 * The \a outbuf must be large enough to hold at least \a rsa_inlen bytes.
167 * \return The size of the recovered plaintext on success, negative on errors.
169 * \sa RSA_private_decrypt(3)
171 int priv_decrypt(const char *key_file, unsigned char *outbuf,
172 unsigned char *inbuf, int inlen)
174 struct asymmetric_key *priv;
179 ret = get_asymmetric_key(key_file, LOAD_PRIVATE_KEY, &priv);
183 * RSA is vulnerable to timing attacks. Generate a random blinding
184 * factor to protect against this kind of attack.
187 if (RSA_blinding_on(priv->rsa, NULL) == 0)
189 ret = RSA_private_decrypt(inlen, inbuf, outbuf, priv->rsa,
190 RSA_PKCS1_OAEP_PADDING);
191 RSA_blinding_off(priv->rsa);
195 free_asymmetric_key(priv);
200 * Encrypt a buffer using an RSA key
202 * \param pub: The public key.
203 * \param inbuf The input buffer.
204 * \param len The length of \a inbuf.
205 * \param outbuf The output buffer.
207 * \return The size of the encrypted data on success, negative on errors.
209 * \sa RSA_public_encrypt(3)
211 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
212 unsigned len, unsigned char *outbuf)
214 int ret, flen = len; /* RSA_public_encrypt expects a signed int */
218 ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
219 RSA_PKCS1_OAEP_PADDING);
220 return ret < 0? -E_ENCRYPT : ret;
224 struct stream_cipher {
229 * Allocate and initialize a stream cipher structure.
231 * \param data The key.
232 * \param len The size of the key.
234 * \return A new stream cipher structure.
236 struct stream_cipher *sc_new(const unsigned char *data, int len)
238 struct stream_cipher *sc = para_malloc(sizeof(*sc));
239 RC4_set_key(&sc->key, len, data);
244 * Deallocate a stream cipher structure.
246 * \param sc A stream cipher previously obtained by sc_new().
248 void sc_free(struct stream_cipher *sc)
254 * Encrypt and send a buffer.
256 * \param scc The context.
257 * \param buf The buffer to send.
258 * \param len The size of \a buf in bytes.
260 * \return The return value of the underyling call to write_all().
262 * \sa \ref write_all(), RC4(3).
264 int sc_send_bin_buffer(struct stream_cipher_context *scc, const char *buf,
269 static unsigned char remainder[RC4_ALIGN];
270 size_t l1 = ROUND_DOWN(len, RC4_ALIGN), l2 = ROUND_UP(len, RC4_ALIGN);
273 tmp = para_malloc(l2);
274 RC4(&scc->send->key, l1, (const unsigned char *)buf, tmp);
276 memcpy(remainder, buf + l1, len - l1);
277 RC4(&scc->send->key, len - l1, remainder, tmp + l1);
279 ret = write_all(scc->fd, (char *)tmp, &len);
285 * Encrypt and send a \p NULL-terminated buffer.
287 * \param scc The context.
288 * \param buf The buffer to send.
290 * \return The return value of the underyling call to sc_send_bin_buffer().
292 int sc_send_buffer(struct stream_cipher_context *scc, const char *buf)
294 return sc_send_bin_buffer(scc, buf, strlen(buf));
298 * Format, encrypt and send a buffer.
300 * \param scc The context.
301 * \param fmt A format string.
303 * \return The return value of the underyling call to sc_send_buffer().
305 __printf_2_3 int sc_send_va_buffer(struct stream_cipher_context *scc,
306 const char *fmt, ...)
311 PARA_VSPRINTF(fmt, msg);
312 ret = sc_send_buffer(scc, msg);
318 * Receive a buffer and decrypt it.
320 * \param scc The context.
321 * \param buf The buffer to write the decrypted data to.
322 * \param size The size of \a buf.
324 * \return The number of bytes received on success, negative on errors, zero if
325 * the peer has performed an orderly shutdown.
327 * \sa recv(2), RC4(3).
329 int sc_recv_bin_buffer(struct stream_cipher_context *scc, char *buf,
332 unsigned char *tmp = para_malloc(size);
333 ssize_t ret = recv(scc->fd, tmp, size, 0);
336 RC4(&scc->recv->key, ret, tmp, (unsigned char *)buf);
338 ret = -ERRNO_TO_PARA_ERROR(errno);
344 * Receive a buffer, decrypt it and write terminating NULL byte.
346 * \param scc The context.
347 * \param buf The buffer to write the decrypted data to.
348 * \param size The size of \a buf.
350 * Read at most \a size - 1 bytes from file descriptor given by \a scc, decrypt
351 * the received data and write a NULL byte at the end of the decrypted data.
353 * \return The return value of the underlying call to \ref
354 * sc_recv_bin_buffer().
356 int sc_recv_buffer(struct stream_cipher_context *scc, char *buf, size_t size)
361 n = sc_recv_bin_buffer(scc, buf, size - 1);
370 * Compute the hash of the given input data.
372 * \param data Pointer to the data to compute the hash value from.
373 * \param len The length of \a data in bytes.
374 * \param hash Result pointer.
376 * \a hash must point to an area at least \p HASH_SIZE bytes large.
378 * \sa sha(3), openssl(1).
380 void hash_function(const char *data, unsigned long len, unsigned char *hash)
384 SHA1_Update(&c, data, len);
385 SHA1_Final(hash, &c);