chiark / gitweb /
server/: Prepare an interface for multiple bulk-crypto transforms.
[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 /*----- Key groups --------------------------------------------------------*/
32
33 /* The key-loading functions here must fill in the kdata slot @g@ and
34  * either @kpriv@ or @kpub@ as appropriate.  The caller will take care of
35  * determining @kpub@ given a private key, and of ensuring that @kpriv@ is
36  * null for a public key.
37  */
38
39 typedef struct kgops {
40   const char *ty;
41   int (*loadpriv)(key_data *, kdata *, dstr *, dstr *);
42   int (*loadpub)(key_data *, kdata *, dstr *, dstr *);
43 } kgops;
44
45 /* --- @KLOAD@ --- *
46  *
47  * Arguments:   @ty@, @TY@ = key type name (lower- and upper-case)
48  *              @which@, @WHICH@ = `pub' or `priv' (and upper-case)
49  *              @setgroup@ = code to initialize @kd->g@
50  *              @setpriv@ = code to initialize @kd->kpriv@
51  *              @setpub@ = code to initialize @kd->kpub@
52  *
53  * Use:         Generates the body of one of the (rather tedious) key loading
54  *              functions.  See the description of @KEYTYPES@ below for the
55  *              details.
56  */
57
58 #define KLOAD(ty, TY, which, WHICH, setgroup, setpriv, setpub)          \
59 static int kg##ty##_##which(key_data *d, kdata *kd, dstr *t, dstr *e)   \
60 {                                                                       \
61   key_packstruct kps[TY##_##WHICH##FETCHSZ];                            \
62   key_packdef *kp;                                                      \
63   ty##_##which p;                                                       \
64   int rc;                                                               \
65                                                                         \
66   /* --- Initialize things we've not set up yet --- */                  \
67                                                                         \
68   kd->g = 0; kd->kpub = 0;                                              \
69                                                                         \
70   /* --- Unpack the key --- */                                          \
71                                                                         \
72   kp = key_fetchinit(ty##_##which##fetch, kps, &p);                     \
73   if ((rc = key_unpack(kp, d, t)) != 0) {                               \
74     a_format(e, "unpack-failed", "%s", key_strerror(rc), A_END);        \
75     goto fail;                                                          \
76   }                                                                     \
77                                                                         \
78   /* --- Extract the pieces of the key --- */                           \
79                                                                         \
80   setgroup;                                                             \
81   setpriv;                                                              \
82   kd->kpub = G_CREATE(kd->g);                                           \
83   setpub;                                                               \
84                                                                         \
85   /* --- We win --- */                                                  \
86                                                                         \
87   rc = 0;                                                               \
88   goto done;                                                            \
89                                                                         \
90 fail:                                                                   \
91   if (kd->kpub) G_DESTROY(kd->g, kd->kpub);                             \
92   if (kd->g) G_DESTROYGROUP(kd->g);                                     \
93   rc = -1;                                                              \
94                                                                         \
95 done:                                                                   \
96   key_fetchdone(kp);                                                    \
97   return (rc);                                                          \
98 }
99
100 /* --- @KEYTYPES@ --- *
101  *
102  * A list of the various key types, and how to unpack them.  Each entry in
103  * the list has the form
104  *
105  *      _(ty, TY, setgroup, setpriv, setpub)
106  *
107  * The @ty@ and @TY@ are lower- and upper-case versions of the key type name,
108  * and there should be @key_fetchdef@s called @ty_{priv,pub}fetch@.
109  *
110  * The @setgroup@, @setpriv@ and @setpub@ items are code fragments which are
111  * passed to @KLOAD@ to build appropriate key-loading methods.  By the time
112  * these code fragments are run, the key has been unpacked from the incoming
113  * key data using @ty_whichfetch@ into a @ty_which@ structure named @p@.
114  * They can report errors by writing an appropriate token sequence to @e@ and
115  * jumping to @fail@.
116  */
117
118 #define KEYTYPES(_)                                                     \
119                                                                         \
120   /* --- Diffie-Hellman --- */                                          \
121                                                                         \
122   _(dh, DH,                                                             \
123     { kd->g = group_prime(&p.dp); },                                    \
124     { kd->kpriv = MP_COPY(p.x); },                                      \
125     { if (G_FROMINT(kd->g, kd->kpub, p.y)) {                            \
126         a_format(e, "bad-public-vector", A_END);                        \
127         goto fail;                                                      \
128       }                                                                 \
129     })                                                                  \
130                                                                         \
131   /* --- Elliptic curves --- */                                         \
132                                                                         \
133   _(ec, EC,                                                             \
134     { ec_info ei; const char *err;                                      \
135       if ((err = ec_getinfo(&ei, p.cstr)) != 0) {                       \
136         a_format(e, "decode-failed", "%s", err, A_END);                 \
137         goto fail;                                                      \
138       }                                                                 \
139       kd->g = group_ec(&ei);                                            \
140     },                                                                  \
141     { kd->kpriv = MP_COPY(p.x); },                                      \
142     { if (G_FROMEC(kd->g, kd->kpub, &p.p)) {                            \
143         a_format(e, "bad-public-vector", A_END);                        \
144         goto fail;                                                      \
145       }                                                                 \
146     })
147
148 #define KEYTYPE_DEF(ty, TY, setgroup, setpriv, setpub)                  \
149   KLOAD(ty, TY, priv, PRIV, setgroup, setpriv,                          \
150         { G_EXP(kd->g, kd->kpub, kd->g->g, kd->kpriv); })               \
151   KLOAD(ty, TY, pub, PUB, setgroup, { }, setpub)                        \
152   static const kgops kg##ty##_ops = { #ty, kg##ty##_priv, kg##ty##_pub };
153 KEYTYPES(KEYTYPE_DEF)
154
155 /* --- Table of supported key types --- */
156
157 static const kgops *kgtab[] = {
158 #define KEYTYPE_ENTRY(ty, TY, setgroup, setpriv, setpub) &kg##ty##_ops,
159   KEYTYPES(KEYTYPE_ENTRY)
160 #undef KEYTYPE_ENTRY
161   0
162 };
163
164 /*----- Algswitch stuff ---------------------------------------------------*/
165
166 /* --- @algs_get@ --- *
167  *
168  * Arguments:   @algswitch *a@ = where to put the algorithms
169  *              @dstr *e@ = where to write errror tokens
170  *              @key_file *kf@ = key file
171  *              @key *k@ = key to inspect
172  *
173  * Returns:     Zero if OK; nonzero on error.
174  *
175  * Use:         Extracts an algorithm choice from a key.
176  */
177
178 static int algs_get(algswitch *a, dstr *e, key_file *kf, key *k)
179 {
180   const char *p;
181   const bulkcrypto *bulk;
182   char *q, *qq;
183   dstr d = DSTR_INIT;
184   int rc = -1;
185
186   /* --- Hash function --- */
187
188   if ((p = key_getattr(kf, k, "hash")) == 0) p = "rmd160";
189   if ((a->h = ghash_byname(p)) == 0) {
190     a_format(e, "unknown-hash", "%s", p, A_END);
191     goto done;
192   }
193
194   /* --- Symmetric encryption for key derivation --- */
195
196   if ((p = key_getattr(kf, k, "mgf")) == 0) {
197     dstr_reset(&d);
198     dstr_putf(&d, "%s-mgf", a->h->name);
199     p = d.buf;
200   }
201   if ((a->mgf = gcipher_byname(p)) == 0) {
202     a_format(e, "unknown-mgf-cipher", "%s", p, A_END);
203     goto done;
204   }
205
206   /* --- Bulk crypto transform --- */
207
208   if ((p = key_getattr(kf, k, "bulk")) == 0) p = "v0";
209   for (bulk = bulktab; bulk->name && strcmp(p, bulk->name) != 0; bulk++);
210   if (!bulk->name) {
211     a_format(e, "unknown-bulk-transform", "%s", p, A_END);
212     goto done;
213   }
214   a->bulk = bulk;
215
216   /* --- Symmetric encryption for bulk data --- */
217
218   if (!(a->bulk->prim & BCP_CIPHER))
219     a->c = 0;
220   else {
221     if ((p = key_getattr(kf, k, "cipher")) == 0) p = "blowfish-cbc";
222     if ((a->c = gcipher_byname(p)) == 0) {
223       a_format(e, "unknown-cipher", "%s", p, A_END);
224       goto done;
225     }
226   }
227
228   /* --- Message authentication for bulk data --- */
229
230   if (!(a->bulk->prim & BCP_MAC)) {
231     a->m = 0;
232     a->tagsz = 0;
233   } else {
234     if ((p = key_getattr(kf, k, "mac")) != 0) {
235       dstr_reset(&d);
236       dstr_puts(&d, p);
237       if ((q = strchr(d.buf, '/')) != 0)
238         *q++ = 0;
239       if ((a->m = gmac_byname(d.buf)) == 0) {
240         a_format(e, "unknown-mac", "%s", d.buf, A_END);
241         goto done;
242       }
243       if (!q)
244         a->tagsz = a->m->hashsz;
245       else {
246         unsigned long n = strtoul(q, &qq, 0);
247         if (*qq)  {
248           a_format(e, "bad-tag-length-string", "%s", q, A_END);
249           goto done;
250         }
251         if (n%8 || n/8 > a->m->hashsz) {
252           a_format(e, "bad-tag-length", "%lu", n, A_END);
253           goto done;
254         }
255         a->tagsz = n/8;
256       }
257     } else {
258       dstr_reset(&d);
259       dstr_putf(&d, "%s-hmac", a->h->name);
260       if ((a->m = gmac_byname(d.buf)) == 0) {
261         a_format(e, "no-hmac-for-hash", "%s", a->h->name, A_END);
262         goto done;
263       }
264       a->tagsz = a->h->hashsz/2;
265     }
266   }
267
268   /* --- All done --- */
269
270   rc = 0;
271 done:
272   dstr_destroy(&d);
273   return (rc);
274 }
275
276 /* --- @algs_check@ --- *
277  *
278  * Arguments:   @algswitch *a@ = a choice of algorithms
279  *              @dstr *e@ = where to write error tokens
280  *              @const group *g@ = the group we're working in
281  *
282  * Returns:     Zero if OK; nonzero on error.
283  *
284  * Use:         Checks an algorithm choice for sensibleness.  This also
285  *              derives some useful information from the choices, and you
286  *              must call this before committing the algorithm selection
287  *              for use by @keyset@ functions.
288  */
289
290 static int algs_check(algswitch *a, dstr *e, const group *g)
291 {
292   /* --- Check the bulk crypto transform --- */
293
294   if (a->bulk->check(a, e)) return (-1);
295
296   /* --- Derive the key sizes --- *
297    *
298    * Must ensure that we have non-empty keys.  This isn't ideal, but it
299    * provides a handy sanity check.  Also must be based on a 64- or 128-bit
300    * block cipher or we can't do the data expiry properly.
301    */
302
303   a->hashsz = a->h->hashsz;
304   if (a->c && (a->cksz = keysz(a->hashsz, a->c->keysz)) == 0) {
305     a_format(e, "cipher", "%s", a->c->name,
306              "no-key-size", "%lu", (unsigned long)a->hashsz,
307              A_END);
308     return (-1);
309   }
310   if (a->m && (a->mksz = keysz(a->hashsz, a->m->keysz)) == 0) {
311     a_format(e, "mac", "%s", a->m->name,
312              "no-key-size", "%lu", (unsigned long)a->hashsz,
313              A_END);
314     return (-1);
315   }
316
317   /* --- Derive the data limit --- */
318
319   if (a->c && a->c->blksz < 16) a->expsz = MEG(64);
320   else a->expsz = MEG(2048);
321
322   /* --- Ensure the MGF accepts hashes as keys --- */
323
324   if (keysz(a->hashsz, a->mgf->keysz) != a->hashsz) {
325     a_format(e, "mgf", "%s", a->mgf->name,
326              "restrictive-key-schedule",
327              A_END);
328     return (-1);
329   }
330
331   /* --- All ship-shape and Bristol-fashion --- */
332
333   return (0);
334 }
335
336 /* --- @km_samealgsp@ --- *
337  *
338  * Arguments:   @const kdata *kdx, *kdy@ = two key data objects
339  *
340  * Returns:     Nonzero if their two algorithm selections are the same.
341  *
342  * Use:         Checks sameness of algorithm selections: used to ensure that
343  *              peers are using sensible algorithms.
344  */
345
346 int km_samealgsp(const kdata *kdx, const kdata *kdy)
347 {
348   const algswitch *a = &kdx->algs, *aa = &kdy->algs;
349
350   return (group_samep(kdx->g, kdy->g) && a->c == aa->c &&
351           a->mgf == aa->mgf && a->h == aa->h &&
352           a->m == aa->m && a->tagsz == aa->tagsz);
353 }
354
355 /*----- Key data and key nodes --------------------------------------------*/
356
357 typedef struct keyhalf {
358   const char *kind;
359   int (*load)(const kgops *, key_data *, kdata *, dstr *, dstr *);
360   const char *kr;
361   key_file *kf;
362   fwatch w;
363   sym_table tab;
364 } keyhalf;
365
366 /* --- @kh_loadpub@, @kh_loadpriv@ --- *
367  *
368  * Arguments:   @const kgops *ko@ = key-group operations for key type
369  *              @key_data *d@ = key data object as stored in keyring
370  *              @kdata *kd@ = our key-data object to fill in
371  *              @dstr *t@ = the key tag name
372  *              @dstr *e@ = a string to write error tokens to
373  *
374  * Returns:     Zero on success, @-1@ on error.
375  *
376  * Use:         These functions handle the main difference between public and
377  *              private key halves.  They are responsible for setting @g@,
378  *              @kpriv@ and @kpub@ appropriately in all keys, handling the
379  *              mismatch between the largely half-indifferent calling code
380  *              and the group-specific loading functions.
381  *
382  *              The function @kh_loadpriv@ is also responsible for checking
383  *              the group for goodness.  We don't bother checking public
384  *              keys, because each public key we actually end up using must
385  *              share a group with a private key which we'll already have
386  *              checked.
387  */
388
389 static int kh_loadpub(const kgops *ko, key_data *d, kdata *kd,
390                       dstr *t, dstr *e)
391 {
392   int rc;
393
394   if ((rc = ko->loadpub(d, kd, t, e)) != 0)
395     goto fail_0;
396   if (group_check(kd->g, kd->kpub)) {
397     a_format(e, "bad-public-group-element", A_END);
398     goto fail_1;
399   }
400   kd->kpriv = 0;
401   return (0);
402
403 fail_1:
404   G_DESTROY(kd->g, kd->kpub);
405   G_DESTROYGROUP(kd->g);
406 fail_0:
407   return (-1);
408 }
409
410 static int kh_loadpriv(const kgops *ko, key_data *d, kdata *kd,
411                        dstr *t, dstr *e)
412 {
413   int rc;
414   const char *err;
415
416   if ((rc = ko->loadpriv(d, kd, t, e)) != 0)
417     goto fail_0;
418   if ((err = G_CHECK(kd->g, &rand_global)) != 0) {
419     a_format(e, "bad-group", "%s", err, A_END);
420     goto fail_1;
421   }
422   return (0);
423
424 fail_1:
425   mp_drop(kd->kpriv);
426   G_DESTROY(kd->g, kd->kpub);
427   G_DESTROYGROUP(kd->g);
428 fail_0:
429   return (-1);
430 }
431
432 static struct keyhalf
433   priv = { "private", kh_loadpriv },
434   pub = { "public", kh_loadpub };
435
436 /* --- @keymoan@ --- *
437  *
438  * Arguments:   @const char *file@ = name of the file
439  *              @int line@ = line number in file
440  *              @const char *msg@ = error message
441  *              @void *p@ = argument pointer (indicates which keyring)
442  *
443  * Returns:     ---
444  *
445  * Use:         Reports an error message about loading a key file.
446  */
447
448 static void keymoan(const char *file, int line, const char *msg, void *p)
449 {
450   keyhalf *kh = p;
451
452   if (!line) {
453     a_warn("KEYMGMT", "%s-keyring", kh->kind, "%s", file,
454            "io-error", "?ERRNO", A_END);
455   } else {
456     a_warn("KEYMGMT", "%s-keyring", kh->kind, "%s", file, "line", "%d", line,
457            "%s", msg, A_END);
458   }
459 }
460
461 /* --- @kh_reopen@ --- *
462  *
463  * Arguments:   @keyhalf *kh@ = pointer to keyhalf structure
464  *
465  * Returns:     Zero on success, @-1@ on error.
466  *
467  * Use:         Reopens the key file for the appropriate key half.  If this
468  *              fails, everything is left as it was; if it succeeds, then the
469  *              old file is closed (if it was non-null) and the new one put
470  *              in its place.
471  */
472
473 static int kh_reopen(keyhalf *kh)
474 {
475   key_file *kf = CREATE(key_file);
476
477   if (key_open(kf, kh->kr, KOPEN_READ, keymoan, kh)) {
478     a_warn("KEYMGMT", "%s-keyring", kh->kind, "%s", kh->kr,
479            "io-error", "?ERRNO", A_END);
480     DESTROY(kf);
481     return (-1);
482   } else {
483     if (kh->kf) {
484       key_close(kh->kf);
485       DESTROY(kh->kf);
486     }
487     kh->kf = kf;
488     return (0);
489   }
490 }
491
492 /* --- @kh_init@ --- *
493  *
494  * Arguments:   @keyhalf *kh@ = pointer to keyhalf structure to set up
495  *              @const char *kr@ = name of the keyring file
496  *
497  * Returns:     ---
498  *
499  * Use:         Initialize a keyhalf structure, maintaining the private or
500  *              public keys.  Intended to be called during initialization:
501  *              exits if there's some kind of problem.
502  */
503
504 static void kh_init(keyhalf *kh, const char *kr)
505 {
506   kh->kr = kr;
507   fwatch_init(&kh->w, kr);
508   sym_create(&kh->tab);
509   kh->kf = 0;
510
511   if (kh_reopen(kh))
512     die(EXIT_FAILURE, "failed to load %s keyring `%s'", kh->kind, kr);
513 }
514
515 /* --- @kh_load@ --- *
516  *
517  * Arguments:   @keyhalf *kh@ = pointer to keyhalf
518  *              @const char *tag@ = key tag to be loaded
519  *              @int complainp@ = whether to complain about missing keys
520  *
521  * Returns:     Pointer to a @kdata@ structure if successful, or null on
522  *              failure.
523  *
524  * Use:         Attempts to load a key from the current key file.  This
525  *              function always reads data from the file: it's used when
526  *              there's a cache miss from @kh_find@, and when refreshing the
527  *              known keys in @kh_refresh@.  The returned kdata has a
528  *              reference count of exactly 1, and has no home knode.
529  */
530
531 static kdata *kh_load(keyhalf *kh, const char *tag, int complainp)
532 {
533   dstr t = DSTR_INIT;
534   dstr e = DSTR_INIT;
535   key *k;
536   key_data **d;
537   kdata *kd;
538   const char *ty;
539   const kgops **ko;
540
541   /* --- Find the key and grab its tag --- */
542
543   if (key_qtag(kh->kf, tag, &t, &k, &d)) {
544     if (complainp) {
545       a_warn("KEYMGMT", "%s-keyring", kh->kind, "%s", kh->kr,
546              "key-not-found", "%s", tag, A_END);
547     }
548     goto fail_0;
549   }
550
551   /* --- Find the key's group type and the appropriate operations --- *
552    *
553    * There are several places to look for the key type.  The most obvious is
554    * the `kx-group' key attribute.  But there's also the key type itself, for
555    * compatibility reasons.
556    */
557
558   ty = key_getattr(kh->kf, k, "kx-group");
559   if (!ty && strncmp(k->type, "tripe-", 6) == 0) ty = k->type + 6;
560   if (!ty) ty = "dh";
561
562   for (ko = kgtab; *ko; ko++)
563     if (strcmp((*ko)->ty, ty) == 0) goto foundko;
564   a_warn("KEYMGMT", "%s-keyring", kh->kind,
565          "%s", kh->kr, "key", "%s", t.buf,
566          "unknown-group-type", "%s", ty, A_END);
567   goto fail_0;
568
569 foundko:
570   kd = CREATE(kdata);
571   if (kh->load(*ko, *d, kd, &t, &e)) {
572     a_warn("KEYMGMT", "%s-keyring", kh->kind,
573            "%s", kh->kr, "key" "%s", t.buf,
574            "*%s", e.buf, A_END);
575     goto fail_1;
576   }
577
578   if (algs_get(&kd->algs, &e, kh->kf, k) ||
579       (kd->kpriv && algs_check(&kd->algs, &e, kd->g))) {
580     a_warn("KEYMGMT", "%s-keyring", kh->kind,
581            "%s", kh->kr, "key", "%s", t.buf,
582            "*%s", e.buf, A_END);
583     goto fail_2;
584   }
585
586   kd->tag = xstrdup(t.buf);
587   kd->indexsz = mp_octets(kd->g->r);
588   kd->ref = 1;
589   kd->kn = 0;
590   kd->t_exp = k->exp;
591
592   IF_TRACING(T_KEYMGMT, {
593     trace(T_KEYMGMT, "keymgmt: loaded %s key `%s'", kh->kind, t.buf);
594     IF_TRACING(T_CRYPTO, {
595       trace(T_CRYPTO, "crypto: r = %s", mpstr(kd->g->r));
596       trace(T_CRYPTO, "crypto: h = %s", mpstr(kd->g->h));
597       if (kd->kpriv)
598         trace(T_CRYPTO, "crypto: x = %s", mpstr(kd->kpriv));
599       trace(T_CRYPTO, "crypto: cipher = %s", kd->algs.c->name);
600       trace(T_CRYPTO, "crypto: mgf = %s", kd->algs.mgf->name);
601       trace(T_CRYPTO, "crypto: hash = %s", kd->algs.h->name);
602       trace(T_CRYPTO, "crypto: mac = %s/%lu",
603             kd->algs.m->name, (unsigned long)kd->algs.tagsz * 8);
604     })
605   })
606
607   goto done;
608
609 fail_2:
610   if (kd->kpriv) mp_drop(kd->kpriv);
611   G_DESTROY(kd->g, kd->kpub);
612   G_DESTROYGROUP(kd->g);
613 fail_1:
614   DESTROY(kd);
615 fail_0:
616   kd = 0;
617 done:
618   dstr_destroy(&t);
619   dstr_destroy(&e);
620   return (kd);
621 }
622
623 /* --- @kh_find@ --- *
624  *
625  * Arguments:   @keyhalf *kh@ = pointer to the keyhalf
626  *              @const char *tag@ = key to be obtained
627  *              @int complainp@ = whether to complain about missing keys
628  *
629  * Returns:     A pointer to the kdata, or null on error.
630  *
631  * Use:         Obtains kdata, maybe from the cache.  This won't update a
632  *              stale cache entry, though @kh_refresh@ ought to have done
633  *              that already.  The returned kdata object may be shared with
634  *              other users.  (One of this function's responsibilities, over
635  *              @kh_load@, is to set the home knode of a freshly loaded
636  *              kdata.)
637  */
638
639 static kdata *kh_find(keyhalf *kh, const char *tag, int complainp)
640 {
641   knode *kn;
642   kdata *kd;
643   unsigned f;
644
645   kn = sym_find(&kh->tab, tag, -1, sizeof(knode), &f);
646
647   if (f) {
648     if (kn->f & KNF_BROKEN) {
649       T( if (complainp)
650            trace(T_KEYMGMT, "keymgmt: key `%s' marked as broken", tag); )
651       return (0);
652     }
653
654     kd = kn->kd;
655     if (kd) kd->ref++;
656     T( trace(T_KEYMGMT, "keymgmt: %scache hit for key `%s'",
657              kd ? "" : "negative ", tag); )
658     return (kd);
659   } else {
660     kd = kh_load(kh, tag, complainp);
661     kn->kd = kd;
662     kn->kh = kh;
663     kn->f = 0;
664     if (!kd)
665       kn->f |= KNF_BROKEN;
666     else {
667       kd->kn = kn;
668       kd->ref++;
669     }
670     return (kd);
671   }
672 }
673
674 /* --- @kh_refresh@ --- *
675  *
676  * Arguments:   @keyhalf *kh@ = pointer to the keyhalf
677  *
678  * Returns:     Zero if nothing needs to be done; nonzero if peers should
679  *              refresh their keys.
680  *
681  * Use:         Refreshes cached keys from files.
682  *
683  *              Each active knode is examined to see if a new key is
684  *              available: the return value is nonzero if any new keys are.
685  *              A key is considered new if its algorithms, public key, or
686  *              expiry time are/is different.
687  *
688  *              Stub knodes (with no kdata attached) are removed, so that a
689  *              later retry can succeed if the file has been fixed.  (This
690  *              doesn't count as a change, since no peers should be relying
691  *              on a nonexistent key.)
692  */
693
694 static int kh_refresh(keyhalf *kh)
695 {
696   knode *kn;
697   kdata *kd;
698   sym_iter i;
699   int changep = 0;
700
701   if (!fwatch_update(&kh->w, kh->kr) || kh_reopen(kh))
702     return (0);
703
704   T( trace(T_KEYMGMT, "keymgmt: rescan %s keyring `%s'", kh->kind, kh->kr); )
705   for (sym_mkiter(&i, &kh->tab); (kn = sym_next(&i)) != 0; ) {
706     if (!kn->kd) {
707       T( trace(T_KEYMGMT, "keymgmt: discard stub entry for key `%s'",
708                SYM_NAME(kn)); )
709       sym_remove(&kh->tab, kn);
710       continue;
711     }
712     if ((kd = kh_load(kh, SYM_NAME(kn), 1)) == 0) {
713       if (!(kn->f & KNF_BROKEN)) {
714         T( trace(T_KEYMGMT, "keymgmt: failed to load new key `%s': "
715                  "marking it as broken",
716                  SYM_NAME(kn)); )
717         kn->f |= KNF_BROKEN;
718       }
719       continue;
720     }
721     kn->f &= ~KNF_BROKEN;
722     if (kd->t_exp == kn->kd->t_exp &&
723         km_samealgsp(kd, kn->kd) &&
724         G_EQ(kd->g, kd->kpub, kn->kd->kpub)) {
725       T( trace(T_KEYMGMT, "keymgmt: key `%s' unchanged", SYM_NAME(kn)); )
726       continue;
727     }
728     T( trace(T_KEYMGMT, "keymgmt: loaded new version of key `%s'",
729              SYM_NAME(kn)); )
730     km_unref(kn->kd);
731     kd->kn = kn;
732     kn->kd = kd;
733     changep = 1;
734   }
735
736   return (changep);
737 }
738
739 /*----- Main code ---------------------------------------------------------*/
740
741 const char *tag_priv;
742 kdata *master;
743
744 /* --- @km_init@ --- *
745  *
746  * Arguments:   @const char *privkr@ = private keyring file
747  *              @const char *pubkr@ = public keyring file
748  *              @const char *ptag@ = default private-key tag
749  *
750  * Returns:     ---
751  *
752  * Use:         Initializes the key-management machinery, loading the
753  *              keyrings and so on.
754  */
755
756 void km_init(const char *privkr, const char *pubkr, const char *ptag)
757 {
758   const gchash *const *hh;
759
760   for (hh = ghashtab; *hh; hh++) {
761     if ((*hh)->hashsz > MAXHASHSZ) {
762       die(EXIT_FAILURE, "INTERNAL ERROR: %s hash length %lu > MAXHASHSZ %d",
763           (*hh)->name, (unsigned long)(*hh)->hashsz, MAXHASHSZ);
764     }
765   }
766
767   kh_init(&priv, privkr);
768   kh_init(&pub, pubkr);
769
770   tag_priv = ptag;
771   if ((master = km_findpriv(ptag)) == 0) exit(EXIT_FAILURE);
772 }
773
774 /* --- @km_reload@ --- *
775  *
776  * Arguments:   ---
777  *
778  * Returns:     Zero if OK, nonzero to force reloading of keys.
779  *
780  * Use:         Checks the keyrings to see if they need reloading.
781  */
782
783 int km_reload(void)
784 {
785   int changep = 0;
786   kdata *kd;
787
788   if (kh_refresh(&priv)) {
789     changep = 1;
790     kd = master->kn->kd;
791     if (kd != master) {
792       km_unref(master);
793       km_ref(kd);
794       master = kd;
795     }
796   }
797   if (kh_refresh(&pub))
798     changep = 1;
799   return (changep);
800 }
801
802 /* --- @km_findpub@, @km_findpriv@ --- *
803  *
804  * Arguments:   @const char *tag@ = key tag to load
805  *
806  * Returns:     Pointer to the kdata object if successful, or null on error.
807  *
808  * Use:         Fetches a public or private key from the keyring.
809  */
810
811 kdata *km_findpub(const char *tag) { return (kh_find(&pub, tag, 1)); }
812
813 kdata *km_findpriv(const char *tag)
814 {
815   kdata *kd;
816
817   /* Unpleasantness for the sake of compatibility. */
818   if (!tag && (kd = kh_find(&priv, "tripe", 0)) != 0) return (kd);
819   else return (kh_find(&priv, tag ? tag : "tripe-dh", 1));
820 }
821
822 /* --- @km_tag@ --- *
823  *
824  * Arguments:   @kdata *kd@ - pointer to the kdata object
825  *
826  * Returns:     A pointer to the short tag by which the kdata was loaded.
827  */
828
829 const char *km_tag(kdata *kd) { return (SYM_NAME(kd->kn)); }
830
831 /* --- @km_ref@ --- *
832  *
833  * Arguments:   @kdata *kd@ = pointer to the kdata object
834  *
835  * Returns:     ---
836  *
837  * Use:         Claim a new reference to a kdata object.
838  */
839
840 void km_ref(kdata *kd) { kd->ref++; }
841
842 /* --- @km_unref@ --- *
843  *
844  * Arguments:   @kdata *kd@ = pointer to the kdata object
845  *
846  * Returns:     ---
847  *
848  * Use:         Releases a reference to a kdata object.
849  */
850
851 void km_unref(kdata *kd)
852 {
853   if (--kd->ref) return;
854   if (kd->kpriv) mp_drop(kd->kpriv);
855   G_DESTROY(kd->g, kd->kpub);
856   xfree(kd->tag);
857   G_DESTROYGROUP(kd->g);
858 }
859
860 /*----- That's all, folks -------------------------------------------------*/