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