chiark / gitweb /
svc/conntrack.in (straddr): Handle `None' as a packed address.
[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, dd = 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   /* --- Block cipher for miscellaneous use --- */
229
230   if (!(a->bulk->prim & BCP_BLKC))
231     a->b = 0;
232   else {
233     if ((p = key_getattr(kf, k, "blkc")) == 0) {
234       dstr_reset(&dd);
235       dstr_puts(&dd, a->c ? a->c->name : "rijndael-");
236       if ((q = strrchr(dd.buf, '-')) != 0) *q = 0;
237       p = dd.buf;
238     }
239     dstr_reset(&d);
240     dstr_putf(&d, "%s-ecb", p);
241     if ((a->b = gcipher_byname(d.buf)) == 0) {
242       a_format(e, "unknown-blkc", "%s", p, A_END);
243       goto done;
244     }
245   }
246
247   /* --- Message authentication for bulk data --- */
248
249   if (!(a->bulk->prim & BCP_MAC)) {
250     a->m = 0;
251     a->tagsz = 0;
252   } else {
253     if ((p = key_getattr(kf, k, "mac")) != 0) {
254       dstr_reset(&d);
255       dstr_puts(&d, p);
256       if ((q = strchr(d.buf, '/')) != 0)
257         *q++ = 0;
258       if ((a->m = gmac_byname(d.buf)) == 0) {
259         a_format(e, "unknown-mac", "%s", d.buf, A_END);
260         goto done;
261       }
262       if (!q)
263         a->tagsz = a->m->hashsz;
264       else {
265         unsigned long n = strtoul(q, &qq, 0);
266         if (*qq)  {
267           a_format(e, "bad-tag-length-string", "%s", q, A_END);
268           goto done;
269         }
270         if (n%8 || n/8 > a->m->hashsz) {
271           a_format(e, "bad-tag-length", "%lu", n, A_END);
272           goto done;
273         }
274         a->tagsz = n/8;
275       }
276     } else {
277       dstr_reset(&d);
278       dstr_putf(&d, "%s-hmac", a->h->name);
279       if ((a->m = gmac_byname(d.buf)) == 0) {
280         a_format(e, "no-hmac-for-hash", "%s", a->h->name, A_END);
281         goto done;
282       }
283       a->tagsz = a->h->hashsz/2;
284     }
285   }
286
287   /* --- All done --- */
288
289   rc = 0;
290 done:
291   dstr_destroy(&d);
292   dstr_destroy(&dd);
293   return (rc);
294 }
295
296 /* --- @algs_check@ --- *
297  *
298  * Arguments:   @algswitch *a@ = a choice of algorithms
299  *              @dstr *e@ = where to write error tokens
300  *              @const group *g@ = the group we're working in
301  *
302  * Returns:     Zero if OK; nonzero on error.
303  *
304  * Use:         Checks an algorithm choice for sensibleness.  This also
305  *              derives some useful information from the choices, and you
306  *              must call this before committing the algorithm selection
307  *              for use by @keyset@ functions.
308  */
309
310 static int algs_check(algswitch *a, dstr *e, const group *g)
311 {
312   /* --- Check the bulk crypto transform --- */
313
314   if (a->bulk->check(a, e)) return (-1);
315
316   /* --- Derive the key sizes --- *
317    *
318    * Must ensure that we have non-empty keys.  This isn't ideal, but it
319    * provides a handy sanity check.  Also must be based on a 64- or 128-bit
320    * block cipher or we can't do the data expiry properly.
321    */
322
323   a->hashsz = a->h->hashsz;
324   if (a->c && (a->cksz = keysz(a->hashsz, a->c->keysz)) == 0) {
325     a_format(e, "cipher", "%s", a->c->name,
326              "no-key-size", "%lu", (unsigned long)a->hashsz,
327              A_END);
328     return (-1);
329   }
330   if (a->m && (a->mksz = keysz(a->hashsz, a->m->keysz)) == 0) {
331     a_format(e, "mac", "%s", a->m->name,
332              "no-key-size", "%lu", (unsigned long)a->hashsz,
333              A_END);
334     return (-1);
335   }
336   if (a->b && (a->bksz = keysz(a->hashsz, a->b->keysz)) == 0) {
337     a_format(e, "blkc", "%.*s", strlen(a->b->name) - 4, a->b->name,
338              "no-key-size", "%lu", (unsigned long)a->hashsz,
339              A_END);
340     return (-1);
341   }
342
343   /* --- Derive the data limit --- */
344
345   if (a->c && a->c->blksz < 16) a->expsz = MEG(64);
346   else a->expsz = MEG(2048);
347
348   /* --- Ensure the MGF accepts hashes as keys --- */
349
350   if (keysz(a->hashsz, a->mgf->keysz) != a->hashsz) {
351     a_format(e, "mgf", "%s", a->mgf->name,
352              "restrictive-key-schedule",
353              A_END);
354     return (-1);
355   }
356
357   /* --- All ship-shape and Bristol-fashion --- */
358
359   return (0);
360 }
361
362 /* --- @km_samealgsp@ --- *
363  *
364  * Arguments:   @const kdata *kdx, *kdy@ = two key data objects
365  *
366  * Returns:     Nonzero if their two algorithm selections are the same.
367  *
368  * Use:         Checks sameness of algorithm selections: used to ensure that
369  *              peers are using sensible algorithms.
370  */
371
372 int km_samealgsp(const kdata *kdx, const kdata *kdy)
373 {
374   const algswitch *a = &kdx->algs, *aa = &kdy->algs;
375
376   return (group_samep(kdx->g, kdy->g) &&
377           a->c == aa->c && a->b == aa->b &&
378           a->mgf == aa->mgf && a->h == aa->h &&
379           a->m == aa->m && a->tagsz == aa->tagsz);
380 }
381
382 /*----- Key data and key nodes --------------------------------------------*/
383
384 typedef struct keyhalf {
385   const char *kind;
386   int (*load)(const kgops *, key_data *, kdata *, dstr *, dstr *);
387   const char *kr;
388   key_file *kf;
389   fwatch w;
390   sym_table tab;
391 } keyhalf;
392
393 /* --- @kh_loadpub@, @kh_loadpriv@ --- *
394  *
395  * Arguments:   @const kgops *ko@ = key-group operations for key type
396  *              @key_data *d@ = key data object as stored in keyring
397  *              @kdata *kd@ = our key-data object to fill in
398  *              @dstr *t@ = the key tag name
399  *              @dstr *e@ = a string to write error tokens to
400  *
401  * Returns:     Zero on success, @-1@ on error.
402  *
403  * Use:         These functions handle the main difference between public and
404  *              private key halves.  They are responsible for setting @g@,
405  *              @kpriv@ and @kpub@ appropriately in all keys, handling the
406  *              mismatch between the largely half-indifferent calling code
407  *              and the group-specific loading functions.
408  *
409  *              The function @kh_loadpriv@ is also responsible for checking
410  *              the group for goodness.  We don't bother checking public
411  *              keys, because each public key we actually end up using must
412  *              share a group with a private key which we'll already have
413  *              checked.
414  */
415
416 static int kh_loadpub(const kgops *ko, key_data *d, kdata *kd,
417                       dstr *t, dstr *e)
418 {
419   int rc;
420
421   if ((rc = ko->loadpub(d, kd, t, e)) != 0)
422     goto fail_0;
423   if (group_check(kd->g, kd->kpub)) {
424     a_format(e, "bad-public-group-element", A_END);
425     goto fail_1;
426   }
427   kd->kpriv = 0;
428   return (0);
429
430 fail_1:
431   G_DESTROY(kd->g, kd->kpub);
432   G_DESTROYGROUP(kd->g);
433 fail_0:
434   return (-1);
435 }
436
437 static int kh_loadpriv(const kgops *ko, key_data *d, kdata *kd,
438                        dstr *t, dstr *e)
439 {
440   int rc;
441   const char *err;
442
443   if ((rc = ko->loadpriv(d, kd, t, e)) != 0)
444     goto fail_0;
445   if ((err = G_CHECK(kd->g, &rand_global)) != 0) {
446     a_format(e, "bad-group", "%s", err, A_END);
447     goto fail_1;
448   }
449   return (0);
450
451 fail_1:
452   mp_drop(kd->kpriv);
453   G_DESTROY(kd->g, kd->kpub);
454   G_DESTROYGROUP(kd->g);
455 fail_0:
456   return (-1);
457 }
458
459 static struct keyhalf
460   priv = { "private", kh_loadpriv },
461   pub = { "public", kh_loadpub };
462
463 /* --- @keymoan@ --- *
464  *
465  * Arguments:   @const char *file@ = name of the file
466  *              @int line@ = line number in file
467  *              @const char *msg@ = error message
468  *              @void *p@ = argument pointer (indicates which keyring)
469  *
470  * Returns:     ---
471  *
472  * Use:         Reports an error message about loading a key file.
473  */
474
475 static void keymoan(const char *file, int line, const char *msg, void *p)
476 {
477   keyhalf *kh = p;
478
479   if (!line) {
480     a_warn("KEYMGMT", "%s-keyring", kh->kind, "%s", file,
481            "io-error", "?ERRNO", A_END);
482   } else {
483     a_warn("KEYMGMT", "%s-keyring", kh->kind, "%s", file, "line", "%d", line,
484            "%s", msg, A_END);
485   }
486 }
487
488 /* --- @kh_reopen@ --- *
489  *
490  * Arguments:   @keyhalf *kh@ = pointer to keyhalf structure
491  *
492  * Returns:     Zero on success, @-1@ on error.
493  *
494  * Use:         Reopens the key file for the appropriate key half.  If this
495  *              fails, everything is left as it was; if it succeeds, then the
496  *              old file is closed (if it was non-null) and the new one put
497  *              in its place.
498  */
499
500 static int kh_reopen(keyhalf *kh)
501 {
502   key_file *kf = CREATE(key_file);
503
504   if (key_open(kf, kh->kr, KOPEN_READ, keymoan, kh)) {
505     a_warn("KEYMGMT", "%s-keyring", kh->kind, "%s", kh->kr,
506            "io-error", "?ERRNO", A_END);
507     DESTROY(kf);
508     return (-1);
509   } else {
510     if (kh->kf) {
511       key_close(kh->kf);
512       DESTROY(kh->kf);
513     }
514     kh->kf = kf;
515     return (0);
516   }
517 }
518
519 /* --- @kh_init@ --- *
520  *
521  * Arguments:   @keyhalf *kh@ = pointer to keyhalf structure to set up
522  *              @const char *kr@ = name of the keyring file
523  *
524  * Returns:     ---
525  *
526  * Use:         Initialize a keyhalf structure, maintaining the private or
527  *              public keys.  Intended to be called during initialization:
528  *              exits if there's some kind of problem.
529  */
530
531 static void kh_init(keyhalf *kh, const char *kr)
532 {
533   kh->kr = kr;
534   fwatch_init(&kh->w, kr);
535   sym_create(&kh->tab);
536   kh->kf = 0;
537
538   if (kh_reopen(kh))
539     die(EXIT_FAILURE, "failed to load %s keyring `%s'", kh->kind, kr);
540 }
541
542 /* --- @kh_load@ --- *
543  *
544  * Arguments:   @keyhalf *kh@ = pointer to keyhalf
545  *              @const char *tag@ = key tag to be loaded
546  *              @int complainp@ = whether to complain about missing keys
547  *
548  * Returns:     Pointer to a @kdata@ structure if successful, or null on
549  *              failure.
550  *
551  * Use:         Attempts to load a key from the current key file.  This
552  *              function always reads data from the file: it's used when
553  *              there's a cache miss from @kh_find@, and when refreshing the
554  *              known keys in @kh_refresh@.  The returned kdata has a
555  *              reference count of exactly 1, and has no home knode.
556  */
557
558 static kdata *kh_load(keyhalf *kh, const char *tag, int complainp)
559 {
560   dstr t = DSTR_INIT;
561   dstr e = DSTR_INIT;
562   key *k;
563   key_data **d;
564   kdata *kd;
565   const char *ty;
566   const kgops **ko;
567
568   /* --- Find the key and grab its tag --- */
569
570   if (key_qtag(kh->kf, tag, &t, &k, &d)) {
571     if (complainp) {
572       a_warn("KEYMGMT", "%s-keyring", kh->kind, "%s", kh->kr,
573              "key-not-found", "%s", tag, A_END);
574     }
575     goto fail_0;
576   }
577
578   /* --- Find the key's group type and the appropriate operations --- *
579    *
580    * There are several places to look for the key type.  The most obvious is
581    * the `kx-group' key attribute.  But there's also the key type itself, for
582    * compatibility reasons.
583    */
584
585   ty = key_getattr(kh->kf, k, "kx-group");
586   if (!ty && strncmp(k->type, "tripe-", 6) == 0) ty = k->type + 6;
587   if (!ty) ty = "dh";
588
589   for (ko = kgtab; *ko; ko++)
590     if (strcmp((*ko)->ty, ty) == 0) goto foundko;
591   a_warn("KEYMGMT", "%s-keyring", kh->kind,
592          "%s", kh->kr, "key", "%s", t.buf,
593          "unknown-group-type", "%s", ty, A_END);
594   goto fail_0;
595
596 foundko:
597   kd = CREATE(kdata);
598   if (kh->load(*ko, *d, kd, &t, &e)) {
599     a_warn("KEYMGMT", "%s-keyring", kh->kind,
600            "%s", kh->kr, "key" "%s", t.buf,
601            "*%s", e.buf, A_END);
602     goto fail_1;
603   }
604
605   if (algs_get(&kd->algs, &e, kh->kf, k) ||
606       (kd->kpriv && algs_check(&kd->algs, &e, kd->g))) {
607     a_warn("KEYMGMT", "%s-keyring", kh->kind,
608            "%s", kh->kr, "key", "%s", t.buf,
609            "*%s", e.buf, A_END);
610     goto fail_2;
611   }
612
613   kd->tag = xstrdup(t.buf);
614   kd->indexsz = mp_octets(kd->g->r);
615   kd->ref = 1;
616   kd->kn = 0;
617   kd->t_exp = k->exp;
618
619   IF_TRACING(T_KEYMGMT, {
620     trace(T_KEYMGMT, "keymgmt: loaded %s key `%s'", kh->kind, t.buf);
621     IF_TRACING(T_CRYPTO, {
622       trace(T_CRYPTO, "crypto: r = %s", mpstr(kd->g->r));
623       trace(T_CRYPTO, "crypto: h = %s", mpstr(kd->g->h));
624       if (kd->kpriv)
625         trace(T_CRYPTO, "crypto: x = %s", mpstr(kd->kpriv));
626       trace(T_CRYPTO, "crypto: cipher = %s", kd->algs.c->name);
627       trace(T_CRYPTO, "crypto: mgf = %s", kd->algs.mgf->name);
628       trace(T_CRYPTO, "crypto: hash = %s", kd->algs.h->name);
629       trace(T_CRYPTO, "crypto: mac = %s/%lu",
630             kd->algs.m->name, (unsigned long)kd->algs.tagsz * 8);
631     })
632   })
633
634   goto done;
635
636 fail_2:
637   if (kd->kpriv) mp_drop(kd->kpriv);
638   G_DESTROY(kd->g, kd->kpub);
639   G_DESTROYGROUP(kd->g);
640 fail_1:
641   DESTROY(kd);
642 fail_0:
643   kd = 0;
644 done:
645   dstr_destroy(&t);
646   dstr_destroy(&e);
647   return (kd);
648 }
649
650 /* --- @kh_find@ --- *
651  *
652  * Arguments:   @keyhalf *kh@ = pointer to the keyhalf
653  *              @const char *tag@ = key to be obtained
654  *              @int complainp@ = whether to complain about missing keys
655  *
656  * Returns:     A pointer to the kdata, or null on error.
657  *
658  * Use:         Obtains kdata, maybe from the cache.  This won't update a
659  *              stale cache entry, though @kh_refresh@ ought to have done
660  *              that already.  The returned kdata object may be shared with
661  *              other users.  (One of this function's responsibilities, over
662  *              @kh_load@, is to set the home knode of a freshly loaded
663  *              kdata.)
664  */
665
666 static kdata *kh_find(keyhalf *kh, const char *tag, int complainp)
667 {
668   knode *kn;
669   kdata *kd;
670   unsigned f;
671
672   kn = sym_find(&kh->tab, tag, -1, sizeof(knode), &f);
673
674   if (f) {
675     if (kn->f & KNF_BROKEN) {
676       T( if (complainp)
677            trace(T_KEYMGMT, "keymgmt: key `%s' marked as broken", tag); )
678       return (0);
679     }
680
681     kd = kn->kd;
682     if (kd) kd->ref++;
683     T( trace(T_KEYMGMT, "keymgmt: %scache hit for key `%s'",
684              kd ? "" : "negative ", tag); )
685     return (kd);
686   } else {
687     kd = kh_load(kh, tag, complainp);
688     kn->kd = kd;
689     kn->kh = kh;
690     kn->f = 0;
691     if (!kd)
692       kn->f |= KNF_BROKEN;
693     else {
694       kd->kn = kn;
695       kd->ref++;
696     }
697     return (kd);
698   }
699 }
700
701 /* --- @kh_refresh@ --- *
702  *
703  * Arguments:   @keyhalf *kh@ = pointer to the keyhalf
704  *
705  * Returns:     Zero if nothing needs to be done; nonzero if peers should
706  *              refresh their keys.
707  *
708  * Use:         Refreshes cached keys from files.
709  *
710  *              Each active knode is examined to see if a new key is
711  *              available: the return value is nonzero if any new keys are.
712  *              A key is considered new if its algorithms, public key, or
713  *              expiry time are/is different.
714  *
715  *              Stub knodes (with no kdata attached) are removed, so that a
716  *              later retry can succeed if the file has been fixed.  (This
717  *              doesn't count as a change, since no peers should be relying
718  *              on a nonexistent key.)
719  */
720
721 static int kh_refresh(keyhalf *kh)
722 {
723   knode *kn;
724   kdata *kd;
725   sym_iter i;
726   int changep = 0;
727
728   if (!fwatch_update(&kh->w, kh->kr) || kh_reopen(kh))
729     return (0);
730
731   T( trace(T_KEYMGMT, "keymgmt: rescan %s keyring `%s'", kh->kind, kh->kr); )
732   for (sym_mkiter(&i, &kh->tab); (kn = sym_next(&i)) != 0; ) {
733     if (!kn->kd) {
734       T( trace(T_KEYMGMT, "keymgmt: discard stub entry for key `%s'",
735                SYM_NAME(kn)); )
736       sym_remove(&kh->tab, kn);
737       continue;
738     }
739     if ((kd = kh_load(kh, SYM_NAME(kn), 1)) == 0) {
740       if (!(kn->f & KNF_BROKEN)) {
741         T( trace(T_KEYMGMT, "keymgmt: failed to load new key `%s': "
742                  "marking it as broken",
743                  SYM_NAME(kn)); )
744         kn->f |= KNF_BROKEN;
745       }
746       continue;
747     }
748     kn->f &= ~KNF_BROKEN;
749     if (kd->t_exp == kn->kd->t_exp &&
750         km_samealgsp(kd, kn->kd) &&
751         G_EQ(kd->g, kd->kpub, kn->kd->kpub)) {
752       T( trace(T_KEYMGMT, "keymgmt: key `%s' unchanged", SYM_NAME(kn)); )
753       continue;
754     }
755     T( trace(T_KEYMGMT, "keymgmt: loaded new version of key `%s'",
756              SYM_NAME(kn)); )
757     km_unref(kn->kd);
758     kd->kn = kn;
759     kn->kd = kd;
760     changep = 1;
761   }
762
763   return (changep);
764 }
765
766 /*----- Main code ---------------------------------------------------------*/
767
768 const char *tag_priv;
769 kdata *master;
770
771 /* --- @km_init@ --- *
772  *
773  * Arguments:   @const char *privkr@ = private keyring file
774  *              @const char *pubkr@ = public keyring file
775  *              @const char *ptag@ = default private-key tag
776  *
777  * Returns:     ---
778  *
779  * Use:         Initializes the key-management machinery, loading the
780  *              keyrings and so on.
781  */
782
783 void km_init(const char *privkr, const char *pubkr, const char *ptag)
784 {
785   const gchash *const *hh;
786
787   for (hh = ghashtab; *hh; hh++) {
788     if ((*hh)->hashsz > MAXHASHSZ) {
789       die(EXIT_FAILURE, "INTERNAL ERROR: %s hash length %lu > MAXHASHSZ %d",
790           (*hh)->name, (unsigned long)(*hh)->hashsz, MAXHASHSZ);
791     }
792   }
793
794   kh_init(&priv, privkr);
795   kh_init(&pub, pubkr);
796
797   tag_priv = ptag;
798   if ((master = km_findpriv(ptag)) == 0) exit(EXIT_FAILURE);
799 }
800
801 /* --- @km_reload@ --- *
802  *
803  * Arguments:   ---
804  *
805  * Returns:     Zero if OK, nonzero to force reloading of keys.
806  *
807  * Use:         Checks the keyrings to see if they need reloading.
808  */
809
810 int km_reload(void)
811 {
812   int changep = 0;
813   kdata *kd;
814
815   if (kh_refresh(&priv)) {
816     changep = 1;
817     kd = master->kn->kd;
818     if (kd != master) {
819       km_unref(master);
820       km_ref(kd);
821       master = kd;
822     }
823   }
824   if (kh_refresh(&pub))
825     changep = 1;
826   return (changep);
827 }
828
829 /* --- @km_findpub@, @km_findpriv@ --- *
830  *
831  * Arguments:   @const char *tag@ = key tag to load
832  *
833  * Returns:     Pointer to the kdata object if successful, or null on error.
834  *
835  * Use:         Fetches a public or private key from the keyring.
836  */
837
838 kdata *km_findpub(const char *tag) { return (kh_find(&pub, tag, 1)); }
839
840 kdata *km_findpriv(const char *tag)
841 {
842   kdata *kd;
843
844   /* Unpleasantness for the sake of compatibility. */
845   if (!tag && (kd = kh_find(&priv, "tripe", 0)) != 0) return (kd);
846   else return (kh_find(&priv, tag ? tag : "tripe-dh", 1));
847 }
848
849 /* --- @km_tag@ --- *
850  *
851  * Arguments:   @kdata *kd@ - pointer to the kdata object
852  *
853  * Returns:     A pointer to the short tag by which the kdata was loaded.
854  */
855
856 const char *km_tag(kdata *kd) { return (SYM_NAME(kd->kn)); }
857
858 /* --- @km_ref@ --- *
859  *
860  * Arguments:   @kdata *kd@ = pointer to the kdata object
861  *
862  * Returns:     ---
863  *
864  * Use:         Claim a new reference to a kdata object.
865  */
866
867 void km_ref(kdata *kd) { kd->ref++; }
868
869 /* --- @km_unref@ --- *
870  *
871  * Arguments:   @kdata *kd@ = pointer to the kdata object
872  *
873  * Returns:     ---
874  *
875  * Use:         Releases a reference to a kdata object.
876  */
877
878 void km_unref(kdata *kd)
879 {
880   if (--kd->ref) return;
881   if (kd->kpriv) mp_drop(kd->kpriv);
882   G_DESTROY(kd->g, kd->kpub);
883   xfree(kd->tag);
884   G_DESTROYGROUP(kd->g);
885 }
886
887 /*----- That's all, folks -------------------------------------------------*/