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 *req_ver = "1.5.0";
69 if (gcry_check_version(req_ver))
71 PARA_EMERG_LOG("fatal: need at least libgcrypt-%s, have: %s\n",
72 req_ver, gcry_check_version(NULL));
76 /** S-expression for the public part of an RSA key. */
77 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
78 /** S-expression for a private RSA key. */
79 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
80 /** S-expression for decryption. */
81 #define RSA_DECRYPT_SEXP "(enc-val(flags oaep)(rsa(a %m)))"
83 struct asymmetric_key {
88 static const char *gcrypt_strerror(gcry_error_t gret)
90 return gcry_strerror(gcry_err_code(gret));
93 static int decode_key(const char *key_file, const char *header_str,
94 const char *footer_str, unsigned char **result)
98 size_t map_size, key_size, blob_size;
99 unsigned char *blob = NULL;
100 char *begin, *footer, *key;
102 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
106 if (strncmp(map, header_str, strlen(header_str)))
108 footer = strstr(map, footer_str);
112 begin = map + strlen(header_str);
113 /* skip whitespace at the beginning */
114 for (; begin < footer; begin++) {
115 if (para_isspace(*begin))
123 key_size = footer - begin;
124 key = para_malloc(key_size + 1);
125 for (i = 0, j = 0; begin + i < footer; i++) {
126 if (para_isspace(begin[i]))
131 ret = base64_decode(key, j, (char **)&blob, &blob_size);
141 ret2 = para_munmap(map, map_size);
142 if (ret >= 0 && ret2 < 0)
153 /** ASN Types and their code. */
155 /** The next object is an integer. */
156 ASN1_TYPE_INTEGER = 0x2,
157 /** Bit string object. */
158 ASN1_TYPE_BIT_STRING = 0x03,
159 /** Keys start with one big type sequence. */
160 ASN1_TYPE_SEQUENCE = 0x30,
163 /* bit 6 has value 0 */
164 static inline bool is_primitive(unsigned char c)
166 return (c & (1<<6)) == 0;
169 static inline bool is_primitive_integer(unsigned char c)
171 if (!is_primitive(c))
173 return (c & 0x1f) == ASN1_TYPE_INTEGER;
176 /* Bit 8 is zero (and bits 7-1 give the length) */
177 static inline bool is_short_form(unsigned char c)
179 return (c & 0x80) == 0;
182 static inline int get_short_form_length(unsigned char c)
187 static inline int get_long_form_num_length_bytes(unsigned char c)
192 static int find_pubkey_bignum_offset(const unsigned char *data, int len)
194 const unsigned char *p = data, *end = data + len;
196 /* the whole thing starts with one sequence */
197 if (*p != ASN1_TYPE_SEQUENCE)
198 return -E_ASN1_PARSE;
201 return -E_ASN1_PARSE;
202 if (is_short_form(*p))
205 p += 1 + get_long_form_num_length_bytes(*p);
207 return -E_ASN1_PARSE;
208 /* another sequence containing the object id, skip it */
209 if (*p != ASN1_TYPE_SEQUENCE)
210 return -E_ASN1_PARSE;
213 return -E_ASN1_PARSE;
214 if (!is_short_form(*p))
215 return -E_ASN1_PARSE;
216 p += 1 + get_short_form_length(*p);
218 return -E_ASN1_PARSE;
219 /* all numbers are wrapped in a bit string object that follows */
220 if (*p != ASN1_TYPE_BIT_STRING)
221 return -E_ASN1_PARSE;
224 return -E_ASN1_PARSE;
225 if (is_short_form(*p))
228 p += 1 + get_long_form_num_length_bytes(*p);
229 p++; /* skip number of unused bits in the bit string */
231 return -E_ASN1_PARSE;
233 /* next, we have a sequence of two integers (n and e) */
234 if (*p != ASN1_TYPE_SEQUENCE)
235 return -E_ASN1_PARSE;
238 return -E_ASN1_PARSE;
239 if (is_short_form(*p))
242 p += 1 + get_long_form_num_length_bytes(*p);
244 return -E_ASN1_PARSE;
245 if (*p != ASN1_TYPE_INTEGER)
246 return -E_ASN1_PARSE;
251 * Returns: Number of bytes scanned. This may differ from the value returned via
252 * bn_bytes because the latter does not include the ASN.1 prefix and a leading
253 * zero is not considered as an additional byte for bn_bytes.
255 static int read_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
260 unsigned char *cp = start;
262 if (!is_primitive_integer(*cp))
263 return -E_BAD_PRIVATE_KEY;
265 if (is_short_form(*cp)) {
266 bn_size = get_short_form_length(*cp);
269 int num_bytes = get_long_form_num_length_bytes(*cp);
270 if (cp + num_bytes > end)
271 return -E_BAD_PRIVATE_KEY;
272 if (num_bytes > 4) /* nobody has such a large modulus */
273 return -E_BAD_PRIVATE_KEY;
276 for (i = 0; i < num_bytes; i++, cp++)
277 bn_size = (bn_size << 8) + *cp;
279 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
280 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
282 PARA_ERROR_LOG("%s while scanning n\n",
283 gcry_strerror(gcry_err_code(gret)));
287 * Don't take the first leading zero into account for the size of the
297 // unsigned char *buf;
298 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
299 // PARA_CRIT_LOG("bn: %s\n", buf);
303 static int find_privkey_bignum_offset(const unsigned char *data, int len)
305 const unsigned char *p = data, *end = data + len;
307 /* like the public key, the whole thing is contained in a sequence */
308 if (*p != ASN1_TYPE_SEQUENCE)
309 return -E_ASN1_PARSE;
312 return -E_ASN1_PARSE;
313 if (is_short_form(*p))
316 p += 1 + get_long_form_num_length_bytes(*p);
318 return -E_ASN1_PARSE;
320 /* skip next integer */
321 if (*p != ASN1_TYPE_INTEGER)
322 return -E_ASN1_PARSE;
325 return -E_ASN1_PARSE;
326 if (is_short_form(*p))
327 p += 1 + get_short_form_length(*p);
329 p += 1 + get_long_form_num_length_bytes(*p);
331 return -E_ASN1_PARSE;
335 /** Private keys start with this header. */
336 #define PRIVATE_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
337 /** Private keys end with this footer. */
338 #define PRIVATE_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
340 static int get_private_key(const char *key_file, struct asymmetric_key **result)
342 gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL,
344 unsigned char *blob, *cp, *end;
345 int blob_size, ret, n_size;
349 struct asymmetric_key *key;
351 ret = decode_key(key_file, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER,
356 end = blob + blob_size;
357 ret = find_privkey_bignum_offset(blob, blob_size);
360 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
363 ret = read_bignum(cp, end, &n, &n_size);
368 ret = read_bignum(cp, end, &e, NULL);
373 ret = read_bignum(cp, end, &d, NULL);
378 ret = read_bignum(cp, end, &p, NULL);
383 ret = read_bignum(cp, end, &q, NULL);
387 ret = read_bignum(cp, end, &u, NULL);
391 * OpenSSL uses slightly different parameters than gcrypt. To use these
392 * parameters we need to swap the values of p and q and recompute u.
394 if (gcry_mpi_cmp(p, q) > 0) {
396 gcry_mpi_invm(u, p, q);
398 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
402 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
403 gcry_strerror(gcry_err_code(gret)));
407 key = para_malloc(sizeof(*key));
411 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
429 /** Public keys start with this header. */
430 #define PUBLIC_KEY_HEADER "-----BEGIN PUBLIC KEY-----"
431 /** Public keys end with this footer. */
432 #define PUBLIC_KEY_FOOTER "-----END PUBLIC KEY-----"
434 static int get_asn_public_key(const char *key_file, struct asymmetric_key **result)
436 gcry_mpi_t n = NULL, e = NULL;
437 unsigned char *blob, *cp, *end;
438 int blob_size, ret, n_size;
442 struct asymmetric_key *key;
444 ret = decode_key(key_file, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER,
449 end = blob + blob_size;
450 ret = find_pubkey_bignum_offset(blob, blob_size);
453 PARA_DEBUG_LOG("decoding public RSA params at offset %d\n", ret);
456 ret = read_bignum(cp, end, &n, &n_size);
461 ret = read_bignum(cp, end, &e, NULL);
465 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
467 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
468 gcry_strerror(gcry_err_code(gret)));
472 key = para_malloc(sizeof(*key));
474 key->num_bytes = n_size;
477 PARA_INFO_LOG("successfully read %d bit asn public key\n", n_size * 8);
488 static int get_ssh_public_key(unsigned char *data, int size, gcry_sexp_t *result)
492 unsigned char *blob = NULL, *p, *end;
493 size_t nr_scanned, erroff, decoded_size;
494 gcry_mpi_t e = NULL, n = NULL;
496 PARA_DEBUG_LOG("decoding %d byte public rsa-ssh key\n", size);
497 ret = uudecode((char *)data, size, (char **)&blob, &decoded_size);
500 end = blob + decoded_size;
501 dump_buffer("decoded key", blob, decoded_size);
502 ret = check_ssh_key_header(blob, decoded_size);
509 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
510 gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
513 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
516 PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
517 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_e);
518 // PARA_CRIT_LOG("e: %s\n", buf);
522 gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
525 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
528 PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
529 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_n);
530 // PARA_CRIT_LOG("n: %s\n", buf);
531 gret = gcry_sexp_build(result, &erroff, RSA_PUBKEY_SEXP, n, e);
533 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
534 gcry_strerror(gcry_err_code(gret)));
538 ret = nr_scanned / 32 * 32;
539 PARA_INFO_LOG("successfully read %d bit ssh public key\n", ret * 8);
549 int get_asymmetric_key(const char *key_file, int private,
550 struct asymmetric_key **result)
555 unsigned char *start, *end;
557 struct asymmetric_key *key;
560 return get_private_key(key_file, result);
561 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
564 ret = is_ssh_rsa_key(map, map_size);
566 ret = para_munmap(map, map_size);
569 return get_asn_public_key(key_file, result);
572 end = map + map_size;
576 ret = get_ssh_public_key(start, end - start, &sexp);
579 key = para_malloc(sizeof(*key));
580 key->num_bytes = ret;
584 ret2 = para_munmap(map, map_size);
585 if (ret >= 0 && ret2 < 0)
590 void free_asymmetric_key(struct asymmetric_key *key)
594 gcry_sexp_release(key->sexp);
598 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
600 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
603 return -E_RSA_DECODE;
604 memcpy(outbuf, p, *nbytes);
608 int priv_decrypt(const char *key_file, unsigned char *outbuf,
609 unsigned char *inbuf, int inlen)
613 struct asymmetric_key *priv;
614 gcry_mpi_t in_mpi = NULL;
615 gcry_sexp_t in, out, priv_key;
618 ret = check_key_file(key_file, true);
621 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
622 /* key_file -> asymmetric key priv */
623 ret = get_private_key(key_file, &priv);
627 /* asymmetric key priv -> sexp priv_key */
629 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
633 /* inbuf -> in_mpi */
634 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
637 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
641 /* in_mpi -> in sexp */
642 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
644 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
649 /* rsa decryption: in sexp -> out sexp */
650 gret = gcry_pk_decrypt(&out, in, priv_key);
652 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
653 ret = -E_SEXP_DECRYPT;
656 ret = decode_rsa(out, outbuf, &nbytes);
659 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
662 gcry_sexp_release(out);
664 gcry_sexp_release(in);
666 gcry_mpi_release(in_mpi);
668 gcry_sexp_release(priv_key);
670 free_asymmetric_key(priv);
674 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
675 unsigned len, unsigned char *outbuf)
678 gcry_sexp_t pub_key, in, out, out_a;
679 gcry_mpi_t out_mpi = NULL;
683 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
686 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
689 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
691 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
695 /* rsa sexp encryption: in -> out */
696 gret = gcry_pk_encrypt(&out, in, pub_key);
698 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
699 ret = -E_SEXP_ENCRYPT;
702 /* extract a, an MPI with the result of the RSA operation */
704 out_a = gcry_sexp_find_token(out, "a", 0);
707 /* convert sexp out_a -> out_mpi */
708 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
713 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
715 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
716 ret = -E_SEXP_ENCRYPT;
717 goto out_mpi_release;
719 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
720 dump_buffer("enc buf", outbuf, nbytes);
724 gcry_mpi_release(out_mpi);
726 gcry_sexp_release(out_a);
728 gcry_sexp_release(out);
730 gcry_sexp_release(in);
732 gcry_sexp_release(pub_key);
736 struct stream_cipher {
737 gcry_cipher_hd_t handle;
740 struct stream_cipher *sc_new(const unsigned char *data, int len,
744 struct stream_cipher *sc = para_malloc(sizeof(*sc));
747 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
748 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
749 GCRY_CIPHER_MODE_CTR, 0);
751 gret = gcry_cipher_setkey(sc->handle, data,
752 AES_CRT128_BLOCK_SIZE);
754 gret = gcry_cipher_setctr(sc->handle,
755 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
759 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_ARCFOUR,
760 GCRY_CIPHER_MODE_STREAM, 0);
762 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
766 gret = gcry_cipher_setkey(sc->handle, data, (size_t)len);
771 void sc_free(struct stream_cipher *sc)
775 gcry_cipher_close(sc->handle);
779 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
781 gcry_cipher_hd_t handle = sc->handle;
784 /* perform in-place encryption */
786 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,