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