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"
15 #include "portable_io.h"
17 //#define GCRYPT_DEBUG 1
20 static void dump_buffer(const char *msg, unsigned char *buf, int len)
24 fprintf(stderr, "%s (%d bytes): ", msg, len);
25 for (i = 0; i < len; i++)
26 fprintf(stderr, "%02x ", buf[i]);
27 fprintf(stderr, "\n");
30 /** Empty. Define GCRYPT_DEBUG to dump buffers. */
31 #define dump_buffer(a, b, c)
34 void hash_function(const char *data, unsigned long len, unsigned char *hash)
40 gret = gcry_md_open(&handle, GCRY_MD_SHA1, 0);
42 gcry_md_write(handle, data, (size_t)len);
43 gcry_md_final(handle);
44 md = gcry_md_read(handle, GCRY_MD_SHA1);
46 memcpy(hash, md, HASH_SIZE);
47 gcry_md_close(handle);
50 void get_random_bytes_or_die(unsigned char *buf, int num)
52 gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
56 * This is called at the beginning of every program that uses libgcrypt. The
57 * call to gcry_check_version() initializes the gcrypt library and checks that
58 * we have at least the minimal required version.
62 const char *req_ver = "1.5.0";
65 if (!gcry_check_version(req_ver)) {
66 PARA_EMERG_LOG("fatal: need at least libgcrypt-%s, have: %s\n",
67 req_ver, gcry_check_version(NULL));
72 * Allocate a pool of secure memory. This also drops privileges where
75 gcry_control(GCRYCTL_INIT_SECMEM, 65536, 0);
77 /* Tell Libgcrypt that initialization has completed. */
78 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
80 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
84 void crypt_shutdown(void)
87 * WK does not see a way to apply a patch for the sake of Valgrind, so
88 * as of 2018 libgrypt has no deinitialization routine to free the
93 /** S-expression for the public part of an RSA key. */
94 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
95 /** S-expression for a private RSA key. */
96 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
97 /** S-expression for decryption. */
98 #define RSA_DECRYPT_SEXP "(enc-val(flags oaep)(rsa(a %m)))"
100 struct asymmetric_key {
105 static const char *gcrypt_strerror(gcry_error_t gret)
107 return gcry_strerror(gcry_err_code(gret));
110 /** Private PEM keys (legacy format) start with this header. */
111 #define PRIVATE_PEM_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
112 /** Private OPENSSH keys (RFC4716) start with this header. */
113 #define PRIVATE_OPENSSH_KEY_HEADER "-----BEGIN OPENSSH PRIVATE KEY-----"
114 /** Private PEM keys (legacy format) end with this footer. */
115 #define PRIVATE_PEM_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
116 /** Private OPENSSH keys (RFC4716) end with this footer. */
117 #define PRIVATE_OPENSSH_KEY_FOOTER "-----END OPENSSH PRIVATE KEY-----"
118 /** Legacy PEM keys (openssh-7.7 and earlier, paraslash.0.6.2 and earlier) */
120 /** OPENSSH keys (since openssh-7.8, paraslash.0.6.3) */
121 #define PKT_OPENSSH (1)
123 static int decode_private_key(const char *key_file, unsigned char **result,
126 int ret, ret2, i, j, key_type;
128 size_t map_size, key_size;
129 unsigned char *blob = NULL;
130 char *begin, *footer, *key;
132 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
136 if (strncmp(map, PRIVATE_PEM_KEY_HEADER,
137 strlen(PRIVATE_PEM_KEY_HEADER)) == 0) {
139 begin = map + strlen(PRIVATE_PEM_KEY_HEADER);
140 footer = strstr(map, PRIVATE_PEM_KEY_FOOTER);
141 PARA_INFO_LOG("detected legacy PEM key %s\n", key_file);
142 } else if (strncmp(map, PRIVATE_OPENSSH_KEY_HEADER,
143 strlen(PRIVATE_OPENSSH_KEY_HEADER)) == 0) {
144 key_type = PKT_OPENSSH;
145 begin = map + strlen(PRIVATE_OPENSSH_KEY_HEADER);
146 footer = strstr(map, PRIVATE_OPENSSH_KEY_FOOTER);
147 PARA_INFO_LOG("detected openssh key %s\n", key_file);
152 /* skip whitespace at the beginning */
153 for (; begin < footer; begin++) {
154 if (para_isspace(*begin))
162 key_size = footer - begin;
163 key = para_malloc(key_size + 1);
164 for (i = 0, j = 0; begin + i < footer; i++) {
165 if (para_isspace(begin[i]))
170 ret = base64_decode(key, j, (char **)&blob, blob_size);
176 ret2 = para_munmap(map, map_size);
177 if (ret >= 0 && ret2 < 0)
188 /** ASN Types and their code. */
190 /** The next object is an integer. */
191 ASN1_TYPE_INTEGER = 0x2,
192 /** Bit string object. */
193 ASN1_TYPE_BIT_STRING = 0x03,
194 /** Keys start with one big type sequence. */
195 ASN1_TYPE_SEQUENCE = 0x30,
198 /* bit 6 has value 0 */
199 static inline bool is_primitive(unsigned char c)
201 return (c & (1<<6)) == 0;
204 static inline bool is_primitive_integer(unsigned char c)
206 if (!is_primitive(c))
208 return (c & 0x1f) == ASN1_TYPE_INTEGER;
211 /* Bit 8 is zero (and bits 7-1 give the length) */
212 static inline bool is_short_form(unsigned char c)
214 return (c & 0x80) == 0;
217 static inline int get_short_form_length(unsigned char c)
222 static inline int get_long_form_num_length_bytes(unsigned char c)
228 * Returns: Number of bytes scanned. This may differ from the value returned via
229 * bitsp because the latter does not include the ASN.1 prefix and a leading
230 * zero is not considered as an additional byte for the number of bits.
232 static int read_pem_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
237 unsigned char *cp = start;
239 if (!is_primitive_integer(*cp))
240 return -E_BAD_PRIVATE_KEY;
242 if (is_short_form(*cp)) {
243 bn_size = get_short_form_length(*cp);
246 int num_bytes = get_long_form_num_length_bytes(*cp);
247 if (cp + num_bytes > end)
248 return -E_BAD_PRIVATE_KEY;
249 if (num_bytes > 4) /* nobody has such a large modulus */
250 return -E_BAD_PRIVATE_KEY;
253 for (i = 0; i < num_bytes; i++, cp++)
254 bn_size = (bn_size << 8) + *cp;
256 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
257 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
259 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
260 gcry_strerror(gcry_err_code(gret)));
264 * Don't take the first leading zero into account for the size of the
272 *bitsp = bn_size * 8;
274 // unsigned char *buf;
275 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
276 // PARA_CRIT_LOG("bn: %s\n", buf);
281 gcry_mpi_t n, e, d, p, q, u;
284 static int read_pem_rsa_params(unsigned char *start, unsigned char *end,
285 struct rsa_params *p)
287 unsigned char *cp = start;
291 ret = read_pem_bignum(cp, end, &p->n, &bits);
295 ret = read_pem_bignum(cp, end, &p->e, NULL);
299 ret = read_pem_bignum(cp, end, &p->d, NULL);
303 ret = read_pem_bignum(cp, end, &p->p, NULL);
307 ret = read_pem_bignum(cp, end, &p->q, NULL);
311 ret = read_pem_bignum(cp, end, &p->u, NULL);
316 gcry_mpi_release(p->q);
318 gcry_mpi_release(p->p);
320 gcry_mpi_release(p->d);
322 gcry_mpi_release(p->e);
324 gcry_mpi_release(p->n);
328 static int find_pem_bignum_offset(const unsigned char *data, int len)
330 const unsigned char *p = data, *end = data + len;
332 /* like the public key, the whole thing is contained in a sequence */
333 if (*p != ASN1_TYPE_SEQUENCE)
334 return -E_ASN1_PARSE;
337 return -E_ASN1_PARSE;
338 if (is_short_form(*p))
341 p += 1 + get_long_form_num_length_bytes(*p);
343 return -E_ASN1_PARSE;
345 /* skip next integer */
346 if (*p != ASN1_TYPE_INTEGER)
347 return -E_ASN1_PARSE;
350 return -E_ASN1_PARSE;
351 if (is_short_form(*p))
352 p += 1 + get_short_form_length(*p);
354 p += 1 + get_long_form_num_length_bytes(*p);
356 return -E_ASN1_PARSE;
360 static int read_openssh_bignum(unsigned char *start, unsigned char *end,
361 gcry_mpi_t *bn, unsigned *bitsp)
367 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_SSH, start, end - start, &nscanned);
369 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
370 gcry_strerror(gcry_err_code(gret)));
373 bits = (nscanned - 4 - (start[4] == '\0')) * 8;
376 PARA_DEBUG_LOG("scanned %u-bit bignum\n", bits);
380 static int read_openssh_rsa_params(unsigned char *start, unsigned char *end,
381 struct rsa_params *p)
383 unsigned char *cp = start;
387 ret = read_openssh_bignum(cp, end, &p->n, &bits);
391 ret = read_openssh_bignum(cp, end, &p->e, NULL);
395 ret = read_openssh_bignum(cp, end, &p->d, NULL);
399 ret = read_openssh_bignum(cp, end, &p->u, NULL);
403 ret = read_openssh_bignum(cp, end, &p->p, NULL);
407 ret = read_openssh_bignum(cp, end, &p->q, NULL);
412 gcry_mpi_release(p->p);
414 gcry_mpi_release(p->u);
416 gcry_mpi_release(p->d);
418 gcry_mpi_release(p->e);
420 gcry_mpi_release(p->n);
424 static int get_private_key(const char *key_file, struct asymmetric_key **result)
426 struct rsa_params params;
427 unsigned char *blob, *end;
431 size_t erroff, blob_size;
433 struct asymmetric_key *key;
436 ret = decode_private_key(key_file, &blob, &blob_size);
440 end = blob + blob_size;
441 if (key_type == PKT_PEM)
442 ret = find_pem_bignum_offset(blob, blob_size);
444 ret = find_openssh_bignum_offset(blob, blob_size);
447 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
448 if (key_type == PKT_PEM)
449 ret = read_pem_rsa_params(blob + ret, end, ¶ms);
451 ret = read_openssh_rsa_params(blob + ret, end, ¶ms);
456 * OpenSSL uses slightly different parameters than gcrypt. To use these
457 * parameters we need to swap the values of p and q and recompute u.
459 if (gcry_mpi_cmp(params.p, params.q) > 0) {
460 gcry_mpi_swap(params.p, params.q);
461 gcry_mpi_invm(params.u, params.p, params.q);
463 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP, params.n,
464 params.e, params.d, params.p, params.q, params.u);
467 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
468 gcry_strerror(gcry_err_code(gret)));
472 key = para_malloc(sizeof(*key));
476 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
478 gcry_mpi_release(params.n);
479 gcry_mpi_release(params.e);
480 gcry_mpi_release(params.d);
481 gcry_mpi_release(params.u);
482 gcry_mpi_release(params.p);
483 gcry_mpi_release(params.q);
490 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
492 unsigned char *blob, *p, *end;
495 size_t erroff, decoded_size;
498 struct asymmetric_key *key;
501 ret = decode_public_key(key_file, &blob, &decoded_size);
505 end = blob + decoded_size;
506 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
507 ret = read_openssh_bignum(p, end, &e, NULL);
511 ret = read_openssh_bignum(p, end, &n, &bits);
514 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
516 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
517 gcry_strerror(gcry_err_code(gret)));
521 PARA_INFO_LOG("successfully read %u bit ssh public key\n", bits);
522 key = para_malloc(sizeof(*key));
523 key->num_bytes = ret;
536 void apc_free_pubkey(struct asymmetric_key *key)
540 gcry_sexp_release(key->sexp);
544 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
546 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
549 return -E_RSA_DECODE;
550 memcpy(outbuf, p, *nbytes);
554 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
555 unsigned char *inbuf, int inlen)
559 struct asymmetric_key *priv;
560 gcry_mpi_t in_mpi = NULL;
561 gcry_sexp_t in, out, priv_key;
564 ret = check_private_key_file(key_file);
567 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
568 /* key_file -> asymmetric key priv */
569 ret = get_private_key(key_file, &priv);
573 /* asymmetric key priv -> sexp priv_key */
575 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
579 /* inbuf -> in_mpi */
580 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
583 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
587 /* in_mpi -> in sexp */
588 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
590 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
595 /* rsa decryption: in sexp -> out sexp */
596 gret = gcry_pk_decrypt(&out, in, priv_key);
598 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
599 ret = -E_SEXP_DECRYPT;
602 ret = decode_rsa(out, outbuf, &nbytes);
605 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
608 gcry_sexp_release(out);
610 gcry_sexp_release(in);
612 gcry_mpi_release(in_mpi);
614 gcry_sexp_release(priv_key);
616 gcry_sexp_release(priv->sexp);
621 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
622 unsigned len, unsigned char *outbuf)
625 gcry_sexp_t pub_key, in, out, out_a;
626 gcry_mpi_t out_mpi = NULL;
630 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
633 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
636 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
638 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
642 /* rsa sexp encryption: in -> out */
643 gret = gcry_pk_encrypt(&out, in, pub_key);
645 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
646 ret = -E_SEXP_ENCRYPT;
649 /* extract a, an MPI with the result of the RSA operation */
651 out_a = gcry_sexp_find_token(out, "a", 0);
654 /* convert sexp out_a -> out_mpi */
655 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
660 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
662 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
663 ret = -E_SEXP_ENCRYPT;
664 goto out_mpi_release;
666 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
667 dump_buffer("enc buf", outbuf, nbytes);
671 gcry_mpi_release(out_mpi);
673 gcry_sexp_release(out_a);
675 gcry_sexp_release(out);
677 gcry_sexp_release(in);
679 gcry_sexp_release(pub_key);
683 struct stream_cipher {
684 gcry_cipher_hd_t handle;
687 struct stream_cipher *sc_new(const unsigned char *data, int len)
690 struct stream_cipher *sc = para_malloc(sizeof(*sc));
692 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
693 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
694 GCRY_CIPHER_MODE_CTR, 0);
696 gret = gcry_cipher_setkey(sc->handle, data,
697 AES_CRT128_BLOCK_SIZE);
699 gret = gcry_cipher_setctr(sc->handle,
700 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
705 void sc_free(struct stream_cipher *sc)
709 gcry_cipher_close(sc->handle);
713 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
715 gcry_cipher_hd_t handle = sc->handle;
718 /* perform in-place encryption */
720 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,