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 {
119 static const char *gcrypt_strerror(gcry_error_t gret)
121 return gcry_strerror(gcry_err_code(gret));
124 /** ASN Types and their code. */
126 /** The next object is an integer. */
127 ASN1_TYPE_INTEGER = 0x2,
128 /** Bit string object. */
129 ASN1_TYPE_BIT_STRING = 0x03,
130 /** Keys start with one big type sequence. */
131 ASN1_TYPE_SEQUENCE = 0x30,
134 /* bit 6 has value 0 */
135 static inline bool is_primitive(unsigned char c)
137 return (c & (1<<6)) == 0;
140 static inline bool is_primitive_integer(unsigned char c)
142 if (!is_primitive(c))
144 return (c & 0x1f) == ASN1_TYPE_INTEGER;
147 /* Bit 8 is zero (and bits 7-1 give the length) */
148 static inline bool is_short_form(unsigned char c)
150 return (c & 0x80) == 0;
153 static inline int get_short_form_length(unsigned char c)
158 static inline int get_long_form_num_length_bytes(unsigned char c)
164 * Returns: Number of bytes scanned. This may differ from the value returned via
165 * bitsp because the latter does not include the ASN.1 prefix and a leading
166 * zero is not considered as an additional byte for the number of bits.
168 static int read_pem_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
173 unsigned char *cp = start;
175 if (!is_primitive_integer(*cp))
176 return -E_BAD_PRIVATE_KEY;
178 if (is_short_form(*cp)) {
179 bn_size = get_short_form_length(*cp);
182 int num_bytes = get_long_form_num_length_bytes(*cp);
183 if (cp + num_bytes > end)
184 return -E_BAD_PRIVATE_KEY;
185 if (num_bytes > 4) /* nobody has such a large modulus */
186 return -E_BAD_PRIVATE_KEY;
189 for (i = 0; i < num_bytes; i++, cp++)
190 bn_size = (bn_size << 8) + *cp;
192 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
193 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
195 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
196 gcry_strerror(gcry_err_code(gret)));
200 * Don't take the first leading zero into account for the size of the
208 *bitsp = bn_size * 8;
210 // unsigned char *buf;
211 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
212 // PARA_CRIT_LOG("bn: %s\n", buf);
217 gcry_mpi_t n, e, d, p, q, u;
220 static int read_pem_rsa_params(unsigned char *start, unsigned char *end,
221 struct rsa_params *p)
223 unsigned char *cp = start;
227 ret = read_pem_bignum(cp, end, &p->n, &bits);
231 ret = read_pem_bignum(cp, end, &p->e, NULL);
235 ret = read_pem_bignum(cp, end, &p->d, NULL);
239 ret = read_pem_bignum(cp, end, &p->p, NULL);
243 ret = read_pem_bignum(cp, end, &p->q, NULL);
247 ret = read_pem_bignum(cp, end, &p->u, NULL);
252 gcry_mpi_release(p->q);
254 gcry_mpi_release(p->p);
256 gcry_mpi_release(p->d);
258 gcry_mpi_release(p->e);
260 gcry_mpi_release(p->n);
264 static int find_pem_bignum_offset(const unsigned char *data, int len)
266 const unsigned char *p = data, *end = data + len;
268 /* like the public key, the whole thing is contained in a sequence */
269 if (*p != ASN1_TYPE_SEQUENCE)
270 return -E_ASN1_PARSE;
273 return -E_ASN1_PARSE;
274 if (is_short_form(*p))
277 p += 1 + get_long_form_num_length_bytes(*p);
279 return -E_ASN1_PARSE;
281 /* skip next integer */
282 if (*p != ASN1_TYPE_INTEGER)
283 return -E_ASN1_PARSE;
286 return -E_ASN1_PARSE;
287 if (is_short_form(*p))
288 p += 1 + get_short_form_length(*p);
290 p += 1 + get_long_form_num_length_bytes(*p);
292 return -E_ASN1_PARSE;
296 static int read_openssh_bignum(unsigned char *start, unsigned char *end,
297 gcry_mpi_t *bn, unsigned *bitsp)
303 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_SSH, start, end - start, &nscanned);
305 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
306 gcry_strerror(gcry_err_code(gret)));
309 bits = (nscanned - 4 - (start[4] == '\0')) * 8;
312 PARA_DEBUG_LOG("scanned %u-bit bignum\n", bits);
316 static int read_openssh_rsa_params(unsigned char *start, unsigned char *end,
317 struct rsa_params *p)
319 unsigned char *cp = start;
323 ret = read_openssh_bignum(cp, end, &p->n, &bits);
327 ret = read_openssh_bignum(cp, end, &p->e, NULL);
331 ret = read_openssh_bignum(cp, end, &p->d, NULL);
335 ret = read_openssh_bignum(cp, end, &p->u, NULL);
339 ret = read_openssh_bignum(cp, end, &p->p, NULL);
343 ret = read_openssh_bignum(cp, end, &p->q, NULL);
348 gcry_mpi_release(p->p);
350 gcry_mpi_release(p->u);
352 gcry_mpi_release(p->d);
354 gcry_mpi_release(p->e);
356 gcry_mpi_release(p->n);
360 static int get_private_key(const char *key_file, struct asymmetric_key **result)
362 struct rsa_params params;
363 unsigned char *blob, *end;
367 size_t erroff, blob_size;
369 struct asymmetric_key *key;
372 ret = decode_private_key(key_file, &blob, &blob_size);
376 end = blob + blob_size;
377 if (key_type == PKT_PEM)
378 ret = find_pem_bignum_offset(blob, blob_size);
380 ret = find_openssh_bignum_offset(blob, blob_size);
383 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
384 if (key_type == PKT_PEM)
385 ret = read_pem_rsa_params(blob + ret, end, ¶ms);
387 ret = read_openssh_rsa_params(blob + ret, end, ¶ms);
392 * OpenSSL uses slightly different parameters than gcrypt. To use these
393 * parameters we need to swap the values of p and q and recompute u.
395 if (gcry_mpi_cmp(params.p, params.q) > 0) {
396 gcry_mpi_swap(params.p, params.q);
397 gcry_mpi_invm(params.u, params.p, params.q);
399 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP, params.n,
400 params.e, params.d, params.p, params.q, params.u);
403 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
404 gcry_strerror(gcry_err_code(gret)));
408 key = alloc(sizeof(*key));
412 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
414 gcry_mpi_release(params.n);
415 gcry_mpi_release(params.e);
416 gcry_mpi_release(params.d);
417 gcry_mpi_release(params.u);
418 gcry_mpi_release(params.p);
419 gcry_mpi_release(params.q);
426 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
428 unsigned char *blob, *p, *end;
431 size_t erroff, decoded_size;
434 struct asymmetric_key *key;
437 ret = decode_public_key(key_file, &blob, &decoded_size);
441 end = blob + decoded_size;
442 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
443 ret = read_openssh_bignum(p, end, &e, NULL);
447 ret = read_openssh_bignum(p, end, &n, &bits);
450 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
452 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
453 gcry_strerror(gcry_err_code(gret)));
457 PARA_INFO_LOG("successfully read %u bit ssh public key\n", bits);
458 key = alloc(sizeof(*key));
471 void apc_free_pubkey(struct asymmetric_key *key)
475 gcry_sexp_release(key->sexp);
479 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
481 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
484 return -E_RSA_DECODE;
485 memcpy(outbuf, p, *nbytes);
489 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
490 unsigned char *inbuf, int inlen)
494 struct asymmetric_key *priv;
495 gcry_mpi_t in_mpi = NULL;
496 gcry_sexp_t in, out, priv_key;
499 ret = check_private_key_file(key_file);
502 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
503 /* key_file -> asymmetric key priv */
504 ret = get_private_key(key_file, &priv);
508 /* asymmetric key priv -> sexp priv_key */
510 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
514 /* inbuf -> in_mpi */
515 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
518 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
522 /* in_mpi -> in sexp */
523 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
525 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
530 /* rsa decryption: in sexp -> out sexp */
531 gret = gcry_pk_decrypt(&out, in, priv_key);
533 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
534 ret = -E_SEXP_DECRYPT;
537 ret = decode_rsa(out, outbuf, &nbytes);
540 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
543 gcry_sexp_release(out);
545 gcry_sexp_release(in);
547 gcry_mpi_release(in_mpi);
549 gcry_sexp_release(priv_key);
551 gcry_sexp_release(priv->sexp);
556 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
557 unsigned len, unsigned char *outbuf)
560 gcry_sexp_t pub_key, in, out, out_a;
561 gcry_mpi_t out_mpi = NULL;
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 = alloc(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,