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