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