]> git.tuebingen.mpg.de Git - paraslash.git/blob - gcrypt.c
ad38dcb83c56920a2e40116cccf6d6382fcad0b5
[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
19 //#define GCRYPT_DEBUG 1
20
21 static bool libgcrypt_has_oaep;
22 static const char *rsa_decrypt_sexp;
23
24 #ifdef GCRYPT_DEBUG
25 static void dump_buffer(const char *msg, unsigned char *buf, int len)
26 {
27         int i;
28
29         fprintf(stderr, "%s (%d bytes): ", msg, len);
30         for (i = 0; i < len; i++)
31                 fprintf(stderr, "%02x ", buf[i]);
32         fprintf(stderr, "\n");
33 }
34 #else
35 /** Empty. Define GCRYPT_DEBUG to dump buffers. */
36 #define dump_buffer(a, b, c)
37 #endif
38
39 void hash_function(const char *data, unsigned long len, unsigned char *hash)
40 {
41         gcry_error_t gret;
42         gcry_md_hd_t handle;
43         unsigned char *md;
44
45         gret = gcry_md_open(&handle, GCRY_MD_SHA1, 0);
46         assert(gret == 0);
47         gcry_md_write(handle, data, (size_t)len);
48         gcry_md_final(handle);
49         md = gcry_md_read(handle, GCRY_MD_SHA1);
50         assert(md);
51         memcpy(hash, md, HASH_SIZE);
52         gcry_md_close(handle);
53 }
54
55 void get_random_bytes_or_die(unsigned char *buf, int num)
56 {
57         gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
58 }
59
60 /*
61  * This is called at the beginning of every program that uses libgcrypt. We
62  * don't have to initialize any random seed here, but we must initialize the
63  * gcrypt library. This task is performed by gcry_check_version() which can
64  * also check that the gcrypt library version is at least the minimal required
65  * version. This function also tells us whether we have to use our own OAEP
66  * padding code.
67  */
68 void init_random_seed_or_die(void)
69 {
70         const char *ver, *req_ver;
71
72         ver = gcry_check_version(NULL);
73         req_ver = "1.4.0";
74         if (!gcry_check_version(req_ver)) {
75                 PARA_EMERG_LOG("fatal: need at least libgcrypt-%s, have: %s\n",
76                         req_ver, ver);
77                 exit(EXIT_FAILURE);
78         }
79         req_ver = "1.5.0";
80         if (gcry_check_version(req_ver)) {
81                 libgcrypt_has_oaep = true;
82                 rsa_decrypt_sexp = "(enc-val(flags oaep)(rsa(a %m)))";
83         } else {
84                 libgcrypt_has_oaep = false;
85                 rsa_decrypt_sexp = "(enc-val(rsa(a %m)))";
86         }
87 }
88
89 /** S-expression for the public part of an RSA key. */
90 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
91 /** S-expression for a private RSA key. */
92 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
93
94 /* rfc 3447, appendix B.2 */
95 static void mgf1(unsigned char *seed, size_t seed_len, unsigned result_len,
96                 unsigned char *result)
97 {
98         gcry_error_t gret;
99         gcry_md_hd_t handle;
100         size_t n;
101         unsigned char *md;
102         unsigned char octet_string[4], *rp = result, *end = rp + result_len;
103
104         assert(result_len / HASH_SIZE < 1ULL << 31);
105         gret = gcry_md_open(&handle, GCRY_MD_SHA1, 0);
106         assert(gret == 0);
107         for (n = 0; rp < end; n++) {
108                 gcry_md_write(handle, seed, seed_len);
109                 octet_string[0] = (unsigned char)((n >> 24) & 255);
110                 octet_string[1] = (unsigned char)((n >> 16) & 255);
111                 octet_string[2] = (unsigned char)((n >> 8)) & 255;
112                 octet_string[3] = (unsigned char)(n & 255);
113                 gcry_md_write(handle, octet_string, 4);
114                 gcry_md_final(handle);
115                 md = gcry_md_read(handle, GCRY_MD_SHA1);
116                 memcpy(rp, md, PARA_MIN(HASH_SIZE, (int)(end - rp)));
117                 rp += HASH_SIZE;
118                 gcry_md_reset(handle);
119         }
120         gcry_md_close(handle);
121 }
122
123 /** The sha1 hash of an empty file. */
124 static const unsigned char empty_hash[HASH_SIZE] =
125         "\xda" "\x39" "\xa3" "\xee" "\x5e"
126         "\x6b" "\x4b" "\x0d" "\x32" "\x55"
127         "\xbf" "\xef" "\x95" "\x60" "\x18"
128         "\x90" "\xaf" "\xd8" "\x07" "\x09";
129
130 /* rfc3447, section 7.1.1 */
131 static void pad_oaep(unsigned char *in, size_t in_len, unsigned char *out,
132                 size_t out_len)
133 {
134         size_t ps_len = out_len - in_len - 2 * HASH_SIZE - 2;
135         size_t n, mask_len = out_len - HASH_SIZE - 1;
136         unsigned char *seed = out + 1, *db = seed + HASH_SIZE,
137                 *ps = db + HASH_SIZE, *one = ps + ps_len;
138         unsigned char *db_mask, seed_mask[HASH_SIZE];
139
140         assert(in_len <= out_len - 2 - 2 * HASH_SIZE);
141         assert(out_len > 2 * HASH_SIZE + 2);
142         PARA_DEBUG_LOG("padding %zu byte input -> %zu byte output\n",
143                 in_len, out_len);
144         dump_buffer("unpadded buffer", in, in_len);
145
146         out[0] = '\0';
147         get_random_bytes_or_die(seed, HASH_SIZE);
148         memcpy(db, empty_hash, HASH_SIZE);
149         memset(ps, 0, ps_len);
150         *one = 0x01;
151         memcpy(one + 1, in, in_len);
152         db_mask = para_malloc(mask_len);
153         mgf1(seed, HASH_SIZE, mask_len, db_mask);
154         for (n = 0; n < mask_len; n++)
155                 db[n] ^= db_mask[n];
156         mgf1(db, mask_len, HASH_SIZE, seed_mask);
157         for (n = 0; n < HASH_SIZE; n++)
158                 seed[n] ^= seed_mask[n];
159         free(db_mask);
160         dump_buffer("padded buffer", out, out_len);
161 }
162
163 /* rfc 3447, section 7.1.2 */
164 static int unpad_oaep(unsigned char *in, size_t in_len, unsigned char *out,
165                 size_t *out_len)
166 {
167         unsigned char *masked_seed = in + 1;
168         unsigned char *db = in + 1 + HASH_SIZE;
169         unsigned char seed[HASH_SIZE], seed_mask[HASH_SIZE];
170         unsigned char *db_mask, *p;
171         size_t n, mask_len = in_len - HASH_SIZE - 1;
172
173         mgf1(db, mask_len, HASH_SIZE, seed_mask);
174         for (n = 0; n < HASH_SIZE; n++)
175                 seed[n] = masked_seed[n] ^ seed_mask[n];
176         db_mask = para_malloc(mask_len);
177         mgf1(seed, HASH_SIZE, mask_len, db_mask);
178         for (n = 0; n < mask_len; n++)
179                 db[n] ^= db_mask[n];
180         free(db_mask);
181         if (memcmp(db, empty_hash, HASH_SIZE))
182                 return -E_OEAP;
183         for (p = db + HASH_SIZE; p < in + in_len - 1; p++)
184                 if (*p != '\0')
185                         break;
186         if (p >= in + in_len - 1)
187                 return -E_OEAP;
188         p++;
189         *out_len = in + in_len - p;
190         memcpy(out, p, *out_len);
191         return 1;
192 }
193
194 struct asymmetric_key {
195         gcry_sexp_t sexp;
196         int num_bytes;
197 };
198
199 static const char *gcrypt_strerror(gcry_error_t gret)
200 {
201         return gcry_strerror(gcry_err_code(gret));
202 }
203
204 static int decode_key(const char *key_file, const char *header_str,
205                 const char *footer_str, unsigned char **result)
206 {
207         int ret, ret2, i, j;
208         void *map;
209         size_t map_size, key_size, blob_size;
210         unsigned char *blob = NULL;
211         char *begin, *footer, *key;
212
213         ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
214         if (ret < 0)
215                 return ret;
216         ret = -E_KEY_MARKER;
217         if (strncmp(map, header_str, strlen(header_str)))
218                 goto unmap;
219         footer = strstr(map, footer_str);
220         ret = -E_KEY_MARKER;
221         if (!footer)
222                 goto unmap;
223         begin = map + strlen(header_str);
224         /* skip whitespace at the beginning */
225         for (; begin < footer; begin++) {
226                 if (para_isspace(*begin))
227                         continue;
228                 break;
229         }
230         ret = -E_KEY_MARKER;
231         if (begin >= footer)
232                 goto unmap;
233
234         key_size = footer - begin;
235         key = para_malloc(key_size + 1);
236         for (i = 0, j = 0; begin + i < footer; i++) {
237                 if (para_isspace(begin[i]))
238                         continue;
239                 key[j++] = begin[i];
240         }
241         key[j] = '\0';
242         blob_size = key_size * 2;
243         blob = para_malloc(blob_size);
244         ret = base64_decode(key, blob, blob_size);
245         free(key);
246         if (ret < 0)
247                 goto free_unmap;
248         goto unmap;
249 free_unmap:
250         free(blob);
251         blob = NULL;
252 unmap:
253         ret2 = para_munmap(map, map_size);
254         if (ret >= 0 && ret2 < 0)
255                 ret = ret2;
256         if (ret < 0) {
257                 free(blob);
258                 blob = NULL;
259         }
260         *result = blob;
261         return ret;
262 }
263
264 /** ASN Types and their code. */
265 enum asn1_types {
266         /** The next object is an integer. */
267         ASN1_TYPE_INTEGER = 0x2,
268         /** Bit string object. */
269         ASN1_TYPE_BIT_STRING = 0x03,
270         /** Keys start with one big type sequence. */
271         ASN1_TYPE_SEQUENCE = 0x30,
272 };
273
274 /* bit 6 has value 0 */
275 static inline bool is_primitive(unsigned char c)
276 {
277         return (c & (1<<6)) == 0;
278 }
279
280 static inline bool is_primitive_integer(unsigned char c)
281 {
282         if (!is_primitive(c))
283                 return false;
284         return (c & 0x1f) == ASN1_TYPE_INTEGER;
285 }
286
287 /* Bit 8 is zero (and bits 7-1 give the length) */
288 static inline bool is_short_form(unsigned char c)
289 {
290         return (c & 0x80) == 0;
291 }
292
293 static inline int get_short_form_length(unsigned char c)
294 {
295         return c & 0x7f;
296 }
297
298 static inline int get_long_form_num_length_bytes(unsigned char c)
299 {
300         return c & 0x7f;
301 }
302
303 static int find_pubkey_bignum_offset(const unsigned char *data, int len)
304 {
305         const unsigned char *p = data, *end = data + len;
306
307         /* the whole thing starts with one sequence */
308         if (*p != ASN1_TYPE_SEQUENCE)
309                 return -E_ASN1_PARSE;
310         p++;
311         if (p >= end)
312                 return -E_ASN1_PARSE;
313         if (is_short_form(*p))
314                 p++;
315         else
316                 p += 1 + get_long_form_num_length_bytes(*p);
317         if (p >= end)
318                 return -E_ASN1_PARSE;
319         /* another sequence containing the object id, skip it */
320         if (*p != ASN1_TYPE_SEQUENCE)
321                 return -E_ASN1_PARSE;
322         p++;
323         if (p >= end)
324                 return -E_ASN1_PARSE;
325         if (!is_short_form(*p))
326                 return -E_ASN1_PARSE;
327         p += 1 + get_short_form_length(*p);
328         if (p >= end)
329                 return -E_ASN1_PARSE;
330         /* all numbers are wrapped in a bit string object that follows */
331         if (*p != ASN1_TYPE_BIT_STRING)
332                 return -E_ASN1_PARSE;
333         p++;
334         if (p >= end)
335                 return -E_ASN1_PARSE;
336         if (is_short_form(*p))
337                 p++;
338         else
339                 p += 1 + get_long_form_num_length_bytes(*p);
340         p++; /* skip number of unused bits in the bit string */
341         if (p >= end)
342                 return -E_ASN1_PARSE;
343
344         /* next, we have a sequence of two integers (n and e) */
345         if (*p != ASN1_TYPE_SEQUENCE)
346                 return -E_ASN1_PARSE;
347         p++;
348         if (p >= end)
349                 return -E_ASN1_PARSE;
350         if (is_short_form(*p))
351                 p++;
352         else
353                 p += 1 + get_long_form_num_length_bytes(*p);
354         if (p >= end)
355                 return -E_ASN1_PARSE;
356         if (*p != ASN1_TYPE_INTEGER)
357                 return -E_ASN1_PARSE;
358         return p - data;
359 }
360
361 /*
362  * Returns: Number of bytes scanned. This may differ from the value returned via
363  * bn_bytes because the latter does not include the ASN.1 prefix and a leading
364  * zero is not considered as an additional byte for bn_bytes.
365  */
366 static int read_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
367                 int *bn_bytes)
368 {
369         int i, bn_size;
370         gcry_error_t gret;
371         unsigned char *cp = start;
372
373         if (!is_primitive_integer(*cp))
374                 return -E_BAD_PRIVATE_KEY;
375         cp++;
376         if (is_short_form(*cp)) {
377                 bn_size = get_short_form_length(*cp);
378                 cp++;
379         } else {
380                 int num_bytes = get_long_form_num_length_bytes(*cp);
381                 if (cp + num_bytes > end)
382                         return -E_BAD_PRIVATE_KEY;
383                 if (num_bytes > 4) /* nobody has such a large modulus */
384                         return -E_BAD_PRIVATE_KEY;
385                 cp++;
386                 bn_size = 0;
387                 for (i = 0; i < num_bytes; i++, cp++)
388                         bn_size = (bn_size << 8) + *cp;
389         }
390         PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, bn_size);
391         gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
392         if (gret) {
393                 PARA_ERROR_LOG("%s while scanning n\n",
394                         gcry_strerror(gcry_err_code(gret)));
395                 return-E_MPI_SCAN;
396         }
397         /*
398          * Don't take the first leading zero into account for the size of the
399          * bignum.
400          */
401         if (*cp == '\0') {
402                 cp++;
403                 bn_size--;
404         }
405         if (bn_bytes)
406                 *bn_bytes = bn_size;
407         cp += bn_size;
408 //      unsigned char *buf;
409 //      gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
410 //      PARA_CRIT_LOG("bn: %s\n", buf);
411         return cp - start;
412 }
413
414 static int find_privkey_bignum_offset(const unsigned char *data, int len)
415 {
416         const unsigned char *p = data, *end = data + len;
417
418         /* like the public key, the whole thing is contained in a sequence */
419         if (*p != ASN1_TYPE_SEQUENCE)
420                 return -E_ASN1_PARSE;
421         p++;
422         if (p >= end)
423                 return -E_ASN1_PARSE;
424         if (is_short_form(*p))
425                 p++;
426         else
427                 p += 1 + get_long_form_num_length_bytes(*p);
428         if (p >= end)
429                 return -E_ASN1_PARSE;
430
431         /* skip next integer */
432         if (*p != ASN1_TYPE_INTEGER)
433                 return -E_ASN1_PARSE;
434         p++;
435         if (p >= end)
436                 return -E_ASN1_PARSE;
437         if (is_short_form(*p))
438                 p += 1 + get_short_form_length(*p);
439         else
440                 p += 1 + get_long_form_num_length_bytes(*p);
441         if (p >= end)
442                 return -E_ASN1_PARSE;
443         return p - data;
444 }
445
446 /** Private keys start with this header. */
447 #define PRIVATE_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
448 /** Private keys end with this footer. */
449 #define PRIVATE_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
450
451 static int get_private_key(const char *key_file, struct asymmetric_key **result)
452 {
453         gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL,
454                 u = NULL;
455         unsigned char *blob, *cp, *end;
456         int blob_size, ret, n_size;
457         gcry_error_t gret;
458         size_t erroff;
459         gcry_sexp_t sexp;
460         struct asymmetric_key *key;
461
462         ret = decode_key(key_file, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER,
463                 &blob);
464         if (ret < 0)
465                 return ret;
466         blob_size = ret;
467         end = blob + blob_size;
468         ret = find_privkey_bignum_offset(blob, blob_size);
469         if (ret < 0)
470                 goto free_blob;
471         PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
472         cp = blob + ret;
473
474         ret = read_bignum(cp, end, &n, &n_size);
475         if (ret < 0)
476                 goto free_blob;
477         cp += ret;
478
479         ret = read_bignum(cp, end, &e, NULL);
480         if (ret < 0)
481                 goto release_n;
482         cp += ret;
483
484         ret = read_bignum(cp, end, &d, NULL);
485         if (ret < 0)
486                 goto release_e;
487         cp += ret;
488
489         ret = read_bignum(cp, end, &p, NULL);
490         if (ret < 0)
491                 goto release_d;
492         cp += ret;
493
494         ret = read_bignum(cp, end, &q, NULL);
495         if (ret < 0)
496                 goto release_p;
497         cp += ret;
498         ret = read_bignum(cp, end, &u, NULL);
499         if (ret < 0)
500                 goto release_q;
501         /*
502          * OpenSSL uses slightly different parameters than gcrypt. To use these
503          * parameters we need to swap the values of p and q and recompute u.
504          */
505         if (gcry_mpi_cmp(p, q) > 0) {
506                 gcry_mpi_swap(p, q);
507                 gcry_mpi_invm(u, p, q);
508         }
509         gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
510                 n, e, d, p, q, u);
511
512         if (gret) {
513                 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
514                         gcry_strerror(gcry_err_code(gret)));
515                 ret = -E_SEXP_BUILD;
516                 goto release_u;
517         }
518         key = para_malloc(sizeof(*key));
519         key->sexp = sexp;
520         *result = key;
521         ret = n_size * 8;
522         PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
523 release_u:
524         gcry_mpi_release(u);
525 release_q:
526         gcry_mpi_release(q);
527 release_p:
528         gcry_mpi_release(p);
529 release_d:
530         gcry_mpi_release(d);
531 release_e:
532         gcry_mpi_release(e);
533 release_n:
534         gcry_mpi_release(n);
535 free_blob:
536         free(blob);
537         return ret;
538 }
539
540 /** Public keys start with this header. */
541 #define PUBLIC_KEY_HEADER "-----BEGIN PUBLIC KEY-----"
542 /** Public keys end with this footer. */
543 #define PUBLIC_KEY_FOOTER "-----END PUBLIC KEY-----"
544
545 static int get_asn_public_key(const char *key_file, struct asymmetric_key **result)
546 {
547         gcry_mpi_t n = NULL, e = NULL;
548         unsigned char *blob, *cp, *end;
549         int blob_size, ret, n_size;
550         gcry_error_t gret;
551         size_t erroff;
552         gcry_sexp_t sexp;
553         struct asymmetric_key *key;
554
555         ret = decode_key(key_file, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER,
556                 &blob);
557         if (ret < 0)
558                 return ret;
559         blob_size = ret;
560         end = blob + blob_size;
561         ret = find_pubkey_bignum_offset(blob, blob_size);
562         if (ret < 0)
563                 goto free_blob;
564         PARA_DEBUG_LOG("decoding public RSA params at offset %d\n", ret);
565         cp = blob + ret;
566
567         ret = read_bignum(cp, end, &n, &n_size);
568         if (ret < 0)
569                 goto free_blob;
570         cp += ret;
571
572         ret = read_bignum(cp, end, &e, NULL);
573         if (ret < 0)
574                 goto release_n;
575
576         gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
577         if (gret) {
578                 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
579                         gcry_strerror(gcry_err_code(gret)));
580                 ret = -E_SEXP_BUILD;
581                 goto release_e;
582         }
583         key = para_malloc(sizeof(*key));
584         key->sexp = sexp;
585         *result = key;
586         ret = n_size;
587         PARA_INFO_LOG("successfully read %u bit asn public key\n", n_size * 8);
588
589 release_e:
590         gcry_mpi_release(e);
591 release_n:
592         gcry_mpi_release(n);
593 free_blob:
594         free(blob);
595         return ret;
596 }
597
598 static int get_ssh_public_key(unsigned char *data, int size, gcry_sexp_t *result)
599 {
600         int ret;
601         gcry_error_t gret;
602         unsigned char *blob = NULL, *p, *end;
603         size_t nr_scanned, erroff, decoded_size;
604         gcry_mpi_t e = NULL, n = NULL;
605
606         PARA_DEBUG_LOG("decoding %d byte public rsa-ssh key\n", size);
607         if (size > INT_MAX / 4)
608                 return -ERRNO_TO_PARA_ERROR(EOVERFLOW);
609         blob = para_malloc(2 * size);
610         ret = uudecode((char *)data, blob, 2 * size);
611         if (ret < 0)
612                 goto free_blob;
613         decoded_size = ret;
614         end = blob + decoded_size;
615         dump_buffer("decoded key", blob, decoded_size);
616         ret = check_ssh_key_header(blob, decoded_size);
617         if (ret < 0)
618                 goto free_blob;
619         p = blob + ret;
620         ret = -E_SSH_PARSE;
621         if (p >= end)
622                 goto free_blob;
623         PARA_DEBUG_LOG("scanning modulus and public exponent\n");
624         gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
625         if (gret) {
626                 ret = -E_MPI_SCAN;
627                 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
628                 goto free_blob;
629         }
630         PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
631 //      gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_e);
632 //      PARA_CRIT_LOG("e: %s\n", buf);
633         p += nr_scanned;
634         if (p >= end)
635                 goto release_e;
636         gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
637         if (gret) {
638                 ret = -E_MPI_SCAN;
639                 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
640                 goto release_e;
641         }
642         PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
643 //      gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_n);
644 //      PARA_CRIT_LOG("n: %s\n", buf);
645         gret = gcry_sexp_build(result, &erroff, RSA_PUBKEY_SEXP, n, e);
646         if (gret) {
647                 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
648                         gcry_strerror(gcry_err_code(gret)));
649                 ret = -E_SEXP_BUILD;
650                 goto release_n;
651         }
652         ret = nr_scanned / 32 * 32;
653         PARA_INFO_LOG("successfully read %u bit ssh public key\n", ret * 8);
654 release_n:
655         gcry_mpi_release(n);
656 release_e:
657         gcry_mpi_release(e);
658 free_blob:
659         free(blob);
660         return ret;
661 }
662
663 int get_asymmetric_key(const char *key_file, int private,
664                 struct asymmetric_key **result)
665 {
666         int ret, ret2;
667         void *map;
668         size_t map_size;
669         unsigned char *start, *end;
670         gcry_sexp_t sexp;
671         struct asymmetric_key *key;
672
673         if (private)
674                 return get_private_key(key_file, result);
675         ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
676         if (ret < 0)
677                 return ret;
678         ret = is_ssh_rsa_key(map, map_size);
679         if (!ret) {
680                 ret = para_munmap(map, map_size);
681                 if (ret < 0)
682                         return ret;
683                 return get_asn_public_key(key_file, result);
684         }
685         start = map + ret;
686         end = map + map_size;
687         ret = -E_SSH_PARSE;
688         if (start >= end)
689                 goto unmap;
690         ret = get_ssh_public_key(start, end - start, &sexp);
691         if (ret < 0)
692                 goto unmap;
693         key = para_malloc(sizeof(*key));
694         key->num_bytes = ret;
695         key->sexp = sexp;
696         *result = key;
697 unmap:
698         ret2 = para_munmap(map, map_size);
699         if (ret >= 0 && ret2 < 0)
700                 ret = ret2;
701         return ret;
702 }
703
704 void free_asymmetric_key(struct asymmetric_key *key)
705 {
706         if (!key)
707                 return;
708         gcry_sexp_release(key->sexp);
709         free(key);
710 }
711
712 static int decode_rsa(gcry_sexp_t sexp, int key_size, unsigned char *outbuf,
713                 size_t *nbytes)
714 {
715         int ret;
716         gcry_error_t gret;
717         unsigned char oaep_buf[512];
718         gcry_mpi_t out_mpi;
719
720         if (libgcrypt_has_oaep) {
721                 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
722
723                 if (!p) {
724                         PARA_ERROR_LOG("could not get data from list\n");
725                         return -E_OEAP;
726                 }
727                 memcpy(outbuf, p, *nbytes);
728                 return 1;
729         }
730         out_mpi = gcry_sexp_nth_mpi(sexp, 0, GCRYMPI_FMT_USG);
731         if (!out_mpi)
732                 return -E_SEXP_FIND;
733         gret = gcry_mpi_print(GCRYMPI_FMT_USG, oaep_buf, sizeof(oaep_buf),
734                 nbytes, out_mpi);
735         if (gret) {
736                 PARA_ERROR_LOG("mpi_print: %s\n", gcrypt_strerror(gret));
737                 ret = -E_MPI_PRINT;
738                 goto out_mpi_release;
739         }
740         /*
741          * An oaep-encoded buffer always starts with at least one zero byte.
742          * However, leading zeroes in an mpi are omitted in the output of
743          * gcry_mpi_print() when using the GCRYMPI_FMT_USG format. The
744          * alternative, GCRYMPI_FMT_STD, does not work either because here the
745          * leading zero(es) might also be omitted, depending on the value of
746          * the second byte.
747          *
748          * To circumvent this, we shift the oaep buffer to the right. But first
749          * we check that the buffer actually started with a zero byte, i.e. that
750          * nbytes < key_size. Otherwise a decoding error occurred.
751          */
752         ret = -E_SEXP_DECRYPT;
753         if (*nbytes >= key_size)
754                 goto out_mpi_release;
755         memmove(oaep_buf + key_size - *nbytes, oaep_buf, *nbytes);
756         memset(oaep_buf, 0, key_size - *nbytes);
757
758         PARA_DEBUG_LOG("decrypted buffer before unpad (%d bytes):\n",
759                 key_size);
760         dump_buffer("non-unpadded decrypted buffer", oaep_buf, key_size);
761         ret = unpad_oaep(oaep_buf, key_size, outbuf, nbytes);
762         if (ret < 0)
763                 goto out_mpi_release;
764         PARA_DEBUG_LOG("decrypted buffer after unpad (%zu bytes):\n",
765                 *nbytes);
766         dump_buffer("unpadded decrypted buffer", outbuf, *nbytes);
767         ret = 1;
768 out_mpi_release:
769         gcry_mpi_release(out_mpi);
770         return ret;
771 }
772
773 int priv_decrypt(const char *key_file, unsigned char *outbuf,
774                 unsigned char *inbuf, int inlen)
775 {
776         gcry_error_t gret;
777         int ret, key_size;
778         struct asymmetric_key *priv;
779         gcry_mpi_t in_mpi = NULL;
780         gcry_sexp_t in, out, priv_key;
781         size_t nbytes;
782
783         PARA_INFO_LOG("decrypting %d byte input\n", inlen);
784         /* key_file -> asymmetric key priv */
785         ret = get_private_key(key_file, &priv);
786         if (ret < 0)
787                 return ret;
788         key_size = ret / 8;
789
790         /* asymmetric key priv -> sexp priv_key */
791         ret = -E_SEXP_FIND;
792         priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
793         if (!priv_key)
794                 goto free_key;
795
796         /* inbuf -> in_mpi */
797         gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
798                 inlen, NULL);
799         if (gret) {
800                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
801                 ret = -E_MPI_SCAN;
802                 goto key_release;
803         }
804         /* in_mpi -> in sexp */
805         gret = gcry_sexp_build(&in, NULL, rsa_decrypt_sexp, in_mpi);
806         if (gret) {
807                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
808                 ret = -E_SEXP_BUILD;
809                 goto in_mpi_release;
810         }
811
812         /* rsa decryption: in sexp -> out sexp */
813         gret = gcry_pk_decrypt(&out, in, priv_key);
814         if (gret) {
815                 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
816                 ret = -E_SEXP_DECRYPT;
817                 goto in_release;
818         }
819         ret = decode_rsa(out, key_size, outbuf, &nbytes);
820         if (ret < 0)
821                 goto out_release;
822         PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
823         ret = nbytes;
824 out_release:
825         gcry_sexp_release(out);
826 in_release:
827         gcry_sexp_release(in);
828 in_mpi_release:
829         gcry_mpi_release(in_mpi);
830 key_release:
831         gcry_sexp_release(priv_key);
832 free_key:
833         free_asymmetric_key(priv);
834         return ret;
835 }
836
837 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
838                 unsigned len, unsigned char *outbuf)
839 {
840         gcry_error_t gret;
841         gcry_sexp_t pub_key, in, out, out_a;
842         gcry_mpi_t out_mpi = NULL;
843         size_t nbytes;
844         int ret;
845
846         PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
847
848         /* get pub key */
849         pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
850         if (!pub_key)
851                 return -E_SEXP_FIND;
852         if (libgcrypt_has_oaep) {
853                 gret = gcry_sexp_build(&in, NULL,
854                         "(data(flags oaep)(value %b))", len, inbuf);
855         } else {
856                 unsigned char padded_input[256];
857                 const size_t pad_size = 256;
858                 /* inbuf -> padded inbuf */
859                 pad_oaep(inbuf, len, padded_input, pad_size);
860                 /* padded inbuf -> in sexp */
861                 gret = gcry_sexp_build(&in, NULL,
862                         "(data(flags raw)(value %b))", pad_size, padded_input);
863         }
864         if (gret) {
865                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
866                 ret = -E_SEXP_BUILD;
867                 goto key_release;
868         }
869         /* rsa sexp encryption: in -> out */
870         gret = gcry_pk_encrypt(&out, in, pub_key);
871         if (gret) {
872                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
873                 ret = -E_SEXP_ENCRYPT;
874                 goto in_release;
875         }
876         /* extract a, an MPI with the result of the RSA operation */
877         ret = -E_SEXP_FIND;
878         out_a = gcry_sexp_find_token(out, "a", 0);
879         if (!out_a)
880                 goto out_release;
881         /* convert sexp out_a -> out_mpi */
882         out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
883         if (!out_mpi) {
884                 ret = -E_SEXP_FIND;
885                 goto out_a_release;
886         }
887         gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
888         if (gret) {
889                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
890                 ret = -E_SEXP_ENCRYPT;
891                 goto out_mpi_release;
892         }
893         PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
894         dump_buffer("enc buf", outbuf, nbytes);
895         ret = nbytes;
896
897 out_mpi_release:
898         gcry_mpi_release(out_mpi);
899 out_a_release:
900         gcry_sexp_release(out_a);
901 out_release:
902         gcry_sexp_release(out);
903 in_release:
904         gcry_sexp_release(in);
905 key_release:
906         gcry_sexp_release(pub_key);
907         return ret;
908 }
909
910 struct stream_cipher {
911         gcry_cipher_hd_t handle;
912 };
913
914 struct stream_cipher *sc_new(const unsigned char *data, int len,
915                 bool use_aes)
916 {
917         gcry_error_t gret;
918         struct stream_cipher *sc = para_malloc(sizeof(*sc));
919
920         if (use_aes) {
921                 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
922                 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
923                         GCRY_CIPHER_MODE_CTR, 0);
924                 assert(gret == 0);
925                 gret = gcry_cipher_setkey(sc->handle, data,
926                         AES_CRT128_BLOCK_SIZE);
927                 assert(gret == 0);
928                 gret = gcry_cipher_setctr(sc->handle,
929                         data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
930                 assert(gret == 0);
931                 return sc;
932         }
933         gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_ARCFOUR,
934                 GCRY_CIPHER_MODE_STREAM, 0);
935         if (gret) {
936                 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
937                 free(sc);
938                 return NULL;
939         }
940         gret = gcry_cipher_setkey(sc->handle, data, (size_t)len);
941         assert(gret == 0);
942         return sc;
943 }
944
945 void sc_free(struct stream_cipher *sc)
946 {
947         if (!sc)
948                 return;
949         gcry_cipher_close(sc->handle);
950         free(sc);
951 }
952
953 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
954 {
955         gcry_cipher_hd_t handle = sc->handle;
956         gcry_error_t gret;
957
958         /* perform in-place encryption */
959         *dst = *src;
960         gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,
961                 NULL, 0);
962         assert(gret == 0);
963 }