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>
18 #include <openssl/bn.h>
25 #include "crypt_backend.h"
27 struct asymmetric_key
{
32 * Fill a buffer with random content.
34 * \param buf The buffer to fill.
35 * \param num The size of \a buf in bytes.
37 * This function puts \a num cryptographically strong pseudo-random bytes into
38 * buf. If libssl can not guarantee an unpredictable byte sequence (for example
39 * because the PRNG has not been seeded with enough randomness) the function
40 * logs an error message and calls exit().
42 void get_random_bytes_or_die(unsigned char *buf
, int num
)
46 /* RAND_bytes() returns 1 on success, 0 otherwise. */
47 if (RAND_bytes(buf
, num
) == 1)
49 err
= ERR_get_error();
50 PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err
));
55 * Seed pseudo random number generators.
57 * This function reads 64 bytes from /dev/urandom and adds them to the SSL
58 * PRNG. It also seeds the PRNG used by random() with a random seed obtained
59 * from SSL. If /dev/random could not be read, an error message is logged and
60 * the function calls exit().
62 * \sa RAND_load_file(3), \ref get_random_bytes_or_die(), srandom(3),
63 * random(3), \ref para_random().
65 void init_random_seed_or_die(void)
67 int seed
, ret
= RAND_load_file("/dev/urandom", 64);
70 PARA_EMERG_LOG("could not seed PRNG (ret = %d)\n", ret
);
73 get_random_bytes_or_die((unsigned char *)&seed
, sizeof(seed
));
77 static EVP_PKEY
*load_key(const char *file
, int private)
80 EVP_PKEY
*pkey
= NULL
;
81 int ret
= check_key_file(file
, private);
84 PARA_ERROR_LOG("%s\n", para_strerror(-ret
));
87 key
= BIO_new(BIO_s_file());
90 if (BIO_read_filename(key
, file
) > 0) {
91 if (private == LOAD_PRIVATE_KEY
)
92 pkey
= PEM_read_bio_PrivateKey(key
, NULL
, NULL
, NULL
);
94 pkey
= PEM_read_bio_PUBKEY(key
, NULL
, NULL
, NULL
);
100 static int get_openssl_key(const char *key_file
, RSA
**rsa
, int private)
102 EVP_PKEY
*key
= load_key(key_file
, private);
105 return (private == LOAD_PRIVATE_KEY
)? -E_PRIVATE_KEY
107 *rsa
= EVP_PKEY_get1_RSA(key
);
111 return RSA_size(*rsa
);
115 * The public key loading functions below were inspired by corresponding code
116 * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
117 * Finland. However, not much of the original code remains.
120 static int read_bignum(const unsigned char *buf
, size_t len
, BIGNUM
**result
)
122 const unsigned char *p
= buf
, *end
= buf
+ len
;
130 bnsize
= read_ssh_u32(p
);
131 PARA_DEBUG_LOG("bnsize: %u\n", bnsize
);
135 if (p
+ bnsize
> end
)
139 bn
= BN_bin2bn(p
, bnsize
, NULL
);
146 static int read_rsa_bignums(const unsigned char *blob
, int blen
, RSA
**result
)
150 const unsigned char *p
= blob
, *end
= blob
+ blen
;
155 ret
= read_bignum(p
, end
- p
, &rsa
->e
);
159 ret
= read_bignum(p
, end
- p
, &rsa
->n
);
171 * Read an asymmetric key from a file.
173 * \param key_file The file containing the key.
174 * \param private if non-zero, read the private key, otherwise the public key.
175 * \param result The key structure is returned here.
177 * \return The size of the key on success, negative on errors.
179 * \sa openssl(1), rsa(1).
181 int get_asymmetric_key(const char *key_file
, int private,
182 struct asymmetric_key
**result
)
184 struct asymmetric_key
*key
= NULL
;
186 unsigned char *blob
= NULL
;
187 size_t map_size
, blob_size
, decoded_size
;
191 key
= para_malloc(sizeof(*key
));
193 ret
= get_openssl_key(key_file
, &key
->rsa
, LOAD_PRIVATE_KEY
);
196 ret
= mmap_full_file(key_file
, O_RDONLY
, &map
, &map_size
, NULL
);
199 ret
= is_ssh_rsa_key(map
, map_size
);
201 ret
= para_munmap(map
, map_size
);
205 ret
= get_openssl_key(key_file
, &key
->rsa
, LOAD_PUBLIC_KEY
);
209 PARA_INFO_LOG("decoding public rsa-ssh key %s\n", key_file
);
210 ret
= -ERRNO_TO_PARA_ERROR(EOVERFLOW
);
211 if (map_size
> INT_MAX
/ 4)
213 blob_size
= 2 * map_size
;
214 blob
= para_malloc(blob_size
);
215 ret
= uudecode(cp
, blob
, blob_size
);
219 ret
= check_ssh_key_header(blob
, decoded_size
);
222 ret
= read_rsa_bignums(blob
+ ret
, decoded_size
- ret
, &key
->rsa
);
225 ret
= RSA_size(key
->rsa
);
227 ret2
= para_munmap(map
, map_size
);
228 if (ret
>= 0 && ret2
< 0)
233 PARA_ERROR_LOG("key %s: %s\n", key_file
, para_strerror(-ret
));
241 * Deallocate an asymmetric key structure.
243 * \param key Pointer to the key structure to free.
245 * This must be called for any key obtained by get_asymmetric_key().
247 void free_asymmetric_key(struct asymmetric_key
*key
)
256 * Decrypt a buffer using a private key.
258 * \param key_file Full path of the key.
259 * \param outbuf The output buffer.
260 * \param inbuf The encrypted input buffer.
261 * \param inlen The length of \a inbuf in bytes.
263 * The \a outbuf must be large enough to hold at least \a rsa_inlen bytes.
265 * \return The size of the recovered plaintext on success, negative on errors.
267 * \sa RSA_private_decrypt(3)
269 int priv_decrypt(const char *key_file
, unsigned char *outbuf
,
270 unsigned char *inbuf
, int inlen
)
272 struct asymmetric_key
*priv
;
277 ret
= get_asymmetric_key(key_file
, LOAD_PRIVATE_KEY
, &priv
);
281 * RSA is vulnerable to timing attacks. Generate a random blinding
282 * factor to protect against this kind of attack.
285 if (RSA_blinding_on(priv
->rsa
, NULL
) == 0)
287 ret
= RSA_private_decrypt(inlen
, inbuf
, outbuf
, priv
->rsa
,
288 RSA_PKCS1_OAEP_PADDING
);
289 RSA_blinding_off(priv
->rsa
);
293 free_asymmetric_key(priv
);
298 * Encrypt a buffer using an RSA key
300 * \param pub: The public key.
301 * \param inbuf The input buffer.
302 * \param len The length of \a inbuf.
303 * \param outbuf The output buffer.
305 * \return The size of the encrypted data on success, negative on errors.
307 * \sa RSA_public_encrypt(3)
309 int pub_encrypt(struct asymmetric_key
*pub
, unsigned char *inbuf
,
310 unsigned len
, unsigned char *outbuf
)
312 int ret
, flen
= len
; /* RSA_public_encrypt expects a signed int */
316 ret
= RSA_public_encrypt(flen
, inbuf
, outbuf
, pub
->rsa
,
317 RSA_PKCS1_OAEP_PADDING
);
318 return ret
< 0? -E_ENCRYPT
: ret
;
321 struct stream_cipher
{
326 * Allocate and initialize a stream cipher structure.
328 * \param data The key.
329 * \param len The size of the key.
331 * \return A new stream cipher structure.
333 struct stream_cipher
*sc_new(const unsigned char *data
, int len
)
335 struct stream_cipher
*sc
= para_malloc(sizeof(*sc
));
336 RC4_set_key(&sc
->key
, len
, data
);
341 * Deallocate a stream cipher structure.
343 * \param sc A stream cipher previously obtained by sc_new().
345 void sc_free(struct stream_cipher
*sc
)
351 * The RC4() implementation of openssl apparently reads and writes data in
352 * blocks of 8 bytes. So we have to make sure our buffer sizes are a multiple
358 * Encrypt and send a buffer.
360 * \param scc The context.
361 * \param buf The buffer to send.
362 * \param len The size of \a buf in bytes.
364 * \return The return value of the underyling call to write_all().
366 * \sa \ref write_all(), RC4(3).
368 int sc_send_bin_buffer(struct stream_cipher_context
*scc
, char *buf
,
373 static unsigned char remainder
[RC4_ALIGN
];
374 size_t l1
= ROUND_DOWN(len
, RC4_ALIGN
), l2
= ROUND_UP(len
, RC4_ALIGN
);
377 tmp
= para_malloc(l2
);
378 RC4(&scc
->send
->key
, l1
, (const unsigned char *)buf
, tmp
);
380 memcpy(remainder
, buf
+ l1
, len
- l1
);
381 RC4(&scc
->send
->key
, len
- l1
, remainder
, tmp
+ l1
);
383 ret
= write_all(scc
->fd
, (char *)tmp
, &len
);
389 * Receive a buffer and decrypt it.
391 * \param scc The context.
392 * \param buf The buffer to write the decrypted data to.
393 * \param size The size of \a buf.
395 * \return The number of bytes received on success, negative on errors, zero if
396 * the peer has performed an orderly shutdown.
398 * \sa recv(2), RC4(3).
400 int sc_recv_bin_buffer(struct stream_cipher_context
*scc
, char *buf
,
403 unsigned char *tmp
= para_malloc(size
);
404 ssize_t ret
= recv(scc
->fd
, tmp
, size
, 0);
407 RC4(&scc
->recv
->key
, ret
, tmp
, (unsigned char *)buf
);
409 ret
= -ERRNO_TO_PARA_ERROR(errno
);
415 * Compute the hash of the given input data.
417 * \param data Pointer to the data to compute the hash value from.
418 * \param len The length of \a data in bytes.
419 * \param hash Result pointer.
421 * \a hash must point to an area at least \p HASH_SIZE bytes large.
423 * \sa sha(3), openssl(1).
425 void hash_function(const char *data
, unsigned long len
, unsigned char *hash
)
429 SHA1_Update(&c
, data
, len
);
430 SHA1_Final(hash
, &c
);