keyexch: Simplify key-exchange protocol.
[tripe] / keymgmt.c
1 /* -*-c-*-
2 *
3 * $Id$
4 *
5 * Key loading and storing
6 *
7 * (c) 2001 Straylight/Edgeware
8 */
9
10 /*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of Trivial IP Encryption (TrIPE).
13 *
14 * TrIPE is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
18 *
19 * TrIPE is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with TrIPE; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 */
28
29 /*----- Header files ------------------------------------------------------*/
30
31 #include "tripe.h"
32
33 /*----- Global variables --------------------------------------------------*/
34
35 group *gg;
36 mp *kpriv;
37 ge *kpub;
38 algswitch algs;
39 size_t indexsz;
40
41 /*----- Static variables --------------------------------------------------*/
42
43 static key_file *kf_pub;
44 static const char *kr_priv, *kr_pub, *tag_priv;
45 static fwatch w_priv, w_pub;
46
47 /*----- Key groups --------------------------------------------------------*/
48
49 typedef struct kgops {
50 const char *ty;
51 const char *(*loadpriv)(key_data *, group **, mp **, dstr *);
52 const char *(*loadpub)(key_data *, group **, ge **, dstr *);
53 } kgops;
54
55 /* --- Diffie-Hellman --- */
56
57 static const char *kgdh_priv(key_data *kd, group **g, mp **x, dstr *t)
58 {
59 key_packstruct kps[DH_PRIVFETCHSZ];
60 key_packdef *kp;
61 dh_priv dp;
62 const char *e;
63 int rc;
64
65 kp = key_fetchinit(dh_privfetch, kps, &dp);
66 if ((rc = key_unpack(kp, kd, t)) != 0) {
67 e = key_strerror(rc);
68 goto done;
69 }
70 *g = group_prime(&dp.dp);
71 *x = MP_COPY(dp.x);
72 e = 0;
73 done:
74 key_fetchdone(kp);
75 return (e);
76 }
77
78 static const char *kgdh_pub(key_data *kd, group **g, ge **p, dstr *t)
79 {
80 key_packstruct kps[DH_PUBFETCHSZ];
81 key_packdef *kp;
82 dh_pub dp;
83 const char *e;
84 int rc;
85
86 kp = key_fetchinit(dh_pubfetch, kps, &dp);
87 if ((rc = key_unpack(kp, kd, t)) != 0) {
88 e = key_strerror(rc);
89 goto done;
90 }
91 *g = group_prime(&dp.dp);
92 *p = G_CREATE(*g);
93 if (G_FROMINT(*g, *p, dp.y)) {
94 e = "bad public value";
95 goto done;
96 }
97 e = 0;
98 done:
99 key_fetchdone(kp);
100 return (e);
101 }
102
103 static const kgops kgdh_ops = { "tripe-dh", kgdh_priv, kgdh_pub };
104
105 /* --- Elliptic curve --- */
106
107 static const char *kgec_priv(key_data *kd, group **g, mp **x, dstr *t)
108 {
109 key_packstruct kps[EC_PRIVFETCHSZ];
110 key_packdef *kp;
111 ec_priv ep;
112 ec_info ei;
113 const char *e;
114 int rc;
115
116 kp = key_fetchinit(ec_privfetch, kps, &ep);
117 if ((rc = key_unpack(kp, kd, t)) != 0) {
118 e = key_strerror(rc);
119 goto done;
120 }
121 if ((e = ec_getinfo(&ei, ep.cstr)) != 0)
122 goto done;
123 *g = group_ec(&ei);
124 *x = MP_COPY(ep.x);
125 e = 0;
126 done:
127 key_fetchdone(kp);
128 return (e);
129 }
130
131 static const char *kgec_pub(key_data *kd, group **g, ge **p, dstr *t)
132 {
133 key_packstruct kps[EC_PUBFETCHSZ];
134 key_packdef *kp;
135 ec_pub ep;
136 ec_info ei;
137 const char *e;
138 int rc;
139
140 kp = key_fetchinit(ec_pubfetch, kps, &ep);
141 if ((rc = key_unpack(kp, kd, t)) != 0) {
142 e = key_strerror(rc);
143 goto done;
144 }
145 if ((e = ec_getinfo(&ei, ep.cstr)) != 0)
146 goto done;
147 *g = group_ec(&ei);
148 *p = G_CREATE(*g);
149 if (G_FROMEC(*g, *p, &ep.p)) {
150 e = "bad public point";
151 goto done;
152 }
153 e = 0;
154 done:
155 key_fetchdone(kp);
156 return (e);
157 }
158
159 static const kgops kgec_ops = { "tripe-ec", kgec_priv, kgec_pub };
160
161 /* --- Table of supported key types --- */
162
163 static const kgops *kgtab[] = { &kgdh_ops, &kgec_ops, 0 };
164
165 /*----- Algswitch stuff ---------------------------------------------------*/
166
167 /* --- @algs_get@ --- *
168 *
169 * Arguments: @algswitch *a@ = where to put the algorithms
170 * @key_file *kf@ = key file (for some stupid reason)
171 * @key *k@ = key to inspect
172 *
173 * Returns: Null if OK, or an error message.
174 *
175 * Use: Extracts an algorithm choice from a key.
176 */
177
178 static const char *algs_get(algswitch *a, key_file *kf, key *k)
179 {
180 const char *p;
181 char *q;
182 dstr d = DSTR_INIT;
183 const char *e;
184
185 #define FAIL(msg) do { e = msg; goto done; } while (0)
186
187 if ((p = key_getattr(kf, k, "cipher")) == 0)
188 p = "blowfish-cbc";
189 if ((a->c = gcipher_byname(p)) == 0)
190 FAIL("unknown-cipher");
191
192 if ((p = key_getattr(kf, k, "hash")) == 0)
193 p = "rmd160";
194 if ((a->h = ghash_byname(p)) == 0)
195 FAIL("unknown-hash");
196
197 if ((p = key_getattr(kf, k, "mgf")) == 0) {
198 dstr_reset(&d);
199 dstr_putf(&d, "%s-mgf", a->h->name);
200 p = d.buf;
201 }
202 if ((a->mgf = gcipher_byname(p)) == 0)
203 FAIL("unknown-mgf-cipher");
204
205 if ((p = key_getattr(kf, k, "mac")) != 0) {
206 dstr_reset(&d);
207 dstr_puts(&d, p);
208 if ((q = strchr(d.buf, '/')) != 0)
209 *q++ = 0;
210 if ((a->m = gmac_byname(d.buf)) == 0)
211 FAIL("unknown-mac");
212 if (!q)
213 a->tagsz = a->m->hashsz;
214 else {
215 unsigned long n = strtoul(q, &q, 0);
216 if (*q) FAIL("bad-tag-length-string");
217 if (n%8 || n > ~(size_t)0) FAIL("bad-tag-length");
218 a->tagsz = n/8;
219 }
220 } else {
221 dstr_reset(&d);
222 dstr_putf(&d, "%s-hmac", a->h->name);
223 if ((a->m = gmac_byname(d.buf)) == 0)
224 FAIL("no-hmac-for-hash");
225 a->tagsz = a->h->hashsz/2;
226 }
227
228 e = 0;
229 done:
230 dstr_destroy(&d);
231 return (e);
232 }
233
234 /* --- @algs_check@ --- *
235 *
236 * Arguments: @algswitch *a@ = a choice of algorithms
237 * @const group *g@ = the group we're working in
238 *
239 * Returns: Null if OK, or an error message.
240 *
241 * Use: Checks an algorithm choice for sensibleness. This also
242 * derives some useful information from the choices, and you
243 * must call this before committing the algorithm selection
244 * for use by @keyset@ functions.
245 */
246
247 static const char *algs_check(algswitch *a, const group *g)
248 {
249 /* --- Derive the key sizes --- *
250 *
251 * Must ensure that we have non-empty keys. This isn't ideal, but it
252 * provides a handy sanity check.
253 */
254
255 a->hashsz = a->h->hashsz;
256 if ((a->cksz = keysz(a->hashsz, a->c->keysz)) == 0)
257 return ("no key size found for cipher");
258 if ((a->mksz = keysz(a->hashsz, a->m->keysz)) == 0)
259 return ("no key size found for MAC");
260
261 /* --- Ensure that the tag size is sane --- */
262
263 if (a->tagsz > a->m->hashsz) return ("tag length too large");
264
265 /* --- Ensure the MGF accepts hashes as keys --- */
266
267 if (keysz(a->hashsz, a->mgf->keysz) != a->hashsz)
268 return ("MGF not suitable -- restrictive key schedule");
269
270 /* --- All ship-shape and Bristol-fashion --- */
271
272 return (0);
273 }
274
275 /* --- @algs_samep@ --- *
276 *
277 * Arguments: @const algswitch *a, *aa@ = two algorithm selections
278 *
279 * Returns: Nonzero if the two selections are the same.
280 *
281 * Use: Checks sameness of algorithm selections: used to ensure that
282 * peers are using sensible algorithms.
283 */
284
285 static int algs_samep(const algswitch *a, const algswitch *aa)
286 {
287 return (a->c == aa->c && a->mgf == aa->mgf && a->h == aa->h &&
288 a->m == aa->m && a->tagsz == aa->tagsz);
289 }
290
291 /*----- Main code ---------------------------------------------------------*/
292
293 /* --- @keymoan@ --- *
294 *
295 * Arguments: @const char *file@ = name of the file
296 * @int line@ = line number in file
297 * @const char *msg@ = error message
298 * @void *p@ = argument pointer
299 *
300 * Returns: ---
301 *
302 * Use: Reports an error message about loading a key file.
303 */
304
305 static void keymoan(const char *file, int line, const char *msg, void *p)
306 {
307 a_warn("KEYMGMT",
308 "key-file-error",
309 "%s:%i", file, line,
310 "%s", msg,
311 A_END);
312 }
313
314 /* --- @loadpriv@ --- *
315 *
316 * Arguments: @dstr *d@ = string to write errors in
317 *
318 * Returns: Zero if OK, nonzero on error.
319 *
320 * Use: Loads the private key from its keyfile.
321 */
322
323 static int loadpriv(dstr *d)
324 {
325 key_file kf;
326 key *k;
327 key_data **kd;
328 dstr t = DSTR_INIT;
329 group *g = 0;
330 mp *x = 0;
331 int rc = -1;
332 const kgops **ko;
333 const char *e;
334 algswitch a;
335
336 /* --- Open the private key file --- */
337
338 if (key_open(&kf, kr_priv, KOPEN_READ, keymoan, 0)) {
339 dstr_putf(d, "error reading private keyring `%s': %s",
340 kr_priv, strerror(errno));
341 goto done_0;
342 }
343
344 /* --- Find the private key --- */
345
346 if (key_qtag(&kf, tag_priv, &t, &k, &kd)) {
347 dstr_putf(d, "private key `%s' not found in keyring `%s'",
348 tag_priv, kr_priv);
349 goto done_1;
350 }
351
352 /* --- Look up the key type in the table --- */
353
354 for (ko = kgtab; *ko; ko++) {
355 if (strcmp((*ko)->ty, k->type) == 0)
356 goto tymatch;
357 }
358 dstr_putf(d, "private key `%s' has unknown type `%s'", t.buf, k->type);
359 goto done_1;
360 tymatch:;
361
362 /* --- Load the key --- */
363
364 if ((e = (*ko)->loadpriv(*kd, &g, &x, &t)) != 0) {
365 dstr_putf(d, "error reading private key `%s': %s", t.buf, e);
366 goto done_1;
367 }
368
369 /* --- Check that the key is sensible --- */
370
371 if ((e = G_CHECK(g, &rand_global)) != 0) {
372 dstr_putf(d, "bad group in private key `%s': %s", t.buf, e);
373 goto done_1;
374 }
375
376 /* --- Collect the algorithms --- */
377
378 if ((e = algs_get(&a, &kf, k)) != 0 ||
379 (e = algs_check(&a, g)) != 0) {
380 dstr_putf(d, "bad symmetric algorithm selection in private key `%s': %s",
381 t.buf, e);
382 goto done_1;
383 }
384
385 /* --- Good, we're happy --- *
386 *
387 * Dodginess! We change the group over here, but don't free any old group
388 * elements. This assumes that the new group is basically the same as the
389 * old one, and will happily adopt the existing elements. If it isn't,
390 * then we lose badly. Check this, then.
391 */
392
393 if (gg) {
394 if (!group_samep(g, gg)) {
395 dstr_putf(d, "private key `%s' has different group", t.buf);
396 goto done_1;
397 }
398 G_DESTROYGROUP(gg);
399 }
400 if (kpriv)
401 mp_drop(kpriv);
402
403 if (kpub)
404 G_DESTROY(g, kpub);
405 kpub = G_CREATE(g);
406 G_EXP(g, kpub, g->g, x);
407 indexsz = mp_octets(g->r);
408
409 /* --- Dump out the group --- */
410
411 IF_TRACING(T_KEYMGMT, {
412 trace(T_KEYMGMT, "keymgmt: extracted private key `%s'", t.buf);
413 IF_TRACING(T_CRYPTO, {
414 trace(T_CRYPTO, "crypto: r = %s", mpstr(g->r));
415 trace(T_CRYPTO, "crypto: h = %s", mpstr(g->h));
416 trace(T_CRYPTO, "crypto: x = %s", mpstr(x));
417 trace(T_CRYPTO, "crypto: cipher = %s", a.c->name);
418 trace(T_CRYPTO, "crypto: mgf = %s", a.mgf->name);
419 trace(T_CRYPTO, "crypto: hash = %s", a.h->name);
420 trace(T_CRYPTO, "crypto: mac = %s/%lu",
421 a.m->name, (unsigned long)a.tagsz * 8);
422 })
423 })
424
425 /* --- Success! --- */
426
427 gg = g; g = 0;
428 algs = a;
429 kpriv = x; x = 0;
430 rc = 0;
431
432 /* --- Tidy up --- */
433
434 done_1:
435 key_close(&kf);
436 done_0:
437 dstr_destroy(&t);
438 if (x) mp_drop(x);
439 if (g) G_DESTROYGROUP(g);
440 return (rc);
441 }
442
443 /* --- @loadpub@ --- *
444 *
445 * Arguments: @dstr *d@ = string to write errors to
446 *
447 * Returns: Zero if OK, nonzero on error.
448 *
449 * Use: Reloads the public keyring.
450 */
451
452 static int loadpub(dstr *d)
453 {
454 key_file *kf = CREATE(key_file);
455
456 if (key_open(kf, kr_pub, KOPEN_READ, keymoan, 0)) {
457 dstr_putf(d, "error reading public keyring `%s': %s",
458 kr_pub, strerror(errno));
459 DESTROY(kf);
460 return (-1);
461 }
462 kf_pub = kf;
463 T( trace(T_KEYMGMT, "keymgmt: loaded public keyring `%s'", kr_pub); )
464 return (0);
465 }
466
467 /* --- @km_reload@ --- *
468 *
469 * Arguments: ---
470 *
471 * Returns: Zero if OK, nonzero to force reloading of keys.
472 *
473 * Use: Checks the keyrings to see if they need reloading.
474 */
475
476 int km_reload(void)
477 {
478 dstr d = DSTR_INIT;
479 key_file *kf;
480 int reload = 0;
481
482 /* --- Check the private key first --- */
483
484 if (fwatch_update(&w_priv, kr_priv)) {
485 T( trace(T_KEYMGMT, "keymgmt: private keyring updated: reloading..."); )
486 DRESET(&d);
487 if (loadpriv(&d))
488 a_warn("KEYMGMT", "bad-private-key", "%s", d.buf, A_END);
489 else
490 reload = 1;
491 }
492
493 /* --- Now check the public keys --- */
494
495 if (fwatch_update(&w_pub, kr_pub)) {
496 T( trace(T_KEYMGMT, "keymgmt: public keyring updated: reloading..."); )
497 kf = kf_pub;
498 DRESET(&d);
499 if (loadpub(&d))
500 a_warn("KEYMGMT", "bad-public-keyring", "%s", d.buf, A_END);
501 else {
502 reload = 1;
503 key_close(kf);
504 DESTROY(kf);
505 }
506 }
507
508 /* --- Done --- */
509
510 return (reload);
511 }
512
513 /* --- @km_init@ --- *
514 *
515 * Arguments: @const char *priv@ = private keyring file
516 * @const char *pub@ = public keyring file
517 * @const char *tag@ = tag to load
518 *
519 * Returns: ---
520 *
521 * Use: Initializes, and loads the private key.
522 */
523
524 void km_init(const char *priv, const char *pub, const char *tag)
525 {
526 dstr d = DSTR_INIT;
527 const gchash *const *hh;
528
529 kr_priv = priv;
530 kr_pub = pub;
531 tag_priv = tag;
532 fwatch_init(&w_priv, kr_priv);
533 fwatch_init(&w_pub, kr_pub);
534
535 for (hh = ghashtab; *hh; hh++) {
536 if ((*hh)->hashsz > MAXHASHSZ) {
537 die(EXIT_FAILURE, "INTERNAL ERROR: %s hash length %lu > MAXHASHSZ %d",
538 (*hh)->name, (unsigned long)(*hh)->hashsz, MAXHASHSZ);
539 }
540 }
541
542 DRESET(&d);
543 if (loadpriv(&d))
544 die(EXIT_FAILURE, "%s", d.buf);
545 if (loadpub(&d))
546 die(EXIT_FAILURE, "%s", d.buf);
547 }
548
549 /* --- @km_getpubkey@ --- *
550 *
551 * Arguments: @const char *tag@ = public key tag to load
552 * @ge *kpub@ = where to put the public key
553 * @time_t *t_exp@ = where to put the expiry time
554 *
555 * Returns: Zero if OK, nonzero if it failed.
556 *
557 * Use: Fetches a public key from the keyring.
558 */
559
560 int km_getpubkey(const char *tag, ge *kpub, time_t *t_exp)
561 {
562 key *k;
563 key_data **kd;
564 dstr t = DSTR_INIT;
565 const kgops **ko;
566 const char *e;
567 group *g = 0;
568 ge *p = 0;
569 algswitch a;
570 int rc = -1;
571
572 /* --- Find the key --- */
573
574 if (key_qtag(kf_pub, tag, &t, &k, &kd)) {
575 a_warn("KEYMGMT", "public-key", "%s", tag, "not-found", A_END);
576 goto done;
577 }
578
579 /* --- Look up the key type in the table --- */
580
581 for (ko = kgtab; *ko; ko++) {
582 if (strcmp((*ko)->ty, k->type) == 0)
583 goto tymatch;
584 }
585 a_warn("KEYMGMT",
586 "public-key", "%s", t.buf,
587 "unknown-type", "%s", k->type,
588 A_END);
589 goto done;
590 tymatch:;
591
592 /* --- Load the key --- */
593
594 if ((e = (*ko)->loadpub(*kd, &g, &p, &t)) != 0) {
595 a_warn("KEYMGMT", "public-key", "%s", t.buf, "bad", "%s", e, A_END);
596 goto done;
597 }
598
599 /* --- Ensure that the group is correct --- *
600 *
601 * Dodginess! We assume that if this works, our global group is willing to
602 * adopt this public element. Probably reasonable.
603 */
604
605 if (!group_samep(gg, g)) {
606 a_warn("KEYMGMT", "public-key", "%s", t.buf, "incorrect-group", A_END);
607 goto done;
608 }
609
610 /* --- Check the public group element --- */
611
612 if (group_check(gg, p)) {
613 a_warn("KEYMGMT",
614 "public-key", "%s", t.buf,
615 "bad-public-group-element",
616 A_END);
617 goto done;
618 }
619
620 /* --- Check the algorithms --- */
621
622 if ((e = algs_get(&a, kf_pub, k)) != 0) {
623 a_warn("KEYMGMT",
624 "public-key", "%s", t.buf,
625 "bad-algorithm-selection", e,
626 A_END);
627 goto done;
628 }
629 if (!algs_samep(&a, &algs)) {
630 a_warn("KEYMGMT",
631 "public-key", "%s", t.buf,
632 "algorithm-mismatch",
633 A_END);
634 goto done;
635 }
636
637 /* --- Dump the public key --- */
638
639 IF_TRACING(T_KEYMGMT, {
640 trace(T_KEYMGMT, "keymgmt: extracted public key `%s'", t.buf);
641 trace(T_CRYPTO, "crypto: p = %s", gestr(gg, p));
642 })
643
644 /* --- OK, accept the public key --- */
645
646 *t_exp = k->exp;
647 G_COPY(gg, kpub, p);
648 rc = 0;
649
650 /* --- Tidy up --- */
651
652 done:
653 if (p) G_DESTROY(g, p);
654 if (g) G_DESTROYGROUP(g);
655 dstr_destroy(&t);
656 return (rc);
657 }
658
659 /*----- That's all, folks -------------------------------------------------*/