1 /* Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file gcrypt.c Libgrcypt-based encryption/decryption routines. */
12 #include "crypt_backend.h"
16 //#define GCRYPT_DEBUG 1
19 static void dump_buffer(const char *msg, unsigned char *buf, int len)
23 fprintf(stderr, "%s (%d bytes): ", msg, len);
24 for (i = 0; i < len; i++)
25 fprintf(stderr, "%02x ", buf[i]);
26 fprintf(stderr, "\n");
29 /** Empty. Define GCRYPT_DEBUG to dump buffers. */
30 #define dump_buffer(a, b, c)
33 void hash_function(const char *data, unsigned long len, unsigned char *hash)
39 gret = gcry_md_open(&handle, GCRY_MD_SHA1, 0);
41 gcry_md_write(handle, data, (size_t)len);
42 gcry_md_final(handle);
43 md = gcry_md_read(handle, GCRY_MD_SHA1);
45 memcpy(hash, md, HASH_SIZE);
46 gcry_md_close(handle);
49 void get_random_bytes_or_die(unsigned char *buf, int num)
51 gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
55 * This is called at the beginning of every program that uses libgcrypt. The
56 * call to gcry_check_version() initializes the gcrypt library and checks that
57 * we have at least the minimal required version.
59 void init_random_seed_or_die(void)
61 const char *req_ver = "1.5.0";
64 if (!gcry_check_version(req_ver)) {
65 PARA_EMERG_LOG("fatal: need at least libgcrypt-%s, have: %s\n",
66 req_ver, gcry_check_version(NULL));
69 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
73 /** S-expression for the public part of an RSA key. */
74 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
75 /** S-expression for a private RSA key. */
76 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
77 /** S-expression for decryption. */
78 #define RSA_DECRYPT_SEXP "(enc-val(flags oaep)(rsa(a %m)))"
80 struct asymmetric_key {
85 static const char *gcrypt_strerror(gcry_error_t gret)
87 return gcry_strerror(gcry_err_code(gret));
90 static int decode_key(const char *key_file, const char *header_str,
91 const char *footer_str, unsigned char **result)
95 size_t map_size, key_size, blob_size;
96 unsigned char *blob = NULL;
97 char *begin, *footer, *key;
99 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
103 if (strncmp(map, header_str, strlen(header_str)))
105 footer = strstr(map, footer_str);
109 begin = map + strlen(header_str);
110 /* skip whitespace at the beginning */
111 for (; begin < footer; begin++) {
112 if (para_isspace(*begin))
120 key_size = footer - begin;
121 key = para_malloc(key_size + 1);
122 for (i = 0, j = 0; begin + i < footer; i++) {
123 if (para_isspace(begin[i]))
128 ret = base64_decode(key, j, (char **)&blob, &blob_size);
138 ret2 = para_munmap(map, map_size);
139 if (ret >= 0 && ret2 < 0)
150 /** ASN Types and their code. */
152 /** The next object is an integer. */
153 ASN1_TYPE_INTEGER = 0x2,
154 /** Bit string object. */
155 ASN1_TYPE_BIT_STRING = 0x03,
156 /** Keys start with one big type sequence. */
157 ASN1_TYPE_SEQUENCE = 0x30,
160 /* bit 6 has value 0 */
161 static inline bool is_primitive(unsigned char c)
163 return (c & (1<<6)) == 0;
166 static inline bool is_primitive_integer(unsigned char c)
168 if (!is_primitive(c))
170 return (c & 0x1f) == ASN1_TYPE_INTEGER;
173 /* Bit 8 is zero (and bits 7-1 give the length) */
174 static inline bool is_short_form(unsigned char c)
176 return (c & 0x80) == 0;
179 static inline int get_short_form_length(unsigned char c)
184 static inline int get_long_form_num_length_bytes(unsigned char c)
190 * Returns: Number of bytes scanned. This may differ from the value returned via
191 * bn_bytes because the latter does not include the ASN.1 prefix and a leading
192 * zero is not considered as an additional byte for bn_bytes.
194 static int read_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
199 unsigned char *cp = start;
201 if (!is_primitive_integer(*cp))
202 return -E_BAD_PRIVATE_KEY;
204 if (is_short_form(*cp)) {
205 bn_size = get_short_form_length(*cp);
208 int num_bytes = get_long_form_num_length_bytes(*cp);
209 if (cp + num_bytes > end)
210 return -E_BAD_PRIVATE_KEY;
211 if (num_bytes > 4) /* nobody has such a large modulus */
212 return -E_BAD_PRIVATE_KEY;
215 for (i = 0; i < num_bytes; i++, cp++)
216 bn_size = (bn_size << 8) + *cp;
218 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
219 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
221 PARA_ERROR_LOG("%s while scanning n\n",
222 gcry_strerror(gcry_err_code(gret)));
226 * Don't take the first leading zero into account for the size of the
236 // unsigned char *buf;
237 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
238 // PARA_CRIT_LOG("bn: %s\n", buf);
242 static int find_privkey_bignum_offset(const unsigned char *data, int len)
244 const unsigned char *p = data, *end = data + len;
246 /* like the public key, the whole thing is contained in a sequence */
247 if (*p != ASN1_TYPE_SEQUENCE)
248 return -E_ASN1_PARSE;
251 return -E_ASN1_PARSE;
252 if (is_short_form(*p))
255 p += 1 + get_long_form_num_length_bytes(*p);
257 return -E_ASN1_PARSE;
259 /* skip next integer */
260 if (*p != ASN1_TYPE_INTEGER)
261 return -E_ASN1_PARSE;
264 return -E_ASN1_PARSE;
265 if (is_short_form(*p))
266 p += 1 + get_short_form_length(*p);
268 p += 1 + get_long_form_num_length_bytes(*p);
270 return -E_ASN1_PARSE;
274 /** Private keys start with this header. */
275 #define PRIVATE_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
276 /** Private keys end with this footer. */
277 #define PRIVATE_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
279 static int get_private_key(const char *key_file, struct asymmetric_key **result)
281 gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL,
283 unsigned char *blob, *cp, *end;
284 int blob_size, ret, n_size;
288 struct asymmetric_key *key;
291 ret = decode_key(key_file, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER,
296 end = blob + blob_size;
297 ret = find_privkey_bignum_offset(blob, blob_size);
300 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
303 ret = read_bignum(cp, end, &n, &n_size);
308 ret = read_bignum(cp, end, &e, NULL);
313 ret = read_bignum(cp, end, &d, NULL);
318 ret = read_bignum(cp, end, &p, NULL);
323 ret = read_bignum(cp, end, &q, NULL);
327 ret = read_bignum(cp, end, &u, NULL);
331 * OpenSSL uses slightly different parameters than gcrypt. To use these
332 * parameters we need to swap the values of p and q and recompute u.
334 if (gcry_mpi_cmp(p, q) > 0) {
336 gcry_mpi_invm(u, p, q);
338 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
342 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
343 gcry_strerror(gcry_err_code(gret)));
347 key = para_malloc(sizeof(*key));
351 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
369 static int get_ssh_public_key(unsigned char *data, int size, gcry_sexp_t *result)
373 unsigned char *blob = NULL, *p, *end;
374 size_t nr_scanned, erroff, decoded_size;
375 gcry_mpi_t e = NULL, n = NULL;
377 PARA_DEBUG_LOG("decoding %d byte public rsa-ssh key\n", size);
378 ret = uudecode((char *)data, size, (char **)&blob, &decoded_size);
381 end = blob + decoded_size;
382 dump_buffer("decoded key", blob, decoded_size);
383 ret = check_ssh_key_header(blob, decoded_size);
390 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
391 gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
394 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
397 PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
398 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_e);
399 // PARA_CRIT_LOG("e: %s\n", buf);
403 gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
406 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
409 PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
410 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_n);
411 // PARA_CRIT_LOG("n: %s\n", buf);
412 gret = gcry_sexp_build(result, &erroff, RSA_PUBKEY_SEXP, n, e);
414 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
415 gcry_strerror(gcry_err_code(gret)));
419 ret = nr_scanned / 32 * 32;
420 PARA_INFO_LOG("successfully read %d bit ssh public key\n", ret * 8);
430 int get_public_key(const char *key_file, struct asymmetric_key **result)
435 unsigned char *start, *end;
437 struct asymmetric_key *key;
439 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
442 ret = is_ssh_rsa_key(map, map_size);
444 para_munmap(map, map_size);
448 end = map + map_size;
452 ret = get_ssh_public_key(start, end - start, &sexp);
455 key = para_malloc(sizeof(*key));
456 key->num_bytes = ret;
460 ret2 = para_munmap(map, map_size);
461 if (ret >= 0 && ret2 < 0)
466 void free_public_key(struct asymmetric_key *key)
470 gcry_sexp_release(key->sexp);
474 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
476 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
479 return -E_RSA_DECODE;
480 memcpy(outbuf, p, *nbytes);
484 int priv_decrypt(const char *key_file, unsigned char *outbuf,
485 unsigned char *inbuf, int inlen)
489 struct asymmetric_key *priv;
490 gcry_mpi_t in_mpi = NULL;
491 gcry_sexp_t in, out, priv_key;
494 ret = check_private_key_file(key_file);
497 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
498 /* key_file -> asymmetric key priv */
499 ret = get_private_key(key_file, &priv);
503 /* asymmetric key priv -> sexp priv_key */
505 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
509 /* inbuf -> in_mpi */
510 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
513 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
517 /* in_mpi -> in sexp */
518 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
520 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
525 /* rsa decryption: in sexp -> out sexp */
526 gret = gcry_pk_decrypt(&out, in, priv_key);
528 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
529 ret = -E_SEXP_DECRYPT;
532 ret = decode_rsa(out, outbuf, &nbytes);
535 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
538 gcry_sexp_release(out);
540 gcry_sexp_release(in);
542 gcry_mpi_release(in_mpi);
544 gcry_sexp_release(priv_key);
546 gcry_sexp_release(priv->sexp);
551 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
552 unsigned len, unsigned char *outbuf)
555 gcry_sexp_t pub_key, in, out, out_a;
556 gcry_mpi_t out_mpi = NULL;
560 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
563 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
566 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
568 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
572 /* rsa sexp encryption: in -> out */
573 gret = gcry_pk_encrypt(&out, in, pub_key);
575 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
576 ret = -E_SEXP_ENCRYPT;
579 /* extract a, an MPI with the result of the RSA operation */
581 out_a = gcry_sexp_find_token(out, "a", 0);
584 /* convert sexp out_a -> out_mpi */
585 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
590 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
592 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
593 ret = -E_SEXP_ENCRYPT;
594 goto out_mpi_release;
596 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
597 dump_buffer("enc buf", outbuf, nbytes);
601 gcry_mpi_release(out_mpi);
603 gcry_sexp_release(out_a);
605 gcry_sexp_release(out);
607 gcry_sexp_release(in);
609 gcry_sexp_release(pub_key);
613 struct stream_cipher {
614 gcry_cipher_hd_t handle;
617 struct stream_cipher *sc_new(const unsigned char *data, int len)
620 struct stream_cipher *sc = para_malloc(sizeof(*sc));
622 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
623 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
624 GCRY_CIPHER_MODE_CTR, 0);
626 gret = gcry_cipher_setkey(sc->handle, data,
627 AES_CRT128_BLOCK_SIZE);
629 gret = gcry_cipher_setctr(sc->handle,
630 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
635 void sc_free(struct stream_cipher *sc)
639 gcry_cipher_close(sc->handle);
643 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
645 gcry_cipher_hd_t handle = sc->handle;
648 /* perform in-place encryption */
650 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,