chiark / gitweb /
Merge branch '2.4.x' into 2.5.x
[catacomb] / progs / cc-kem.c
1 /* -*-c-*-
2  *
3  * Catcrypt key-encapsulation
4  *
5  * (c) 2004 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Catacomb.
11  *
12  * Catacomb is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Library General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * Catacomb 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 Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with Catacomb; if not, write to the Free
24  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25  * MA 02111-1307, USA.
26  */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #define _FILE_OFFSET_BITS 64
31
32 #include <stdlib.h>
33
34 #include <mLib/alloc.h>
35 #include <mLib/dstr.h>
36 #include <mLib/report.h>
37 #include <mLib/sub.h>
38
39 #include "gaead.h"
40 #include "mprand.h"
41 #include "rand.h"
42
43 #include "ec.h"
44 #include "ec-keys.h"
45 #include "dh.h"
46 #include "rsa.h"
47 #include "x25519.h"
48 #include "x448.h"
49
50 #include "rmd160.h"
51 #include "blowfish-cbc.h"
52 #include "chacha20-poly1305.h"
53 #include "poly1305.h"
54 #include "salsa20.h"
55 #include "chacha.h"
56
57 #include "cc.h"
58
59 /*----- Bulk crypto -------------------------------------------------------*/
60
61 /* --- Authenticated encryption schemes --- */
62
63 typedef struct aead_encctx {
64   bulk b;
65   const gcaead *aec;
66   gaead_key *key;
67   union { gaead_enc *enc; gaead_dec *dec; } ed;
68   octet *t;
69   size_t nsz, tsz;
70 } aead_encctx;
71
72 static bulk *aead_internalinit(key *k, const gcaead *aec)
73 {
74   aead_encctx *ctx = CREATE(aead_encctx);
75
76   ctx->key = 0;
77   ctx->aec = aec;
78   if ((ctx->nsz = keysz_pad(4, aec->noncesz)) == 0)
79     die(EXIT_FAILURE, "no suitable nonce size for `%s'", aec->name);
80   ctx->tsz = keysz(0, ctx->aec->tagsz);
81
82   return (&ctx->b);
83 }
84
85 static bulk *aead_init(key *k, const char *calg, const char *halg)
86 {
87   const gcaead *aec;
88   const char *q;
89   dstr t = DSTR_INIT;
90
91   key_fulltag(k, &t);
92
93   if ((q = key_getattr(0, k, "cipher")) != 0) calg = q;
94   if (!calg) aec = &chacha20_poly1305;
95   else if ((aec = gaead_byname(calg)) == 0)
96     die(EXIT_FAILURE, "AEAD scheme `%s' not found in key `%s'",
97         calg, t.buf);
98
99   dstr_destroy(&t);
100   return (aead_internalinit(k, aec));
101 }
102
103 static int aead_commonsetup(aead_encctx *ctx, gcipher *cx)
104 {
105   size_t ksz, n;
106
107   n = ksz = keysz(0, ctx->aec->keysz);
108   if (n < ctx->nsz) n = ctx->nsz;
109   if (n < ctx->tsz) n = ctx->tsz;
110   ctx->t = xmalloc(n);
111
112   GC_ENCRYPT(cx, 0, ctx->t, ksz);
113   ctx->key = GAEAD_KEY(ctx->aec, ctx->t, ksz);
114   return (0);
115 }
116
117 static size_t aead_overhead(bulk *b)
118   { aead_encctx *ctx = (aead_encctx *)b; return (ctx->aec->ohd + ctx->tsz); }
119
120 static void aead_commondestroy(aead_encctx *ctx)
121 {
122   if (ctx->key) GAEAD_DESTROY(ctx->key);
123   xfree(ctx->t);
124   DESTROY(ctx);
125 }
126
127 static int aead_encsetup(bulk *b, gcipher *cx)
128 {
129   aead_encctx *ctx = (aead_encctx *)b;
130   ctx->ed.enc = 0; return (aead_commonsetup(ctx, cx));
131 }
132
133 static const char *aead_encdoit(bulk *b, uint32 seq, buf *bb,
134                                 const void *p, size_t sz)
135 {
136   aead_encctx *ctx = (aead_encctx *)b;
137   octet *t;
138   int rc;
139
140   memset(ctx->t + 4, 0, ctx->nsz - 4); STORE32_B(ctx->t, seq);
141   if (!ctx->ed.enc)
142     ctx->ed.enc = GAEAD_ENC(ctx->key, ctx->t, ctx->nsz, 0, sz, ctx->tsz);
143   else
144     GAEAD_REINIT(ctx->ed.enc, ctx->t, ctx->nsz, 0, sz, ctx->tsz);
145   t = buf_get(bb, ctx->tsz); assert(t);
146   rc = GAEAD_ENCRYPT(ctx->ed.enc, p, sz, bb); assert(rc >= 0);
147   rc = GAEAD_DONE(ctx->ed.enc, 0, bb, t, ctx->tsz); assert(rc >= 0);
148   return (0);
149 }
150
151 static void aead_encdestroy(bulk *b)
152 {
153   aead_encctx *ctx = (aead_encctx *)b;
154   if (ctx->ed.enc) GAEAD_DESTROY(ctx->ed.enc);
155   aead_commondestroy(ctx);
156 }
157
158 static int aead_decsetup(bulk *b, gcipher *cx)
159 {
160   aead_encctx *ctx = (aead_encctx *)b;
161   ctx->ed.dec = 0; return (aead_commonsetup(ctx, cx));
162 }
163
164 static const char *aead_decdoit(bulk *b, uint32 seq, buf *bb,
165                                 const void *p, size_t sz)
166 {
167   aead_encctx *ctx = (aead_encctx *)b;
168   buf bin;
169   const octet *t;
170   int rc;
171
172   memset(ctx->t + 4, 0, ctx->nsz - 4); STORE32_B(ctx->t, seq);
173   if (!ctx->ed.dec)
174     ctx->ed.dec = GAEAD_DEC(ctx->key, ctx->t, ctx->nsz, 0, sz, ctx->tsz);
175   else
176     GAEAD_REINIT(ctx->ed.enc, ctx->t, ctx->nsz, 0, sz, ctx->tsz);
177
178   buf_init(&bin, (/*unconst*/ void *)p, sz);
179   t = buf_get(&bin, ctx->tsz); if (!t) return ("no tag");
180   rc = GAEAD_DECRYPT(ctx->ed.dec, BCUR(&bin), BLEFT(&bin), bb);
181   assert(rc >= 0);
182   rc = GAEAD_DONE(ctx->ed.dec, 0, bb, t, ctx->tsz); assert(rc >= 0);
183   if (!rc) return ("authentication failure");
184   return (0);
185 }
186
187 static void aead_decdestroy(bulk *b)
188 {
189   aead_encctx *ctx = (aead_encctx *)b;
190   if (ctx->ed.dec) GAEAD_DESTROY(ctx->ed.dec);
191   aead_commondestroy(ctx);
192 }
193
194 static const struct bulkops aead_encops = {
195   aead_init, aead_encsetup, aead_overhead,
196   aead_encdoit, aead_encdestroy
197 }, aead_decops = {
198   aead_init, aead_decsetup, aead_overhead,
199   aead_decdoit, aead_decdestroy
200 };
201
202 /* --- NaCl `secretbox' in terms of AEAD --- */
203
204 static bulk *naclbox_init(key *k, const char *calg, const char *halg)
205 {
206   const gcaead *aec;
207   dstr t = DSTR_INIT;
208   const char *q;
209
210   key_fulltag(k, &t);
211
212   if ((q = key_getattr(0, k, "cipher")) != 0) calg = q;
213   if (!calg || strcmp(calg, "salsa20") == 0) aec = &salsa20_naclbox;
214   else if (strcmp(calg, "salsa20/12") == 0) aec = &salsa2012_naclbox;
215   else if (strcmp(calg, "salsa20/8") == 0) aec = &salsa208_naclbox;
216   else if (strcmp(calg, "chacha20") == 0) aec = &chacha20_naclbox;
217   else if (strcmp(calg, "chacha12") == 0) aec = &chacha12_naclbox;
218   else if (strcmp(calg, "chacha8") == 0) aec = &chacha8_naclbox;
219   else {
220     die(EXIT_FAILURE,
221         "unknown or inappropriate encryption scheme `%s' in key `%s'",
222         calg, t.buf);
223   }
224
225   dstr_destroy(&t);
226   return (aead_internalinit(k, aec));
227 }
228
229 static const bulkops naclbox_encops = {
230   naclbox_init, aead_encsetup, aead_overhead,
231   aead_encdoit, aead_encdestroy
232 }, naclbox_decops = {
233   naclbox_init, aead_decsetup, aead_overhead,
234   aead_decdoit, aead_decdestroy
235 };
236
237 /* --- Generic composition --- */
238
239 typedef struct gencomp_encctx {
240   bulk b;
241   const gccipher *cc;
242   const gcmac *mc;
243   gcipher *c, *cx;
244   gmac *m;
245   octet *t; size_t tsz;
246 } gencomp_encctx;
247
248 static bulk *gencomp_init(key *k, const char *calg, const char *halg)
249 {
250   gencomp_encctx *ctx = CREATE(gencomp_encctx);
251   const char *q;
252   dstr d = DSTR_INIT, t = DSTR_INIT;
253
254   key_fulltag(k, &t);
255
256   if ((q = key_getattr(0, k, "cipher")) != 0) calg = q;
257   if (!calg) ctx->cc = &blowfish_cbc;
258   else if ((ctx->cc = gcipher_byname(calg)) == 0) {
259     die(EXIT_FAILURE, "encryption scheme `%s' not found in key `%s'",
260         calg, t.buf);
261   }
262
263   dstr_reset(&d);
264   if ((q = key_getattr(0, k, "mac")) == 0) {
265     dstr_putf(&d, "%s-hmac", halg);
266     q = d.buf;
267   }
268   if ((ctx->mc = gmac_byname(q)) == 0) {
269     die(EXIT_FAILURE,
270         "message authentication code `%s' not found in key `%s'",
271         q, t.buf);
272   }
273
274   return (&ctx->b);
275 }
276
277 static int gencomp_setup(bulk *b, gcipher *cx)
278 {
279   gencomp_encctx *ctx = (gencomp_encctx *)b;
280   size_t cn, mn, n;
281   octet *kd;
282
283   ctx->cx = cx;
284   n = ctx->cc->blksz;
285   cn = keysz(0, ctx->cc->keysz); if (cn > n) n = cn;
286   mn = keysz(0, ctx->mc->keysz); if (mn > n) n = mn;
287   ctx->t = kd = xmalloc(n); ctx->tsz = n;
288   GC_ENCRYPT(cx, 0, kd, cn);
289   ctx->c = GC_INIT(ctx->cc, kd, cn);
290   GC_ENCRYPT(cx, 0, kd, mn);
291   ctx->m = GM_KEY(ctx->mc, kd, mn);
292   return (0);
293 }
294
295 static size_t gencomp_overhead(bulk *b)
296 {
297   gencomp_encctx *ctx = (gencomp_encctx *)b;
298   return (ctx->cc->blksz + ctx->mc->hashsz); }
299
300 static void gencomp_destroy(bulk *b)
301 {
302   gencomp_encctx *ctx = (gencomp_encctx *)b;
303
304   GC_DESTROY(ctx->c);
305   GC_DESTROY(ctx->m);
306   xfree(ctx->t);
307   DESTROY(ctx);
308 }
309
310 static const char *gencomp_encdoit(bulk *b, uint32 seq, buf *bb,
311                                    const void *p, size_t sz)
312 {
313   gencomp_encctx *ctx = (gencomp_encctx *)b;
314   octet *tag, *ct;
315   ghash *h = GM_INIT(ctx->m);
316
317   GH_HASHU32(h, seq);
318   if (ctx->cc->blksz) {
319     GC_ENCRYPT(ctx->cx, 0, ctx->t, ctx->cc->blksz);
320     GC_SETIV(ctx->c, ctx->t);
321   }
322   tag = buf_get(bb, ctx->mc->hashsz); assert(tag);
323   ct = buf_get(bb, sz); assert(ct);
324   GC_ENCRYPT(ctx->c, p, ct, sz);
325   GH_HASH(h, ct, sz);
326   GH_DONE(h, tag);
327   GH_DESTROY(h);
328   return (0);
329 }
330
331 static const char *gencomp_decdoit(bulk *b, uint32 seq, buf *bb,
332                                    const void *p, size_t sz)
333 {
334   gencomp_encctx *ctx = (gencomp_encctx *)b;
335   buf bin;
336   const octet *tag, *ct;
337   octet *pt;
338   ghash *h;
339   int ok;
340
341   buf_init(&bin, (/*unconst*/ void *)p, sz);
342   if ((tag = buf_get(&bin, ctx->mc->hashsz)) == 0) return ("no tag");
343   ct = BCUR(&bin); sz = BLEFT(&bin);
344   pt = buf_get(bb, sz); assert(pt);
345
346   h = GM_INIT(ctx->m);
347   GH_HASHU32(h, seq);
348   GH_HASH(h, ct, sz);
349   ok = ct_memeq(tag, GH_DONE(h, 0), ctx->mc->hashsz);
350   GH_DESTROY(h);
351   if (!ok) return ("authentication failure");
352
353   if (ctx->cc->blksz) {
354     GC_ENCRYPT(ctx->cx, 0, ctx->t, ctx->cc->blksz);
355     GC_SETIV(ctx->c, ctx->t);
356   }
357   GC_DECRYPT(ctx->c, ct, pt, sz);
358   return (0);
359 }
360
361 static const bulkops gencomp_encops = {
362   gencomp_init, gencomp_setup, gencomp_overhead,
363   gencomp_encdoit, gencomp_destroy
364 }, gencomp_decops = {
365   gencomp_init, gencomp_setup, gencomp_overhead,
366   gencomp_decdoit, gencomp_destroy
367 };
368
369 const struct bulktab bulktab[] = {
370   { "gencomp",  &gencomp_encops,        &gencomp_decops },
371   { "naclbox",  &naclbox_encops,        &naclbox_decops },
372   { "aead",     &aead_encops,           &aead_decops },
373   { 0,          0,                      0 }
374 };
375
376 /*----- Key encapsulation -------------------------------------------------*/
377
378 /* --- RSA --- */
379
380 typedef struct rsa_encctx {
381   kem k;
382   rsa_pubctx rp;
383 } rsa_encctx;
384
385 static kem *rsa_encinit(key *k, void *kd)
386 {
387   rsa_encctx *re = CREATE(rsa_encctx);
388   rsa_pubcreate(&re->rp, kd);
389   return (&re->k);
390 }
391
392 static int rsa_encdoit(kem *k, dstr *d, ghash *h)
393 {
394   rsa_encctx *re = (rsa_encctx *)k;
395   mp *x = mprand_range(MP_NEW, re->rp.rp->n, &rand_global, 0);
396   mp *y = rsa_pubop(&re->rp, MP_NEW, x);
397   size_t n = mp_octets(re->rp.rp->n);
398   dstr_ensure(d, n);
399   mp_storeb(x, d->buf, n);
400   GH_HASH(h, d->buf, n);
401   mp_storeb(y, d->buf, n);
402   d->len += n;
403   mp_drop(x);
404   mp_drop(y);
405   return (0);
406 }
407
408 static const char *rsa_lengthcheck(mp *n)
409 {
410   if (mp_bits(n) < 1020) return ("key too short");
411   return (0);
412 }
413
414 static const char *rsa_enccheck(kem *k)
415 {
416   rsa_encctx *re = (rsa_encctx *)k;
417   const char *e;
418   if ((e = rsa_lengthcheck(re->rp.rp->n)) != 0) return (e);
419   return (0);
420 }
421
422 static void rsa_encdestroy(kem *k)
423 {
424   rsa_encctx *re = (rsa_encctx *)k;
425   rsa_pubdestroy(&re->rp);
426   DESTROY(re);
427 }
428
429 static const kemops rsa_encops = {
430   rsa_pubfetch, sizeof(rsa_pub),
431   rsa_encinit, rsa_encdoit, rsa_enccheck, rsa_encdestroy
432 };
433
434 typedef struct rsa_decctx {
435   kem k;
436   rsa_privctx rp;
437 } rsa_decctx;
438
439 static kem *rsa_decinit(key *k, void *kd)
440 {
441   rsa_decctx *rd = CREATE(rsa_decctx);
442   rsa_privcreate(&rd->rp, kd, &rand_global);
443   return (&rd->k);
444 }
445
446 static int rsa_decdoit(kem *k, dstr *d, ghash *h)
447 {
448   rsa_decctx *rd = (rsa_decctx *)k;
449   mp *x = mp_loadb(MP_NEW, d->buf, d->len);
450   size_t n;
451   char *p;
452
453   if (MP_CMP(x, >=, rd->rp.rp->n)) {
454     mp_drop(x);
455     return (-1);
456   }
457   n = mp_octets(rd->rp.rp->n);
458   p = xmalloc(n);
459   x = rsa_privop(&rd->rp, x, x);
460   mp_storeb(x, p, n);
461   GH_HASH(h, p, n);
462   mp_drop(x);
463   xfree(p);
464   return (0);
465 }
466
467 static const char *rsa_deccheck(kem *k)
468 {
469   rsa_decctx *rd = (rsa_decctx *)k;
470   const char *e;
471   if ((e = rsa_lengthcheck(rd->rp.rp->n)) != 0) return (e);
472   return (0);
473 }
474
475 static void rsa_decdestroy(kem *k)
476 {
477   rsa_decctx *rd = (rsa_decctx *)k;
478   rsa_privdestroy(&rd->rp);
479   DESTROY(rd);
480 }
481
482 static const kemops rsa_decops = {
483   rsa_privfetch, sizeof(rsa_priv),
484   rsa_decinit, rsa_decdoit, rsa_deccheck, rsa_decdestroy
485 };
486
487 /* --- DH and EC --- */
488
489 typedef struct dh_encctx {
490   kem k;
491   group *g;
492   mp *x;
493   ge *y;
494 } dh_encctx;
495
496 static dh_encctx *dh_doinit(key *k, const gprime_param *gp, mp *y,
497                             group *(*makegroup)(const gprime_param *),
498                             const char *what)
499 {
500   dh_encctx *de = CREATE(dh_encctx);
501   dstr t = DSTR_INIT;
502
503   key_fulltag(k, &t);
504   if ((de->g = makegroup(gp)) == 0)
505     die(EXIT_FAILURE, "bad %s group in key `%s'", what, t.buf);
506   de->x = MP_NEW;
507   de->y = G_CREATE(de->g);
508   if (G_FROMINT(de->g, de->y, y))
509     die(EXIT_FAILURE, "bad public key `%s'", t.buf);
510   dstr_destroy(&t);
511   return (de);
512 }
513
514 static dh_encctx *ec_doinit(key *k, const char *cstr, const ec *y)
515 {
516   dh_encctx *de = CREATE(dh_encctx);
517   ec_info ei;
518   const char *e;
519   dstr t = DSTR_INIT;
520
521   key_fulltag(k, &t);
522   if ((e = ec_getinfo(&ei, cstr)) != 0 ||
523       (de->g = group_ec(&ei)) == 0)
524     die(EXIT_FAILURE, "bad elliptic curve spec in key `%s': %s", t.buf, e);
525   de->x = MP_NEW;
526   de->y = G_CREATE(de->g);
527   if (G_FROMEC(de->g, de->y, y))
528     die(EXIT_FAILURE, "bad public curve point `%s'", t.buf);
529   dstr_destroy(&t);
530   return (de);
531 }
532
533 static kem *dh_encinit(key *k, void *kd)
534 {
535   dh_pub *dp = kd;
536   dh_encctx *de = dh_doinit(k, &dp->dp, dp->y, group_prime, "prime");
537   return (&de->k);
538 }
539
540 static kem *bindh_encinit(key *k, void *kd)
541 {
542   dh_pub *dp = kd;
543   dh_encctx *de = dh_doinit(k, &dp->dp, dp->y, group_binary, "binary");
544   return (&de->k);
545 }
546
547 static kem *ec_encinit(key *k, void *kd)
548 {
549   ec_pub *ep = kd;
550   dh_encctx *de = ec_doinit(k, ep->cstr, &ep->p);
551   return (&de->k);
552 }
553
554 static int dh_encdoit(kem *k, dstr *d, ghash *h)
555 {
556   dh_encctx *de = (dh_encctx *)k;
557   mp *r = mprand_range(MP_NEW, de->g->r, &rand_global, 0);
558   ge *x = G_CREATE(de->g);
559   ge *y = G_CREATE(de->g);
560   size_t n = de->g->noctets;
561   buf b;
562
563   G_EXP(de->g, x, de->g->g, r);
564   G_EXP(de->g, y, de->y, r);
565   dstr_ensure(d, n);
566   buf_init(&b, d->buf, n);
567   G_TORAW(de->g, &b, y);
568   GH_HASH(h, BBASE(&b), BLEN(&b));
569   buf_init(&b, d->buf, n);
570   G_TORAW(de->g, &b, x);
571   GH_HASH(h, BBASE(&b), BLEN(&b));
572   d->len += BLEN(&b);
573   mp_drop(r);
574   G_DESTROY(de->g, x);
575   G_DESTROY(de->g, y);
576   return (0);
577 }
578
579 static const char *dh_enccheck(kem *k)
580 {
581   dh_encctx *de = (dh_encctx *)k;
582   const char *e;
583   if ((e = G_CHECK(de->g, &rand_global)) != 0)
584     return (0);
585   if (group_check(de->g, de->y))
586     return ("public key not in subgroup");
587   return (0);
588 }
589
590 static void dh_encdestroy(kem *k)
591 {
592   dh_encctx *de = (dh_encctx *)k;
593   G_DESTROY(de->g, de->y);
594   mp_drop(de->x);
595   G_DESTROYGROUP(de->g);
596   DESTROY(de);
597 }
598
599 static const kemops dh_encops = {
600   dh_pubfetch, sizeof(dh_pub),
601   dh_encinit, dh_encdoit, dh_enccheck, dh_encdestroy
602 };
603
604 static const kemops bindh_encops = {
605   dh_pubfetch, sizeof(dh_pub),
606   bindh_encinit, dh_encdoit, dh_enccheck, dh_encdestroy
607 };
608
609 static const kemops ec_encops = {
610   ec_pubfetch, sizeof(ec_pub),
611   ec_encinit, dh_encdoit, dh_enccheck, dh_encdestroy
612 };
613
614 static kem *dh_decinit(key *k, void *kd)
615 {
616   dh_priv *dp = kd;
617   dh_encctx *de = dh_doinit(k, &dp->dp, dp->y, group_prime, "prime");
618   de->x = MP_COPY(dp->x);
619   return (&de->k);
620 }
621
622 static kem *bindh_decinit(key *k, void *kd)
623 {
624   dh_priv *dp = kd;
625   dh_encctx *de = dh_doinit(k, &dp->dp, dp->y, group_binary, "binary");
626   de->x = MP_COPY(dp->x);
627   return (&de->k);
628 }
629
630 static kem *ec_decinit(key *k, void *kd)
631 {
632   ec_priv *ep = kd;
633   dh_encctx *de = ec_doinit(k, ep->cstr, &ep->p);
634   de->x = MP_COPY(ep->x);
635   return (&de->k);
636 }
637
638 static int dh_decdoit(kem *k, dstr *d, ghash *h)
639 {
640   dh_encctx *de = (dh_encctx *)k;
641   ge *x = G_CREATE(de->g);
642   size_t n = de->g->noctets;
643   void *p = xmalloc(n);
644   buf b;
645   int rc = -1;
646
647   buf_init(&b, d->buf, d->len);
648   if (G_FROMRAW(de->g, &b, x) || group_check(de->g, x))
649     goto done;
650   G_EXP(de->g, x, x, de->x);
651   buf_init(&b, p, n);
652   G_TORAW(de->g, &b, x);
653   GH_HASH(h, BBASE(&b), BLEN(&b));
654   GH_HASH(h, d->buf, d->len);
655   rc = 0;
656 done:
657   G_DESTROY(de->g, x);
658   xfree(p);
659   return (rc);
660 }
661
662 static const kemops dh_decops = {
663   dh_privfetch, sizeof(dh_priv),
664   dh_decinit, dh_decdoit, dh_enccheck, dh_encdestroy
665 };
666
667 static const kemops bindh_decops = {
668   dh_privfetch, sizeof(dh_priv),
669   bindh_decinit, dh_decdoit, dh_enccheck, dh_encdestroy
670 };
671
672 static const kemops ec_decops = {
673   ec_privfetch, sizeof(ec_priv),
674   ec_decinit, dh_decdoit, dh_enccheck, dh_encdestroy
675 };
676
677 /* --- X25519 and similar schemes --- */
678
679 #define XDHS(_)                                                         \
680   _(x25519, X25519)                                                     \
681   _(x448, X448)
682
683 #define XDHDEF(xdh, XDH)                                                \
684                                                                         \
685   static kem *xdh##_encinit(key *k, void *kd) { return (CREATE(kem)); } \
686   static void xdh##_encdestroy(kem *k) { DESTROY(k); }                  \
687                                                                         \
688   static const char *xdh##_enccheck(kem *k)                             \
689   {                                                                     \
690     xdh##_pub *kd = k->kd;                                              \
691                                                                         \
692     if (kd->pub.sz != XDH##_PUBSZ)                                      \
693       return ("incorrect " #XDH "public key length");                   \
694     return (0);                                                         \
695   }                                                                     \
696                                                                         \
697   static int xdh##_encdoit(kem *k, dstr *d, ghash *h)                   \
698   {                                                                     \
699     octet t[XDH##_KEYSZ], z[XDH##_OUTSZ];                               \
700     xdh##_pub *kd = k->kd;                                              \
701                                                                         \
702     rand_get(RAND_GLOBAL, t, sizeof(t));                                \
703     dstr_ensure(d, XDH##_PUBSZ);                                        \
704     xdh((octet *)d->buf, t, xdh##_base);                                \
705     xdh(z, t, kd->pub.k);                                               \
706     d->len += XDH##_PUBSZ;                                              \
707     GH_HASH(h, d->buf, XDH##_PUBSZ);                                    \
708     GH_HASH(h, z, XDH##_OUTSZ);                                         \
709     return (0);                                                         \
710   }                                                                     \
711                                                                         \
712   static const char *xdh##_deccheck(kem *k)                             \
713   {                                                                     \
714     xdh##_priv *kd = k->kd;                                             \
715                                                                         \
716     if (kd->priv.sz != XDH##_KEYSZ)                                     \
717       return ("incorrect " #XDH " private key length");                 \
718     if (kd->pub.sz != XDH##_PUBSZ)                                      \
719       return ("incorrect " #XDH " public key length");                  \
720     return (0);                                                         \
721   }                                                                     \
722                                                                         \
723   static int xdh##_decdoit(kem *k, dstr *d, ghash *h)                   \
724   {                                                                     \
725     octet z[XDH##_OUTSZ];                                               \
726     xdh##_priv *kd = k->kd;                                             \
727     int rc = -1;                                                        \
728                                                                         \
729     if (d->len != XDH##_PUBSZ) goto done;                               \
730     xdh(z, kd->priv.k, (const octet *)d->buf);                          \
731     GH_HASH(h, d->buf, XDH##_PUBSZ);                                    \
732     GH_HASH(h, z, XDH##_OUTSZ);                                         \
733     rc = 0;                                                             \
734   done:                                                                 \
735     return (rc);                                                        \
736   }                                                                     \
737                                                                         \
738   static const kemops xdh##_encops = {                                  \
739     xdh##_pubfetch, sizeof(xdh##_pub),                                  \
740     xdh##_encinit, xdh##_encdoit, xdh##_enccheck, xdh##_encdestroy      \
741   };                                                                    \
742                                                                         \
743   static const kemops xdh##_decops = {                                  \
744     xdh##_privfetch, sizeof(xdh##_priv),                                \
745     xdh##_encinit, xdh##_decdoit, xdh##_deccheck, xdh##_encdestroy      \
746   };
747
748 XDHS(XDHDEF)
749 #undef XDHDEF
750
751 /* --- Symmetric --- */
752
753 typedef struct symm_ctx {
754   kem k;
755   key_packdef kp;
756   key_bin kb;
757 } symm_ctx;
758
759 static kem *symm_init(key *k, void *kd)
760 {
761   symm_ctx *s;
762   dstr d = DSTR_INIT;
763   int err;
764
765   s = CREATE(symm_ctx);
766
767   key_fulltag(k, &d);
768   s->kp.e = KENC_BINARY;
769   s->kp.p = &s->kb;
770   s->kp.kd = 0;
771
772   if ((err = key_unpack(&s->kp, kd, &d)) != 0) {
773     die(EXIT_FAILURE, "failed to unpack symmetric key `%s': %s",
774         d.buf, key_strerror(err));
775   }
776   dstr_destroy(&d);
777   return (&s->k);
778 }
779
780 static int symm_decdoit(kem *k, dstr *d, ghash *h)
781 {
782   symm_ctx *s = (symm_ctx *)k;
783
784   GH_HASH(h, s->kb.k, s->kb.sz);
785   GH_HASH(h, d->buf, d->len);
786   return (0);
787 }
788
789 static int symm_encdoit(kem *k, dstr *d, ghash *h)
790 {
791   dstr_ensure(d, h->ops->c->hashsz);
792   d->len += h->ops->c->hashsz;
793   rand_get(RAND_GLOBAL, d->buf, d->len);
794   return (symm_decdoit(k, d, h));
795 }
796
797 static const char *symm_check(kem *k) { return (0); }
798
799 static void symm_destroy(kem *k)
800   { symm_ctx *s = (symm_ctx *)k; key_unpackdone(&s->kp); }
801
802 static const kemops symm_encops = {
803   0, 0,
804   symm_init, symm_encdoit, symm_check, symm_destroy
805 };
806
807 static const kemops symm_decops = {
808   0, 0,
809   symm_init, symm_decdoit, symm_check, symm_destroy
810 };
811
812 /* --- The switch table --- */
813
814 const struct kemtab kemtab[] = {
815   { "rsa",      &rsa_encops,    &rsa_decops },
816   { "dh",       &dh_encops,     &dh_decops },
817   { "bindh",    &bindh_encops,  &bindh_decops },
818   { "ec",       &ec_encops,     &ec_decops },
819 #define XDHTAB(xdh, XDH)                                                \
820   { #xdh,       &xdh##_encops,  &xdh##_decops },
821   XDHS(XDHTAB)
822 #undef XDHTAB
823   { "symm",     &symm_encops,   &symm_decops },
824   { 0,          0,              0 }
825 };
826
827 /* --- @getkem@ --- *
828  *
829  * Arguments:   @key *k@ = the key to load
830  *              @const char *app@ = application name
831  *              @int wantpriv@ = nonzero if we want to decrypt
832  *              @bulk **bc@ = bulk crypto context to set up
833  *
834  * Returns:     A key-encapsulating thing.
835  *
836  * Use:         Loads a key.
837  */
838
839 kem *getkem(key *k, const char *app, int wantpriv, bulk **bc)
840 {
841   const char *kalg, *halg = 0, *balg = 0;
842   dstr d = DSTR_INIT;
843   dstr t = DSTR_INIT;
844   size_t n;
845   char *p = 0;
846   const char *q;
847   kem *kk;
848   const struct kemtab *kt;
849   const kemops *ko;
850   const struct bulktab *bt;
851   const bulkops *bo;
852   void *kd;
853   int e;
854   key_packdef *kp;
855
856   /* --- Setup stuff --- */
857
858   key_fulltag(k, &t);
859
860   /* --- Get the KEM name --- *
861    *
862    * Take the attribute if it's there; otherwise use the key type.
863    */
864
865   n = strlen(app);
866   if ((q = key_getattr(0, k, "kem")) != 0) {
867     dstr_puts(&d, q);
868     p = d.buf;
869   } else if (strncmp(k->type, app, n) == 0 && k->type[n] == '-') {
870     dstr_puts(&d, k->type);
871     p = d.buf + n + 1;
872   } else
873     die(EXIT_FAILURE, "no KEM for key `%s'", t.buf);
874   kalg = p;
875
876   /* --- Grab the bulk encryption scheme --- *
877    *
878    * Grab it from the KEM if it's there, but override it from the attribute.
879    */
880
881   if (p && (p = strchr(p, '/')) != 0) {
882     *p++ = 0;
883     balg = p;
884   }
885   if ((q = key_getattr(0, k, "bulk")) != 0)
886     balg = q;
887
888   /* --- Grab the hash function --- */
889
890   if (p && (p = strchr(p, '/')) != 0) {
891     *p++ = 0;
892     halg = p;
893   }
894   if ((q = key_getattr(0, k, "hash")) != 0)
895     halg = q;
896
897   /* --- Instantiate the KEM --- */
898
899   for (kt = kemtab; kt->name; kt++) {
900     if (strcmp(kt->name, kalg) == 0)
901       goto k_found;
902   }
903   die(EXIT_FAILURE, "key encapsulation mechanism `%s' not found in key `%s'",
904       kalg, t.buf);
905 k_found:;
906   ko = wantpriv ? kt->decops : kt->encops;
907   if (!ko->kf) {
908     kd = k->k;
909     key_incref(kd);
910     kp = 0;
911   } else {
912     kd = xmalloc(ko->kdsz);
913     kp = key_fetchinit(ko->kf, 0, kd);
914     if ((e = key_fetch(kp, k)) != 0) {
915       die(EXIT_FAILURE, "error fetching key `%s': %s",
916           t.buf, key_strerror(e));
917     }
918   }
919   kk = ko->init(k, kd);
920   kk->kp = kp;
921   kk->ops = ko;
922   kk->kd = kd;
923
924   /* --- Set up the bulk crypto --- */
925
926   if (!halg)
927     kk->hc = &rmd160;
928   else if ((kk->hc = ghash_byname(halg)) == 0) {
929     die(EXIT_FAILURE, "hash algorithm `%s' not found in key `%s'",
930         halg, t.buf);
931   }
932
933   if (!balg)
934     bt = bulktab;
935   else {
936     for (bt = bulktab, bo = 0; bt->name; bt++) {
937       if (strcmp(balg, bt->name) == 0)
938         { balg = 0; goto b_found; }
939       n = strlen(bt->name);
940       if (strncmp(balg, bt->name, n) == 0 && balg[n] == '-')
941         { balg += n + 1; goto b_found; }
942     }
943     bt = bulktab;
944   b_found:;
945   }
946   bo = wantpriv ? bt->decops : bt->encops;
947   *bc = bo->init(k, balg, kk->hc->name);
948   (*bc)->ops = bo;
949
950   dstr_reset(&d);
951   if ((q = key_getattr(0, k, "kdf")) == 0) {
952     dstr_putf(&d, "%s-mgf", kk->hc->name);
953     q = d.buf;
954   }
955   if ((kk->cxc = gcipher_byname(q)) == 0) {
956     die(EXIT_FAILURE, "encryption scheme (KDF) `%s' not found in key `%s'",
957         q, t.buf);
958   }
959
960   /* --- Tidy up --- */
961
962   dstr_destroy(&d);
963   dstr_destroy(&t);
964   return (kk);
965 }
966
967 /* --- @setupkem@ --- *
968  *
969  * Arguments:   @kem *k@ = key-encapsulation thing
970  *              @dstr *d@ = key-encapsulation data
971  *              @bulk *bc@ = bulk crypto context to set up
972  *
973  * Returns:     Zero on success, nonzero on failure.
974  *
975  * Use:         Initializes all the various symmetric things from a KEM.
976  */
977
978 int setupkem(kem *k, dstr *d, bulk *bc)
979 {
980   octet *kd;
981   size_t n;
982   ghash *h;
983   int rc = -1;
984
985   h = GH_INIT(k->hc);
986   if (k->ops->doit(k, d, h))
987     goto done;
988   n = keysz(GH_CLASS(h)->hashsz, k->cxc->keysz);
989   if (!n)
990     goto done;
991   kd = GH_DONE(h, 0);
992   k->cx = GC_INIT(k->cxc, kd, n);
993   bc->ops->setup(bc, k->cx);
994
995   rc = 0;
996 done:
997   GH_DESTROY(h);
998   return (rc);
999 }
1000
1001 /* --- @freekem@ --- *
1002  *
1003  * Arguments:   @kem *k@ = key-encapsulation thing
1004  *
1005  * Returns:     ---
1006  *
1007  * Use:         Frees up a key-encapsulation thing.
1008  */
1009
1010 void freekem(kem *k)
1011 {
1012   if (!k->ops->kf)
1013     key_drop(k->kd);
1014   else {
1015     key_fetchdone(k->kp);
1016     xfree(k->kd);
1017   }
1018   GC_DESTROY(k->cx);
1019   k->ops->destroy(k);
1020 }
1021
1022 /*----- That's all, folks -------------------------------------------------*/