Merge branch 'refs/heads/t/ogg_afh'
[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 get_random_bytes_or_die(unsigned char *buf, int num)
50 {
51 gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
52 }
53
54 /*
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.
58 */
59 void crypt_init(void)
60 {
61 const char *req_ver = "1.5.0";
62 int seed;
63
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));
67 exit(EXIT_FAILURE);
68 }
69
70 /*
71 * Allocate a pool of secure memory. This also drops privileges where
72 * needed.
73 */
74 gcry_control(GCRYCTL_INIT_SECMEM, 65536, 0);
75
76 /* Tell Libgcrypt that initialization has completed. */
77 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
78
79 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
80 srandom(seed);
81 }
82
83 void crypt_shutdown(void)
84 {
85 /*
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
88 * resources on exit.
89 */
90 }
91
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)))"
98
99 struct asymmetric_key {
100 gcry_sexp_t sexp;
101 int num_bytes;
102 };
103
104 static const char *gcrypt_strerror(gcry_error_t gret)
105 {
106 return gcry_strerror(gcry_err_code(gret));
107 }
108
109 /** ASN Types and their code. */
110 enum asn1_types {
111 /** The next object is an integer. */
112 ASN1_TYPE_INTEGER = 0x2,
113 /** Bit string object. */
114 ASN1_TYPE_BIT_STRING = 0x03,
115 /** Keys start with one big type sequence. */
116 ASN1_TYPE_SEQUENCE = 0x30,
117 };
118
119 /* bit 6 has value 0 */
120 static inline bool is_primitive(unsigned char c)
121 {
122 return (c & (1<<6)) == 0;
123 }
124
125 static inline bool is_primitive_integer(unsigned char c)
126 {
127 if (!is_primitive(c))
128 return false;
129 return (c & 0x1f) == ASN1_TYPE_INTEGER;
130 }
131
132 /* Bit 8 is zero (and bits 7-1 give the length) */
133 static inline bool is_short_form(unsigned char c)
134 {
135 return (c & 0x80) == 0;
136 }
137
138 static inline int get_short_form_length(unsigned char c)
139 {
140 return c & 0x7f;
141 }
142
143 static inline int get_long_form_num_length_bytes(unsigned char c)
144 {
145 return c & 0x7f;
146 }
147
148 /*
149 * Returns: Number of bytes scanned. This may differ from the value returned via
150 * bitsp because the latter does not include the ASN.1 prefix and a leading
151 * zero is not considered as an additional byte for the number of bits.
152 */
153 static int read_pem_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
154 unsigned *bitsp)
155 {
156 int i, bn_size;
157 gcry_error_t gret;
158 unsigned char *cp = start;
159
160 if (!is_primitive_integer(*cp))
161 return -E_BAD_PRIVATE_KEY;
162 cp++;
163 if (is_short_form(*cp)) {
164 bn_size = get_short_form_length(*cp);
165 cp++;
166 } else {
167 int num_bytes = get_long_form_num_length_bytes(*cp);
168 if (cp + num_bytes > end)
169 return -E_BAD_PRIVATE_KEY;
170 if (num_bytes > 4) /* nobody has such a large modulus */
171 return -E_BAD_PRIVATE_KEY;
172 cp++;
173 bn_size = 0;
174 for (i = 0; i < num_bytes; i++, cp++)
175 bn_size = (bn_size << 8) + *cp;
176 }
177 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
178 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
179 if (gret) {
180 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
181 gcry_strerror(gcry_err_code(gret)));
182 return-E_MPI_SCAN;
183 }
184 /*
185 * Don't take the first leading zero into account for the size of the
186 * bignum.
187 */
188 if (*cp == '\0') {
189 cp++;
190 bn_size--;
191 }
192 if (bitsp)
193 *bitsp = bn_size * 8;
194 cp += bn_size;
195 // unsigned char *buf;
196 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
197 // PARA_CRIT_LOG("bn: %s\n", buf);
198 return cp - start;
199 }
200
201 struct rsa_params {
202 gcry_mpi_t n, e, d, p, q, u;
203 };
204
205 static int read_pem_rsa_params(unsigned char *start, unsigned char *end,
206 struct rsa_params *p)
207 {
208 unsigned char *cp = start;
209 unsigned bits;
210 int ret;
211
212 ret = read_pem_bignum(cp, end, &p->n, &bits);
213 if (ret < 0)
214 return ret;
215 cp += ret;
216 ret = read_pem_bignum(cp, end, &p->e, NULL);
217 if (ret < 0)
218 goto release_n;
219 cp += ret;
220 ret = read_pem_bignum(cp, end, &p->d, NULL);
221 if (ret < 0)
222 goto release_e;
223 cp += ret;
224 ret = read_pem_bignum(cp, end, &p->p, NULL);
225 if (ret < 0)
226 goto release_d;
227 cp += ret;
228 ret = read_pem_bignum(cp, end, &p->q, NULL);
229 if (ret < 0)
230 goto release_p;
231 cp += ret;
232 ret = read_pem_bignum(cp, end, &p->u, NULL);
233 if (ret < 0)
234 goto release_q;
235 return bits;
236 release_q:
237 gcry_mpi_release(p->q);
238 release_p:
239 gcry_mpi_release(p->p);
240 release_d:
241 gcry_mpi_release(p->d);
242 release_e:
243 gcry_mpi_release(p->e);
244 release_n:
245 gcry_mpi_release(p->n);
246 return ret;
247 }
248
249 static int find_pem_bignum_offset(const unsigned char *data, int len)
250 {
251 const unsigned char *p = data, *end = data + len;
252
253 /* like the public key, the whole thing is contained in a sequence */
254 if (*p != ASN1_TYPE_SEQUENCE)
255 return -E_ASN1_PARSE;
256 p++;
257 if (p >= end)
258 return -E_ASN1_PARSE;
259 if (is_short_form(*p))
260 p++;
261 else
262 p += 1 + get_long_form_num_length_bytes(*p);
263 if (p >= end)
264 return -E_ASN1_PARSE;
265
266 /* skip next integer */
267 if (*p != ASN1_TYPE_INTEGER)
268 return -E_ASN1_PARSE;
269 p++;
270 if (p >= end)
271 return -E_ASN1_PARSE;
272 if (is_short_form(*p))
273 p += 1 + get_short_form_length(*p);
274 else
275 p += 1 + get_long_form_num_length_bytes(*p);
276 if (p >= end)
277 return -E_ASN1_PARSE;
278 return p - data;
279 }
280
281 static int read_openssh_bignum(unsigned char *start, unsigned char *end,
282 gcry_mpi_t *bn, unsigned *bitsp)
283 {
284 gcry_error_t gret;
285 size_t nscanned;
286 unsigned bits;
287
288 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_SSH, start, end - start, &nscanned);
289 if (gret) {
290 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
291 gcry_strerror(gcry_err_code(gret)));
292 return -E_MPI_SCAN;
293 }
294 bits = (nscanned - 4 - (start[4] == '\0')) * 8;
295 if (bitsp)
296 *bitsp = bits;
297 PARA_DEBUG_LOG("scanned %u-bit bignum\n", bits);
298 return nscanned;
299 }
300
301 static int read_openssh_rsa_params(unsigned char *start, unsigned char *end,
302 struct rsa_params *p)
303 {
304 unsigned char *cp = start;
305 unsigned bits;
306 int ret;
307
308 ret = read_openssh_bignum(cp, end, &p->n, &bits);
309 if (ret < 0)
310 return ret;
311 cp += ret;
312 ret = read_openssh_bignum(cp, end, &p->e, NULL);
313 if (ret < 0)
314 goto release_n;
315 cp += ret;
316 ret = read_openssh_bignum(cp, end, &p->d, NULL);
317 if (ret < 0)
318 goto release_e;
319 cp += ret;
320 ret = read_openssh_bignum(cp, end, &p->u, NULL);
321 if (ret < 0)
322 goto release_d;
323 cp += ret;
324 ret = read_openssh_bignum(cp, end, &p->p, NULL);
325 if (ret < 0)
326 goto release_u;
327 cp += ret;
328 ret = read_openssh_bignum(cp, end, &p->q, NULL);
329 if (ret < 0)
330 goto release_p;
331 return bits;
332 release_p:
333 gcry_mpi_release(p->p);
334 release_u:
335 gcry_mpi_release(p->u);
336 release_d:
337 gcry_mpi_release(p->d);
338 release_e:
339 gcry_mpi_release(p->e);
340 release_n:
341 gcry_mpi_release(p->n);
342 return ret;
343 }
344
345 static int get_private_key(const char *key_file, struct asymmetric_key **result)
346 {
347 struct rsa_params params;
348 unsigned char *blob, *end;
349 unsigned bits;
350 int ret, key_type;
351 gcry_error_t gret;
352 size_t erroff, blob_size;
353 gcry_sexp_t sexp;
354 struct asymmetric_key *key;
355
356 *result = NULL;
357 ret = decode_private_key(key_file, &blob, &blob_size);
358 if (ret < 0)
359 return ret;
360 key_type = ret;
361 end = blob + blob_size;
362 if (key_type == PKT_PEM)
363 ret = find_pem_bignum_offset(blob, blob_size);
364 else
365 ret = find_openssh_bignum_offset(blob, blob_size);
366 if (ret < 0)
367 goto free_blob;
368 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
369 if (key_type == PKT_PEM)
370 ret = read_pem_rsa_params(blob + ret, end, &params);
371 else
372 ret = read_openssh_rsa_params(blob + ret, end, &params);
373 if (ret < 0)
374 goto free_blob;
375 bits = ret;
376 /*
377 * OpenSSL uses slightly different parameters than gcrypt. To use these
378 * parameters we need to swap the values of p and q and recompute u.
379 */
380 if (gcry_mpi_cmp(params.p, params.q) > 0) {
381 gcry_mpi_swap(params.p, params.q);
382 gcry_mpi_invm(params.u, params.p, params.q);
383 }
384 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP, params.n,
385 params.e, params.d, params.p, params.q, params.u);
386
387 if (gret) {
388 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
389 gcry_strerror(gcry_err_code(gret)));
390 ret = -E_SEXP_BUILD;
391 goto free_params;
392 }
393 key = para_malloc(sizeof(*key));
394 key->sexp = sexp;
395 *result = key;
396 ret = bits;
397 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
398 free_params:
399 gcry_mpi_release(params.n);
400 gcry_mpi_release(params.e);
401 gcry_mpi_release(params.d);
402 gcry_mpi_release(params.u);
403 gcry_mpi_release(params.p);
404 gcry_mpi_release(params.q);
405
406 free_blob:
407 free(blob);
408 return ret;
409 }
410
411 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
412 {
413 unsigned char *blob, *p, *end;
414 int ret;
415 gcry_error_t gret;
416 size_t erroff, decoded_size;
417 gcry_mpi_t e, n;
418 gcry_sexp_t sexp;
419 struct asymmetric_key *key;
420 unsigned bits;
421
422 ret = decode_public_key(key_file, &blob, &decoded_size);
423 if (ret < 0)
424 return ret;
425 p = blob + ret;
426 end = blob + decoded_size;
427 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
428 ret = read_openssh_bignum(p, end, &e, NULL);
429 if (ret < 0)
430 goto free_blob;
431 p += ret;
432 ret = read_openssh_bignum(p, end, &n, &bits);
433 if (ret < 0)
434 goto release_e;
435 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
436 if (gret) {
437 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
438 gcry_strerror(gcry_err_code(gret)));
439 ret = -E_SEXP_BUILD;
440 goto release_n;
441 }
442 PARA_INFO_LOG("successfully read %u bit ssh public key\n", bits);
443 key = para_malloc(sizeof(*key));
444 key->num_bytes = ret;
445 key->sexp = sexp;
446 *result = key;
447 ret = bits;
448 release_n:
449 gcry_mpi_release(n);
450 release_e:
451 gcry_mpi_release(e);
452 free_blob:
453 free(blob);
454 return ret;
455 }
456
457 void apc_free_pubkey(struct asymmetric_key *key)
458 {
459 if (!key)
460 return;
461 gcry_sexp_release(key->sexp);
462 free(key);
463 }
464
465 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
466 {
467 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
468
469 if (!p)
470 return -E_RSA_DECODE;
471 memcpy(outbuf, p, *nbytes);
472 return 1;
473 }
474
475 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
476 unsigned char *inbuf, int inlen)
477 {
478 gcry_error_t gret;
479 int ret;
480 struct asymmetric_key *priv;
481 gcry_mpi_t in_mpi = NULL;
482 gcry_sexp_t in, out, priv_key;
483 size_t nbytes;
484
485 ret = check_private_key_file(key_file);
486 if (ret < 0)
487 return ret;
488 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
489 /* key_file -> asymmetric key priv */
490 ret = get_private_key(key_file, &priv);
491 if (ret < 0)
492 return ret;
493
494 /* asymmetric key priv -> sexp priv_key */
495 ret = -E_SEXP_FIND;
496 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
497 if (!priv_key)
498 goto free_key;
499
500 /* inbuf -> in_mpi */
501 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
502 inlen, NULL);
503 if (gret) {
504 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
505 ret = -E_MPI_SCAN;
506 goto key_release;
507 }
508 /* in_mpi -> in sexp */
509 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
510 if (gret) {
511 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
512 ret = -E_SEXP_BUILD;
513 goto in_mpi_release;
514 }
515
516 /* rsa decryption: in sexp -> out sexp */
517 gret = gcry_pk_decrypt(&out, in, priv_key);
518 if (gret) {
519 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
520 ret = -E_SEXP_DECRYPT;
521 goto in_release;
522 }
523 ret = decode_rsa(out, outbuf, &nbytes);
524 if (ret < 0)
525 goto out_release;
526 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
527 ret = nbytes;
528 out_release:
529 gcry_sexp_release(out);
530 in_release:
531 gcry_sexp_release(in);
532 in_mpi_release:
533 gcry_mpi_release(in_mpi);
534 key_release:
535 gcry_sexp_release(priv_key);
536 free_key:
537 gcry_sexp_release(priv->sexp);
538 free(priv);
539 return ret;
540 }
541
542 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
543 unsigned len, unsigned char *outbuf)
544 {
545 gcry_error_t gret;
546 gcry_sexp_t pub_key, in, out, out_a;
547 gcry_mpi_t out_mpi = NULL;
548 size_t nbytes;
549 int ret;
550
551 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
552
553 /* get pub key */
554 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
555 if (!pub_key)
556 return -E_SEXP_FIND;
557 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
558 if (gret) {
559 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
560 ret = -E_SEXP_BUILD;
561 goto key_release;
562 }
563 /* rsa sexp encryption: in -> out */
564 gret = gcry_pk_encrypt(&out, in, pub_key);
565 if (gret) {
566 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
567 ret = -E_SEXP_ENCRYPT;
568 goto in_release;
569 }
570 /* extract a, an MPI with the result of the RSA operation */
571 ret = -E_SEXP_FIND;
572 out_a = gcry_sexp_find_token(out, "a", 0);
573 if (!out_a)
574 goto out_release;
575 /* convert sexp out_a -> out_mpi */
576 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
577 if (!out_mpi) {
578 ret = -E_SEXP_FIND;
579 goto out_a_release;
580 }
581 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
582 if (gret) {
583 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
584 ret = -E_SEXP_ENCRYPT;
585 goto out_mpi_release;
586 }
587 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
588 dump_buffer("enc buf", outbuf, nbytes);
589 ret = nbytes;
590
591 out_mpi_release:
592 gcry_mpi_release(out_mpi);
593 out_a_release:
594 gcry_sexp_release(out_a);
595 out_release:
596 gcry_sexp_release(out);
597 in_release:
598 gcry_sexp_release(in);
599 key_release:
600 gcry_sexp_release(pub_key);
601 return ret;
602 }
603
604 struct stream_cipher {
605 gcry_cipher_hd_t handle;
606 };
607
608 struct stream_cipher *sc_new(const unsigned char *data, int len)
609 {
610 gcry_error_t gret;
611 struct stream_cipher *sc = para_malloc(sizeof(*sc));
612
613 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
614 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
615 GCRY_CIPHER_MODE_CTR, 0);
616 assert(gret == 0);
617 gret = gcry_cipher_setkey(sc->handle, data,
618 AES_CRT128_BLOCK_SIZE);
619 assert(gret == 0);
620 gret = gcry_cipher_setctr(sc->handle,
621 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
622 assert(gret == 0);
623 return sc;
624 }
625
626 void sc_free(struct stream_cipher *sc)
627 {
628 if (!sc)
629 return;
630 gcry_cipher_close(sc->handle);
631 free(sc);
632 }
633
634 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
635 {
636 gcry_cipher_hd_t handle = sc->handle;
637 gcry_error_t gret;
638
639 /* perform in-place encryption */
640 *dst = *src;
641 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,
642 NULL, 0);
643 assert(gret == 0);
644 }