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