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)
193 * Returns: Number of bytes scanned. This may differ from the value returned via
194 * bn_bytes because the latter does not include the ASN.1 prefix and a leading
195 * zero is not considered as an additional byte for bn_bytes.
197 static int read_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
202 unsigned char *cp = start;
204 if (!is_primitive_integer(*cp))
205 return -E_BAD_PRIVATE_KEY;
207 if (is_short_form(*cp)) {
208 bn_size = get_short_form_length(*cp);
211 int num_bytes = get_long_form_num_length_bytes(*cp);
212 if (cp + num_bytes > end)
213 return -E_BAD_PRIVATE_KEY;
214 if (num_bytes > 4) /* nobody has such a large modulus */
215 return -E_BAD_PRIVATE_KEY;
218 for (i = 0; i < num_bytes; i++, cp++)
219 bn_size = (bn_size << 8) + *cp;
221 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
222 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
224 PARA_ERROR_LOG("%s while scanning n\n",
225 gcry_strerror(gcry_err_code(gret)));
229 * Don't take the first leading zero into account for the size of the
239 // unsigned char *buf;
240 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
241 // PARA_CRIT_LOG("bn: %s\n", buf);
245 static int find_privkey_bignum_offset(const unsigned char *data, int len)
247 const unsigned char *p = data, *end = data + len;
249 /* like the public key, the whole thing is contained in a sequence */
250 if (*p != ASN1_TYPE_SEQUENCE)
251 return -E_ASN1_PARSE;
254 return -E_ASN1_PARSE;
255 if (is_short_form(*p))
258 p += 1 + get_long_form_num_length_bytes(*p);
260 return -E_ASN1_PARSE;
262 /* skip next integer */
263 if (*p != ASN1_TYPE_INTEGER)
264 return -E_ASN1_PARSE;
267 return -E_ASN1_PARSE;
268 if (is_short_form(*p))
269 p += 1 + get_short_form_length(*p);
271 p += 1 + get_long_form_num_length_bytes(*p);
273 return -E_ASN1_PARSE;
277 /** Private keys start with this header. */
278 #define PRIVATE_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
279 /** Private keys end with this footer. */
280 #define PRIVATE_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
282 static int get_private_key(const char *key_file, struct asymmetric_key **result)
284 gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL,
286 unsigned char *blob, *cp, *end;
287 int blob_size, ret, n_size;
291 struct asymmetric_key *key;
294 ret = decode_key(key_file, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER,
299 end = blob + blob_size;
300 ret = find_privkey_bignum_offset(blob, blob_size);
303 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
306 ret = read_bignum(cp, end, &n, &n_size);
311 ret = read_bignum(cp, end, &e, NULL);
316 ret = read_bignum(cp, end, &d, NULL);
321 ret = read_bignum(cp, end, &p, NULL);
326 ret = read_bignum(cp, end, &q, NULL);
330 ret = read_bignum(cp, end, &u, NULL);
334 * OpenSSL uses slightly different parameters than gcrypt. To use these
335 * parameters we need to swap the values of p and q and recompute u.
337 if (gcry_mpi_cmp(p, q) > 0) {
339 gcry_mpi_invm(u, p, q);
341 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
345 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
346 gcry_strerror(gcry_err_code(gret)));
350 key = para_malloc(sizeof(*key));
354 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
372 static int get_ssh_public_key(unsigned char *data, int size, gcry_sexp_t *result)
376 unsigned char *blob = NULL, *p, *end;
377 size_t nr_scanned, erroff, decoded_size;
378 gcry_mpi_t e = NULL, n = NULL;
380 PARA_DEBUG_LOG("decoding %d byte public rsa-ssh key\n", size);
381 ret = uudecode((char *)data, size, (char **)&blob, &decoded_size);
384 end = blob + decoded_size;
385 dump_buffer("decoded key", blob, decoded_size);
386 ret = check_ssh_key_header(blob, decoded_size);
393 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
394 gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
397 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
400 PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
401 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_e);
402 // PARA_CRIT_LOG("e: %s\n", buf);
406 gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
409 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
412 PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
413 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_n);
414 // PARA_CRIT_LOG("n: %s\n", buf);
415 gret = gcry_sexp_build(result, &erroff, RSA_PUBKEY_SEXP, n, e);
417 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
418 gcry_strerror(gcry_err_code(gret)));
422 ret = nr_scanned / 32 * 32;
423 PARA_INFO_LOG("successfully read %d bit ssh public key\n", ret * 8);
433 int get_public_key(const char *key_file, struct asymmetric_key **result)
438 unsigned char *start, *end;
440 struct asymmetric_key *key;
442 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
445 ret = is_ssh_rsa_key(map, map_size);
447 para_munmap(map, map_size);
451 end = map + map_size;
455 ret = get_ssh_public_key(start, end - start, &sexp);
458 key = para_malloc(sizeof(*key));
459 key->num_bytes = ret;
463 ret2 = para_munmap(map, map_size);
464 if (ret >= 0 && ret2 < 0)
469 void free_public_key(struct asymmetric_key *key)
473 gcry_sexp_release(key->sexp);
477 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
479 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
482 return -E_RSA_DECODE;
483 memcpy(outbuf, p, *nbytes);
487 int priv_decrypt(const char *key_file, unsigned char *outbuf,
488 unsigned char *inbuf, int inlen)
492 struct asymmetric_key *priv;
493 gcry_mpi_t in_mpi = NULL;
494 gcry_sexp_t in, out, priv_key;
497 ret = check_private_key_file(key_file);
500 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
501 /* key_file -> asymmetric key priv */
502 ret = get_private_key(key_file, &priv);
506 /* asymmetric key priv -> sexp priv_key */
508 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
512 /* inbuf -> in_mpi */
513 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
516 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
520 /* in_mpi -> in sexp */
521 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
523 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
528 /* rsa decryption: in sexp -> out sexp */
529 gret = gcry_pk_decrypt(&out, in, priv_key);
531 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
532 ret = -E_SEXP_DECRYPT;
535 ret = decode_rsa(out, outbuf, &nbytes);
538 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
541 gcry_sexp_release(out);
543 gcry_sexp_release(in);
545 gcry_mpi_release(in_mpi);
547 gcry_sexp_release(priv_key);
549 gcry_sexp_release(priv->sexp);
554 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
555 unsigned len, unsigned char *outbuf)
558 gcry_sexp_t pub_key, in, out, out_a;
559 gcry_mpi_t out_mpi = NULL;
563 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
566 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
569 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
571 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
575 /* rsa sexp encryption: in -> out */
576 gret = gcry_pk_encrypt(&out, in, pub_key);
578 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
579 ret = -E_SEXP_ENCRYPT;
582 /* extract a, an MPI with the result of the RSA operation */
584 out_a = gcry_sexp_find_token(out, "a", 0);
587 /* convert sexp out_a -> out_mpi */
588 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
593 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
595 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
596 ret = -E_SEXP_ENCRYPT;
597 goto out_mpi_release;
599 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
600 dump_buffer("enc buf", outbuf, nbytes);
604 gcry_mpi_release(out_mpi);
606 gcry_sexp_release(out_a);
608 gcry_sexp_release(out);
610 gcry_sexp_release(in);
612 gcry_sexp_release(pub_key);
616 struct stream_cipher {
617 gcry_cipher_hd_t handle;
620 struct stream_cipher *sc_new(const unsigned char *data, int len)
623 struct stream_cipher *sc = para_malloc(sizeof(*sc));
625 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
626 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
627 GCRY_CIPHER_MODE_CTR, 0);
629 gret = gcry_cipher_setkey(sc->handle, data,
630 AES_CRT128_BLOCK_SIZE);
632 gret = gcry_cipher_setctr(sc->handle,
633 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
638 void sc_free(struct stream_cipher *sc)
642 gcry_cipher_close(sc->handle);
646 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
648 gcry_cipher_hd_t handle = sc->handle;
651 /* perform in-place encryption */
653 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,