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