Merge branch 'refs/heads/t/ls-p_deprecation'
[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 static int find_pubkey_bignum_offset(const unsigned char *data, int len)
305 {
306 const unsigned char *p = data, *end = data + len;
307
308 /* the whole thing starts with one sequence */
309 if (*p != ASN1_TYPE_SEQUENCE)
310 return -E_ASN1_PARSE;
311 p++;
312 if (p >= end)
313 return -E_ASN1_PARSE;
314 if (is_short_form(*p))
315 p++;
316 else
317 p += 1 + get_long_form_num_length_bytes(*p);
318 if (p >= end)
319 return -E_ASN1_PARSE;
320 /* another sequence containing the object id, skip it */
321 if (*p != ASN1_TYPE_SEQUENCE)
322 return -E_ASN1_PARSE;
323 p++;
324 if (p >= end)
325 return -E_ASN1_PARSE;
326 if (!is_short_form(*p))
327 return -E_ASN1_PARSE;
328 p += 1 + get_short_form_length(*p);
329 if (p >= end)
330 return -E_ASN1_PARSE;
331 /* all numbers are wrapped in a bit string object that follows */
332 if (*p != ASN1_TYPE_BIT_STRING)
333 return -E_ASN1_PARSE;
334 p++;
335 if (p >= end)
336 return -E_ASN1_PARSE;
337 if (is_short_form(*p))
338 p++;
339 else
340 p += 1 + get_long_form_num_length_bytes(*p);
341 p++; /* skip number of unused bits in the bit string */
342 if (p >= end)
343 return -E_ASN1_PARSE;
344
345 /* next, we have a sequence of two integers (n and e) */
346 if (*p != ASN1_TYPE_SEQUENCE)
347 return -E_ASN1_PARSE;
348 p++;
349 if (p >= end)
350 return -E_ASN1_PARSE;
351 if (is_short_form(*p))
352 p++;
353 else
354 p += 1 + get_long_form_num_length_bytes(*p);
355 if (p >= end)
356 return -E_ASN1_PARSE;
357 if (*p != ASN1_TYPE_INTEGER)
358 return -E_ASN1_PARSE;
359 return p - data;
360 }
361
362 /*
363 * Returns: Number of bytes scanned. This may differ from the value returned via
364 * bn_bytes because the latter does not include the ASN.1 prefix and a leading
365 * zero is not considered as an additional byte for bn_bytes.
366 */
367 static int read_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
368 int *bn_bytes)
369 {
370 int i, bn_size;
371 gcry_error_t gret;
372 unsigned char *cp = start;
373
374 if (!is_primitive_integer(*cp))
375 return -E_BAD_PRIVATE_KEY;
376 cp++;
377 if (is_short_form(*cp)) {
378 bn_size = get_short_form_length(*cp);
379 cp++;
380 } else {
381 int num_bytes = get_long_form_num_length_bytes(*cp);
382 if (cp + num_bytes > end)
383 return -E_BAD_PRIVATE_KEY;
384 if (num_bytes > 4) /* nobody has such a large modulus */
385 return -E_BAD_PRIVATE_KEY;
386 cp++;
387 bn_size = 0;
388 for (i = 0; i < num_bytes; i++, cp++)
389 bn_size = (bn_size << 8) + *cp;
390 }
391 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, bn_size);
392 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
393 if (gret) {
394 PARA_ERROR_LOG("%s while scanning n\n",
395 gcry_strerror(gcry_err_code(gret)));
396 return-E_MPI_SCAN;
397 }
398 /*
399 * Don't take the first leading zero into account for the size of the
400 * bignum.
401 */
402 if (*cp == '\0') {
403 cp++;
404 bn_size--;
405 }
406 if (bn_bytes)
407 *bn_bytes = bn_size;
408 cp += bn_size;
409 // unsigned char *buf;
410 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
411 // PARA_CRIT_LOG("bn: %s\n", buf);
412 return cp - start;
413 }
414
415 static int find_privkey_bignum_offset(const unsigned char *data, int len)
416 {
417 const unsigned char *p = data, *end = data + len;
418
419 /* like the public key, the whole thing is contained in a sequence */
420 if (*p != ASN1_TYPE_SEQUENCE)
421 return -E_ASN1_PARSE;
422 p++;
423 if (p >= end)
424 return -E_ASN1_PARSE;
425 if (is_short_form(*p))
426 p++;
427 else
428 p += 1 + get_long_form_num_length_bytes(*p);
429 if (p >= end)
430 return -E_ASN1_PARSE;
431
432 /* skip next integer */
433 if (*p != ASN1_TYPE_INTEGER)
434 return -E_ASN1_PARSE;
435 p++;
436 if (p >= end)
437 return -E_ASN1_PARSE;
438 if (is_short_form(*p))
439 p += 1 + get_short_form_length(*p);
440 else
441 p += 1 + get_long_form_num_length_bytes(*p);
442 if (p >= end)
443 return -E_ASN1_PARSE;
444 return p - data;
445 }
446
447 /** Private keys start with this header. */
448 #define PRIVATE_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
449 /** Private keys end with this footer. */
450 #define PRIVATE_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
451
452 static int get_private_key(const char *key_file, struct asymmetric_key **result)
453 {
454 gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL,
455 u = NULL;
456 unsigned char *blob, *cp, *end;
457 int blob_size, ret, n_size;
458 gcry_error_t gret;
459 size_t erroff;
460 gcry_sexp_t sexp;
461 struct asymmetric_key *key;
462
463 ret = decode_key(key_file, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER,
464 &blob);
465 if (ret < 0)
466 return ret;
467 blob_size = ret;
468 end = blob + blob_size;
469 ret = find_privkey_bignum_offset(blob, blob_size);
470 if (ret < 0)
471 goto free_blob;
472 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
473 cp = blob + ret;
474
475 ret = read_bignum(cp, end, &n, &n_size);
476 if (ret < 0)
477 goto free_blob;
478 cp += ret;
479
480 ret = read_bignum(cp, end, &e, NULL);
481 if (ret < 0)
482 goto release_n;
483 cp += ret;
484
485 ret = read_bignum(cp, end, &d, NULL);
486 if (ret < 0)
487 goto release_e;
488 cp += ret;
489
490 ret = read_bignum(cp, end, &p, NULL);
491 if (ret < 0)
492 goto release_d;
493 cp += ret;
494
495 ret = read_bignum(cp, end, &q, NULL);
496 if (ret < 0)
497 goto release_p;
498 cp += ret;
499 ret = read_bignum(cp, end, &u, NULL);
500 if (ret < 0)
501 goto release_q;
502 /*
503 * OpenSSL uses slightly different parameters than gcrypt. To use these
504 * parameters we need to swap the values of p and q and recompute u.
505 */
506 if (gcry_mpi_cmp(p, q) > 0) {
507 gcry_mpi_swap(p, q);
508 gcry_mpi_invm(u, p, q);
509 }
510 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
511 n, e, d, p, q, u);
512
513 if (gret) {
514 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
515 gcry_strerror(gcry_err_code(gret)));
516 ret = -E_SEXP_BUILD;
517 goto release_u;
518 }
519 key = para_malloc(sizeof(*key));
520 key->sexp = sexp;
521 *result = key;
522 ret = n_size * 8;
523 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
524 release_u:
525 gcry_mpi_release(u);
526 release_q:
527 gcry_mpi_release(q);
528 release_p:
529 gcry_mpi_release(p);
530 release_d:
531 gcry_mpi_release(d);
532 release_e:
533 gcry_mpi_release(e);
534 release_n:
535 gcry_mpi_release(n);
536 free_blob:
537 free(blob);
538 return ret;
539 }
540
541 /** Public keys start with this header. */
542 #define PUBLIC_KEY_HEADER "-----BEGIN PUBLIC KEY-----"
543 /** Public keys end with this footer. */
544 #define PUBLIC_KEY_FOOTER "-----END PUBLIC KEY-----"
545
546 static int get_asn_public_key(const char *key_file, struct asymmetric_key **result)
547 {
548 gcry_mpi_t n = NULL, e = NULL;
549 unsigned char *blob, *cp, *end;
550 int blob_size, ret, n_size;
551 gcry_error_t gret;
552 size_t erroff;
553 gcry_sexp_t sexp;
554 struct asymmetric_key *key;
555
556 ret = decode_key(key_file, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER,
557 &blob);
558 if (ret < 0)
559 return ret;
560 blob_size = ret;
561 end = blob + blob_size;
562 ret = find_pubkey_bignum_offset(blob, blob_size);
563 if (ret < 0)
564 goto free_blob;
565 PARA_DEBUG_LOG("decoding public RSA params at offset %d\n", ret);
566 cp = blob + ret;
567
568 ret = read_bignum(cp, end, &n, &n_size);
569 if (ret < 0)
570 goto free_blob;
571 cp += ret;
572
573 ret = read_bignum(cp, end, &e, NULL);
574 if (ret < 0)
575 goto release_n;
576
577 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
578 if (gret) {
579 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
580 gcry_strerror(gcry_err_code(gret)));
581 ret = -E_SEXP_BUILD;
582 goto release_e;
583 }
584 key = para_malloc(sizeof(*key));
585 key->sexp = sexp;
586 key->num_bytes = n_size;
587 *result = key;
588 ret = n_size;
589 PARA_INFO_LOG("successfully read %u bit asn public key\n", n_size * 8);
590
591 release_e:
592 gcry_mpi_release(e);
593 release_n:
594 gcry_mpi_release(n);
595 free_blob:
596 free(blob);
597 return ret;
598 }
599
600 static int get_ssh_public_key(unsigned char *data, int size, gcry_sexp_t *result)
601 {
602 int ret;
603 gcry_error_t gret;
604 unsigned char *blob = NULL, *p, *end;
605 size_t nr_scanned, erroff, decoded_size;
606 gcry_mpi_t e = NULL, n = NULL;
607
608 PARA_DEBUG_LOG("decoding %d byte public rsa-ssh key\n", size);
609 ret = uudecode((char *)data, size, (char **)&blob, &decoded_size);
610 if (ret < 0)
611 goto free_blob;
612 end = blob + decoded_size;
613 dump_buffer("decoded key", blob, decoded_size);
614 ret = check_ssh_key_header(blob, decoded_size);
615 if (ret < 0)
616 goto free_blob;
617 p = blob + ret;
618 ret = -E_SSH_PARSE;
619 if (p >= end)
620 goto free_blob;
621 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
622 gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
623 if (gret) {
624 ret = -E_MPI_SCAN;
625 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
626 goto free_blob;
627 }
628 PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
629 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_e);
630 // PARA_CRIT_LOG("e: %s\n", buf);
631 p += nr_scanned;
632 if (p >= end)
633 goto release_e;
634 gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
635 if (gret) {
636 ret = -E_MPI_SCAN;
637 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
638 goto release_e;
639 }
640 PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
641 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_n);
642 // PARA_CRIT_LOG("n: %s\n", buf);
643 gret = gcry_sexp_build(result, &erroff, RSA_PUBKEY_SEXP, n, e);
644 if (gret) {
645 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
646 gcry_strerror(gcry_err_code(gret)));
647 ret = -E_SEXP_BUILD;
648 goto release_n;
649 }
650 ret = nr_scanned / 32 * 32;
651 PARA_INFO_LOG("successfully read %u bit ssh public key\n", ret * 8);
652 release_n:
653 gcry_mpi_release(n);
654 release_e:
655 gcry_mpi_release(e);
656 free_blob:
657 free(blob);
658 return ret;
659 }
660
661 int get_asymmetric_key(const char *key_file, int private,
662 struct asymmetric_key **result)
663 {
664 int ret, ret2;
665 void *map;
666 size_t map_size;
667 unsigned char *start, *end;
668 gcry_sexp_t sexp;
669 struct asymmetric_key *key;
670
671 if (private)
672 return get_private_key(key_file, result);
673 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
674 if (ret < 0)
675 return ret;
676 ret = is_ssh_rsa_key(map, map_size);
677 if (!ret) {
678 ret = para_munmap(map, map_size);
679 if (ret < 0)
680 return ret;
681 return get_asn_public_key(key_file, result);
682 }
683 start = map + ret;
684 end = map + map_size;
685 ret = -E_SSH_PARSE;
686 if (start >= end)
687 goto unmap;
688 ret = get_ssh_public_key(start, end - start, &sexp);
689 if (ret < 0)
690 goto unmap;
691 key = para_malloc(sizeof(*key));
692 key->num_bytes = ret;
693 key->sexp = sexp;
694 *result = key;
695 unmap:
696 ret2 = para_munmap(map, map_size);
697 if (ret >= 0 && ret2 < 0)
698 ret = ret2;
699 return ret;
700 }
701
702 void free_asymmetric_key(struct asymmetric_key *key)
703 {
704 if (!key)
705 return;
706 gcry_sexp_release(key->sexp);
707 free(key);
708 }
709
710 static int decode_rsa(gcry_sexp_t sexp, int key_size, unsigned char *outbuf,
711 size_t *nbytes)
712 {
713 int ret;
714 gcry_error_t gret;
715 unsigned char oaep_buf[512];
716 gcry_mpi_t out_mpi;
717
718 if (libgcrypt_has_oaep) {
719 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
720
721 if (!p) {
722 PARA_ERROR_LOG("could not get data from list\n");
723 return -E_OEAP;
724 }
725 memcpy(outbuf, p, *nbytes);
726 return 1;
727 }
728 out_mpi = gcry_sexp_nth_mpi(sexp, 0, GCRYMPI_FMT_USG);
729 if (!out_mpi)
730 return -E_SEXP_FIND;
731 gret = gcry_mpi_print(GCRYMPI_FMT_USG, oaep_buf, sizeof(oaep_buf),
732 nbytes, out_mpi);
733 if (gret) {
734 PARA_ERROR_LOG("mpi_print: %s\n", gcrypt_strerror(gret));
735 ret = -E_MPI_PRINT;
736 goto out_mpi_release;
737 }
738 /*
739 * An oaep-encoded buffer always starts with at least one zero byte.
740 * However, leading zeroes in an mpi are omitted in the output of
741 * gcry_mpi_print() when using the GCRYMPI_FMT_USG format. The
742 * alternative, GCRYMPI_FMT_STD, does not work either because here the
743 * leading zero(es) might also be omitted, depending on the value of
744 * the second byte.
745 *
746 * To circumvent this, we shift the oaep buffer to the right. But first
747 * we check that the buffer actually started with a zero byte, i.e. that
748 * nbytes < key_size. Otherwise a decoding error occurred.
749 */
750 ret = -E_SEXP_DECRYPT;
751 if (*nbytes >= key_size)
752 goto out_mpi_release;
753 memmove(oaep_buf + key_size - *nbytes, oaep_buf, *nbytes);
754 memset(oaep_buf, 0, key_size - *nbytes);
755
756 PARA_DEBUG_LOG("decrypted buffer before unpad (%d bytes):\n",
757 key_size);
758 dump_buffer("non-unpadded decrypted buffer", oaep_buf, key_size);
759 ret = unpad_oaep(oaep_buf, key_size, outbuf, nbytes);
760 if (ret < 0)
761 goto out_mpi_release;
762 PARA_DEBUG_LOG("decrypted buffer after unpad (%zu bytes):\n",
763 *nbytes);
764 dump_buffer("unpadded decrypted buffer", outbuf, *nbytes);
765 ret = 1;
766 out_mpi_release:
767 gcry_mpi_release(out_mpi);
768 return ret;
769 }
770
771 int priv_decrypt(const char *key_file, unsigned char *outbuf,
772 unsigned char *inbuf, int inlen)
773 {
774 gcry_error_t gret;
775 int ret, key_size;
776 struct asymmetric_key *priv;
777 gcry_mpi_t in_mpi = NULL;
778 gcry_sexp_t in, out, priv_key;
779 size_t nbytes;
780
781 ret = check_key_file(key_file, true);
782 if (ret < 0)
783 return ret;
784 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
785 /* key_file -> asymmetric key priv */
786 ret = get_private_key(key_file, &priv);
787 if (ret < 0)
788 return ret;
789 key_size = ret / 8;
790
791 /* asymmetric key priv -> sexp priv_key */
792 ret = -E_SEXP_FIND;
793 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
794 if (!priv_key)
795 goto free_key;
796
797 /* inbuf -> in_mpi */
798 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
799 inlen, NULL);
800 if (gret) {
801 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
802 ret = -E_MPI_SCAN;
803 goto key_release;
804 }
805 /* in_mpi -> in sexp */
806 gret = gcry_sexp_build(&in, NULL, rsa_decrypt_sexp, in_mpi);
807 if (gret) {
808 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
809 ret = -E_SEXP_BUILD;
810 goto in_mpi_release;
811 }
812
813 /* rsa decryption: in sexp -> out sexp */
814 gret = gcry_pk_decrypt(&out, in, priv_key);
815 if (gret) {
816 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
817 ret = -E_SEXP_DECRYPT;
818 goto in_release;
819 }
820 ret = decode_rsa(out, key_size, outbuf, &nbytes);
821 if (ret < 0)
822 goto out_release;
823 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
824 ret = nbytes;
825 out_release:
826 gcry_sexp_release(out);
827 in_release:
828 gcry_sexp_release(in);
829 in_mpi_release:
830 gcry_mpi_release(in_mpi);
831 key_release:
832 gcry_sexp_release(priv_key);
833 free_key:
834 free_asymmetric_key(priv);
835 return ret;
836 }
837
838 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
839 unsigned len, unsigned char *outbuf)
840 {
841 gcry_error_t gret;
842 gcry_sexp_t pub_key, in, out, out_a;
843 gcry_mpi_t out_mpi = NULL;
844 size_t nbytes;
845 int ret;
846
847 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
848
849 /* get pub key */
850 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
851 if (!pub_key)
852 return -E_SEXP_FIND;
853 if (libgcrypt_has_oaep) {
854 gret = gcry_sexp_build(&in, NULL,
855 "(data(flags oaep)(value %b))", len, inbuf);
856 } else {
857 unsigned char padded_input[256];
858 const size_t pad_size = 256;
859 /* inbuf -> padded inbuf */
860 pad_oaep(inbuf, len, padded_input, pad_size);
861 /* padded inbuf -> in sexp */
862 gret = gcry_sexp_build(&in, NULL,
863 "(data(flags raw)(value %b))", pad_size, padded_input);
864 }
865 if (gret) {
866 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
867 ret = -E_SEXP_BUILD;
868 goto key_release;
869 }
870 /* rsa sexp encryption: in -> out */
871 gret = gcry_pk_encrypt(&out, in, pub_key);
872 if (gret) {
873 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
874 ret = -E_SEXP_ENCRYPT;
875 goto in_release;
876 }
877 /* extract a, an MPI with the result of the RSA operation */
878 ret = -E_SEXP_FIND;
879 out_a = gcry_sexp_find_token(out, "a", 0);
880 if (!out_a)
881 goto out_release;
882 /* convert sexp out_a -> out_mpi */
883 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
884 if (!out_mpi) {
885 ret = -E_SEXP_FIND;
886 goto out_a_release;
887 }
888 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
889 if (gret) {
890 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
891 ret = -E_SEXP_ENCRYPT;
892 goto out_mpi_release;
893 }
894 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
895 dump_buffer("enc buf", outbuf, nbytes);
896 ret = nbytes;
897
898 out_mpi_release:
899 gcry_mpi_release(out_mpi);
900 out_a_release:
901 gcry_sexp_release(out_a);
902 out_release:
903 gcry_sexp_release(out);
904 in_release:
905 gcry_sexp_release(in);
906 key_release:
907 gcry_sexp_release(pub_key);
908 return ret;
909 }
910
911 struct stream_cipher {
912 gcry_cipher_hd_t handle;
913 };
914
915 struct stream_cipher *sc_new(const unsigned char *data, int len,
916 bool use_aes)
917 {
918 gcry_error_t gret;
919 struct stream_cipher *sc = para_malloc(sizeof(*sc));
920
921 if (use_aes) {
922 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
923 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
924 GCRY_CIPHER_MODE_CTR, 0);
925 assert(gret == 0);
926 gret = gcry_cipher_setkey(sc->handle, data,
927 AES_CRT128_BLOCK_SIZE);
928 assert(gret == 0);
929 gret = gcry_cipher_setctr(sc->handle,
930 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
931 assert(gret == 0);
932 return sc;
933 }
934 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_ARCFOUR,
935 GCRY_CIPHER_MODE_STREAM, 0);
936 if (gret) {
937 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
938 free(sc);
939 return NULL;
940 }
941 gret = gcry_cipher_setkey(sc->handle, data, (size_t)len);
942 assert(gret == 0);
943 return sc;
944 }
945
946 void sc_free(struct stream_cipher *sc)
947 {
948 if (!sc)
949 return;
950 gcry_cipher_close(sc->handle);
951 free(sc);
952 }
953
954 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
955 {
956 gcry_cipher_hd_t handle = sc->handle;
957 gcry_error_t gret;
958
959 /* perform in-place encryption */
960 *dst = *src;
961 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,
962 NULL, 0);
963 assert(gret == 0);
964 }