Merge branch 't/sched_improvements'
[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 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 (%u 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 return ret;
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 //PARA_CRIT_LOG("key: %s\n", key);
244 blob_size = key_size * 2;
245 blob = para_malloc(blob_size);
246 ret = base64_decode(key, blob, blob_size);
247 free(key);
248 if (ret < 0)
249 goto free_unmap;
250 goto unmap;
251 free_unmap:
252 free(blob);
253 blob = NULL;
254 unmap:
255 ret2 = para_munmap(map, map_size);
256 if (ret >= 0 && ret2 < 0)
257 ret = ret2;
258 if (ret < 0) {
259 free(blob);
260 blob = NULL;
261 }
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 istarts 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, 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 cp += ret;
504 /*
505 * OpenSSL uses slightly different parameters than gcrypt. To use these
506 * parameters we need to swap the values of p and q and recompute u.
507 */
508 if (gcry_mpi_cmp(p, q) > 0) {
509 gcry_mpi_swap(p, q);
510 gcry_mpi_invm(u, p, q);
511 }
512 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
513 n, e, d, p, q, u);
514
515 if (gret) {
516 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
517 gcry_strerror(gcry_err_code(gret)));
518 ret = -E_SEXP_BUILD;
519 goto release_u;
520 }
521 key = para_malloc(sizeof(*key));
522 key->sexp = sexp;
523 *result = key;
524 ret = n_size * 8;
525 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
526 release_u:
527 gcry_mpi_release(u);
528 release_q:
529 gcry_mpi_release(q);
530 release_p:
531 gcry_mpi_release(p);
532 release_d:
533 gcry_mpi_release(d);
534 release_e:
535 gcry_mpi_release(e);
536 release_n:
537 gcry_mpi_release(n);
538 free_blob:
539 free(blob);
540 return ret;
541 }
542
543 /** Public keys start with this header. */
544 #define PUBLIC_KEY_HEADER "-----BEGIN PUBLIC KEY-----"
545 /** Public keys end with this footer. */
546 #define PUBLIC_KEY_FOOTER "-----END PUBLIC KEY-----"
547
548 static int get_asn_public_key(const char *key_file, struct asymmetric_key **result)
549 {
550 gcry_mpi_t n = NULL, e = NULL;
551 unsigned char *blob, *cp, *end;
552 int blob_size, ret, n_size;
553 gcry_error_t gret;
554 size_t erroff;
555 gcry_sexp_t sexp;
556 struct asymmetric_key *key;
557
558 ret = decode_key(key_file, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER,
559 &blob);
560 if (ret < 0)
561 return ret;
562 blob_size = ret;
563 end = blob + blob_size;
564 ret = find_pubkey_bignum_offset(blob, blob_size);
565 if (ret < 0)
566 goto free_blob;
567 PARA_DEBUG_LOG("decoding public RSA params at offset %d\n", ret);
568 cp = blob + ret;
569
570 ret = read_bignum(cp, end, &n, &n_size);
571 if (ret < 0)
572 goto free_blob;
573 cp += ret;
574
575 ret = read_bignum(cp, end, &e, NULL);
576 if (ret < 0)
577 goto release_n;
578 cp += ret;
579
580 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
581 if (gret) {
582 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
583 gcry_strerror(gcry_err_code(gret)));
584 ret = -E_SEXP_BUILD;
585 goto release_e;
586 }
587 key = para_malloc(sizeof(*key));
588 key->sexp = sexp;
589 *result = key;
590 ret = n_size;
591 PARA_INFO_LOG("successfully read %u bit asn public key\n", n_size * 8);
592
593 release_e:
594 gcry_mpi_release(e);
595 release_n:
596 gcry_mpi_release(n);
597 free_blob:
598 free(blob);
599 return ret;
600 }
601
602 static int get_ssh_public_key(unsigned char *data, int size, gcry_sexp_t *result)
603 {
604 int ret;
605 gcry_error_t gret;
606 unsigned char *blob = NULL, *p, *end;
607 size_t nr_scanned, erroff, decoded_size;
608 gcry_mpi_t e = NULL, n = NULL;
609
610 PARA_DEBUG_LOG("decoding %d byte public rsa-ssh key\n", size);
611 if (size > INT_MAX / 4)
612 return -ERRNO_TO_PARA_ERROR(EOVERFLOW);
613 blob = para_malloc(2 * size);
614 ret = uudecode((char *)data, blob, 2 * size);
615 if (ret < 0)
616 goto free_blob;
617 decoded_size = ret;
618 end = blob + decoded_size;
619 dump_buffer("decoded key", blob, decoded_size);
620 ret = check_ssh_key_header(blob, decoded_size);
621 if (ret < 0)
622 goto free_blob;
623 p = blob + ret;
624 ret = -E_SSH_PARSE;
625 if (p >= end)
626 goto free_blob;
627 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
628 gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
629 if (gret) {
630 ret = -E_MPI_SCAN;
631 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
632 goto free_blob;
633 }
634 PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
635 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_e);
636 // PARA_CRIT_LOG("e: %s\n", buf);
637 p += nr_scanned;
638 if (p >= end)
639 goto release_e;
640 gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
641 if (gret) {
642 ret = -E_MPI_SCAN;
643 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
644 goto release_e;
645 }
646 PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
647 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, rsa_n);
648 // PARA_CRIT_LOG("n: %s\n", buf);
649 gret = gcry_sexp_build(result, &erroff, RSA_PUBKEY_SEXP, n, e);
650 if (gret) {
651 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
652 gcry_strerror(gcry_err_code(gret)));
653 ret = -E_SEXP_BUILD;
654 goto release_n;
655 }
656 ret = nr_scanned / 32 * 32;
657 PARA_INFO_LOG("successfully read %u bit ssh public key\n", ret * 8);
658 release_n:
659 gcry_mpi_release(n);
660 release_e:
661 gcry_mpi_release(e);
662 free_blob:
663 free(blob);
664 return ret;
665 }
666
667 int get_asymmetric_key(const char *key_file, int private,
668 struct asymmetric_key **result)
669 {
670 int ret, ret2;
671 void *map;
672 size_t map_size;
673 unsigned char *start, *end;
674 gcry_sexp_t sexp;
675 struct asymmetric_key *key;
676
677 if (private)
678 return get_private_key(key_file, result);
679 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
680 if (ret < 0)
681 return ret;
682 ret = is_ssh_rsa_key(map, map_size);
683 if (!ret) {
684 ret = para_munmap(map, map_size);
685 if (ret < 0)
686 return ret;
687 return get_asn_public_key(key_file, result);
688 }
689 start = map + ret;
690 end = map + map_size;
691 ret = -E_SSH_PARSE;
692 if (start >= end)
693 goto unmap;
694 ret = get_ssh_public_key(start, end - start, &sexp);
695 if (ret < 0)
696 goto unmap;
697 key = para_malloc(sizeof(*key));
698 key->num_bytes = ret;
699 key->sexp = sexp;
700 *result = key;
701 ret = key->num_bytes;
702 unmap:
703 ret2 = para_munmap(map, map_size);
704 if (ret >= 0 && ret2 < 0)
705 ret = ret2;
706 return ret;
707 }
708
709 void free_asymmetric_key(struct asymmetric_key *key)
710 {
711 if (!key)
712 return;
713 gcry_sexp_release(key->sexp);
714 free(key);
715 }
716
717 static int decode_rsa(gcry_sexp_t sexp, int key_size, unsigned char *outbuf,
718 size_t *nbytes)
719 {
720 int ret;
721 gcry_error_t gret;
722 unsigned char oaep_buf[512];
723 gcry_mpi_t out_mpi;
724
725 if (libgcrypt_has_oaep) {
726 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
727
728 if (!p) {
729 PARA_ERROR_LOG("could not get data from list\n");
730 return -E_OEAP;
731 }
732 memcpy(outbuf, p, *nbytes);
733 return 1;
734 }
735 out_mpi = gcry_sexp_nth_mpi(sexp, 0, GCRYMPI_FMT_USG);
736 if (!out_mpi)
737 return -E_SEXP_FIND;
738 gret = gcry_mpi_print(GCRYMPI_FMT_USG, oaep_buf, sizeof(oaep_buf),
739 nbytes, out_mpi);
740 if (gret) {
741 PARA_ERROR_LOG("mpi_print: %s\n", gcrypt_strerror(gret));
742 ret = -E_MPI_PRINT;
743 goto out_mpi_release;
744 }
745 /*
746 * An oaep-encoded buffer always starts with at least one zero byte.
747 * However, leading zeroes in an mpi are omitted in the output of
748 * gcry_mpi_print() when using the GCRYMPI_FMT_USG format. The
749 * alternative, GCRYMPI_FMT_STD, does not work either because here the
750 * leading zero(es) might also be omitted, depending on the value of
751 * the second byte.
752 *
753 * To circumvent this, we shift the oaep buffer to the right. But first
754 * we check that the buffer actually started with a zero byte, i.e. that
755 * nbytes < key_size. Otherwise a decoding error occurred.
756 */
757 ret = -E_SEXP_DECRYPT;
758 if (*nbytes >= key_size)
759 goto out_mpi_release;
760 memmove(oaep_buf + key_size - *nbytes, oaep_buf, *nbytes);
761 memset(oaep_buf, 0, key_size - *nbytes);
762
763 PARA_DEBUG_LOG("decrypted buffer before unpad (%d bytes):\n",
764 key_size);
765 dump_buffer("non-unpadded decrypted buffer", oaep_buf, key_size);;
766 ret = unpad_oaep(oaep_buf, key_size, outbuf, nbytes);
767 if (ret < 0)
768 goto out_mpi_release;
769 PARA_DEBUG_LOG("decrypted buffer after unpad (%zu bytes):\n",
770 *nbytes);
771 dump_buffer("unpadded decrypted buffer", outbuf, *nbytes);;
772 ret = 1;
773 out_mpi_release:
774 gcry_mpi_release(out_mpi);
775 return ret;
776 }
777
778 int priv_decrypt(const char *key_file, unsigned char *outbuf,
779 unsigned char *inbuf, int inlen)
780 {
781 gcry_error_t gret;
782 int ret, key_size;
783 struct asymmetric_key *priv;
784 gcry_mpi_t in_mpi = NULL;
785 gcry_sexp_t in, out, priv_key;
786 size_t nbytes;
787
788 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
789 /* key_file -> asymmetric key priv */
790 ret = get_private_key(key_file, &priv);
791 if (ret < 0)
792 return ret;
793 key_size = ret / 8;
794
795 /* asymmetric key priv -> sexp priv_key */
796 ret = -E_SEXP_FIND;
797 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
798 if (!priv_key)
799 goto free_key;
800
801 /* inbuf -> in_mpi */
802 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
803 inlen, NULL);
804 if (gret) {
805 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
806 ret = -E_MPI_SCAN;
807 goto key_release;
808 }
809 /* in_mpi -> in sexp */
810 gret = gcry_sexp_build(&in, NULL, rsa_decrypt_sexp, in_mpi);
811 if (gret) {
812 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
813 ret = -E_SEXP_BUILD;
814 goto in_mpi_release;
815 }
816
817 /* rsa decryption: in sexp -> out sexp */
818 gret = gcry_pk_decrypt(&out, in, priv_key);
819 if (gret) {
820 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
821 ret = -E_SEXP_DECRYPT;
822 goto in_release;
823 }
824 ret = decode_rsa(out, key_size, outbuf, &nbytes);
825 if (ret < 0)
826 goto out_release;
827 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
828 ret = nbytes;
829 out_release:
830 gcry_sexp_release(out);
831 in_release:
832 gcry_sexp_release(in);
833 in_mpi_release:
834 gcry_mpi_release(in_mpi);
835 key_release:
836 gcry_sexp_release(priv_key);
837 free_key:
838 free_asymmetric_key(priv);
839 return ret;
840 }
841
842 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
843 unsigned len, unsigned char *outbuf)
844 {
845 gcry_error_t gret;
846 gcry_sexp_t pub_key, in, out, out_a;
847 gcry_mpi_t out_mpi = NULL;
848 size_t nbytes;
849 int ret;
850
851 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
852
853 /* get pub key */
854 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
855 if (!pub_key)
856 return -E_SEXP_FIND;
857 if (libgcrypt_has_oaep) {
858 gret = gcry_sexp_build(&in, NULL,
859 "(data(flags oaep)(value %b))", len, inbuf);
860 } else {
861 unsigned char padded_input[256];
862 const size_t pad_size = 256;
863 /* inbuf -> padded inbuf */
864 pad_oaep(inbuf, len, padded_input, pad_size);
865 /* padded inbuf -> in sexp */
866 gret = gcry_sexp_build(&in, NULL,
867 "(data(flags raw)(value %b))", pad_size, padded_input);
868 }
869 if (gret) {
870 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
871 ret = -E_SEXP_BUILD;
872 goto key_release;
873 }
874 /* rsa sexp encryption: in -> out */
875 gret = gcry_pk_encrypt(&out, in, pub_key);
876 if (gret) {
877 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
878 ret = -E_SEXP_ENCRYPT;
879 goto in_release;
880 }
881 /* extract a, an MPI with the result of the RSA operation */
882 ret = -E_SEXP_FIND;
883 out_a = gcry_sexp_find_token(out, "a", 0);
884 if (!out_a)
885 goto out_release;
886 /* convert sexp out_a -> out_mpi */
887 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
888 if (!out_mpi) {
889 ret = -E_SEXP_FIND;
890 goto out_a_release;
891 }
892 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
893 if (gret) {
894 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
895 ret = -E_SEXP_ENCRYPT;
896 goto out_mpi_release;
897 }
898 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
899 dump_buffer("enc buf", outbuf, nbytes);
900 ret = nbytes;
901
902 out_mpi_release:
903 gcry_mpi_release(out_mpi);
904 out_a_release:
905 gcry_sexp_release(out_a);
906 out_release:
907 gcry_sexp_release(out);
908 in_release:
909 gcry_sexp_release(in);
910 key_release:
911 gcry_sexp_release(pub_key);
912 return ret;
913 }
914
915 struct stream_cipher {
916 gcry_cipher_hd_t handle;
917 };
918
919 struct stream_cipher *sc_new(const unsigned char *data, int len)
920 {
921 gcry_error_t gret;
922
923 struct stream_cipher *sc = para_malloc(sizeof(*sc));
924 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_ARCFOUR,
925 GCRY_CIPHER_MODE_STREAM, 0);
926 if (gret) {
927 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
928 free(sc);
929 return NULL;
930 }
931 gret = gcry_cipher_setkey(sc->handle, data, (size_t)len);
932 assert(gret == 0);
933 return sc;
934 }
935
936 void sc_free(struct stream_cipher *sc)
937 {
938 if (!sc)
939 return;
940 gcry_cipher_close(sc->handle);
941 free(sc);
942 }
943
944 int sc_send_bin_buffer(struct stream_cipher_context *scc, char *buf,
945 size_t size)
946 {
947 gcry_error_t gret;
948 int ret;
949 unsigned char *tmp = para_malloc(size);
950
951 assert(size);
952 gret = gcry_cipher_encrypt(scc->send->handle, tmp, size,
953 (unsigned char *)buf, size);
954 assert(gret == 0);
955 ret = write_all(scc->fd, (char *)tmp, &size);
956 free(tmp);
957 return ret;
958 }
959
960 int sc_recv_bin_buffer(struct stream_cipher_context *scc, char *buf,
961 size_t size)
962 {
963 gcry_error_t gret;
964 ssize_t ret = recv(scc->fd, buf, size, 0);
965
966 if (ret < 0)
967 ret = -ERRNO_TO_PARA_ERROR(errno);
968 if (ret <= 0)
969 return ret;
970 /* perform in-place encryption */
971 gret = gcry_cipher_encrypt(scc->recv->handle, (unsigned char *)buf, ret,
972 NULL, 0);
973 assert(gret == 0);
974 return ret;
975 }