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