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 hash2_function(const char *data, unsigned long len, unsigned char *hash)
55 gret = gcry_md_open(&handle, GCRY_MD_SHA256, 0);
57 gcry_md_write(handle, data, (size_t)len);
58 gcry_md_final(handle);
59 md = gcry_md_read(handle, GCRY_MD_SHA256);
61 memcpy(hash, md, HASH2_SIZE);
62 gcry_md_close(handle);
65 void get_random_bytes_or_die(unsigned char *buf, int num)
67 gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
71 * This is called at the beginning of every program that uses libgcrypt. The
72 * call to gcry_check_version() initializes the gcrypt library and checks that
73 * we have at least the minimal required version.
77 const char *req_ver = "1.5.0";
80 if (!gcry_check_version(req_ver)) {
81 PARA_EMERG_LOG("fatal: need at least libgcrypt-%s, have: %s\n",
82 req_ver, gcry_check_version(NULL));
87 * Allocate a pool of secure memory. This also drops privileges where
90 gcry_control(GCRYCTL_INIT_SECMEM, 65536, 0);
92 /* Tell Libgcrypt that initialization has completed. */
93 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
95 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
99 void crypt_shutdown(void)
102 * WK does not see a way to apply a patch for the sake of Valgrind, so
103 * as of 2018 libgrypt has no deinitialization routine to free the
108 /** S-expression for the public part of an RSA key. */
109 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
110 /** S-expression for a private RSA key. */
111 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
112 /** S-expression for decryption. */
113 #define RSA_DECRYPT_SEXP "(enc-val(flags oaep)(rsa(a %m)))"
115 struct asymmetric_key {
120 static const char *gcrypt_strerror(gcry_error_t gret)
122 return gcry_strerror(gcry_err_code(gret));
125 /** ASN Types and their code. */
127 /** The next object is an integer. */
128 ASN1_TYPE_INTEGER = 0x2,
129 /** Bit string object. */
130 ASN1_TYPE_BIT_STRING = 0x03,
131 /** Keys start with one big type sequence. */
132 ASN1_TYPE_SEQUENCE = 0x30,
135 /* bit 6 has value 0 */
136 static inline bool is_primitive(unsigned char c)
138 return (c & (1<<6)) == 0;
141 static inline bool is_primitive_integer(unsigned char c)
143 if (!is_primitive(c))
145 return (c & 0x1f) == ASN1_TYPE_INTEGER;
148 /* Bit 8 is zero (and bits 7-1 give the length) */
149 static inline bool is_short_form(unsigned char c)
151 return (c & 0x80) == 0;
154 static inline int get_short_form_length(unsigned char c)
159 static inline int get_long_form_num_length_bytes(unsigned char c)
165 * Returns: Number of bytes scanned. This may differ from the value returned via
166 * bitsp because the latter does not include the ASN.1 prefix and a leading
167 * zero is not considered as an additional byte for the number of bits.
169 static int read_pem_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
174 unsigned char *cp = start;
176 if (!is_primitive_integer(*cp))
177 return -E_BAD_PRIVATE_KEY;
179 if (is_short_form(*cp)) {
180 bn_size = get_short_form_length(*cp);
183 int num_bytes = get_long_form_num_length_bytes(*cp);
184 if (cp + num_bytes > end)
185 return -E_BAD_PRIVATE_KEY;
186 if (num_bytes > 4) /* nobody has such a large modulus */
187 return -E_BAD_PRIVATE_KEY;
190 for (i = 0; i < num_bytes; i++, cp++)
191 bn_size = (bn_size << 8) + *cp;
193 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
194 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
196 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
197 gcry_strerror(gcry_err_code(gret)));
201 * Don't take the first leading zero into account for the size of the
209 *bitsp = bn_size * 8;
211 // unsigned char *buf;
212 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
213 // PARA_CRIT_LOG("bn: %s\n", buf);
218 gcry_mpi_t n, e, d, p, q, u;
221 static int read_pem_rsa_params(unsigned char *start, unsigned char *end,
222 struct rsa_params *p)
224 unsigned char *cp = start;
228 ret = read_pem_bignum(cp, end, &p->n, &bits);
232 ret = read_pem_bignum(cp, end, &p->e, NULL);
236 ret = read_pem_bignum(cp, end, &p->d, NULL);
240 ret = read_pem_bignum(cp, end, &p->p, NULL);
244 ret = read_pem_bignum(cp, end, &p->q, NULL);
248 ret = read_pem_bignum(cp, end, &p->u, NULL);
253 gcry_mpi_release(p->q);
255 gcry_mpi_release(p->p);
257 gcry_mpi_release(p->d);
259 gcry_mpi_release(p->e);
261 gcry_mpi_release(p->n);
265 static int find_pem_bignum_offset(const unsigned char *data, int len)
267 const unsigned char *p = data, *end = data + len;
269 /* like the public key, the whole thing is contained in a sequence */
270 if (*p != ASN1_TYPE_SEQUENCE)
271 return -E_ASN1_PARSE;
274 return -E_ASN1_PARSE;
275 if (is_short_form(*p))
278 p += 1 + get_long_form_num_length_bytes(*p);
280 return -E_ASN1_PARSE;
282 /* skip next integer */
283 if (*p != ASN1_TYPE_INTEGER)
284 return -E_ASN1_PARSE;
287 return -E_ASN1_PARSE;
288 if (is_short_form(*p))
289 p += 1 + get_short_form_length(*p);
291 p += 1 + get_long_form_num_length_bytes(*p);
293 return -E_ASN1_PARSE;
297 static int read_openssh_bignum(unsigned char *start, unsigned char *end,
298 gcry_mpi_t *bn, unsigned *bitsp)
304 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_SSH, start, end - start, &nscanned);
306 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
307 gcry_strerror(gcry_err_code(gret)));
310 bits = (nscanned - 4 - (start[4] == '\0')) * 8;
313 PARA_DEBUG_LOG("scanned %u-bit bignum\n", bits);
317 static int read_openssh_rsa_params(unsigned char *start, unsigned char *end,
318 struct rsa_params *p)
320 unsigned char *cp = start;
324 ret = read_openssh_bignum(cp, end, &p->n, &bits);
328 ret = read_openssh_bignum(cp, end, &p->e, NULL);
332 ret = read_openssh_bignum(cp, end, &p->d, NULL);
336 ret = read_openssh_bignum(cp, end, &p->u, NULL);
340 ret = read_openssh_bignum(cp, end, &p->p, NULL);
344 ret = read_openssh_bignum(cp, end, &p->q, NULL);
349 gcry_mpi_release(p->p);
351 gcry_mpi_release(p->u);
353 gcry_mpi_release(p->d);
355 gcry_mpi_release(p->e);
357 gcry_mpi_release(p->n);
361 static int get_private_key(const char *key_file, struct asymmetric_key **result)
363 struct rsa_params params;
364 unsigned char *blob, *end;
368 size_t erroff, blob_size;
370 struct asymmetric_key *key;
373 ret = decode_private_key(key_file, &blob, &blob_size);
377 end = blob + blob_size;
378 if (key_type == PKT_PEM)
379 ret = find_pem_bignum_offset(blob, blob_size);
381 ret = find_openssh_bignum_offset(blob, blob_size);
384 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
385 if (key_type == PKT_PEM)
386 ret = read_pem_rsa_params(blob + ret, end, ¶ms);
388 ret = read_openssh_rsa_params(blob + ret, end, ¶ms);
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(params.p, params.q) > 0) {
397 gcry_mpi_swap(params.p, params.q);
398 gcry_mpi_invm(params.u, params.p, params.q);
400 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP, params.n,
401 params.e, params.d, params.p, params.q, params.u);
404 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
405 gcry_strerror(gcry_err_code(gret)));
409 key = alloc(sizeof(*key));
413 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
415 gcry_mpi_release(params.n);
416 gcry_mpi_release(params.e);
417 gcry_mpi_release(params.d);
418 gcry_mpi_release(params.u);
419 gcry_mpi_release(params.p);
420 gcry_mpi_release(params.q);
427 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
429 unsigned char *blob, *p, *end;
432 size_t erroff, decoded_size;
435 struct asymmetric_key *key;
438 ret = decode_public_key(key_file, &blob, &decoded_size);
442 end = blob + decoded_size;
443 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
444 ret = read_openssh_bignum(p, end, &e, NULL);
448 ret = read_openssh_bignum(p, end, &n, &bits);
451 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
453 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
454 gcry_strerror(gcry_err_code(gret)));
458 PARA_INFO_LOG("successfully read %u bit ssh public key\n", bits);
459 key = alloc(sizeof(*key));
473 void apc_free_pubkey(struct asymmetric_key *key)
477 gcry_sexp_release(key->sexp);
481 static int decode_rsa(gcry_sexp_t sexp, unsigned char **outbuf, size_t *nbytes)
483 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
487 return -E_RSA_DECODE;
489 *outbuf = alloc(*nbytes);
490 memcpy(*outbuf, p, *nbytes);
494 int apc_priv_decrypt(const char *key_file, unsigned char **outbuf,
495 unsigned char *inbuf, int inlen)
499 struct asymmetric_key *priv;
500 gcry_mpi_t in_mpi = NULL;
501 gcry_sexp_t in, out, priv_key;
505 ret = check_private_key_file(key_file);
508 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
509 /* key_file -> asymmetric key priv */
510 ret = get_private_key(key_file, &priv);
514 /* asymmetric key priv -> sexp priv_key */
516 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
520 /* inbuf -> in_mpi */
521 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
524 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
528 /* in_mpi -> in sexp */
529 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
531 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
536 /* rsa decryption: in sexp -> out sexp */
537 gret = gcry_pk_decrypt(&out, in, priv_key);
539 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
540 ret = -E_SEXP_DECRYPT;
543 ret = decode_rsa(out, outbuf, &nbytes);
546 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
549 gcry_sexp_release(out);
551 gcry_sexp_release(in);
553 gcry_mpi_release(in_mpi);
555 gcry_sexp_release(priv_key);
557 gcry_sexp_release(priv->sexp);
562 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
563 unsigned len, unsigned char **outbuf)
566 gcry_sexp_t pub_key, in, out, out_a;
567 gcry_mpi_t out_mpi = NULL;
573 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
576 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
578 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
582 /* rsa sexp encryption: in -> out */
583 gret = gcry_pk_encrypt(&out, in, pub_key);
585 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
586 ret = -E_SEXP_ENCRYPT;
589 /* extract a, an MPI with the result of the RSA operation */
591 out_a = gcry_sexp_find_token(out, "a", 0);
594 /* convert sexp out_a -> out_mpi */
595 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
600 *outbuf = alloc(pub->bits);
601 gret = gcry_mpi_print(GCRYMPI_FMT_USG, *outbuf, pub->bits, &nbytes,
606 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
607 ret = -E_SEXP_ENCRYPT;
608 goto out_mpi_release;
610 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
611 dump_buffer("enc buf", *outbuf, nbytes);
615 gcry_mpi_release(out_mpi);
617 gcry_sexp_release(out_a);
619 gcry_sexp_release(out);
621 gcry_sexp_release(in);
623 gcry_sexp_release(pub_key);
627 struct stream_cipher {
628 gcry_cipher_hd_t handle;
631 struct stream_cipher *sc_new(const unsigned char *data, int len)
634 struct stream_cipher *sc = alloc(sizeof(*sc));
636 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
637 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
638 GCRY_CIPHER_MODE_CTR, 0);
640 gret = gcry_cipher_setkey(sc->handle, data,
641 AES_CRT128_BLOCK_SIZE);
643 gret = gcry_cipher_setctr(sc->handle,
644 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
649 void sc_free(struct stream_cipher *sc)
653 gcry_cipher_close(sc->handle);
657 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
659 gcry_cipher_hd_t handle = sc->handle;
662 /* perform in-place encryption */
664 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,