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.
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));
71 * Allocate a pool of secure memory. This also drops privileges where
74 gcry_control(GCRYCTL_INIT_SECMEM, 65536, 0);
76 /* Tell Libgcrypt that initialization has completed. */
77 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
79 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
83 void crypt_shutdown(void)
86 * WK does not see a way to apply a patch for the sake of Valgrind, so
87 * as of 2018 libgrypt has no deinitialization routine to free the
92 /** S-expression for the public part of an RSA key. */
93 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
94 /** S-expression for a private RSA key. */
95 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
96 /** S-expression for decryption. */
97 #define RSA_DECRYPT_SEXP "(enc-val(flags oaep)(rsa(a %m)))"
99 struct asymmetric_key {
104 static const char *gcrypt_strerror(gcry_error_t gret)
106 return gcry_strerror(gcry_err_code(gret));
109 /** Private keys start with this header. */
110 #define PRIVATE_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
111 /** Private keys end with this footer. */
112 #define PRIVATE_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
114 static int decode_key(const char *key_file, unsigned char **result,
119 size_t map_size, key_size;
120 unsigned char *blob = NULL;
121 char *begin, *footer, *key;
123 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
127 if (strncmp(map, PRIVATE_KEY_HEADER, strlen(PRIVATE_KEY_HEADER)))
129 footer = strstr(map, PRIVATE_KEY_FOOTER);
133 begin = map + strlen(PRIVATE_KEY_HEADER);
134 /* skip whitespace at the beginning */
135 for (; begin < footer; begin++) {
136 if (para_isspace(*begin))
144 key_size = footer - begin;
145 key = para_malloc(key_size + 1);
146 for (i = 0, j = 0; begin + i < footer; i++) {
147 if (para_isspace(begin[i]))
152 ret = base64_decode(key, j, (char **)&blob, blob_size);
155 ret2 = para_munmap(map, map_size);
156 if (ret >= 0 && ret2 < 0)
167 /** ASN Types and their code. */
169 /** The next object is an integer. */
170 ASN1_TYPE_INTEGER = 0x2,
171 /** Bit string object. */
172 ASN1_TYPE_BIT_STRING = 0x03,
173 /** Keys start with one big type sequence. */
174 ASN1_TYPE_SEQUENCE = 0x30,
177 /* bit 6 has value 0 */
178 static inline bool is_primitive(unsigned char c)
180 return (c & (1<<6)) == 0;
183 static inline bool is_primitive_integer(unsigned char c)
185 if (!is_primitive(c))
187 return (c & 0x1f) == ASN1_TYPE_INTEGER;
190 /* Bit 8 is zero (and bits 7-1 give the length) */
191 static inline bool is_short_form(unsigned char c)
193 return (c & 0x80) == 0;
196 static inline int get_short_form_length(unsigned char c)
201 static inline int get_long_form_num_length_bytes(unsigned char c)
207 * Returns: Number of bytes scanned. This may differ from the value returned via
208 * bn_bytes because the latter does not include the ASN.1 prefix and a leading
209 * zero is not considered as an additional byte for bn_bytes.
211 static int read_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
216 unsigned char *cp = start;
218 if (!is_primitive_integer(*cp))
219 return -E_BAD_PRIVATE_KEY;
221 if (is_short_form(*cp)) {
222 bn_size = get_short_form_length(*cp);
225 int num_bytes = get_long_form_num_length_bytes(*cp);
226 if (cp + num_bytes > end)
227 return -E_BAD_PRIVATE_KEY;
228 if (num_bytes > 4) /* nobody has such a large modulus */
229 return -E_BAD_PRIVATE_KEY;
232 for (i = 0; i < num_bytes; i++, cp++)
233 bn_size = (bn_size << 8) + *cp;
235 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
236 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
238 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
239 gcry_strerror(gcry_err_code(gret)));
243 * Don't take the first leading zero into account for the size of the
253 // unsigned char *buf;
254 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
255 // PARA_CRIT_LOG("bn: %s\n", buf);
259 static int find_privkey_bignum_offset(const unsigned char *data, int len)
261 const unsigned char *p = data, *end = data + len;
263 /* like the public key, the whole thing is contained in a sequence */
264 if (*p != ASN1_TYPE_SEQUENCE)
265 return -E_ASN1_PARSE;
268 return -E_ASN1_PARSE;
269 if (is_short_form(*p))
272 p += 1 + get_long_form_num_length_bytes(*p);
274 return -E_ASN1_PARSE;
276 /* skip next integer */
277 if (*p != ASN1_TYPE_INTEGER)
278 return -E_ASN1_PARSE;
281 return -E_ASN1_PARSE;
282 if (is_short_form(*p))
283 p += 1 + get_short_form_length(*p);
285 p += 1 + get_long_form_num_length_bytes(*p);
287 return -E_ASN1_PARSE;
291 static int get_private_key(const char *key_file, struct asymmetric_key **result)
293 gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL,
295 unsigned char *blob, *cp, *end;
298 size_t erroff, blob_size;
300 struct asymmetric_key *key;
303 ret = decode_key(key_file, &blob, &blob_size);
306 end = blob + blob_size;
307 ret = find_privkey_bignum_offset(blob, blob_size);
310 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
313 ret = read_bignum(cp, end, &n, &n_size);
318 ret = read_bignum(cp, end, &e, NULL);
323 ret = read_bignum(cp, end, &d, NULL);
328 ret = read_bignum(cp, end, &p, NULL);
333 ret = read_bignum(cp, end, &q, NULL);
337 ret = read_bignum(cp, end, &u, NULL);
341 * OpenSSL uses slightly different parameters than gcrypt. To use these
342 * parameters we need to swap the values of p and q and recompute u.
344 if (gcry_mpi_cmp(p, q) > 0) {
346 gcry_mpi_invm(u, p, q);
348 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
352 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
353 gcry_strerror(gcry_err_code(gret)));
357 key = para_malloc(sizeof(*key));
361 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
379 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
381 unsigned char *blob, *p, *end;
384 size_t nr_scanned, erroff, decoded_size;
387 struct asymmetric_key *key;
389 ret = decode_ssh_key(key_file, &blob, &decoded_size);
393 end = blob + decoded_size;
394 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
395 gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
398 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
401 PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
405 gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
408 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
411 PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
412 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
414 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
415 gcry_strerror(gcry_err_code(gret)));
419 ret = ROUND_DOWN(nr_scanned, 32);
420 PARA_INFO_LOG("successfully read %d bit ssh public key\n", ret * 8);
421 key = para_malloc(sizeof(*key));
422 key->num_bytes = ret;
434 void apc_free_pubkey(struct asymmetric_key *key)
438 gcry_sexp_release(key->sexp);
442 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
444 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
447 return -E_RSA_DECODE;
448 memcpy(outbuf, p, *nbytes);
452 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
453 unsigned char *inbuf, int inlen)
457 struct asymmetric_key *priv;
458 gcry_mpi_t in_mpi = NULL;
459 gcry_sexp_t in, out, priv_key;
462 ret = check_private_key_file(key_file);
465 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
466 /* key_file -> asymmetric key priv */
467 ret = get_private_key(key_file, &priv);
471 /* asymmetric key priv -> sexp priv_key */
473 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
477 /* inbuf -> in_mpi */
478 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
481 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
485 /* in_mpi -> in sexp */
486 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
488 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
493 /* rsa decryption: in sexp -> out sexp */
494 gret = gcry_pk_decrypt(&out, in, priv_key);
496 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
497 ret = -E_SEXP_DECRYPT;
500 ret = decode_rsa(out, outbuf, &nbytes);
503 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
506 gcry_sexp_release(out);
508 gcry_sexp_release(in);
510 gcry_mpi_release(in_mpi);
512 gcry_sexp_release(priv_key);
514 gcry_sexp_release(priv->sexp);
519 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
520 unsigned len, unsigned char *outbuf)
523 gcry_sexp_t pub_key, in, out, out_a;
524 gcry_mpi_t out_mpi = NULL;
528 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
531 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
534 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
536 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
540 /* rsa sexp encryption: in -> out */
541 gret = gcry_pk_encrypt(&out, in, pub_key);
543 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
544 ret = -E_SEXP_ENCRYPT;
547 /* extract a, an MPI with the result of the RSA operation */
549 out_a = gcry_sexp_find_token(out, "a", 0);
552 /* convert sexp out_a -> out_mpi */
553 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
558 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
560 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
561 ret = -E_SEXP_ENCRYPT;
562 goto out_mpi_release;
564 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
565 dump_buffer("enc buf", outbuf, nbytes);
569 gcry_mpi_release(out_mpi);
571 gcry_sexp_release(out_a);
573 gcry_sexp_release(out);
575 gcry_sexp_release(in);
577 gcry_sexp_release(pub_key);
581 struct stream_cipher {
582 gcry_cipher_hd_t handle;
585 struct stream_cipher *sc_new(const unsigned char *data, int len)
588 struct stream_cipher *sc = para_malloc(sizeof(*sc));
590 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
591 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
592 GCRY_CIPHER_MODE_CTR, 0);
594 gret = gcry_cipher_setkey(sc->handle, data,
595 AES_CRT128_BLOCK_SIZE);
597 gret = gcry_cipher_setctr(sc->handle,
598 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
603 void sc_free(struct stream_cipher *sc)
607 gcry_cipher_close(sc->handle);
611 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
613 gcry_cipher_hd_t handle = sc->handle;
616 /* perform in-place encryption */
618 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,