]> git.tuebingen.mpg.de Git - paraslash.git/blob - gcrypt.c
crypt: Rename decoding functions.
[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_private_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 struct rsa_params {
260         gcry_mpi_t n, e, d, p, q, u;
261 };
262
263 static int read_pem_rsa_params(unsigned char *start, unsigned char *end,
264                 struct rsa_params *p)
265 {
266         unsigned char *cp = start;
267         unsigned bits;
268         int ret;
269
270         ret = read_bignum(cp, end, &p->n, &bits);
271         if (ret < 0)
272                 return ret;
273         cp += ret;
274         ret = read_bignum(cp, end, &p->e, NULL);
275         if (ret < 0)
276                 goto release_n;
277         cp += ret;
278         ret = read_bignum(cp, end, &p->d, NULL);
279         if (ret < 0)
280                 goto release_e;
281         cp += ret;
282         ret = read_bignum(cp, end, &p->p, NULL);
283         if (ret < 0)
284                 goto release_d;
285         cp += ret;
286         ret = read_bignum(cp, end, &p->q, NULL);
287         if (ret < 0)
288                 goto release_p;
289         cp += ret;
290         ret = read_bignum(cp, end, &p->u, NULL);
291         if (ret < 0)
292                 goto release_q;
293         return bits;
294 release_q:
295         gcry_mpi_release(p->q);
296 release_p:
297         gcry_mpi_release(p->p);
298 release_d:
299         gcry_mpi_release(p->d);
300 release_e:
301         gcry_mpi_release(p->e);
302 release_n:
303         gcry_mpi_release(p->n);
304         return ret;
305 }
306
307 static int find_privkey_bignum_offset(const unsigned char *data, int len)
308 {
309         const unsigned char *p = data, *end = data + len;
310
311         /* like the public key, the whole thing is contained in a sequence */
312         if (*p != ASN1_TYPE_SEQUENCE)
313                 return -E_ASN1_PARSE;
314         p++;
315         if (p >= end)
316                 return -E_ASN1_PARSE;
317         if (is_short_form(*p))
318                 p++;
319         else
320                 p += 1 + get_long_form_num_length_bytes(*p);
321         if (p >= end)
322                 return -E_ASN1_PARSE;
323
324         /* skip next integer */
325         if (*p != ASN1_TYPE_INTEGER)
326                 return -E_ASN1_PARSE;
327         p++;
328         if (p >= end)
329                 return -E_ASN1_PARSE;
330         if (is_short_form(*p))
331                 p += 1 + get_short_form_length(*p);
332         else
333                 p += 1 + get_long_form_num_length_bytes(*p);
334         if (p >= end)
335                 return -E_ASN1_PARSE;
336         return p - data;
337 }
338
339 static int read_openssh_bignum(unsigned char *start, unsigned char *end,
340                 gcry_mpi_t *bn, unsigned *bitsp)
341 {
342         gcry_error_t gret;
343         size_t nscanned;
344         unsigned bits;
345
346         gret = gcry_mpi_scan(bn, GCRYMPI_FMT_SSH, start, end - start, &nscanned);
347         if (gret) {
348                 PARA_ERROR_LOG("gcry_mpi_scan: %s\n",
349                         gcry_strerror(gcry_err_code(gret)));
350                 return -E_MPI_SCAN;
351         }
352         bits = (nscanned - 4 - (start[4] == '\0')) * 8;
353         if (bitsp)
354                 *bitsp = bits;
355         PARA_DEBUG_LOG("scanned %u-bit bignum\n", bits);
356         return nscanned;
357 }
358
359 static int get_private_key(const char *key_file, struct asymmetric_key **result)
360 {
361         struct rsa_params params;
362         unsigned char *blob, *end;
363         int ret;
364         unsigned bits;
365         gcry_error_t gret;
366         size_t erroff, blob_size;
367         gcry_sexp_t sexp;
368         struct asymmetric_key *key;
369
370         *result = NULL;
371         ret = decode_private_key(key_file, &blob, &blob_size);
372         if (ret < 0)
373                 return ret;
374         end = blob + blob_size;
375         ret = find_privkey_bignum_offset(blob, blob_size);
376         if (ret < 0)
377                 goto free_blob;
378         PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
379         ret = read_pem_rsa_params(blob + ret, end, &params);
380         if (ret < 0)
381                 goto free_blob;
382         bits = ret;
383         /*
384          * OpenSSL uses slightly different parameters than gcrypt. To use these
385          * parameters we need to swap the values of p and q and recompute u.
386          */
387         if (gcry_mpi_cmp(params.p, params.q) > 0) {
388                 gcry_mpi_swap(params.p, params.q);
389                 gcry_mpi_invm(params.u, params.p, params.q);
390         }
391         gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP, params.n,
392                 params.e, params.d, params.p, params.q, params.u);
393
394         if (gret) {
395                 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
396                         gcry_strerror(gcry_err_code(gret)));
397                 ret = -E_SEXP_BUILD;
398                 goto free_params;
399         }
400         key = para_malloc(sizeof(*key));
401         key->sexp = sexp;
402         *result = key;
403         ret = bits;
404         PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
405 free_params:
406         gcry_mpi_release(params.n);
407         gcry_mpi_release(params.e);
408         gcry_mpi_release(params.d);
409         gcry_mpi_release(params.u);
410         gcry_mpi_release(params.p);
411         gcry_mpi_release(params.q);
412
413 free_blob:
414         free(blob);
415         return ret;
416 }
417
418 int apc_get_pubkey(const char *key_file, struct asymmetric_key **result)
419 {
420         unsigned char *blob, *p, *end;
421         int ret;
422         gcry_error_t gret;
423         size_t erroff, decoded_size;
424         gcry_mpi_t e, n;
425         gcry_sexp_t sexp;
426         struct asymmetric_key *key;
427         unsigned bits;
428
429         ret = decode_public_key(key_file, &blob, &decoded_size);
430         if (ret < 0)
431                 return ret;
432         p = blob + ret;
433         end = blob + decoded_size;
434         PARA_DEBUG_LOG("scanning modulus and public exponent\n");
435         ret = read_openssh_bignum(p, end, &e, NULL);
436         if (ret < 0)
437                 goto free_blob;
438         p += ret;
439         ret = read_openssh_bignum(p, end, &n, &bits);
440         if (ret < 0)
441                 goto release_e;
442         gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
443         if (gret) {
444                 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
445                         gcry_strerror(gcry_err_code(gret)));
446                 ret = -E_SEXP_BUILD;
447                 goto release_n;
448         }
449         PARA_INFO_LOG("successfully read %u bit ssh public key\n", bits);
450         key = para_malloc(sizeof(*key));
451         key->num_bytes = ret;
452         key->sexp = sexp;
453         *result = key;
454         ret = bits;
455 release_n:
456         gcry_mpi_release(n);
457 release_e:
458         gcry_mpi_release(e);
459 free_blob:
460         free(blob);
461         return ret;
462 }
463
464 void apc_free_pubkey(struct asymmetric_key *key)
465 {
466         if (!key)
467                 return;
468         gcry_sexp_release(key->sexp);
469         free(key);
470 }
471
472 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
473 {
474         const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
475
476         if (!p)
477                 return -E_RSA_DECODE;
478         memcpy(outbuf, p, *nbytes);
479         return 1;
480 }
481
482 int apc_priv_decrypt(const char *key_file, unsigned char *outbuf,
483                 unsigned char *inbuf, int inlen)
484 {
485         gcry_error_t gret;
486         int ret;
487         struct asymmetric_key *priv;
488         gcry_mpi_t in_mpi = NULL;
489         gcry_sexp_t in, out, priv_key;
490         size_t nbytes;
491
492         ret = check_private_key_file(key_file);
493         if (ret < 0)
494                 return ret;
495         PARA_INFO_LOG("decrypting %d byte input\n", inlen);
496         /* key_file -> asymmetric key priv */
497         ret = get_private_key(key_file, &priv);
498         if (ret < 0)
499                 return ret;
500
501         /* asymmetric key priv -> sexp priv_key */
502         ret = -E_SEXP_FIND;
503         priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
504         if (!priv_key)
505                 goto free_key;
506
507         /* inbuf -> in_mpi */
508         gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
509                 inlen, NULL);
510         if (gret) {
511                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
512                 ret = -E_MPI_SCAN;
513                 goto key_release;
514         }
515         /* in_mpi -> in sexp */
516         gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
517         if (gret) {
518                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
519                 ret = -E_SEXP_BUILD;
520                 goto in_mpi_release;
521         }
522
523         /* rsa decryption: in sexp -> out sexp */
524         gret = gcry_pk_decrypt(&out, in, priv_key);
525         if (gret) {
526                 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
527                 ret = -E_SEXP_DECRYPT;
528                 goto in_release;
529         }
530         ret = decode_rsa(out, outbuf, &nbytes);
531         if (ret < 0)
532                 goto out_release;
533         PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
534         ret = nbytes;
535 out_release:
536         gcry_sexp_release(out);
537 in_release:
538         gcry_sexp_release(in);
539 in_mpi_release:
540         gcry_mpi_release(in_mpi);
541 key_release:
542         gcry_sexp_release(priv_key);
543 free_key:
544         gcry_sexp_release(priv->sexp);
545         free(priv);
546         return ret;
547 }
548
549 int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
550                 unsigned len, unsigned char *outbuf)
551 {
552         gcry_error_t gret;
553         gcry_sexp_t pub_key, in, out, out_a;
554         gcry_mpi_t out_mpi = NULL;
555         size_t nbytes;
556         int ret;
557
558         PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
559
560         /* get pub key */
561         pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
562         if (!pub_key)
563                 return -E_SEXP_FIND;
564         gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
565         if (gret) {
566                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
567                 ret = -E_SEXP_BUILD;
568                 goto key_release;
569         }
570         /* rsa sexp encryption: in -> out */
571         gret = gcry_pk_encrypt(&out, in, pub_key);
572         if (gret) {
573                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
574                 ret = -E_SEXP_ENCRYPT;
575                 goto in_release;
576         }
577         /* extract a, an MPI with the result of the RSA operation */
578         ret = -E_SEXP_FIND;
579         out_a = gcry_sexp_find_token(out, "a", 0);
580         if (!out_a)
581                 goto out_release;
582         /* convert sexp out_a -> out_mpi */
583         out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
584         if (!out_mpi) {
585                 ret = -E_SEXP_FIND;
586                 goto out_a_release;
587         }
588         gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
589         if (gret) {
590                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
591                 ret = -E_SEXP_ENCRYPT;
592                 goto out_mpi_release;
593         }
594         PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
595         dump_buffer("enc buf", outbuf, nbytes);
596         ret = nbytes;
597
598 out_mpi_release:
599         gcry_mpi_release(out_mpi);
600 out_a_release:
601         gcry_sexp_release(out_a);
602 out_release:
603         gcry_sexp_release(out);
604 in_release:
605         gcry_sexp_release(in);
606 key_release:
607         gcry_sexp_release(pub_key);
608         return ret;
609 }
610
611 struct stream_cipher {
612         gcry_cipher_hd_t handle;
613 };
614
615 struct stream_cipher *sc_new(const unsigned char *data, int len)
616 {
617         gcry_error_t gret;
618         struct stream_cipher *sc = para_malloc(sizeof(*sc));
619
620         assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
621         gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
622                 GCRY_CIPHER_MODE_CTR, 0);
623         assert(gret == 0);
624         gret = gcry_cipher_setkey(sc->handle, data,
625                 AES_CRT128_BLOCK_SIZE);
626         assert(gret == 0);
627         gret = gcry_cipher_setctr(sc->handle,
628                 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
629         assert(gret == 0);
630         return sc;
631 }
632
633 void sc_free(struct stream_cipher *sc)
634 {
635         if (!sc)
636                 return;
637         gcry_cipher_close(sc->handle);
638         free(sc);
639 }
640
641 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
642 {
643         gcry_cipher_hd_t handle = sc->handle;
644         gcry_error_t gret;
645
646         /* perform in-place encryption */
647         *dst = *src;
648         gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,
649                 NULL, 0);
650         assert(gret == 0);
651 }