crypt: Deduplicate get_public_key().
[paraslash.git] / gcrypt.c
1 /* Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file gcrypt.c Libgrcypt-based encryption/decryption routines. */
4
5 #include <regex.h>
6 #include <gcrypt.h>
7
8 #include "para.h"
9 #include "error.h"
10 #include "string.h"
11 #include "crypt.h"
12 #include "crypt_backend.h"
13 #include "fd.h"
14 #include "base64.h"
15
16 //#define GCRYPT_DEBUG 1
17
18 #ifdef GCRYPT_DEBUG
19 static void dump_buffer(const char *msg, unsigned char *buf, int len)
20 {
21 int i;
22
23 fprintf(stderr, "%s (%d bytes): ", msg, len);
24 for (i = 0; i < len; i++)
25 fprintf(stderr, "%02x ", buf[i]);
26 fprintf(stderr, "\n");
27 }
28 #else
29 /** Empty. Define GCRYPT_DEBUG to dump buffers. */
30 #define dump_buffer(a, b, c)
31 #endif
32
33 void hash_function(const char *data, unsigned long len, unsigned char *hash)
34 {
35 gcry_error_t gret;
36 gcry_md_hd_t handle;
37 unsigned char *md;
38
39 gret = gcry_md_open(&handle, GCRY_MD_SHA1, 0);
40 assert(gret == 0);
41 gcry_md_write(handle, data, (size_t)len);
42 gcry_md_final(handle);
43 md = gcry_md_read(handle, GCRY_MD_SHA1);
44 assert(md);
45 memcpy(hash, md, HASH_SIZE);
46 gcry_md_close(handle);
47 }
48
49 void get_random_bytes_or_die(unsigned char *buf, int num)
50 {
51 gcry_randomize(buf, (size_t)num, GCRY_STRONG_RANDOM);
52 }
53
54 /*
55 * This is called at the beginning of every program that uses libgcrypt. The
56 * call to gcry_check_version() initializes the gcrypt library and checks that
57 * we have at least the minimal required version.
58 */
59 void init_random_seed_or_die(void)
60 {
61 const char *req_ver = "1.5.0";
62 int seed;
63
64 if (!gcry_check_version(req_ver)) {
65 PARA_EMERG_LOG("fatal: need at least libgcrypt-%s, have: %s\n",
66 req_ver, gcry_check_version(NULL));
67 exit(EXIT_FAILURE);
68 }
69 get_random_bytes_or_die((unsigned char *)&seed, sizeof(seed));
70 srandom(seed);
71 }
72
73 /** S-expression for the public part of an RSA key. */
74 #define RSA_PUBKEY_SEXP "(public-key (rsa (n %m) (e %m)))"
75 /** S-expression for a private RSA key. */
76 #define RSA_PRIVKEY_SEXP "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))"
77 /** S-expression for decryption. */
78 #define RSA_DECRYPT_SEXP "(enc-val(flags oaep)(rsa(a %m)))"
79
80 struct asymmetric_key {
81 gcry_sexp_t sexp;
82 int num_bytes;
83 };
84
85 static const char *gcrypt_strerror(gcry_error_t gret)
86 {
87 return gcry_strerror(gcry_err_code(gret));
88 }
89
90 static int decode_key(const char *key_file, const char *header_str,
91 const char *footer_str, unsigned char **result)
92 {
93 int ret, ret2, i, j;
94 void *map;
95 size_t map_size, key_size, blob_size;
96 unsigned char *blob = NULL;
97 char *begin, *footer, *key;
98
99 ret = mmap_full_file(key_file, O_RDONLY, &map, &map_size, NULL);
100 if (ret < 0)
101 goto out;
102 ret = -E_KEY_MARKER;
103 if (strncmp(map, header_str, strlen(header_str)))
104 goto unmap;
105 footer = strstr(map, footer_str);
106 ret = -E_KEY_MARKER;
107 if (!footer)
108 goto unmap;
109 begin = map + strlen(header_str);
110 /* skip whitespace at the beginning */
111 for (; begin < footer; begin++) {
112 if (para_isspace(*begin))
113 continue;
114 break;
115 }
116 ret = -E_KEY_MARKER;
117 if (begin >= footer)
118 goto unmap;
119
120 key_size = footer - begin;
121 key = para_malloc(key_size + 1);
122 for (i = 0, j = 0; begin + i < footer; i++) {
123 if (para_isspace(begin[i]))
124 continue;
125 key[j++] = begin[i];
126 }
127 key[j] = '\0';
128 ret = base64_decode(key, j, (char **)&blob, &blob_size);
129 free(key);
130 if (ret < 0)
131 goto free_unmap;
132 ret = blob_size;
133 goto unmap;
134 free_unmap:
135 free(blob);
136 blob = NULL;
137 unmap:
138 ret2 = para_munmap(map, map_size);
139 if (ret >= 0 && ret2 < 0)
140 ret = ret2;
141 if (ret < 0) {
142 free(blob);
143 blob = NULL;
144 }
145 out:
146 *result = blob;
147 return ret;
148 }
149
150 /** ASN Types and their code. */
151 enum asn1_types {
152 /** The next object is an integer. */
153 ASN1_TYPE_INTEGER = 0x2,
154 /** Bit string object. */
155 ASN1_TYPE_BIT_STRING = 0x03,
156 /** Keys start with one big type sequence. */
157 ASN1_TYPE_SEQUENCE = 0x30,
158 };
159
160 /* bit 6 has value 0 */
161 static inline bool is_primitive(unsigned char c)
162 {
163 return (c & (1<<6)) == 0;
164 }
165
166 static inline bool is_primitive_integer(unsigned char c)
167 {
168 if (!is_primitive(c))
169 return false;
170 return (c & 0x1f) == ASN1_TYPE_INTEGER;
171 }
172
173 /* Bit 8 is zero (and bits 7-1 give the length) */
174 static inline bool is_short_form(unsigned char c)
175 {
176 return (c & 0x80) == 0;
177 }
178
179 static inline int get_short_form_length(unsigned char c)
180 {
181 return c & 0x7f;
182 }
183
184 static inline int get_long_form_num_length_bytes(unsigned char c)
185 {
186 return c & 0x7f;
187 }
188
189 /*
190 * Returns: Number of bytes scanned. This may differ from the value returned via
191 * bn_bytes because the latter does not include the ASN.1 prefix and a leading
192 * zero is not considered as an additional byte for bn_bytes.
193 */
194 static int read_bignum(unsigned char *start, unsigned char *end, gcry_mpi_t *bn,
195 int *bn_bytes)
196 {
197 int i, bn_size;
198 gcry_error_t gret;
199 unsigned char *cp = start;
200
201 if (!is_primitive_integer(*cp))
202 return -E_BAD_PRIVATE_KEY;
203 cp++;
204 if (is_short_form(*cp)) {
205 bn_size = get_short_form_length(*cp);
206 cp++;
207 } else {
208 int num_bytes = get_long_form_num_length_bytes(*cp);
209 if (cp + num_bytes > end)
210 return -E_BAD_PRIVATE_KEY;
211 if (num_bytes > 4) /* nobody has such a large modulus */
212 return -E_BAD_PRIVATE_KEY;
213 cp++;
214 bn_size = 0;
215 for (i = 0; i < num_bytes; i++, cp++)
216 bn_size = (bn_size << 8) + *cp;
217 }
218 PARA_DEBUG_LOG("bn_size %d (0x%x)\n", bn_size, (unsigned)bn_size);
219 gret = gcry_mpi_scan(bn, GCRYMPI_FMT_STD, cp, bn_size, NULL);
220 if (gret) {
221 PARA_ERROR_LOG("%s while scanning n\n",
222 gcry_strerror(gcry_err_code(gret)));
223 return-E_MPI_SCAN;
224 }
225 /*
226 * Don't take the first leading zero into account for the size of the
227 * bignum.
228 */
229 if (*cp == '\0') {
230 cp++;
231 bn_size--;
232 }
233 if (bn_bytes)
234 *bn_bytes = bn_size;
235 cp += bn_size;
236 // unsigned char *buf;
237 // gcry_mpi_aprint(GCRYMPI_FMT_HEX, &buf, NULL, *bn);
238 // PARA_CRIT_LOG("bn: %s\n", buf);
239 return cp - start;
240 }
241
242 static int find_privkey_bignum_offset(const unsigned char *data, int len)
243 {
244 const unsigned char *p = data, *end = data + len;
245
246 /* like the public key, the whole thing is contained in a sequence */
247 if (*p != ASN1_TYPE_SEQUENCE)
248 return -E_ASN1_PARSE;
249 p++;
250 if (p >= end)
251 return -E_ASN1_PARSE;
252 if (is_short_form(*p))
253 p++;
254 else
255 p += 1 + get_long_form_num_length_bytes(*p);
256 if (p >= end)
257 return -E_ASN1_PARSE;
258
259 /* skip next integer */
260 if (*p != ASN1_TYPE_INTEGER)
261 return -E_ASN1_PARSE;
262 p++;
263 if (p >= end)
264 return -E_ASN1_PARSE;
265 if (is_short_form(*p))
266 p += 1 + get_short_form_length(*p);
267 else
268 p += 1 + get_long_form_num_length_bytes(*p);
269 if (p >= end)
270 return -E_ASN1_PARSE;
271 return p - data;
272 }
273
274 /** Private keys start with this header. */
275 #define PRIVATE_KEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
276 /** Private keys end with this footer. */
277 #define PRIVATE_KEY_FOOTER "-----END RSA PRIVATE KEY-----"
278
279 static int get_private_key(const char *key_file, struct asymmetric_key **result)
280 {
281 gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL,
282 u = NULL;
283 unsigned char *blob, *cp, *end;
284 int blob_size, ret, n_size;
285 gcry_error_t gret;
286 size_t erroff;
287 gcry_sexp_t sexp;
288 struct asymmetric_key *key;
289
290 *result = NULL;
291 ret = decode_key(key_file, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER,
292 &blob);
293 if (ret < 0)
294 return ret;
295 blob_size = ret;
296 end = blob + blob_size;
297 ret = find_privkey_bignum_offset(blob, blob_size);
298 if (ret < 0)
299 goto free_blob;
300 PARA_INFO_LOG("reading RSA params at offset %d\n", ret);
301 cp = blob + ret;
302
303 ret = read_bignum(cp, end, &n, &n_size);
304 if (ret < 0)
305 goto free_blob;
306 cp += ret;
307
308 ret = read_bignum(cp, end, &e, NULL);
309 if (ret < 0)
310 goto release_n;
311 cp += ret;
312
313 ret = read_bignum(cp, end, &d, NULL);
314 if (ret < 0)
315 goto release_e;
316 cp += ret;
317
318 ret = read_bignum(cp, end, &p, NULL);
319 if (ret < 0)
320 goto release_d;
321 cp += ret;
322
323 ret = read_bignum(cp, end, &q, NULL);
324 if (ret < 0)
325 goto release_p;
326 cp += ret;
327 ret = read_bignum(cp, end, &u, NULL);
328 if (ret < 0)
329 goto release_q;
330 /*
331 * OpenSSL uses slightly different parameters than gcrypt. To use these
332 * parameters we need to swap the values of p and q and recompute u.
333 */
334 if (gcry_mpi_cmp(p, q) > 0) {
335 gcry_mpi_swap(p, q);
336 gcry_mpi_invm(u, p, q);
337 }
338 gret = gcry_sexp_build(&sexp, &erroff, RSA_PRIVKEY_SEXP,
339 n, e, d, p, q, u);
340
341 if (gret) {
342 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
343 gcry_strerror(gcry_err_code(gret)));
344 ret = -E_SEXP_BUILD;
345 goto release_u;
346 }
347 key = para_malloc(sizeof(*key));
348 key->sexp = sexp;
349 *result = key;
350 ret = n_size * 8;
351 PARA_INFO_LOG("succesfully read %d bit private key\n", ret);
352 release_u:
353 gcry_mpi_release(u);
354 release_q:
355 gcry_mpi_release(q);
356 release_p:
357 gcry_mpi_release(p);
358 release_d:
359 gcry_mpi_release(d);
360 release_e:
361 gcry_mpi_release(e);
362 release_n:
363 gcry_mpi_release(n);
364 free_blob:
365 free(blob);
366 return ret;
367 }
368
369 int get_public_key(const char *key_file, struct asymmetric_key **result)
370 {
371 unsigned char *blob, *p, *end;
372 int ret;
373 gcry_error_t gret;
374 size_t nr_scanned, erroff, decoded_size;
375 gcry_mpi_t e, n;
376 gcry_sexp_t sexp;
377 struct asymmetric_key *key;
378
379 ret = decode_ssh_key(key_file, &blob, &decoded_size);
380 if (ret < 0)
381 return ret;
382 p = blob + ret;
383 end = blob + decoded_size;
384 PARA_DEBUG_LOG("scanning modulus and public exponent\n");
385 gret = gcry_mpi_scan(&e, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
386 if (gret) {
387 ret = -E_MPI_SCAN;
388 PARA_CRIT_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
389 goto free_blob;
390 }
391 PARA_DEBUG_LOG("scanned e (%zu bytes)\n", nr_scanned);
392 p += nr_scanned;
393 if (p >= end)
394 goto release_e;
395 gret = gcry_mpi_scan(&n, GCRYMPI_FMT_SSH, p, end - p, &nr_scanned);
396 if (gret) {
397 ret = -E_MPI_SCAN;
398 PARA_ERROR_LOG("%s\n", gcry_strerror(gcry_err_code(gret)));
399 goto release_e;
400 }
401 PARA_DEBUG_LOG("scanned n (%zu bytes)\n", nr_scanned);
402 gret = gcry_sexp_build(&sexp, &erroff, RSA_PUBKEY_SEXP, n, e);
403 if (gret) {
404 PARA_ERROR_LOG("offset %zu: %s\n", erroff,
405 gcry_strerror(gcry_err_code(gret)));
406 ret = -E_SEXP_BUILD;
407 goto release_n;
408 }
409 ret = nr_scanned / 32 * 32;
410 PARA_INFO_LOG("successfully read %d bit ssh public key\n", ret * 8);
411 key = para_malloc(sizeof(*key));
412 key->num_bytes = ret;
413 key->sexp = sexp;
414 *result = key;
415 release_n:
416 gcry_mpi_release(n);
417 release_e:
418 gcry_mpi_release(e);
419 free_blob:
420 free(blob);
421 return ret;
422 }
423
424 void free_public_key(struct asymmetric_key *key)
425 {
426 if (!key)
427 return;
428 gcry_sexp_release(key->sexp);
429 free(key);
430 }
431
432 static int decode_rsa(gcry_sexp_t sexp, unsigned char *outbuf, size_t *nbytes)
433 {
434 const char *p = gcry_sexp_nth_data(sexp, 1, nbytes);
435
436 if (!p)
437 return -E_RSA_DECODE;
438 memcpy(outbuf, p, *nbytes);
439 return 1;
440 }
441
442 int priv_decrypt(const char *key_file, unsigned char *outbuf,
443 unsigned char *inbuf, int inlen)
444 {
445 gcry_error_t gret;
446 int ret;
447 struct asymmetric_key *priv;
448 gcry_mpi_t in_mpi = NULL;
449 gcry_sexp_t in, out, priv_key;
450 size_t nbytes;
451
452 ret = check_private_key_file(key_file);
453 if (ret < 0)
454 return ret;
455 PARA_INFO_LOG("decrypting %d byte input\n", inlen);
456 /* key_file -> asymmetric key priv */
457 ret = get_private_key(key_file, &priv);
458 if (ret < 0)
459 return ret;
460
461 /* asymmetric key priv -> sexp priv_key */
462 ret = -E_SEXP_FIND;
463 priv_key = gcry_sexp_find_token(priv->sexp, "private-key", 0);
464 if (!priv_key)
465 goto free_key;
466
467 /* inbuf -> in_mpi */
468 gret = gcry_mpi_scan(&in_mpi, GCRYMPI_FMT_USG, inbuf,
469 inlen, NULL);
470 if (gret) {
471 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
472 ret = -E_MPI_SCAN;
473 goto key_release;
474 }
475 /* in_mpi -> in sexp */
476 gret = gcry_sexp_build(&in, NULL, RSA_DECRYPT_SEXP, in_mpi);
477 if (gret) {
478 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
479 ret = -E_SEXP_BUILD;
480 goto in_mpi_release;
481 }
482
483 /* rsa decryption: in sexp -> out sexp */
484 gret = gcry_pk_decrypt(&out, in, priv_key);
485 if (gret) {
486 PARA_ERROR_LOG("decrypt: %s\n", gcrypt_strerror(gret));
487 ret = -E_SEXP_DECRYPT;
488 goto in_release;
489 }
490 ret = decode_rsa(out, outbuf, &nbytes);
491 if (ret < 0)
492 goto out_release;
493 PARA_INFO_LOG("successfully decrypted %zu byte message\n", nbytes);
494 ret = nbytes;
495 out_release:
496 gcry_sexp_release(out);
497 in_release:
498 gcry_sexp_release(in);
499 in_mpi_release:
500 gcry_mpi_release(in_mpi);
501 key_release:
502 gcry_sexp_release(priv_key);
503 free_key:
504 gcry_sexp_release(priv->sexp);
505 free(priv);
506 return ret;
507 }
508
509 int pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
510 unsigned len, unsigned char *outbuf)
511 {
512 gcry_error_t gret;
513 gcry_sexp_t pub_key, in, out, out_a;
514 gcry_mpi_t out_mpi = NULL;
515 size_t nbytes;
516 int ret;
517
518 PARA_INFO_LOG("encrypting %u byte input with %d-byte key\n", len, pub->num_bytes);
519
520 /* get pub key */
521 pub_key = gcry_sexp_find_token(pub->sexp, "public-key", 0);
522 if (!pub_key)
523 return -E_SEXP_FIND;
524 gret = gcry_sexp_build(&in, NULL, "(data(flags oaep)(value %b))", len, inbuf);
525 if (gret) {
526 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
527 ret = -E_SEXP_BUILD;
528 goto key_release;
529 }
530 /* rsa sexp encryption: in -> out */
531 gret = gcry_pk_encrypt(&out, in, pub_key);
532 if (gret) {
533 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
534 ret = -E_SEXP_ENCRYPT;
535 goto in_release;
536 }
537 /* extract a, an MPI with the result of the RSA operation */
538 ret = -E_SEXP_FIND;
539 out_a = gcry_sexp_find_token(out, "a", 0);
540 if (!out_a)
541 goto out_release;
542 /* convert sexp out_a -> out_mpi */
543 out_mpi = gcry_sexp_nth_mpi(out_a, 1, GCRYMPI_FMT_USG);
544 if (!out_mpi) {
545 ret = -E_SEXP_FIND;
546 goto out_a_release;
547 }
548 gret = gcry_mpi_print(GCRYMPI_FMT_USG, outbuf, 512 /* FIXME */, &nbytes, out_mpi);
549 if (gret) {
550 PARA_ERROR_LOG("%s\n", gcrypt_strerror(gret));
551 ret = -E_SEXP_ENCRYPT;
552 goto out_mpi_release;
553 }
554 PARA_INFO_LOG("encrypted buffer is %zu bytes\n", nbytes);
555 dump_buffer("enc buf", outbuf, nbytes);
556 ret = nbytes;
557
558 out_mpi_release:
559 gcry_mpi_release(out_mpi);
560 out_a_release:
561 gcry_sexp_release(out_a);
562 out_release:
563 gcry_sexp_release(out);
564 in_release:
565 gcry_sexp_release(in);
566 key_release:
567 gcry_sexp_release(pub_key);
568 return ret;
569 }
570
571 struct stream_cipher {
572 gcry_cipher_hd_t handle;
573 };
574
575 struct stream_cipher *sc_new(const unsigned char *data, int len)
576 {
577 gcry_error_t gret;
578 struct stream_cipher *sc = para_malloc(sizeof(*sc));
579
580 assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
581 gret = gcry_cipher_open(&sc->handle, GCRY_CIPHER_AES128,
582 GCRY_CIPHER_MODE_CTR, 0);
583 assert(gret == 0);
584 gret = gcry_cipher_setkey(sc->handle, data,
585 AES_CRT128_BLOCK_SIZE);
586 assert(gret == 0);
587 gret = gcry_cipher_setctr(sc->handle,
588 data + AES_CRT128_BLOCK_SIZE, AES_CRT128_BLOCK_SIZE);
589 assert(gret == 0);
590 return sc;
591 }
592
593 void sc_free(struct stream_cipher *sc)
594 {
595 if (!sc)
596 return;
597 gcry_cipher_close(sc->handle);
598 free(sc);
599 }
600
601 void sc_crypt(struct stream_cipher *sc, struct iovec *src, struct iovec *dst)
602 {
603 gcry_cipher_hd_t handle = sc->handle;
604 gcry_error_t gret;
605
606 /* perform in-place encryption */
607 *dst = *src;
608 gret = gcry_cipher_encrypt(handle, src->iov_base, src->iov_len,
609 NULL, 0);
610 assert(gret == 0);
611 }