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