3 * Key loading and storing
5 * (c) 2001 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Trivial IP Encryption (TrIPE).
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.
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.
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.
27 /*----- Header files ------------------------------------------------------*/
31 /*----- Key groups --------------------------------------------------------*/
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.
39 typedef struct kgops
{
41 int (*loadpriv
)(key_data
*, kdata
*, dstr
*, dstr
*);
42 int (*loadpub
)(key_data
*, kdata
*, dstr
*, dstr
*);
45 /* --- Diffie-Hellman --- */
47 static int kgdh_priv(key_data
*d
, kdata
*kd
, dstr
*t
, dstr
*e
)
49 key_packstruct kps
[DH_PRIVFETCHSZ
];
54 kp
= key_fetchinit(dh_privfetch
, kps
, &dp
);
55 if ((rc
= key_unpack(kp
, d
, t
)) != 0) {
56 a_format(e
, "unpack-failed", "%s", key_strerror(rc
), A_END
);
59 kd
->g
= group_prime(&dp
.dp
);
60 kd
->kpriv
= MP_COPY(dp
.x
);
70 static int kgdh_pub(key_data
*d
, kdata
*kd
, dstr
*t
, dstr
*e
)
72 key_packstruct kps
[DH_PUBFETCHSZ
];
77 kp
= key_fetchinit(dh_pubfetch
, kps
, &dp
);
78 if ((rc
= key_unpack(kp
, d
, t
)) != 0) {
79 a_format(e
, "unpack-failed", "%s", key_strerror(rc
), A_END
);
82 kd
->g
= group_prime(&dp
.dp
);
83 kd
->kpub
= G_CREATE(kd
->g
);
84 if (G_FROMINT(kd
->g
, kd
->kpub
, dp
.y
)) {
85 a_format(e
, "bad-public-vector", A_END
);
91 G_DESTROY(kd
->g
, kd
->kpub
);
92 G_DESTROYGROUP(kd
->g
);
100 static const kgops kgdh_ops
= { "dh", kgdh_priv
, kgdh_pub
};
102 /* --- Elliptic curve --- */
104 static int kgec_priv(key_data
*d
, kdata
*kd
, dstr
*t
, dstr
*e
)
106 key_packstruct kps
[EC_PRIVFETCHSZ
];
113 kp
= key_fetchinit(ec_privfetch
, kps
, &ep
);
114 if ((rc
= key_unpack(kp
, d
, t
)) != 0) {
115 a_format(e
, "unpack-failed", "%s", key_strerror(rc
), A_END
);
118 if ((err
= ec_getinfo(&ei
, ep
.cstr
)) != 0) {
119 a_format(e
, "decode-failed", "%s", err
, A_END
);
122 kd
->g
= group_ec(&ei
);
123 kd
->kpriv
= MP_COPY(ep
.x
);
133 static int kgec_pub(key_data
*d
, kdata
*kd
, dstr
*t
, dstr
*e
)
135 key_packstruct kps
[EC_PUBFETCHSZ
];
142 kp
= key_fetchinit(ec_pubfetch
, kps
, &ep
);
143 if ((rc
= key_unpack(kp
, d
, t
)) != 0) {
144 a_format(e
, "unpack-failed", "%s", key_strerror(rc
), A_END
);
147 if ((err
= ec_getinfo(&ei
, ep
.cstr
)) != 0) {
148 a_format(e
, "decode-failed", "%s", err
, A_END
);
151 kd
->g
= group_ec(&ei
);
152 kd
->kpub
= G_CREATE(kd
->g
);
153 if (G_FROMEC(kd
->g
, kd
->kpub
, &ep
.p
)) {
154 a_format(e
, "bad-public-vector", A_END
);
160 G_DESTROY(kd
->g
, kd
->kpub
);
161 G_DESTROYGROUP(kd
->g
);
169 static const kgops kgec_ops
= { "ec", kgec_priv
, kgec_pub
};
171 /* --- Table of supported key types --- */
173 static const kgops
*kgtab
[] = { &kgdh_ops
, &kgec_ops
, 0 };
175 /*----- Algswitch stuff ---------------------------------------------------*/
177 /* --- @algs_get@ --- *
179 * Arguments: @algswitch *a@ = where to put the algorithms
180 * @dstr *e@ = where to write errror tokens
181 * @key_file *kf@ = key file
182 * @key *k@ = key to inspect
184 * Returns: Zero if OK; nonzero on error.
186 * Use: Extracts an algorithm choice from a key.
189 static int algs_get(algswitch
*a
, dstr
*e
, key_file
*kf
, key
*k
)
196 /* --- Symmetric encryption for bulk data --- */
198 if ((p
= key_getattr(kf
, k
, "cipher")) == 0) p
= "blowfish-cbc";
199 if ((a
->c
= gcipher_byname(p
)) == 0) {
200 a_format(e
, "unknown-cipher", "%s", p
, A_END
);
204 /* --- Hash function --- */
206 if ((p
= key_getattr(kf
, k
, "hash")) == 0) p
= "rmd160";
207 if ((a
->h
= ghash_byname(p
)) == 0) {
208 a_format(e
, "unknown-hash", "%s", p
, A_END
);
212 /* --- Symmetric encryption for key derivation --- */
214 if ((p
= key_getattr(kf
, k
, "mgf")) == 0) {
216 dstr_putf(&d
, "%s-mgf", a
->h
->name
);
219 if ((a
->mgf
= gcipher_byname(p
)) == 0) {
220 a_format(e
, "unknown-mgf-cipher", "%s", p
, A_END
);
224 /* --- Message authentication for bulk data --- */
226 if ((p
= key_getattr(kf
, k
, "mac")) != 0) {
229 if ((q
= strchr(d
.buf
, '/')) != 0)
231 if ((a
->m
= gmac_byname(d
.buf
)) == 0) {
232 a_format(e
, "unknown-mac", "%s", d
.buf
, A_END
);
236 a
->tagsz
= a
->m
->hashsz
;
238 unsigned long n
= strtoul(q
, &qq
, 0);
240 a_format(e
, "bad-tag-length-string", "%s", q
, A_END
);
243 if (n
%8 || n
/8 > a
->m
->hashsz
) {
244 a_format(e
, "bad-tag-length", "%lu", n
, A_END
);
251 dstr_putf(&d
, "%s-hmac", a
->h
->name
);
252 if ((a
->m
= gmac_byname(d
.buf
)) == 0) {
253 a_format(e
, "no-hmac-for-hash", "%s", a
->h
->name
, A_END
);
256 a
->tagsz
= a
->h
->hashsz
/2;
265 /* --- @algs_check@ --- *
267 * Arguments: @algswitch *a@ = a choice of algorithms
268 * @dstr *e@ = where to write error tokens
269 * @const group *g@ = the group we're working in
271 * Returns: Zero if OK; nonzero on error.
273 * Use: Checks an algorithm choice for sensibleness. This also
274 * derives some useful information from the choices, and you
275 * must call this before committing the algorithm selection
276 * for use by @keyset@ functions.
279 static int algs_check(algswitch
*a
, dstr
*e
, const group
*g
)
281 /* --- Derive the key sizes --- *
283 * Must ensure that we have non-empty keys. This isn't ideal, but it
284 * provides a handy sanity check. Also must be based on a 64- or 128-bit
285 * block cipher or we can't do the data expiry properly.
288 a
->hashsz
= a
->h
->hashsz
;
289 if ((a
->cksz
= keysz(a
->hashsz
, a
->c
->keysz
)) == 0) {
290 a_format(e
, "cipher", "%s", a
->c
->name
,
291 "no-key-size", "%lu", (unsigned long)a
->hashsz
,
295 if ((a
->mksz
= keysz(a
->hashsz
, a
->m
->keysz
)) == 0) {
296 a_format(e
, "mac", "%s", a
->m
->name
,
297 "no-key-size", "%lu", (unsigned long)a
->hashsz
,
302 /* --- Derive the data limit --- */
304 if (a
->c
->blksz
< 16) a
->expsz
= MEG(64);
305 else a
->expsz
= MEG(2048);
307 /* --- Ensure the MGF accepts hashes as keys --- */
309 if (keysz(a
->hashsz
, a
->mgf
->keysz
) != a
->hashsz
) {
310 a_format(e
, "mgf", "%s", a
->mgf
->name
,
311 "restrictive-key-schedule",
316 /* --- All ship-shape and Bristol-fashion --- */
321 /* --- @km_samealgsp@ --- *
323 * Arguments: @const kdata *kdx, *kdy@ = two key data objects
325 * Returns: Nonzero if their two algorithm selections are the same.
327 * Use: Checks sameness of algorithm selections: used to ensure that
328 * peers are using sensible algorithms.
331 int km_samealgsp(const kdata
*kdx
, const kdata
*kdy
)
333 const algswitch
*a
= &kdx
->algs
, *aa
= &kdy
->algs
;
335 return (group_samep(kdx
->g
, kdy
->g
) && a
->c
== aa
->c
&&
336 a
->mgf
== aa
->mgf
&& a
->h
== aa
->h
&&
337 a
->m
== aa
->m
&& a
->tagsz
== aa
->tagsz
);
340 /*----- Key data and key nodes --------------------------------------------*/
342 typedef struct keyhalf
{
344 int (*load
)(const kgops
*, key_data
*, kdata
*, dstr
*, dstr
*);
351 /* --- @kh_loadpub@, @kh_loadpriv@ --- *
353 * Arguments: @const kgops *ko@ = key-group operations for key type
354 * @key_data *d@ = key data object as stored in keyring
355 * @kdata *kd@ = our key-data object to fill in
356 * @dstr *t@ = the key tag name
357 * @dstr *e@ = a string to write error tokens to
359 * Returns: Zero on success, @-1@ on error.
361 * Use: These functions handle the main difference between public and
362 * private key halves. They are responsible for setting @g@,
363 * @kpriv@ and @kpub@ appropriately in all keys, handling the
364 * mismatch between the largely half-indifferent calling code
365 * and the group-specific loading functions.
367 * The function @kh_loadpriv@ is also responsible for checking
368 * the group for goodness. We don't bother checking public
369 * keys, because each public key we actually end up using must
370 * share a group with a private key which we'll already have
374 static int kh_loadpub(const kgops
*ko
, key_data
*d
, kdata
*kd
,
379 if ((rc
= ko
->loadpub(d
, kd
, t
, e
)) != 0)
381 if (group_check(kd
->g
, kd
->kpub
)) {
382 a_format(e
, "bad-public-group-element");
389 G_DESTROY(kd
->g
, kd
->kpub
);
390 G_DESTROYGROUP(kd
->g
);
395 static int kh_loadpriv(const kgops
*ko
, key_data
*d
, kdata
*kd
,
401 if ((rc
= ko
->loadpriv(d
, kd
, t
, e
)) != 0)
403 if ((err
= G_CHECK(kd
->g
, &rand_global
)) != 0) {
404 a_format(e
, "bad-group", "%s", err
, A_END
);
407 kd
->kpub
= G_CREATE(kd
->g
);
408 G_EXP(kd
->g
, kd
->kpub
, kd
->g
->g
, kd
->kpriv
);
413 G_DESTROYGROUP(kd
->g
);
418 static struct keyhalf
419 priv
= { "private", kh_loadpriv
},
420 pub
= { "public", kh_loadpub
};
422 /* --- @keymoan@ --- *
424 * Arguments: @const char *file@ = name of the file
425 * @int line@ = line number in file
426 * @const char *msg@ = error message
427 * @void *p@ = argument pointer (indicates which keyring)
431 * Use: Reports an error message about loading a key file.
434 static void keymoan(const char *file
, int line
, const char *msg
, void *p
)
439 a_warn("KEYMGMT", "%s-keyring", kh
->kind
, "%s", file
,
440 "io-error", "?ERRNO", A_END
);
442 a_warn("KEYMGMT", "%s-keyring", kh
->kind
, "%s", file
, "line", "%d", line
,
447 /* --- @kh_reopen@ --- *
449 * Arguments: @keyhalf *kh@ = pointer to keyhalf structure
451 * Returns: Zero on success, @-1@ on error.
453 * Use: Reopens the key file for the appropriate key half. If this
454 * fails, everything is left as it was; if it succeeds, then the
455 * old file is closed (if it was non-null) and the new one put
459 static int kh_reopen(keyhalf
*kh
)
461 key_file
*kf
= CREATE(key_file
);
463 if (key_open(kf
, kh
->kr
, KOPEN_READ
, keymoan
, kh
)) {
464 a_warn("KEYMGMT", "%s-keyring", kh
->kind
, "%s", kh
->kr
,
465 "io-error", "?ERRNO", A_END
);
478 /* --- @kh_init@ --- *
480 * Arguments: @keyhalf *kh@ = pointer to keyhalf structure to set up
481 * @const char *kr@ = name of the keyring file
485 * Use: Initialize a keyhalf structure, maintaining the private or
486 * public keys. Intended to be called during initialization:
487 * exits if there's some kind of problem.
490 static void kh_init(keyhalf
*kh
, const char *kr
)
493 fwatch_init(&kh
->w
, kr
);
494 sym_create(&kh
->tab
);
498 die(EXIT_FAILURE
, "failed to load %s keyring `%s'", kh
->kind
, kr
);
501 /* --- @kh_load@ --- *
503 * Arguments: @keyhalf *kh@ = pointer to keyhalf
504 * @const char *tag@ = key tag to be loaded
505 * @int complainp@ = whether to complain about missing keys
507 * Returns: Pointer to a @kdata@ structure if successful, or null on
510 * Use: Attempts to load a key from the current key file. This
511 * function always reads data from the file: it's used when
512 * there's a cache miss from @kh_find@, and when refreshing the
513 * known keys in @kh_refresh@. The returned kdata has a
514 * reference count of exactly 1, and has no home knode.
517 static kdata
*kh_load(keyhalf
*kh
, const char *tag
, int complainp
)
527 /* --- Find the key and grab its tag --- */
529 if (key_qtag(kh
->kf
, tag
, &t
, &k
, &d
)) {
531 a_warn("KEYMGMT", "%s-keyring", kh
->kind
, "%s", kh
->kr
,
532 "key-not-found", "%s", tag
, A_END
);
537 /* --- Find the key's group type and the appropriate operations --- *
539 * There are several places to look for the key type. The most obvious is
540 * the `kx-group' key attribute. But there's also the key type itself, for
541 * compatibility reasons.
544 ty
= key_getattr(kh
->kf
, k
, "kx-group");
545 if (!ty
&& strncmp(k
->type
, "tripe-", 6) == 0) ty
= k
->type
+ 6;
548 for (ko
= kgtab
; *ko
; ko
++)
549 if (strcmp((*ko
)->ty
, ty
) == 0) goto foundko
;
550 a_warn("KEYMGMT", "%s-keyring", kh
->kind
,
551 "%s", kh
->kr
, "key", "%s", t
.buf
,
552 "unknown-group-type", "%s", ty
, A_END
);
557 if (kh
->load(*ko
, *d
, kd
, &t
, &e
)) {
558 a_warn("KEYMGMT", "%s-keyring", kh
->kind
,
559 "%s", kh
->kr
, "key" "%s", t
.buf
,
560 "*%s", e
.buf
, A_END
);
564 if (algs_get(&kd
->algs
, &e
, kh
->kf
, k
) ||
565 (kd
->kpriv
&& algs_check(&kd
->algs
, &e
, kd
->g
))) {
566 a_warn("KEYMGMT", "%s-keyring", kh
->kind
,
567 "%s", kh
->kr
, "key", "%s", t
.buf
,
568 "*%s", e
.buf
, A_END
);
572 kd
->tag
= xstrdup(t
.buf
);
573 kd
->indexsz
= mp_octets(kd
->g
->r
);
578 IF_TRACING(T_KEYMGMT
, {
579 trace(T_KEYMGMT
, "keymgmt: loaded %s key `%s'", kh
->kind
, t
.buf
);
580 IF_TRACING(T_CRYPTO
, {
581 trace(T_CRYPTO
, "crypto: r = %s", mpstr(kd
->g
->r
));
582 trace(T_CRYPTO
, "crypto: h = %s", mpstr(kd
->g
->h
));
584 trace(T_CRYPTO
, "crypto: x = %s", mpstr(kd
->kpriv
));
585 trace(T_CRYPTO
, "crypto: cipher = %s", kd
->algs
.c
->name
);
586 trace(T_CRYPTO
, "crypto: mgf = %s", kd
->algs
.mgf
->name
);
587 trace(T_CRYPTO
, "crypto: hash = %s", kd
->algs
.h
->name
);
588 trace(T_CRYPTO
, "crypto: mac = %s/%lu",
589 kd
->algs
.m
->name
, (unsigned long)kd
->algs
.tagsz
* 8);
596 if (kd
->kpriv
) mp_drop(kd
->kpriv
);
597 G_DESTROY(kd
->g
, kd
->kpub
);
598 G_DESTROYGROUP(kd
->g
);
609 /* --- @kh_find@ --- *
611 * Arguments: @keyhalf *kh@ = pointer to the keyhalf
612 * @const char *tag@ = key to be obtained
613 * @int complainp@ = whether to complain about missing keys
615 * Returns: A pointer to the kdata, or null on error.
617 * Use: Obtains kdata, maybe from the cache. This won't update a
618 * stale cache entry, though @kh_refresh@ ought to have done
619 * that already. The returned kdata object may be shared with
620 * other users. (One of this function's responsibilities, over
621 * @kh_load@, is to set the home knode of a freshly loaded
625 static kdata
*kh_find(keyhalf
*kh
, const char *tag
, int complainp
)
631 kn
= sym_find(&kh
->tab
, tag
, -1, sizeof(knode
), &f
);
634 if (kn
->f
& KNF_BROKEN
) {
636 trace(T_KEYMGMT
, "keymgmt: key `%s' marked as broken", tag
); )
642 T( trace(T_KEYMGMT
, "keymgmt: %scache hit for key `%s'",
643 kd ?
"" : "negative ", tag
); )
646 kd
= kh_load(kh
, tag
, complainp
);
660 /* --- @kh_refresh@ --- *
662 * Arguments: @keyhalf *kh@ = pointer to the keyhalf
664 * Returns: Zero if nothing needs to be done; nonzero if peers should
665 * refresh their keys.
667 * Use: Refreshes cached keys from files.
669 * Each active knode is examined to see if a new key is
670 * available: the return value is nonzero if any new keys are.
671 * A key is considered new if its algorithms, public key, or
672 * expiry time are/is different.
674 * Stub knodes (with no kdata attached) are removed, so that a
675 * later retry can succeed if the file has been fixed. (This
676 * doesn't count as a change, since no peers should be relying
677 * on a nonexistent key.)
680 static int kh_refresh(keyhalf
*kh
)
687 if (!fwatch_update(&kh
->w
, kh
->kr
) || kh_reopen(kh
))
690 T( trace(T_KEYMGMT
, "keymgmt: rescan %s keyring `%s'", kh
->kind
, kh
->kr
); )
691 for (sym_mkiter(&i
, &kh
->tab
); (kn
= sym_next(&i
)) != 0; ) {
693 T( trace(T_KEYMGMT
, "keymgmt: discard stub entry for key `%s'",
695 sym_remove(&kh
->tab
, kn
);
698 if ((kd
= kh_load(kh
, SYM_NAME(kn
), 1)) == 0) {
699 if (!(kn
->f
& KNF_BROKEN
)) {
700 T( trace(T_KEYMGMT
, "keymgmt: failed to load new key `%s': "
701 "marking it as broken",
707 kn
->f
&= ~KNF_BROKEN
;
708 if (kd
->t_exp
== kn
->kd
->t_exp
&&
709 km_samealgsp(kd
, kn
->kd
) &&
710 G_EQ(kd
->g
, kd
->kpub
, kn
->kd
->kpub
)) {
711 T( trace(T_KEYMGMT
, "keymgmt: key `%s' unchanged", SYM_NAME(kn
)); )
714 T( trace(T_KEYMGMT
, "keymgmt: loaded new version of key `%s'",
725 /*----- Main code ---------------------------------------------------------*/
727 const char *tag_priv
;
730 /* --- @km_init@ --- *
732 * Arguments: @const char *privkr@ = private keyring file
733 * @const char *pubkr@ = public keyring file
734 * @const char *ptag@ = default private-key tag
738 * Use: Initializes the key-management machinery, loading the
739 * keyrings and so on.
742 void km_init(const char *privkr
, const char *pubkr
, const char *ptag
)
744 const gchash
*const *hh
;
746 for (hh
= ghashtab
; *hh
; hh
++) {
747 if ((*hh
)->hashsz
> MAXHASHSZ
) {
748 die(EXIT_FAILURE
, "INTERNAL ERROR: %s hash length %lu > MAXHASHSZ %d",
749 (*hh
)->name
, (unsigned long)(*hh
)->hashsz
, MAXHASHSZ
);
753 kh_init(&priv
, privkr
);
754 kh_init(&pub
, pubkr
);
757 if ((master
= km_findpriv(ptag
)) == 0) exit(EXIT_FAILURE
);
760 /* --- @km_reload@ --- *
764 * Returns: Zero if OK, nonzero to force reloading of keys.
766 * Use: Checks the keyrings to see if they need reloading.
774 if (kh_refresh(&priv
)) {
783 if (kh_refresh(&pub
))
788 /* --- @km_findpub@, @km_findpriv@ --- *
790 * Arguments: @const char *tag@ = key tag to load
792 * Returns: Pointer to the kdata object if successful, or null on error.
794 * Use: Fetches a public or private key from the keyring.
797 kdata
*km_findpub(const char *tag
) { return (kh_find(&pub
, tag
, 1)); }
799 kdata
*km_findpriv(const char *tag
)
803 /* Unpleasantness for the sake of compatibility. */
804 if (!tag
&& (kd
= kh_find(&priv
, "tripe", 0)) != 0) return (kd
);
805 else return (kh_find(&priv
, tag ? tag
: "tripe-dh", 1));
808 /* --- @km_tag@ --- *
810 * Arguments: @kdata *kd@ - pointer to the kdata object
812 * Returns: A pointer to the short tag by which the kdata was loaded.
815 const char *km_tag(kdata
*kd
) { return (SYM_NAME(kd
->kn
)); }
817 /* --- @km_ref@ --- *
819 * Arguments: @kdata *kd@ = pointer to the kdata object
823 * Use: Claim a new reference to a kdata object.
826 void km_ref(kdata
*kd
) { kd
->ref
++; }
828 /* --- @km_unref@ --- *
830 * Arguments: @kdata *kd@ = pointer to the kdata object
834 * Use: Releases a reference to a kdata object.
837 void km_unref(kdata
*kd
)
839 if (--kd
->ref
) return;
840 if (kd
->kpriv
) mp_drop(kd
->kpriv
);
841 G_DESTROY(kd
->g
, kd
->kpub
);
843 G_DESTROYGROUP(kd
->g
);
846 /*----- That's all, folks -------------------------------------------------*/