2 * Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file gcrypt.c Libgrcypt-based encryption/decryption routines. */
16 #include "crypt_backend.h"
20 //#define GCRYPT_DEBUG 1
23 static void dump_buffer(const char *msg, unsigned char *buf, int len)
27 fprintf(stderr, "%s (%d bytes): ", msg, len);
28 for (i = 0; i < len; i++)
29 fprintf(stderr, "%02x ", buf[i]);
30 fprintf(stderr, "\n");
33 /** Empty. Define GCRYPT_DEBUG to dump buffers. */
34 #define dump_buffer(a, b, c)
37 void hash_function(const char *data, unsigned long len, unsigned char *hash)
43 gret = gcry_md_open(&handle, GCRY_MD_SHA1, 0);
45 gcry_md_write(handle, data, (size_t)len);
46 gcry_md_final(handle);
47 md = gcry_md_read(handle, GCRY_MD_SHA1);
49 memcpy(hash, md, HASH_SIZE);
50 gcry_md_close(handle);
53 void get_random_bytes_or_die(unsigned char *buf, int num)
55 gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
59 * This is called at the beginning of every program that uses libgcrypt. We
60 * don't have to initialize any random seed here, but we must initialize the
61 * gcrypt library. This task is performed by gcry_check_version() which can
62 * also check that the gcrypt library version is at least the minimal required
65 void init_random_seed_or_die(void)
67 const char *ver, *req_ver;
69 ver = gcry_check_version(NULL);
71 if (!gcry_check_version(req_ver)) {
72 PARA_EMERG_LOG("fatal: need at least libgcrypt-%s, have: %s\n",
78 /** S-expression for the public part of an RSA key. */
79 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
80 /** S-expression for a private RSA key. */
81 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
82 /** S-expression for decryption. */
83 #define RSA_DECRYPT_SEXP "(enc-val(flags oaep)(rsa(a %m)))"
85 struct asymmetric_key {
90 static const char *gcrypt_strerror(gcry_error_t gret)
92 return gcry_strerror(gcry_err_code(gret));
95 static int decode_key(const char *key_file, const char *header_str,
96 const char *footer_str, unsigned char **result)
100 size_t map_size, key_size, blob_size;
101 unsigned char *blob = NULL;
102 char *begin, *footer, *key;
104 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
108 if (strncmp(map, header_str, strlen(header_str)))
110 footer = strstr(map, footer_str);
114 begin = map + strlen(header_str);
115 /* skip whitespace at the beginning */
116 for (; begin < footer; begin++) {
117 if (para_isspace(*begin))
125 key_size = footer - begin;
126 key = para_malloc(key_size + 1);
127 for (i = 0, j = 0; begin + i < footer; i++) {
128 if (para_isspace(begin[i]))
133 ret = base64_decode(key, j, (char **)&blob, &blob_size);
143 ret2 = para_munmap(map, map_size);
144 if (ret >= 0 && ret2 < 0)
155 /** ASN Types and their code. */
157 /** The next object is an integer. */
158 ASN1_TYPE_INTEGER = 0x2,
159 /** Bit string object. */
160 ASN1_TYPE_BIT_STRING = 0x03,
161 /** Keys start with one big type sequence. */
162 ASN1_TYPE_SEQUENCE = 0x30,
165 /* bit 6 has value 0 */
166 static inline bool is_primitive(unsigned char c)
168 return (c & (1<<6)) == 0;
171 static inline bool is_primitive_integer(unsigned char c)
173 if (!is_primitive(c))
175 return (c & 0x1f) == ASN1_TYPE_INTEGER;
178 /* Bit 8 is zero (and bits 7-1 give the length) */
179 static inline bool is_short_form(unsigned char c)
181 return (c & 0x80) == 0;
184 static inline int get_short_form_length(unsigned char c)
189 static inline int get_long_form_num_length_bytes(unsigned char c)
194 static int find_pubkey_bignum_offset(const unsigned char *data, int len)
196 const unsigned char *p = data, *end = data + len;
198 /* the whole thing starts with one sequence */
199 if (*p != ASN1_TYPE_SEQUENCE)
200 return -E_ASN1_PARSE;
203 return -E_ASN1_PARSE;
204 if (is_short_form(*p))
207 p += 1 + get_long_form_num_length_bytes(*p);
209 return -E_ASN1_PARSE;
210 /* another sequence containing the object id, skip it */
211 if (*p != ASN1_TYPE_SEQUENCE)
212 return -E_ASN1_PARSE;
215 return -E_ASN1_PARSE;
216 if (!is_short_form(*p))
217 return -E_ASN1_PARSE;
218 p += 1 + get_short_form_length(*p);
220 return -E_ASN1_PARSE;
221 /* all numbers are wrapped in a bit string object that follows */
222 if (*p != ASN1_TYPE_BIT_STRING)
223 return -E_ASN1_PARSE;
226 return -E_ASN1_PARSE;
227 if (is_short_form(*p))
230 p += 1 + get_long_form_num_length_bytes(*p);
231 p++; /* skip number of unused bits in the bit string */
233 return -E_ASN1_PARSE;
235 /* next, we have a sequence of two integers (n and e) */
236 if (*p != ASN1_TYPE_SEQUENCE)
237 return -E_ASN1_PARSE;
240 return -E_ASN1_PARSE;
241 if (is_short_form(*p))
244 p += 1 + get_long_form_num_length_bytes(*p);
246 return -E_ASN1_PARSE;
247 if (*p != ASN1_TYPE_INTEGER)
248 return -E_ASN1_PARSE;
253 * Returns: Number of bytes scanned. This may differ from the value returned via
254 * bn_bytes because the latter does not include the ASN.1 prefix and a leading
255 * zero is not considered as an additional byte for bn_bytes.
257 static int read_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
262 unsigned char *cp = start;
264 if (!is_primitive_integer(*cp))
265 return -E_BAD_PRIVATE_KEY;
267 if (is_short_form(*cp)) {
268 bn_size = get_short_form_length(*cp);
271 int num_bytes = get_long_form_num_length_bytes(*cp);
272 if (cp + num_bytes > end)
273 return -E_BAD_PRIVATE_KEY;
274 if (num_bytes > 4) /* nobody has such a large modulus */
275 return -E_BAD_PRIVATE_KEY;
278 for (i = 0; i < num_bytes; i++, cp++)
279 bn_size = (bn_size << 8) + *cp;
281 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
282 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
284 PARA_ERROR_LOG("%s while scanning n\n",
285 gcry_strerror(gcry_err_code(gret)));
289 * Don't take the first leading zero into account for the size of the
299 // unsigned char *buf;
300 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
301 // PARA_CRIT_LOG("bn: %s\n", buf);
305 static int find_privkey_bignum_offset(const unsigned char *data, int len)
307 const unsigned char *p = data, *end = data + len;
309 /* like the public key, the whole thing is contained in a sequence */
310 if (*p != ASN1_TYPE_SEQUENCE)
311 return -E_ASN1_PARSE;
314 return -E_ASN1_PARSE;
315 if (is_short_form(*p))
318 p += 1 + get_long_form_num_length_bytes(*p);
320 return -E_ASN1_PARSE;
322 /* skip next integer */
323 if (*p != ASN1_TYPE_INTEGER)
324 return -E_ASN1_PARSE;
327 return -E_ASN1_PARSE;
328 if (is_short_form(*p))
329 p += 1 + get_short_form_length(*p);
331 p += 1 + get_long_form_num_length_bytes(*p);
333 return -E_ASN1_PARSE;
337 /** Private keys start with this header. */
338 #define PRIVATE_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
339 /** Private keys end with this footer. */
340 #define PRIVATE_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
342 static int get_private_key(const char *key_file, struct asymmetric_key **result)
344 gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL,
346 unsigned char *blob, *cp, *end;
347 int blob_size, ret, n_size;
351 struct asymmetric_key *key;
353 ret = decode_key(key_file, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER,
358 end = blob + blob_size;
359 ret = find_privkey_bignum_offset(blob, blob_size);
362 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
365 ret = read_bignum(cp, end, &n, &n_size);
370 ret = read_bignum(cp, end, &e, NULL);
375 ret = read_bignum(cp, end, &d, NULL);
380 ret = read_bignum(cp, end, &p, NULL);
385 ret = read_bignum(cp, end, &q, NULL);
389 ret = read_bignum(cp, end, &u, NULL);
393 * OpenSSL uses slightly different parameters than gcrypt. To use these
394 * parameters we need to swap the values of p and q and recompute u.
396 if (gcry_mpi_cmp(p, q) > 0) {
398 gcry_mpi_invm(u, p, q);
400 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
404 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
405 gcry_strerror(gcry_err_code(gret)));
409 key = para_malloc(sizeof(*key));
413 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
431 /** Public keys start with this header. */
432 #define PUBLIC_KEY_HEADER "-----BEGIN PUBLIC KEY-----"
433 /** Public keys end with this footer. */
434 #define PUBLIC_KEY_FOOTER "-----END PUBLIC KEY-----"
436 static int get_asn_public_key(const char *key_file, struct asymmetric_key **result)
438 gcry_mpi_t n = NULL, e = NULL;
439 unsigned char *blob, *cp, *end;
440 int blob_size, ret, n_size;
444 struct asymmetric_key *key;
446 ret = decode_key(key_file, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER,
451 end = blob + blob_size;
452 ret = find_pubkey_bignum_offset(blob, blob_size);
455 PARA_DEBUG_LOG("decoding public RSA params at offset %d\n", ret);
458 ret = read_bignum(cp, end, &n, &n_size);
463 ret = read_bignum(cp, end, &e, NULL);
467 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
469 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
470 gcry_strerror(gcry_err_code(gret)));
474 key = para_malloc(sizeof(*key));
476 key->num_bytes = n_size;
479 PARA_INFO_LOG("successfully read %d bit asn public key\n", n_size * 8);
490 static int get_ssh_public_key(unsigned char *data, int size, gcry_sexp_t *result)
494 unsigned char *blob = NULL, *p, *end;
495 size_t nr_scanned, erroff, decoded_size;
496 gcry_mpi_t e = NULL, n = NULL;
498 PARA_DEBUG_LOG("decoding %d byte public rsa-ssh key\n", size);
499 ret = uudecode((char *)data, size, (char **)&blob, &decoded_size);
502 end = blob + decoded_size;
503 dump_buffer("decoded key", blob, decoded_size);
504 ret = check_ssh_key_header(blob, decoded_size);
511 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
512 gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
515 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
518 PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
519 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_e);
520 // PARA_CRIT_LOG("e: %s\n", buf);
524 gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
527 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
530 PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
531 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_n);
532 // PARA_CRIT_LOG("n: %s\n", buf);
533 gret = gcry_sexp_build(result, &erroff, RSA_PUBKEY_SEXP, n, e);
535 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
536 gcry_strerror(gcry_err_code(gret)));
540 ret = nr_scanned / 32 * 32;
541 PARA_INFO_LOG("successfully read %d bit ssh public key\n", ret * 8);
551 int get_asymmetric_key(const char *key_file, int private,
552 struct asymmetric_key **result)
557 unsigned char *start, *end;
559 struct asymmetric_key *key;
562 return get_private_key(key_file, result);
563 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
566 ret = is_ssh_rsa_key(map, map_size);
568 ret = para_munmap(map, map_size);
571 return get_asn_public_key(key_file, result);
574 end = map + map_size;
578 ret = get_ssh_public_key(start, end - start, &sexp);
581 key = para_malloc(sizeof(*key));
582 key->num_bytes = ret;
586 ret2 = para_munmap(map, map_size);
587 if (ret >= 0 && ret2 < 0)
592 void free_asymmetric_key(struct asymmetric_key *key)
596 gcry_sexp_release(key->sexp);
600 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
602 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
605 PARA_ERROR_LOG("could not get data from list\n");
608 memcpy(outbuf, p, *nbytes);
612 int priv_decrypt(const char *key_file, unsigned char *outbuf,
613 unsigned char *inbuf, int inlen)
617 struct asymmetric_key *priv;
618 gcry_mpi_t in_mpi = NULL;
619 gcry_sexp_t in, out, priv_key;
622 ret = check_key_file(key_file, true);
625 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
626 /* key_file -> asymmetric key priv */
627 ret = get_private_key(key_file, &priv);
631 /* asymmetric key priv -> sexp priv_key */
633 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
637 /* inbuf -> in_mpi */
638 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
641 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
645 /* in_mpi -> in sexp */
646 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
648 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
653 /* rsa decryption: in sexp -> out sexp */
654 gret = gcry_pk_decrypt(&out, in, priv_key);
656 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
657 ret = -E_SEXP_DECRYPT;
660 ret = decode_rsa(out, outbuf, &nbytes);
663 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
666 gcry_sexp_release(out);
668 gcry_sexp_release(in);
670 gcry_mpi_release(in_mpi);
672 gcry_sexp_release(priv_key);
674 free_asymmetric_key(priv);
678 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
679 unsigned len, unsigned char *outbuf)
682 gcry_sexp_t pub_key, in, out, out_a;
683 gcry_mpi_t out_mpi = NULL;
687 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
690 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
693 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
695 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
699 /* rsa sexp encryption: in -> out */
700 gret = gcry_pk_encrypt(&out, in, pub_key);
702 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
703 ret = -E_SEXP_ENCRYPT;
706 /* extract a, an MPI with the result of the RSA operation */
708 out_a = gcry_sexp_find_token(out, "a", 0);
711 /* convert sexp out_a -> out_mpi */
712 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
717 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
719 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
720 ret = -E_SEXP_ENCRYPT;
721 goto out_mpi_release;
723 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
724 dump_buffer("enc buf", outbuf, nbytes);
728 gcry_mpi_release(out_mpi);
730 gcry_sexp_release(out_a);
732 gcry_sexp_release(out);
734 gcry_sexp_release(in);
736 gcry_sexp_release(pub_key);
740 struct stream_cipher {
741 gcry_cipher_hd_t handle;
744 struct stream_cipher *sc_new(const unsigned char *data, int len,
748 struct stream_cipher *sc = para_malloc(sizeof(*sc));
751 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
752 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
753 GCRY_CIPHER_MODE_CTR, 0);
755 gret = gcry_cipher_setkey(sc->handle, data,
756 AES_CRT128_BLOCK_SIZE);
758 gret = gcry_cipher_setctr(sc->handle,
759 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
763 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_ARCFOUR,
764 GCRY_CIPHER_MODE_STREAM, 0);
766 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
770 gret = gcry_cipher_setkey(sc->handle, data, (size_t)len);
775 void sc_free(struct stream_cipher *sc)
779 gcry_cipher_close(sc->handle);
783 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
785 gcry_cipher_hd_t handle = sc->handle;
788 /* perform in-place encryption */
790 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,