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