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