6f7e611d0364035560819f7659bbb71d62d4f1b1
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. */
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>
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
);
111 static int get_openssl_key(const char *key_file
, RSA
**rsa
, int private)
113 EVP_PKEY
*key
= load_key(key_file
, private);
116 return (private == LOAD_PRIVATE_KEY
)? -E_PRIVATE_KEY
118 *rsa
= EVP_PKEY_get1_RSA(key
);
122 return RSA_size(*rsa
);
125 #define KEY_TYPE_TXT "ssh-rsa"
127 /* check if it is an ssh rsa key */
128 static size_t is_ssh_rsa_key(char *data
, size_t size
)
132 if (size
< strlen(KEY_TYPE_TXT
) + 2)
134 cp
= memchr(data
, ' ', size
);
137 if (strncmp(KEY_TYPE_TXT
, data
, strlen(KEY_TYPE_TXT
)))
140 if (cp
>= data
+ size
)
148 * This base64/uudecode stuff below is taken from openssh-5.2p1, Copyright (c)
149 * 1996 by Internet Software Consortium. Portions Copyright (c) 1995 by
150 * International Business Machines, Inc.
153 static const char Base64
[] =
154 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
155 static const char Pad64
= '=';
157 * Skips all whitespace anywhere. Converts characters, four at a time, starting
158 * at (or after) src from base - 64 numbers into three 8 bit bytes in the
159 * target area. it returns the number of data bytes stored at the target, or -1
162 static int base64_decode(char const *src
, unsigned char *target
, size_t targsize
)
164 unsigned int tarindex
, state
;
171 while ((ch
= *src
++) != '\0') {
172 if (para_isspace(ch
)) /* Skip whitespace anywhere. */
178 pos
= strchr(Base64
, ch
);
179 if (pos
== 0) /* A non-base64 character. */
185 if (tarindex
>= targsize
)
187 target
[tarindex
] = (pos
- Base64
) << 2;
193 if (tarindex
+ 1 >= targsize
)
195 target
[tarindex
] |= (pos
- Base64
) >> 4;
196 target
[tarindex
+1] = ((pos
- Base64
) & 0x0f)
204 if (tarindex
+ 1 >= targsize
)
206 target
[tarindex
] |= (pos
- Base64
) >> 2;
207 target
[tarindex
+1] = ((pos
- Base64
) & 0x03)
215 if (tarindex
>= targsize
)
217 target
[tarindex
] |= (pos
- Base64
);
226 * We are done decoding Base-64 chars. Let's see if we ended
227 * on a byte boundary, and/or with erroneous trailing characters.
230 if (ch
== Pad64
) { /* We got a pad char. */
231 ch
= *src
++; /* Skip it, get next. */
233 case 0: /* Invalid = in first position */
234 case 1: /* Invalid = in second position */
237 case 2: /* Valid, means one byte of info */
238 /* Skip any number of spaces. */
239 for (; ch
!= '\0'; ch
= *src
++)
242 /* Make sure there is another trailing = sign. */
245 ch
= *src
++; /* Skip the = */
246 /* Fall through to "single trailing =" case. */
249 case 3: /* Valid, means two bytes of info */
251 * We know this char is an =. Is there anything but
252 * whitespace after it?
254 for (; ch
!= '\0'; ch
= *src
++)
259 * Now make sure for cases 2 and 3 that the "extra"
260 * bits that slopped past the last full byte were
261 * zeros. If we don't check them, they become a
262 * subliminal channel.
264 if (target
&& target
[tarindex
] != 0)
269 * We ended by seeing the end of the string. Make sure we
270 * have no partial bytes lying around.
279 static int uudecode(const char *src
, unsigned char *target
, size_t targsize
)
284 /* copy the 'readonly' source */
285 encoded
= para_strdup(src
);
286 /* skip whitespace and data */
287 for (p
= encoded
; *p
== ' ' || *p
== '\t'; p
++)
289 for (; *p
!= '\0' && *p
!= ' ' && *p
!= '\t'; p
++)
291 /* and remove trailing whitespace because base64_decode needs this */
293 len
= base64_decode(encoded
, target
, targsize
);
295 return len
>= 0? len
: -E_BASE64
;
299 * The public key loading functions below were inspired by corresponding code
300 * of openssh-5.2p1, Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo,
301 * Finland. However, not much of the original code remains.
306 * Can not use the inline functions of portable_io.h here because the byte
307 * order is different.
309 static uint32_t read_ssh_u32(const void *vp
)
311 const unsigned char *p
= (const unsigned char *)vp
;
314 v
= (uint32_t)p
[0] << 24;
315 v
|= (uint32_t)p
[1] << 16;
316 v
|= (uint32_t)p
[2] << 8;
322 static int read_bignum(const unsigned char *buf
, size_t len
, BIGNUM
**result
)
324 const unsigned char *p
= buf
, *end
= buf
+ len
;
332 bnsize
= read_ssh_u32(p
);
333 PARA_DEBUG_LOG("bnsize: %u\n", bnsize
);
337 if (p
+ bnsize
> end
)
341 bn
= BN_bin2bn(p
, bnsize
, NULL
);
348 static int read_rsa_bignums(const unsigned char *blob
, int blen
, RSA
**result
)
352 const unsigned char *p
= blob
, *end
= blob
+ blen
;
358 rlen
= read_ssh_u32(p
);
364 if (rlen
< strlen(KEY_TYPE_TXT
))
366 PARA_DEBUG_LOG("type: %s, rlen: %d\n", p
, rlen
);
367 if (strncmp((char *)p
, KEY_TYPE_TXT
, strlen(KEY_TYPE_TXT
)))
374 ret
= read_bignum(p
, end
- p
, &rsa
->e
);
378 ret
= read_bignum(p
, end
- p
, &rsa
->n
);
390 * Read an asymmetric key from a file.
392 * \param key_file The file containing the key.
393 * \param private if non-zero, read the private key, otherwise the public key.
394 * \param result The key structure is returned here.
396 * \return The size of the key on success, negative on errors.
398 * \sa openssl(1), rsa(1).
400 int get_asymmetric_key(const char *key_file
, int private,
401 struct asymmetric_key
**result
)
403 struct asymmetric_key
*key
= NULL
;
405 unsigned char *blob
= NULL
;
406 size_t map_size
, blob_size
;
410 key
= para_malloc(sizeof(*key
));
412 ret
= get_openssl_key(key_file
, &key
->rsa
, LOAD_PRIVATE_KEY
);
415 ret
= mmap_full_file(key_file
, O_RDONLY
, &map
, &map_size
, NULL
);
418 ret
= is_ssh_rsa_key(map
, map_size
);
420 ret
= para_munmap(map
, map_size
);
424 ret
= get_openssl_key(key_file
, &key
->rsa
, LOAD_PUBLIC_KEY
);
428 PARA_INFO_LOG("decoding public rsa-ssh key %s\n", key_file
);
429 ret
= -ERRNO_TO_PARA_ERROR(EOVERFLOW
);
430 if (map_size
> INT_MAX
/ 4)
432 blob_size
= 2 * map_size
;
433 blob
= para_malloc(blob_size
);
434 ret
= uudecode(cp
, blob
, blob_size
);
437 ret
= read_rsa_bignums(blob
, ret
, &key
->rsa
);
440 ret
= RSA_size(key
->rsa
);
442 ret2
= para_munmap(map
, map_size
);
443 if (ret
>= 0 && ret2
< 0)
448 PARA_ERROR_LOG("key %s: %s\n", key_file
, para_strerror(-ret
));
456 * Deallocate an asymmetric key structure.
458 * \param key Pointer to the key structure to free.
460 * This must be called for any key obtained by get_asymmetric_key().
462 void free_asymmetric_key(struct asymmetric_key
*key
)
471 * Decrypt a buffer using a private key.
473 * \param key_file Full path of the key.
474 * \param outbuf The output buffer.
475 * \param inbuf The encrypted input buffer.
476 * \param inlen The length of \a inbuf in bytes.
478 * The \a outbuf must be large enough to hold at least \a rsa_inlen bytes.
480 * \return The size of the recovered plaintext on success, negative on errors.
482 * \sa RSA_private_decrypt(3)
484 int priv_decrypt(const char *key_file
, unsigned char *outbuf
,
485 unsigned char *inbuf
, int inlen
)
487 struct asymmetric_key
*priv
;
492 ret
= get_asymmetric_key(key_file
, LOAD_PRIVATE_KEY
, &priv
);
496 * RSA is vulnerable to timing attacks. Generate a random blinding
497 * factor to protect against this kind of attack.
500 if (RSA_blinding_on(priv
->rsa
, NULL
) == 0)
502 ret
= RSA_private_decrypt(inlen
, inbuf
, outbuf
, priv
->rsa
,
503 RSA_PKCS1_OAEP_PADDING
);
504 RSA_blinding_off(priv
->rsa
);
508 free_asymmetric_key(priv
);
513 * Encrypt a buffer using an RSA key
515 * \param pub: The public key.
516 * \param inbuf The input buffer.
517 * \param len The length of \a inbuf.
518 * \param outbuf The output buffer.
520 * \return The size of the encrypted data on success, negative on errors.
522 * \sa RSA_public_encrypt(3)
524 int pub_encrypt(struct asymmetric_key
*pub
, unsigned char *inbuf
,
525 unsigned len
, unsigned char *outbuf
)
527 int ret
, flen
= len
; /* RSA_public_encrypt expects a signed int */
531 ret
= RSA_public_encrypt(flen
, inbuf
, outbuf
, pub
->rsa
,
532 RSA_PKCS1_OAEP_PADDING
);
533 return ret
< 0? -E_ENCRYPT
: ret
;
536 struct stream_cipher
{
541 * Allocate and initialize a stream cipher structure.
543 * \param data The key.
544 * \param len The size of the key.
546 * \return A new stream cipher structure.
548 struct stream_cipher
*sc_new(const unsigned char *data
, int len
)
550 struct stream_cipher
*sc
= para_malloc(sizeof(*sc
));
551 RC4_set_key(&sc
->key
, len
, data
);
556 * Deallocate a stream cipher structure.
558 * \param sc A stream cipher previously obtained by sc_new().
560 void sc_free(struct stream_cipher
*sc
)
566 * The RC4() implementation of openssl apparently reads and writes data in
567 * blocks of 8 bytes. So we have to make sure our buffer sizes are a multiple
573 * Encrypt and send a buffer.
575 * \param scc The context.
576 * \param buf The buffer to send.
577 * \param len The size of \a buf in bytes.
579 * \return The return value of the underyling call to write_all().
581 * \sa \ref write_all(), RC4(3).
583 int sc_send_bin_buffer(struct stream_cipher_context
*scc
, const char *buf
,
588 static unsigned char remainder
[RC4_ALIGN
];
589 size_t l1
= ROUND_DOWN(len
, RC4_ALIGN
), l2
= ROUND_UP(len
, RC4_ALIGN
);
592 tmp
= para_malloc(l2
);
593 RC4(&scc
->send
->key
, l1
, (const unsigned char *)buf
, tmp
);
595 memcpy(remainder
, buf
+ l1
, len
- l1
);
596 RC4(&scc
->send
->key
, len
- l1
, remainder
, tmp
+ l1
);
598 ret
= write_all(scc
->fd
, (char *)tmp
, &len
);
604 * Encrypt and send a \p NULL-terminated buffer.
606 * \param scc The context.
607 * \param buf The buffer to send.
609 * \return The return value of the underyling call to sc_send_bin_buffer().
611 int sc_send_buffer(struct stream_cipher_context
*scc
, const char *buf
)
613 return sc_send_bin_buffer(scc
, buf
, strlen(buf
));
617 * Format, encrypt and send a buffer.
619 * \param scc The context.
620 * \param fmt A format string.
622 * \return The return value of the underyling call to sc_send_buffer().
624 __printf_2_3
int sc_send_va_buffer(struct stream_cipher_context
*scc
,
625 const char *fmt
, ...)
630 PARA_VSPRINTF(fmt
, msg
);
631 ret
= sc_send_buffer(scc
, msg
);
637 * Receive a buffer and decrypt it.
639 * \param scc The context.
640 * \param buf The buffer to write the decrypted data to.
641 * \param size The size of \a buf.
643 * \return The number of bytes received on success, negative on errors, zero if
644 * the peer has performed an orderly shutdown.
646 * \sa recv(2), RC4(3).
648 int sc_recv_bin_buffer(struct stream_cipher_context
*scc
, char *buf
,
651 unsigned char *tmp
= para_malloc(size
);
652 ssize_t ret
= recv(scc
->fd
, tmp
, size
, 0);
655 RC4(&scc
->recv
->key
, ret
, tmp
, (unsigned char *)buf
);
657 ret
= -ERRNO_TO_PARA_ERROR(errno
);
663 * Receive a buffer, decrypt it and write terminating NULL byte.
665 * \param scc The context.
666 * \param buf The buffer to write the decrypted data to.
667 * \param size The size of \a buf.
669 * Read at most \a size - 1 bytes from file descriptor given by \a scc, decrypt
670 * the received data and write a NULL byte at the end of the decrypted data.
672 * \return The return value of the underlying call to \ref
673 * sc_recv_bin_buffer().
675 int sc_recv_buffer(struct stream_cipher_context
*scc
, char *buf
, size_t size
)
680 n
= sc_recv_bin_buffer(scc
, buf
, size
- 1);
689 * Compute the hash of the given input data.
691 * \param data Pointer to the data to compute the hash value from.
692 * \param len The length of \a data in bytes.
693 * \param hash Result pointer.
695 * \a hash must point to an area at least \p HASH_SIZE bytes large.
697 * \sa sha(3), openssl(1).
699 void hash_function(const char *data
, unsigned long len
, unsigned char *hash
)
703 SHA1_Update(&c
, data
, len
);
704 SHA1_Final(hash
, &c
);