Merge branch 'refs/heads/t/ll'
[paraslash.git] / gcrypt.c
1 /* Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file gcrypt.c Libgrcypt-based encryption/decryption routines. */
4
5 #include <regex.h>
6 #include <gcrypt.h>
7
8 #include "para.h"
9 #include "error.h"
10 #include "string.h"
11 #include "crypt.h"
12 #include "crypt_backend.h"
13 #include "fd.h"
14 #include "base64.h"
15
16 //#define GCRYPT_DEBUG 1
17
18 #ifdef GCRYPT_DEBUG
19 static void dump_buffer(const char *msg, unsigned char *buf, int len)
20 {
21 int i;
22
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");
27 }
28 #else
29 /** Empty. Define GCRYPT_DEBUG to dump buffers. */
30 #define dump_buffer(a, b, c)
31 #endif
32
33 void hash_function(const char *data, unsigned long len, unsigned char *hash)
34 {
35 gcry_error_t gret;
36 gcry_md_hd_t handle;
37 unsigned char *md;
38
39 gret = gcry_md_open(&handle, GCRY_MD_SHA1, 0);
40 assert(gret == 0);
41 gcry_md_write(handle, data, (size_t)len);
42 gcry_md_final(handle);
43 md = gcry_md_read(handle, GCRY_MD_SHA1);
44 assert(md);
45 memcpy(hash, md, HASH_SIZE);
46 gcry_md_close(handle);
47 }
48
49 void hash2_function(const char *data, unsigned long len, unsigned char *hash)
50 {
51 gcry_error_t gret;
52 gcry_md_hd_t handle;
53 unsigned char *md;
54
55 gret = gcry_md_open(&handle, GCRY_MD_SHA256, 0);
56 assert(gret == 0);
57 gcry_md_write(handle, data, (size_t)len);
58 gcry_md_final(handle);
59 md = gcry_md_read(handle, GCRY_MD_SHA256);
60 assert(md);
61 memcpy(hash, md, HASH2_SIZE);
62 gcry_md_close(handle);
63 }
64
65 void get_random_bytes_or_die(unsigned char *buf, int num)
66 {
67 gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
68 }
69
70 /*
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.
74 */
75 void crypt_init(void)
76 {
77 const char *req_ver = "1.5.0";
78 int seed;
79
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));
83 exit(EXIT_FAILURE);
84 }
85
86 /*
87 * Allocate a pool of secure memory. This also drops privileges where
88 * needed.
89 */
90 gcry_control(GCRYCTL_INIT_SECMEM, 65536, 0);
91
92 /* Tell Libgcrypt that initialization has completed. */
93 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
94
95 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
96 srandom(seed);
97 }
98
99 void crypt_shutdown(void)
100 {
101 /*
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
104 * resources on exit.
105 */
106 }
107
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)))"
114
115 struct asymmetric_key {
116 gcry_sexp_t sexp;
117 int num_bytes;
118 };
119
120 static const char *gcrypt_strerror(gcry_error_t gret)
121 {
122 return gcry_strerror(gcry_err_code(gret));
123 }
124
125 /** ASN Types and their code. */
126 enum asn1_types {
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,
133 };
134
135 /* bit 6 has value 0 */
136 static inline bool is_primitive(unsigned char c)
137 {
138 return (c & (1<<6)) == 0;
139 }
140
141 static inline bool is_primitive_integer(unsigned char c)
142 {
143 if (!is_primitive(c))
144 return false;
145 return (c & 0x1f) == ASN1_TYPE_INTEGER;
146 }
147
148 /* Bit 8 is zero (and bits 7-1 give the length) */
149 static inline bool is_short_form(unsigned char c)
150 {
151 return (c & 0x80) == 0;
152 }
153
154 static inline int get_short_form_length(unsigned char c)
155 {
156 return c & 0x7f;
157 }
158
159 static inline int get_long_form_num_length_bytes(unsigned char c)
160 {
161 return c & 0x7f;
162 }
163
164 /*
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.
168 */
169 static int read_pem_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
170 unsigned *bitsp)
171 {
172 int i, bn_size;
173 gcry_error_t gret;
174 unsigned char *cp = start;
175
176 if (!is_primitive_integer(*cp))
177 return -E_BAD_PRIVATE_KEY;
178 cp++;
179 if (is_short_form(*cp)) {
180 bn_size = get_short_form_length(*cp);
181 cp++;
182 } else {
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;
188 cp++;
189 bn_size = 0;
190 for (i = 0; i < num_bytes; i++, cp++)
191 bn_size = (bn_size << 8) + *cp;
192 }
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);
195 if (gret) {
196 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
197 gcry_strerror(gcry_err_code(gret)));
198 return-E_MPI_SCAN;
199 }
200 /*
201 * Don't take the first leading zero into account for the size of the
202 * bignum.
203 */
204 if (*cp == '\0') {
205 cp++;
206 bn_size--;
207 }
208 if (bitsp)
209 *bitsp = bn_size * 8;
210 cp += bn_size;
211 // unsigned char *buf;
212 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
213 // PARA_CRIT_LOG("bn: %s\n", buf);
214 return cp - start;
215 }
216
217 struct rsa_params {
218 gcry_mpi_t n, e, d, p, q, u;
219 };
220
221 static int read_pem_rsa_params(unsigned char *start, unsigned char *end,
222 struct rsa_params *p)
223 {
224 unsigned char *cp = start;
225 unsigned bits;
226 int ret;
227
228 ret = read_pem_bignum(cp, end, &p->n, &bits);
229 if (ret < 0)
230 return ret;
231 cp += ret;
232 ret = read_pem_bignum(cp, end, &p->e, NULL);
233 if (ret < 0)
234 goto release_n;
235 cp += ret;
236 ret = read_pem_bignum(cp, end, &p->d, NULL);
237 if (ret < 0)
238 goto release_e;
239 cp += ret;
240 ret = read_pem_bignum(cp, end, &p->p, NULL);
241 if (ret < 0)
242 goto release_d;
243 cp += ret;
244 ret = read_pem_bignum(cp, end, &p->q, NULL);
245 if (ret < 0)
246 goto release_p;
247 cp += ret;
248 ret = read_pem_bignum(cp, end, &p->u, NULL);
249 if (ret < 0)
250 goto release_q;
251 return bits;
252 release_q:
253 gcry_mpi_release(p->q);
254 release_p:
255 gcry_mpi_release(p->p);
256 release_d:
257 gcry_mpi_release(p->d);
258 release_e:
259 gcry_mpi_release(p->e);
260 release_n:
261 gcry_mpi_release(p->n);
262 return ret;
263 }
264
265 static int find_pem_bignum_offset(const unsigned char *data, int len)
266 {
267 const unsigned char *p = data, *end = data + len;
268
269 /* like the public key, the whole thing is contained in a sequence */
270 if (*p != ASN1_TYPE_SEQUENCE)
271 return -E_ASN1_PARSE;
272 p++;
273 if (p >= end)
274 return -E_ASN1_PARSE;
275 if (is_short_form(*p))
276 p++;
277 else
278 p += 1 + get_long_form_num_length_bytes(*p);
279 if (p >= end)
280 return -E_ASN1_PARSE;
281
282 /* skip next integer */
283 if (*p != ASN1_TYPE_INTEGER)
284 return -E_ASN1_PARSE;
285 p++;
286 if (p >= end)
287 return -E_ASN1_PARSE;
288 if (is_short_form(*p))
289 p += 1 + get_short_form_length(*p);
290 else
291 p += 1 + get_long_form_num_length_bytes(*p);
292 if (p >= end)
293 return -E_ASN1_PARSE;
294 return p - data;
295 }
296
297 static int read_openssh_bignum(unsigned char *start, unsigned char *end,
298 gcry_mpi_t *bn, unsigned *bitsp)
299 {
300 gcry_error_t gret;
301 size_t nscanned;
302 unsigned bits;
303
304 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_SSH, start, end - start, &nscanned);
305 if (gret) {
306 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
307 gcry_strerror(gcry_err_code(gret)));
308 return -E_MPI_SCAN;
309 }
310 bits = (nscanned - 4 - (start[4] == '\0')) * 8;
311 if (bitsp)
312 *bitsp = bits;
313 PARA_DEBUG_LOG("scanned %u-bit bignum\n", bits);
314 return nscanned;
315 }
316
317 static int read_openssh_rsa_params(unsigned char *start, unsigned char *end,
318 struct rsa_params *p)
319 {
320 unsigned char *cp = start;
321 unsigned bits;
322 int ret;
323
324 ret = read_openssh_bignum(cp, end, &p->n, &bits);
325 if (ret < 0)
326 return ret;
327 cp += ret;
328 ret = read_openssh_bignum(cp, end, &p->e, NULL);
329 if (ret < 0)
330 goto release_n;
331 cp += ret;
332 ret = read_openssh_bignum(cp, end, &p->d, NULL);
333 if (ret < 0)
334 goto release_e;
335 cp += ret;
336 ret = read_openssh_bignum(cp, end, &p->u, NULL);
337 if (ret < 0)
338 goto release_d;
339 cp += ret;
340 ret = read_openssh_bignum(cp, end, &p->p, NULL);
341 if (ret < 0)
342 goto release_u;
343 cp += ret;
344 ret = read_openssh_bignum(cp, end, &p->q, NULL);
345 if (ret < 0)
346 goto release_p;
347 return bits;
348 release_p:
349 gcry_mpi_release(p->p);
350 release_u:
351 gcry_mpi_release(p->u);
352 release_d:
353 gcry_mpi_release(p->d);
354 release_e:
355 gcry_mpi_release(p->e);
356 release_n:
357 gcry_mpi_release(p->n);
358 return ret;
359 }
360
361 static int get_private_key(const char *key_file, struct asymmetric_key **result)
362 {
363 struct rsa_params params;
364 unsigned char *blob, *end;
365 unsigned bits;
366 int ret, key_type;
367 gcry_error_t gret;
368 size_t erroff, blob_size;
369 gcry_sexp_t sexp;
370 struct asymmetric_key *key;
371
372 *result = NULL;
373 ret = decode_private_key(key_file, &blob, &blob_size);
374 if (ret < 0)
375 return ret;
376 key_type = ret;
377 end = blob + blob_size;
378 if (key_type == PKT_PEM)
379 ret = find_pem_bignum_offset(blob, blob_size);
380 else
381 ret = find_openssh_bignum_offset(blob, blob_size);
382 if (ret < 0)
383 goto free_blob;
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, &params);
387 else
388 ret = read_openssh_rsa_params(blob + ret, end, &params);
389 if (ret < 0)
390 goto free_blob;
391 bits = ret;
392 /*
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.
395 */
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);
399 }
400 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP, params.n,
401 params.e, params.d, params.p, params.q, params.u);
402
403 if (gret) {
404 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
405 gcry_strerror(gcry_err_code(gret)));
406 ret = -E_SEXP_BUILD;
407 goto free_params;
408 }
409 key = para_malloc(sizeof(*key));
410 key->sexp = sexp;
411 *result = key;
412 ret = bits;
413 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
414 free_params:
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);
421
422 free_blob:
423 free(blob);
424 return ret;
425 }
426
427 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
428 {
429 unsigned char *blob, *p, *end;
430 int ret;
431 gcry_error_t gret;
432 size_t erroff, decoded_size;
433 gcry_mpi_t e, n;
434 gcry_sexp_t sexp;
435 struct asymmetric_key *key;
436 unsigned bits;
437
438 ret = decode_public_key(key_file, &blob, &decoded_size);
439 if (ret < 0)
440 return ret;
441 p = blob + ret;
442 end = blob + decoded_size;
443 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
444 ret = read_openssh_bignum(p, end, &e, NULL);
445 if (ret < 0)
446 goto free_blob;
447 p += ret;
448 ret = read_openssh_bignum(p, end, &n, &bits);
449 if (ret < 0)
450 goto release_e;
451 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
452 if (gret) {
453 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
454 gcry_strerror(gcry_err_code(gret)));
455 ret = -E_SEXP_BUILD;
456 goto release_n;
457 }
458 PARA_INFO_LOG("successfully read %u bit ssh public key\n", bits);
459 key = para_malloc(sizeof(*key));
460 key->num_bytes = ret;
461 key->sexp = sexp;
462 *result = key;
463 ret = bits;
464 release_n:
465 gcry_mpi_release(n);
466 release_e:
467 gcry_mpi_release(e);
468 free_blob:
469 free(blob);
470 return ret;
471 }
472
473 void apc_free_pubkey(struct asymmetric_key *key)
474 {
475 if (!key)
476 return;
477 gcry_sexp_release(key->sexp);
478 free(key);
479 }
480
481 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
482 {
483 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
484
485 if (!p)
486 return -E_RSA_DECODE;
487 memcpy(outbuf, p, *nbytes);
488 return 1;
489 }
490
491 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
492 unsigned char *inbuf, int inlen)
493 {
494 gcry_error_t gret;
495 int ret;
496 struct asymmetric_key *priv;
497 gcry_mpi_t in_mpi = NULL;
498 gcry_sexp_t in, out, priv_key;
499 size_t nbytes;
500
501 ret = check_private_key_file(key_file);
502 if (ret < 0)
503 return ret;
504 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
505 /* key_file -> asymmetric key priv */
506 ret = get_private_key(key_file, &priv);
507 if (ret < 0)
508 return ret;
509
510 /* asymmetric key priv -> sexp priv_key */
511 ret = -E_SEXP_FIND;
512 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
513 if (!priv_key)
514 goto free_key;
515
516 /* inbuf -> in_mpi */
517 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
518 inlen, NULL);
519 if (gret) {
520 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
521 ret = -E_MPI_SCAN;
522 goto key_release;
523 }
524 /* in_mpi -> in sexp */
525 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
526 if (gret) {
527 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
528 ret = -E_SEXP_BUILD;
529 goto in_mpi_release;
530 }
531
532 /* rsa decryption: in sexp -> out sexp */
533 gret = gcry_pk_decrypt(&out, in, priv_key);
534 if (gret) {
535 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
536 ret = -E_SEXP_DECRYPT;
537 goto in_release;
538 }
539 ret = decode_rsa(out, outbuf, &nbytes);
540 if (ret < 0)
541 goto out_release;
542 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
543 ret = nbytes;
544 out_release:
545 gcry_sexp_release(out);
546 in_release:
547 gcry_sexp_release(in);
548 in_mpi_release:
549 gcry_mpi_release(in_mpi);
550 key_release:
551 gcry_sexp_release(priv_key);
552 free_key:
553 gcry_sexp_release(priv->sexp);
554 free(priv);
555 return ret;
556 }
557
558 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
559 unsigned len, unsigned char *outbuf)
560 {
561 gcry_error_t gret;
562 gcry_sexp_t pub_key, in, out, out_a;
563 gcry_mpi_t out_mpi = NULL;
564 size_t nbytes;
565 int ret;
566
567 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
568
569 /* get pub key */
570 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
571 if (!pub_key)
572 return -E_SEXP_FIND;
573 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
574 if (gret) {
575 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
576 ret = -E_SEXP_BUILD;
577 goto key_release;
578 }
579 /* rsa sexp encryption: in -> out */
580 gret = gcry_pk_encrypt(&out, in, pub_key);
581 if (gret) {
582 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
583 ret = -E_SEXP_ENCRYPT;
584 goto in_release;
585 }
586 /* extract a, an MPI with the result of the RSA operation */
587 ret = -E_SEXP_FIND;
588 out_a = gcry_sexp_find_token(out, "a", 0);
589 if (!out_a)
590 goto out_release;
591 /* convert sexp out_a -> out_mpi */
592 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
593 if (!out_mpi) {
594 ret = -E_SEXP_FIND;
595 goto out_a_release;
596 }
597 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
598 if (gret) {
599 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
600 ret = -E_SEXP_ENCRYPT;
601 goto out_mpi_release;
602 }
603 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
604 dump_buffer("enc buf", outbuf, nbytes);
605 ret = nbytes;
606
607 out_mpi_release:
608 gcry_mpi_release(out_mpi);
609 out_a_release:
610 gcry_sexp_release(out_a);
611 out_release:
612 gcry_sexp_release(out);
613 in_release:
614 gcry_sexp_release(in);
615 key_release:
616 gcry_sexp_release(pub_key);
617 return ret;
618 }
619
620 struct stream_cipher {
621 gcry_cipher_hd_t handle;
622 };
623
624 struct stream_cipher *sc_new(const unsigned char *data, int len)
625 {
626 gcry_error_t gret;
627 struct stream_cipher *sc = para_malloc(sizeof(*sc));
628
629 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
630 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
631 GCRY_CIPHER_MODE_CTR, 0);
632 assert(gret == 0);
633 gret = gcry_cipher_setkey(sc->handle, data,
634 AES_CRT128_BLOCK_SIZE);
635 assert(gret == 0);
636 gret = gcry_cipher_setctr(sc->handle,
637 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
638 assert(gret == 0);
639 return sc;
640 }
641
642 void sc_free(struct stream_cipher *sc)
643 {
644 if (!sc)
645 return;
646 gcry_cipher_close(sc->handle);
647 free(sc);
648 }
649
650 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
651 {
652 gcry_cipher_hd_t handle = sc->handle;
653 gcry_error_t gret;
654
655 /* perform in-place encryption */
656 *dst = *src;
657 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,
658 NULL, 0);
659 assert(gret == 0);
660 }