chiark / gitweb /
server/bulkcrypto.c: Support smaller nonce spaces, down to 40 bits.
[tripe] / server / bulkcrypto.c
1 /* -*-c-*-
2  *
3  * Bulk crypto transformations
4  *
5  * (c) 2014 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 it under
13  * the terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your
15  * option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20  * for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
24  */
25
26 /*----- Header files ------------------------------------------------------*/
27
28 #include "tripe.h"
29
30 /*----- Utilities ---------------------------------------------------------*/
31
32 #define SEQSZ 4                         /* Size of sequence number packet */
33
34 #define TRACE_IV(qiv, ivsz) do { IF_TRACING(T_KEYSET, {                 \
35   trace_block(T_CRYPTO, "crypto: initialization vector",                \
36               (qiv), (ivsz));                                           \
37 }) } while (0)
38
39 #define TRACE_CT(qpk, sz) do { IF_TRACING(T_KEYSET, {                   \
40   trace_block(T_CRYPTO, "crypto: encrypted packet", (qpk), (sz));       \
41 }) } while (0)
42
43 #define TRACE_MAC(qmac, tagsz) do { IF_TRACING(T_KEYSET, {              \
44   trace_block(T_CRYPTO, "crypto: computed MAC", (qmac), (tagsz));       \
45 }) } while (0)
46
47 #define TRACE_MACERR(pmac, tagsz) do { IF_TRACING(T_KEYSET, {           \
48   trace(T_KEYSET, "keyset: incorrect MAC: decryption failed");          \
49   trace_block(T_CRYPTO, "crypto: provided MAC", (pmac), (tagsz));       \
50 }) } while (0)
51
52 /* --- @derivekey@ --- *
53  *
54  * Arguments:   @octet *k@ = pointer to an output buffer of at least
55  *                      @MAXHASHSZ@ bytes
56  *              @size_t ksz@ = actual size wanted (for tracing)
57  *              @const deriveargs@ = derivation parameters, as passed into
58  *                      @genkeys@
59  *              @int dir@ = direction for the key (@DIR_IN@ or @DIR_OUT@)
60  *              @const char *what@ = label for the key (input to derivation)
61  *
62  * Returns:     ---
63  *
64  * Use:         Derives a session key, for use on incoming or outgoing data.
65  */
66
67 static void derivekey(octet *k, size_t ksz, const deriveargs *a,
68                       int dir, const char *what)
69 {
70   const gchash *hc = a->hc;
71   ghash *h;
72
73   assert(ksz <= hc->hashsz);
74   assert(hc->hashsz <= MAXHASHSZ);
75   h = GH_INIT(hc);
76   GH_HASH(h, a->what, strlen(a->what)); GH_HASH(h, what, strlen(what) + 1);
77   switch (dir) {
78     case DIR_IN:
79       if (a->x) GH_HASH(h, a->k, a->x);
80       if (a->y != a->x) GH_HASH(h, a->k + a->x, a->y - a->x);
81       break;
82     case DIR_OUT:
83       if (a->y != a->x) GH_HASH(h, a->k + a->x, a->y - a->x);
84       if (a->x) GH_HASH(h, a->k, a->x);
85       break;
86     default:
87       abort();
88   }
89   GH_HASH(h, a->k + a->y, a->z - a->y);
90   GH_DONE(h, k);
91   GH_DESTROY(h);
92   IF_TRACING(T_KEYSET, { IF_TRACING(T_CRYPTO, {
93     char _buf[32];
94     sprintf(_buf, "crypto: %s key %s", dir ? "outgoing" : "incoming", what);
95     trace_block(T_CRYPTO, _buf, k, ksz);
96   }) })
97 }
98
99 /*----- Common functionality for generic-composition transforms -----------*/
100
101 #define CHECK_MAC(h, pmac, tagsz) do {                                  \
102   ghash *_h = (h);                                                      \
103   const octet *_pmac = (pmac);                                          \
104   size_t _tagsz = (tagsz);                                              \
105   octet *_mac = GH_DONE(_h, 0);                                         \
106   int _eq = ct_memeq(_mac, _pmac, _tagsz);                              \
107   TRACE_MAC(_mac, _tagsz);                                              \
108   GH_DESTROY(_h);                                                       \
109   if (!_eq) {                                                           \
110     TRACE_MACERR(_pmac, _tagsz);                                        \
111     return (KSERR_DECRYPT);                                             \
112   }                                                                     \
113 } while (0)
114
115 typedef struct gencomp_algs {
116   const gccipher *c; size_t cksz;
117   const gcmac *m; size_t mksz; size_t tagsz;
118 } gencomp_algs;
119
120 typedef struct gencomp_chal {
121   bulkchal _b;
122   gmac *m;
123 } gencomp_chal;
124
125 static int gencomp_getalgs(gencomp_algs *a, const algswitch *asw,
126                            dstr *e, key_file *kf, key *k)
127 {
128   const char *p;
129   char *q, *qq;
130   unsigned long n;
131   dstr d = DSTR_INIT;
132   int rc = -1;
133
134   /* --- Symmetric encryption --- */
135
136   if ((p = key_getattr(kf, k, "cipher")) == 0) p = "blowfish-cbc";
137   if ((a->c = gcipher_byname(p)) == 0) {
138     a_format(e, "unknown-cipher", "%s", p, A_END);
139     goto done;
140   }
141
142   /* --- Message authentication --- */
143
144   if ((p = key_getattr(kf, k, "mac")) != 0) {
145     dstr_reset(&d);
146     dstr_puts(&d, p);
147     if ((q = strrchr(d.buf, '/')) != 0)
148       *q++ = 0;
149     if ((a->m = gmac_byname(d.buf)) == 0) {
150       a_format(e, "unknown-mac", "%s", d.buf, A_END);
151       goto done;
152     }
153     if (!q)
154       a->tagsz = a->m->hashsz;
155     else {
156       n = strtoul(q, &qq, 0);
157       if (*qq)  {
158         a_format(e, "bad-tag-length-string", "%s", q, A_END);
159         goto done;
160       }
161       if (n%8 || n/8 > a->m->hashsz) {
162         a_format(e, "bad-tag-length", "%lu", n, A_END);
163         goto done;
164       }
165       a->tagsz = n/8;
166     }
167   } else {
168     dstr_reset(&d);
169     dstr_putf(&d, "%s-hmac", asw->h->name);
170     if ((a->m = gmac_byname(d.buf)) == 0) {
171       a_format(e, "no-hmac-for-hash", "%s", asw->h->name, A_END);
172       goto done;
173     }
174     a->tagsz = asw->h->hashsz/2;
175   }
176
177   rc = 0;
178 done:
179   dstr_destroy(&d);
180   return (rc);
181 }
182
183 #ifndef NTRACE
184 static void gencomp_tracealgs(const gencomp_algs *a)
185 {
186   trace(T_CRYPTO, "crypto: cipher = %s", a->c->name);
187   trace(T_CRYPTO, "crypto: mac = %s/%lu",
188         a->m->name, (unsigned long)a->tagsz * 8);
189 }
190 #endif
191
192 static int gencomp_checkalgs(gencomp_algs *a, const algswitch *asw, dstr *e)
193 {
194   /* --- Derive the key sizes --- *
195    *
196    * Must ensure that we have non-empty keys.  This isn't ideal, but it
197    * provides a handy sanity check.  Also must be based on a 64- or 128-bit
198    * block cipher or we can't do the data expiry properly.
199    */
200
201   if ((a->cksz = keysz(asw->hashsz, a->c->keysz)) == 0) {
202     a_format(e, "cipher", "%s", a->c->name,
203              "no-key-size", "%lu", (unsigned long)asw->hashsz,
204              A_END);
205     return (-1);
206   }
207   if ((a->mksz = keysz(asw->hashsz, a->m->keysz)) == 0) {
208     a_format(e, "mac", "%s", a->m->name,
209              "no-key-size", "%lu", (unsigned long)asw->hashsz,
210              A_END);
211     return (-1);
212   }
213
214   return (0);
215 }
216
217 static void gencomp_alginfo(const gencomp_algs *a, admin *adm)
218 {
219   a_info(adm,
220          "cipher=%s", a->c->name,
221          "cipher-keysz=%lu", (unsigned long)a->cksz,
222          "cipher-blksz=%lu", (unsigned long)a->c->blksz,
223          A_END);
224   a_info(adm,
225          "mac=%s", a->m->name,
226          "mac-keysz=%lu", (unsigned long)a->mksz,
227          "mac-tagsz=%lu", (unsigned long)a->tagsz,
228          A_END);
229 }
230
231 static int gencomp_samealgsp(const gencomp_algs *a, const gencomp_algs *aa)
232 {
233   return (a->c == aa->c &&
234           a->m == aa->m && a->tagsz == aa->tagsz);
235 }
236
237 static size_t gencomp_expsz(const gencomp_algs *a)
238   { return (a->c->blksz < 16 ? MEG(64) : MEG(2048)); }
239
240 static bulkchal *gencomp_genchal(const gencomp_algs *a)
241 {
242   gencomp_chal *gc = CREATE(gencomp_chal);
243
244   rand_get(RAND_GLOBAL, buf_t, a->mksz);
245   gc->m = GM_KEY(a->m, buf_t, a->mksz);
246   gc->_b.tagsz = a->tagsz;
247   IF_TRACING(T_CHAL, {
248     trace(T_CHAL, "chal: generated new challenge key");
249     trace_block(T_CRYPTO, "chal: new key", buf_t, a->mksz);
250   })
251   return (&gc->_b);
252 }
253
254 static int gencomp_chaltag(bulkchal *bc, const void *m, size_t msz,
255                            uint32 seq, void *t)
256 {
257   gencomp_chal *gc = (gencomp_chal *)bc;
258   ghash *h = GM_INIT(gc->m);
259
260   GH_HASHU32(h, seq); if (msz) GH_HASH(h, m, msz);
261   memcpy(t, GH_DONE(h, 0), bc->tagsz);
262   GH_DESTROY(h);
263   return (0);
264 }
265
266 static int gencomp_chalvrf(bulkchal *bc, const void *m, size_t msz,
267                            uint32 seq, const void *t)
268 {
269   gencomp_chal *gc = (gencomp_chal *)bc;
270   ghash *h = GM_INIT(gc->m);
271   int ok;
272
273   GH_HASHU32(h, seq); if (msz) GH_HASH(h, m, msz);
274   ok = ct_memeq(GH_DONE(h, 0), t, gc->_b.tagsz);
275   GH_DESTROY(h);
276   return (ok ? 0 : -1);
277 }
278
279 static void gencomp_freechal(bulkchal *bc)
280   { gencomp_chal *gc = (gencomp_chal *)bc; GM_DESTROY(gc->m); DESTROY(gc); }
281
282 /*----- The original transform --------------------------------------------*
283  *
284  * We generate a random initialization vector (if the cipher needs one).  We
285  * encrypt the input message with the cipher, and format the type, sequence
286  * number, IV, and ciphertext as follows.
287  *
288  *              +--------+ +--------+---...---+------...------+
289  *              |  type  | |  seq   |   iv    |   ciphertext  |
290  *              +--------+ +--------+---...---+------...------+
291  *                  32         32      blksz         sz
292  *
293  * All of this is fed into the MAC to compute a tag.  The type is not
294  * transmitted: the other end knows what type of message it expects, and the
295  * type is only here to prevent us from being confused because some other
296  * kind of ciphertext has been substituted.  The tag is prepended to the
297  * remainder, to yield the finished cryptogram, as follows.
298  *
299  *              +---...---+--------+---...---+------...------+
300  *              |   tag   |  seq   |   iv    |   ciphertext  |
301  *              +---...---+--------+---...---+------...------+
302  *                 tagsz      32      blksz         sz
303  *
304  * Decryption: checks the overall size, verifies the tag, then decrypts the
305  * ciphertext and extracts the sequence number.
306  */
307
308 typedef struct v0_algs {
309   bulkalgs _b;
310   gencomp_algs ga;
311 } v0_algs;
312
313 typedef struct v0_ctx {
314   bulkctx _b;
315   size_t tagsz;
316   struct {
317     gcipher *c;
318     gmac *m;
319   } d[NDIR];
320 } v0_ctx;
321
322 static bulkalgs *v0_getalgs(const algswitch *asw, dstr *e,
323                             key_file *kf, key *k)
324 {
325   v0_algs *a = CREATE(v0_algs);
326   if (gencomp_getalgs(&a->ga, asw, e, kf, k)) { DESTROY(a); return (0); }
327   return (&a->_b);
328 }
329
330 #ifndef NTRACE
331 static void v0_tracealgs(const bulkalgs *aa)
332   { const v0_algs *a = (const v0_algs *)aa; gencomp_tracealgs(&a->ga); }
333 #endif
334
335 static int v0_checkalgs(bulkalgs *aa, const algswitch *asw, dstr *e)
336 {
337   v0_algs *a = (v0_algs *)aa;
338   if (gencomp_checkalgs(&a->ga, asw, e)) return (-1);
339   return (0);
340 }
341
342 static int v0_samealgsp(const bulkalgs *aa, const bulkalgs *bb)
343 {
344   const v0_algs *a = (const v0_algs *)aa, *b = (const v0_algs *)bb;
345   return (gencomp_samealgsp(&a->ga, &b->ga));
346 }
347
348 static void v0_alginfo(const bulkalgs *aa, admin *adm)
349   { const v0_algs *a = (const v0_algs *)aa; gencomp_alginfo(&a->ga, adm); }
350
351 static size_t v0_overhead(const bulkalgs *aa)
352 {
353   const v0_algs *a = (const v0_algs *)aa;
354   return (a->ga.tagsz + SEQSZ + a->ga.c->blksz);
355 }
356
357 static size_t v0_expsz(const bulkalgs *aa)
358   { const v0_algs *a = (const v0_algs *)aa; return (gencomp_expsz(&a->ga)); }
359
360 static bulkctx *v0_genkeys(const bulkalgs *aa, const deriveargs *da)
361 {
362   const v0_algs *a = (const v0_algs *)aa;
363   v0_ctx *bc = CREATE(v0_ctx);
364   octet k[MAXHASHSZ];
365   int i;
366
367   bc->tagsz = a->ga.tagsz;
368   for (i = 0; i < NDIR; i++) {
369     if (!(da->f&(1 << i))) { bc->d[i].c = 0; bc->d[i].m = 0; continue; }
370     derivekey(k, a->ga.cksz, da, i, "encryption");
371     bc->d[i].c = GC_INIT(a->ga.c, k, a->ga.cksz);
372     derivekey(k, a->ga.mksz, da, i, "integrity");
373     bc->d[i].m = GM_KEY(a->ga.m, k, a->ga.mksz);
374   }
375   return (&bc->_b);
376 }
377
378 static bulkchal *v0_genchal(const bulkalgs *aa)
379 {
380   const v0_algs *a = (const v0_algs *)aa;
381   return (gencomp_genchal(&a->ga));
382 }
383 #define v0_chaltag gencomp_chaltag
384 #define v0_chalvrf gencomp_chalvrf
385 #define v0_freechal gencomp_freechal
386
387 static void v0_freealgs(bulkalgs *aa)
388   { v0_algs *a = (v0_algs *)aa; DESTROY(a); }
389
390 static void v0_freectx(bulkctx *bbc)
391 {
392   v0_ctx *bc = (v0_ctx *)bbc;
393   int i;
394
395   for (i = 0; i < NDIR; i++) {
396     if (bc->d[i].c) GC_DESTROY(bc->d[i].c);
397     if (bc->d[i].m) GM_DESTROY(bc->d[i].m);
398   }
399   DESTROY(bc);
400 }
401
402 static int v0_encrypt(bulkctx *bbc, unsigned ty,
403                       buf *b, buf *bb, uint32 seq)
404 {
405   v0_ctx *bc = (v0_ctx *)bbc;
406   ghash *h;
407   gcipher *c = bc->d[DIR_OUT].c;
408   const octet *p = BCUR(b);
409   size_t sz = BLEFT(b);
410   octet *qmac, *qseq, *qiv, *qpk;
411   size_t ivsz;
412   size_t tagsz = bc->tagsz;
413   octet t[4];
414
415   assert(c);
416   ivsz = GC_CLASS(c)->blksz;
417
418   /* --- Determine the ciphertext layout --- */
419
420   if (buf_ensure(bb, tagsz + SEQSZ + ivsz + sz)) return (0);
421   qmac = BCUR(bb); qseq = qmac + tagsz; qiv = qseq + SEQSZ; qpk = qiv + ivsz;
422   BSTEP(bb, tagsz + SEQSZ + ivsz + sz);
423
424   /* --- Store the type --- *
425    *
426    * This isn't transmitted, but it's covered by the MAC.
427    */
428
429   STORE32(t, ty);
430
431   /* --- Store the sequence number --- */
432
433   STORE32(qseq, seq);
434
435   /* --- Establish an initialization vector if necessary --- */
436
437   if (ivsz) {
438     rand_get(RAND_GLOBAL, qiv, ivsz);
439     GC_SETIV(c, qiv);
440     TRACE_IV(qiv, ivsz);
441   }
442
443   /* --- Encrypt the packet --- */
444
445   GC_ENCRYPT(c, p, qpk, sz);
446   TRACE_CT(qpk, sz);
447
448   /* --- Compute a MAC over type, sequence number, IV, and ciphertext --- */
449
450   if (tagsz) {
451     h = GM_INIT(bc->d[DIR_OUT].m);
452     GH_HASH(h, t, sizeof(t));
453     GH_HASH(h, qseq, SEQSZ + ivsz + sz);
454     memcpy(qmac, GH_DONE(h, 0), tagsz);
455     GH_DESTROY(h);
456     TRACE_MAC(qmac, tagsz);
457   }
458
459   /* --- We're done --- */
460
461   return (0);
462 }
463
464 static int v0_decrypt(bulkctx *bbc, unsigned ty,
465                       buf *b, buf *bb, uint32 *seq)
466 {
467   v0_ctx *bc = (v0_ctx *)bbc;
468   const octet *pmac, *piv, *pseq, *ppk;
469   size_t psz = BLEFT(b);
470   size_t sz;
471   octet *q = BCUR(bb);
472   ghash *h;
473   gcipher *c = bc->d[DIR_IN].c;
474   size_t ivsz;
475   size_t tagsz = bc->tagsz;
476   octet t[4];
477
478   assert(c);
479   ivsz = GC_CLASS(c)->blksz;
480
481   /* --- Break up the packet into its components --- */
482
483   if (psz < ivsz + SEQSZ + tagsz) {
484     T( trace(T_KEYSET, "keyset: block too small for keyset"); )
485     return (KSERR_MALFORMED);
486   }
487   sz = psz - ivsz - SEQSZ - tagsz;
488   pmac = BCUR(b); pseq = pmac + tagsz; piv = pseq + SEQSZ; ppk = piv + ivsz;
489   STORE32(t, ty);
490
491   /* --- Verify the MAC on the packet --- */
492
493   if (tagsz) {
494     h = GM_INIT(bc->d[DIR_IN].m);
495     GH_HASH(h, t, sizeof(t));
496     GH_HASH(h, pseq, SEQSZ + ivsz + sz);
497     CHECK_MAC(h, pmac, tagsz);
498   }
499
500   /* --- Decrypt the packet --- */
501
502   if (ivsz) {
503     TRACE_IV(piv, ivsz);
504     GC_SETIV(c, piv);
505   }
506   GC_DECRYPT(c, ppk, q, sz);
507
508   /* --- Finished --- */
509
510   *seq = LOAD32(pseq);
511   BSTEP(bb, sz);
512   return (0);
513 }
514
515 /*----- The implicit-IV transform -----------------------------------------*
516  *
517  * The v0 transform makes everything explicit.  There's an IV because the
518  * cipher needs an IV; there's a sequence number because replay prevention
519  * needs a sequence number.
520  *
521  * This new transform works rather differently.  We make use of a block
522  * cipher to encrypt the sequence number, and use that as the IV.  We
523  * transmit the sequence number in the clear, as before.  This reduces
524  * overhead; and it's not a significant privacy leak because the adversary
525  * can see the order in which the messages are transmitted -- i.e., the
526  * sequence numbers are almost completely predictable anyway.
527  *
528  * So, a MAC is computed over
529  *
530  *              +--------+ +--------+------...------+
531  *              |  type  | |  seq   |   ciphertext  |
532  *              +--------+ +--------+------...------+
533  *                  32         32          sz
534  *
535  * and we actually transmit the following as the cryptogram.
536  *
537  *              +---...---+------+------...------+
538  *              |   tag   | seq  |   ciphertext  |
539  *              +---...---+------+------...------+
540  *                 tagsz     32         sz
541  */
542
543 typedef struct iiv_algs {
544   bulkalgs _b;
545   gencomp_algs ga;
546   const gccipher *b; size_t bksz;
547 } iiv_algs;
548
549 typedef struct iiv_ctx {
550   bulkctx _b;
551   size_t tagsz;
552   struct {
553     gcipher *c, *b;
554     gmac *m;
555   } d[NDIR];
556 } iiv_ctx;
557
558
559 static bulkalgs *iiv_getalgs(const algswitch *asw, dstr *e,
560                             key_file *kf, key *k)
561 {
562   iiv_algs *a = CREATE(iiv_algs);
563   dstr d = DSTR_INIT, dd = DSTR_INIT;
564   const char *p;
565   char *q;
566
567   if (gencomp_getalgs(&a->ga, asw, e, kf, k)) goto fail;
568
569   if ((p = key_getattr(kf, k, "blkc")) == 0) {
570     dstr_puts(&dd, a->ga.c->name);
571     if ((q = strrchr(dd.buf, '-')) != 0) *q = 0;
572     p = dd.buf;
573   }
574   dstr_putf(&d, "%s-ecb", p);
575   if ((a->b = gcipher_byname(d.buf)) == 0) {
576     a_format(e, "unknown-blkc", "%s", p, A_END);
577     goto fail;
578   }
579
580   dstr_destroy(&d); dstr_destroy(&dd);
581   return (&a->_b);
582 fail:
583   dstr_destroy(&d); dstr_destroy(&dd);
584   DESTROY(a);
585   return (0);
586 }
587
588 #ifndef NTRACE
589 static void iiv_tracealgs(const bulkalgs *aa)
590 {
591   const iiv_algs *a = (const iiv_algs *)aa;
592
593   gencomp_tracealgs(&a->ga);
594   trace(T_CRYPTO,
595         "crypto: blkc = %.*s", (int)strlen(a->b->name) - 4, a->b->name);
596 }
597 #endif
598
599 static int iiv_checkalgs(bulkalgs *aa, const algswitch *asw, dstr *e)
600 {
601   iiv_algs *a = (iiv_algs *)aa;
602
603   if (gencomp_checkalgs(&a->ga, asw, e)) return (-1);
604
605   if ((a->bksz = keysz(asw->hashsz, a->b->keysz)) == 0) {
606     a_format(e, "blkc", "%.*s", strlen(a->b->name) - 4, a->b->name,
607              "no-key-size", "%lu", (unsigned long)asw->hashsz,
608              A_END);
609     return (-1);
610   }
611   if (a->b->blksz < a->ga.c->blksz) {
612     a_format(e, "blkc", "%.*s", strlen(a->b->name) - 4, a->b->name,
613              "blksz-insufficient", A_END);
614     return (-1);
615   }
616   return (0);
617 }
618
619 static int iiv_samealgsp(const bulkalgs *aa, const bulkalgs *bb)
620 {
621   const iiv_algs *a = (const iiv_algs *)aa, *b = (const iiv_algs *)bb;
622   return (gencomp_samealgsp(&a->ga, &b->ga) && a->b == b->b);
623 }
624
625 static void iiv_alginfo(const bulkalgs *aa, admin *adm)
626 {
627   const iiv_algs *a = (const iiv_algs *)aa;
628   gencomp_alginfo(&a->ga, adm);
629   a_info(adm,
630          "blkc=%.*s", strlen(a->b->name) - 4, a->b->name,
631          "blkc-keysz=%lu", (unsigned long)a->bksz,
632          "blkc-blksz=%lu", (unsigned long)a->b->blksz,
633          A_END);
634 }
635
636 static size_t iiv_overhead(const bulkalgs *aa)
637   { const iiv_algs *a = (const iiv_algs *)aa; return (a->ga.tagsz + SEQSZ); }
638
639 static size_t iiv_expsz(const bulkalgs *aa)
640 {
641   const iiv_algs *a = (const iiv_algs *)aa;
642   return (gencomp_expsz(&a->ga));
643 }
644
645 static bulkctx *iiv_genkeys(const bulkalgs *aa, const deriveargs *da)
646 {
647   const iiv_algs *a = (const iiv_algs *)aa;
648   iiv_ctx *bc = CREATE(iiv_ctx);
649   octet k[MAXHASHSZ];
650   int i;
651
652   bc->tagsz = a->ga.tagsz;
653   for (i = 0; i < NDIR; i++) {
654     if (!(da->f&(1 << i)))
655       { bc->d[i].c = 0; bc->d[i].b = 0; bc->d[i].m = 0; continue; }
656     derivekey(k, a->ga.cksz, da, i, "encryption");
657     bc->d[i].c = GC_INIT(a->ga.c, k, a->ga.cksz);
658     derivekey(k, a->bksz, da, i, "blkc");
659     bc->d[i].b = GC_INIT(a->b, k, a->bksz);
660     derivekey(k, a->ga.mksz, da, i, "integrity");
661     bc->d[i].m = GM_KEY(a->ga.m, k, a->ga.mksz);
662   }
663   return (&bc->_b);
664 }
665
666 static bulkchal *iiv_genchal(const bulkalgs *aa)
667 {
668   const iiv_algs *a = (const iiv_algs *)aa;
669   return (gencomp_genchal(&a->ga));
670 }
671 #define iiv_chaltag gencomp_chaltag
672 #define iiv_chalvrf gencomp_chalvrf
673 #define iiv_freechal gencomp_freechal
674
675 static void iiv_freealgs(bulkalgs *aa)
676   { iiv_algs *a = (iiv_algs *)aa; DESTROY(a); }
677
678 static void iiv_freectx(bulkctx *bbc)
679 {
680   iiv_ctx *bc = (iiv_ctx *)bbc;
681   int i;
682
683   for (i = 0; i < NDIR; i++) {
684     if (bc->d[i].c) GC_DESTROY(bc->d[i].c);
685     if (bc->d[i].b) GC_DESTROY(bc->d[i].b);
686     if (bc->d[i].m) GM_DESTROY(bc->d[i].m);
687   }
688   DESTROY(bc);
689 }
690
691 #define TRACE_PRESEQ(qseq, ivsz) do { IF_TRACING(T_KEYSET, {            \
692   trace_block(T_CRYPTO, "crypto: IV derivation input", (qseq), (ivsz)); \
693 }) } while (0)
694
695 static int iiv_encrypt(bulkctx *bbc, unsigned ty,
696                        buf *b, buf *bb, uint32 seq)
697 {
698   iiv_ctx *bc = (iiv_ctx *)bbc;
699   ghash *h;
700   gcipher *c = bc->d[DIR_OUT].c, *blkc = bc->d[DIR_OUT].b;
701   const octet *p = BCUR(b);
702   size_t sz = BLEFT(b);
703   octet *qmac, *qseq, *qpk;
704   size_t ivsz, blkcsz;
705   size_t tagsz = bc->tagsz;
706   octet t[4];
707
708   assert(c); assert(blkc);
709   ivsz = GC_CLASS(c)->blksz;
710   blkcsz = GC_CLASS(blkc)->blksz;
711
712   /* --- Determine the ciphertext layout --- */
713
714   if (buf_ensure(bb, tagsz + SEQSZ + sz)) return (0);
715   qmac = BCUR(bb); qseq = qmac + tagsz; qpk = qseq + SEQSZ;
716   BSTEP(bb, tagsz + SEQSZ + sz);
717
718   /* --- Store the type --- *
719    *
720    * This isn't transmitted, but it's covered by the MAC.
721    */
722
723   STORE32(t, ty);
724
725   /* --- Store the sequence number --- */
726
727   STORE32(qseq, seq);
728
729   /* --- Establish an initialization vector if necessary --- */
730
731   if (ivsz) {
732     memset(buf_u, 0, blkcsz - SEQSZ);
733     memcpy(buf_u + blkcsz - SEQSZ, qseq, SEQSZ);
734     TRACE_PRESEQ(buf_u, ivsz);
735     GC_ENCRYPT(blkc, buf_u, buf_u, blkcsz);
736     GC_SETIV(c, buf_u);
737     TRACE_IV(buf_u, ivsz);
738   }
739
740   /* --- Encrypt the packet --- */
741
742   GC_ENCRYPT(c, p, qpk, sz);
743   TRACE_CT(qpk, sz);
744
745   /* --- Compute a MAC over type, sequence number, and ciphertext --- */
746
747   if (tagsz) {
748     h = GM_INIT(bc->d[DIR_OUT].m);
749     GH_HASH(h, t, sizeof(t));
750     GH_HASH(h, qseq, SEQSZ + sz);
751     memcpy(qmac, GH_DONE(h, 0), tagsz);
752     GH_DESTROY(h);
753     TRACE_MAC(qmac, tagsz);
754   }
755
756   /* --- We're done --- */
757
758   return (0);
759 }
760
761 static int iiv_decrypt(bulkctx *bbc, unsigned ty,
762                        buf *b, buf *bb, uint32 *seq)
763 {
764   iiv_ctx *bc = (iiv_ctx *)bbc;
765   const octet *pmac, *pseq, *ppk;
766   size_t psz = BLEFT(b);
767   size_t sz;
768   octet *q = BCUR(bb);
769   ghash *h;
770   gcipher *c = bc->d[DIR_IN].c, *blkc = bc->d[DIR_IN].b;
771   size_t ivsz, blkcsz;
772   size_t tagsz = bc->tagsz;
773   octet t[4];
774
775   assert(c); assert(blkc);
776   ivsz = GC_CLASS(c)->blksz;
777   blkcsz = GC_CLASS(blkc)->blksz;
778
779   /* --- Break up the packet into its components --- */
780
781   if (psz < SEQSZ + tagsz) {
782     T( trace(T_KEYSET, "keyset: block too small for keyset"); )
783     return (KSERR_MALFORMED);
784   }
785   sz = psz - SEQSZ - tagsz;
786   pmac = BCUR(b); pseq = pmac + tagsz; ppk = pseq + SEQSZ;
787   STORE32(t, ty);
788
789   /* --- Verify the MAC on the packet --- */
790
791   if (tagsz) {
792     h = GM_INIT(bc->d[DIR_IN].m);
793     GH_HASH(h, t, sizeof(t));
794     GH_HASH(h, pseq, SEQSZ + sz);
795     CHECK_MAC(h, pmac, tagsz);
796   }
797
798   /* --- Decrypt the packet --- */
799
800   if (ivsz) {
801     memset(buf_u, 0, blkcsz - SEQSZ);
802     memcpy(buf_u + blkcsz - SEQSZ, pseq, SEQSZ);
803     TRACE_PRESEQ(buf_u, ivsz);
804     GC_ENCRYPT(blkc, buf_u, buf_u, blkcsz);
805     GC_SETIV(c, buf_u);
806     TRACE_IV(buf_u, ivsz);
807   }
808   GC_DECRYPT(c, ppk, q, sz);
809
810   /* --- Finished --- */
811
812   *seq = LOAD32(pseq);
813   BSTEP(bb, sz);
814   return (0);
815 }
816
817 /*----- The AEAD transform ------------------------------------------------*
818  *
819  * This transform uses a general authenticated encryption scheme (the
820  * additional data isn't necessary).  Good options include
821  * `chacha20-poly1305' or `rijndael-ocb3'.
822  *
823  * To be acceptable, the scheme must accept at least a 40-bit nonce.  (All of
824  * Catacomb's current AEAD schemes are suitable.)  The low 32 bits are the
825  * sequence number.  The type is written to the next 8--32 bytes: if the
826  * nonce size is 64 bits or more (preferred, for compatibility reasons) then
827  * the type is written as 32 bits, and the remaining space is padded with
828  * zero bytes; otherwise, the type is right-aligned in the remaining space.
829  * Both fields are big-endian.
830  *
831  *              +--------+--+
832  *              |  seq   |ty|
833  *              +--------+--+
834  *                  32    8
835  *
836  *              +--------+----+
837  *              |  seq   | ty |
838  *              +--------+----+
839  *                  32     16
840  *
841  *              +--------+------+
842  *              |  seq   | type |
843  *              +--------+------+
844  *                  32      24
845  *
846  *              +--------+--------+---...---+
847  *              |  seq   |  type  |    0    |
848  *              +--------+--------+---...---+
849  *                  32       32     nsz - 64
850  *
851  * The ciphertext is formatted as
852  *
853  *              +---...---+--------+------...------+
854  *              |   tag   |  seq   |   ciphertext  |
855  *              +---...---+--------+------...------+
856  *                 tagsz      32          sz
857  *
858  */
859
860 #define AEAD_NONCEMAX 64
861
862 typedef struct aead_algs {
863   bulkalgs _b;
864   const gcaead *c;
865   size_t ksz, nsz, tsz;
866 } aead_algs;
867
868 typedef struct aead_ctx {
869   bulkctx _b;
870   struct { gaead_key *k; } d[NDIR];
871   size_t nsz, tsz;
872 } aead_ctx;
873
874 static bulkalgs *aead_getalgs(const algswitch *asw, dstr *e,
875                               key_file *kf, key *k)
876 {
877   aead_algs *a = CREATE(aead_algs);
878   const char *p;
879   char *qq;
880   gaead_key *kk = 0;
881   size_t ksz;
882   size_t csz = 0;
883   unsigned long n;
884
885   /* --- Collect the selected cipher and check that it's supported --- */
886
887   p = key_getattr(kf, k, "cipher"); if (!p) p = "rijndael-ocb3";
888   a->c = gaead_byname(p);
889   if (!a->c) { a_format(e, "unknown-cipher", "%s", p, A_END); goto fail; }
890   if (a->c->f&AEADF_NOAAD) {
891     a_format(e, "unsuitable-aead-cipher", "%s", p, "no-aad", A_END);
892     goto fail;
893   }
894   a->nsz = keysz_pad(8, a->c->noncesz);
895   if (!a->nsz) a->nsz = keysz_pad(5, a->c->noncesz);
896   if (!a->nsz) {
897     a_format(e, "unsuitable-aead-cipher", "%s", p, "nonce-too-small", A_END);
898     goto fail;
899   } else if (a->nsz > AEAD_NONCEMAX) {
900     a_format(e, "unsuitable-aead-cipher", "%s", p, "nonce-too-large", A_END);
901     goto fail;
902   }
903
904   /* --- Collect the selected MAC, and check the tag length --- *
905    *
906    * Of course, there isn't a separate MAC, so only accept `aead'.
907    */
908
909   p = key_getattr(kf, k, "tagsz");
910   if (!p) {
911     p = key_getattr(kf, k, "mac");
912     if (!p) ;
913     else if (strncmp(p, "aead", 4) != 0 || (p[4] && p[4] != '/'))
914       { a_format(e, "unknown-mac", "%s", p, A_END); goto fail; }
915     else if (p[4] == '/') p += 5;
916     else p = 0;
917   }
918   if (!p)
919     a->tsz = keysz(0, a->c->tagsz);
920   else {
921     n = strtoul(p, &qq, 0);
922     if (*qq) {
923       a_format(e, "bad-tag-length-string", "%s", p, A_END);
924       goto fail;
925     }
926     if (n%8 || (a->tsz = keysz(n/8, a->c->tagsz)) == 0)
927       { a_format(e, "bad-tag-length", "%lu", n, A_END); goto fail; }
928   }
929
930   /* --- Check that an empty message gives an empty ciphertext --- *
931    *
932    * This is necessary for producing challenges.  If the overhead is zero
933    * then we're fine; otherwise, we have to check the hard way.
934    */
935
936   if (a->c->ohd) {
937     ksz = keysz(0, a->c->keysz);
938     memset(buf_t, 0, ksz > a->nsz ? ksz : a->nsz);
939     kk = GAEAD_KEY(a->c, buf_t, ksz);
940     if (gaead_encrypt(kk, buf_t, a->nsz,
941                       buf_t, ksz,
942                       0, 0,
943                       buf_t, &csz,
944                       buf_t, a->tsz)) {
945       a_format(e, "unsuitable-aead-cipher", "%s", a->c->name,
946                "nonempty-ciphertext-for-empty-message", A_END);
947       goto fail;
948     }
949     GAEAD_DESTROY(kk); kk = 0;
950   }
951
952   return (&a->_b);
953 fail:
954   if (kk) GAEAD_DESTROY(kk);
955   DESTROY(a);
956   return (0);
957 }
958
959 #ifndef NTRACE
960 static void aead_tracealgs(const bulkalgs *aa)
961 {
962   const aead_algs *a = (const aead_algs *)aa;
963
964   trace(T_CRYPTO, "crypto: cipher = %s", a->c->name);
965   trace(T_CRYPTO, "crypto: noncesz = %lu", (unsigned long)a->nsz);
966   trace(T_CRYPTO, "crypto: tagsz = %lu", (unsigned long)a->tsz);
967 }
968 #endif
969
970 static int aead_checkalgs(bulkalgs *aa, const algswitch *asw, dstr *e)
971 {
972   aead_algs *a = (aead_algs *)aa;
973
974   if ((a->ksz = keysz(asw->hashsz, a->c->keysz)) == 0) {
975     a_format(e, "cipher", "%s", a->c->name,
976              "no-key-size", "%lu", (unsigned long)asw->hashsz,
977              A_END);
978     return (-1);
979   }
980   return (0);
981 }
982
983 static int aead_samealgsp(const bulkalgs *aa, const bulkalgs *bb)
984 {
985   const aead_algs *a = (const aead_algs *)aa,
986     *b = (const aead_algs *)bb;
987   return (a->c == b->c && a->tsz == b->tsz);
988 }
989
990 static void aead_alginfo(const bulkalgs *aa, admin *adm)
991 {
992   const aead_algs *a = (const aead_algs *)aa;
993   a_info(adm, "cipher=%s", a->c->name,
994          "cipher-keysz=%lu", (unsigned long)a->ksz,
995          A_END);
996   a_info(adm, "mac=aead", "mac-tagsz=%lu", (unsigned long)a->tsz, A_END);
997 }
998
999 static size_t aead_overhead(const bulkalgs *aa)
1000 {
1001   const aead_algs *a = (const aead_algs *)aa;
1002   return (a->tsz + SEQSZ + a->c->ohd);
1003 }
1004
1005 static size_t aead_expsz(const bulkalgs *aa)
1006 {
1007   const aead_algs *a = (const aead_algs *)aa;
1008   return (a->c->blksz < 16 ? MEG(64) : MEG(2048));
1009 }
1010
1011 static bulkctx *aead_genkeys(const bulkalgs *aa, const deriveargs *da)
1012 {
1013   const aead_algs *a = (const aead_algs *)aa;
1014   aead_ctx *bc = CREATE(aead_ctx);
1015   octet k[MAXHASHSZ];
1016   int i;
1017
1018   for (i = 0; i < NDIR; i++) {
1019     if (!(da->f&(1 << i))) { bc->d[i].k = 0; continue; }
1020     derivekey(k, a->ksz, da, i, "encryption");
1021     bc->d[i].k = GAEAD_KEY(a->c, k, a->ksz);
1022   }
1023   bc->nsz = a->nsz; bc->tsz = a->tsz;
1024   return (&bc->_b);
1025 }
1026
1027 typedef struct aead_chal {
1028   bulkchal _b;
1029   gaead_key *k;
1030 } aead_chal;
1031
1032 static bulkchal *aead_genchal(const bulkalgs *aa)
1033 {
1034   const aead_algs *a = (const aead_algs *)aa;
1035   aead_chal *c = CREATE(aead_chal);
1036   rand_get(RAND_GLOBAL, buf_t, a->ksz);
1037   c->k = GAEAD_KEY(a->c, buf_t, a->ksz);
1038   IF_TRACING(T_CHAL, {
1039     trace(T_CHAL, "chal: generated new challenge key");
1040     trace_block(T_CRYPTO, "chal: new key", buf_t, a->ksz);
1041   })
1042   c->_b.tagsz = a->tsz;
1043   return (&c->_b);
1044 }
1045
1046 static int aead_chaltag(bulkchal *bc, const void *m, size_t msz,
1047                         uint32 seq, void *t)
1048 {
1049   aead_chal *c = (aead_chal *)bc;
1050   octet b[AEAD_NONCEMAX];
1051   size_t nsz = keysz_pad(4, c->k->ops->c->noncesz);
1052   size_t csz = 0;
1053   int rc;
1054
1055   assert(nsz); assert(nsz <= sizeof(b));
1056   memset(b, 0, nsz - 4); STORE32(b + nsz - 4, seq);
1057   rc = gaead_encrypt(c->k, b, nsz, m, msz, 0, 0,
1058                      buf_t, &csz, t, c->_b.tagsz);
1059   assert(!rc);
1060   return (0);
1061 }
1062
1063 static int aead_chalvrf(bulkchal *bc, const void *m, size_t msz,
1064                            uint32 seq, const void *t)
1065 {
1066   aead_chal *c = (aead_chal *)bc;
1067   octet b[AEAD_NONCEMAX];
1068   size_t nsz = keysz(4, c->k->ops->c->noncesz);
1069   size_t psz = 0;
1070   int rc;
1071
1072   assert(nsz); assert(nsz <= sizeof(b));
1073   memset(b, 0, nsz - 4); STORE32(b + nsz - 4, seq);
1074   rc = gaead_decrypt(c->k, b, nsz, m, msz, 0, 0,
1075                      buf_t, &psz, t, c->_b.tagsz);
1076   assert(rc >= 0);
1077   return (rc == 1 ? 0 : -1);
1078 }
1079
1080 static void aead_freechal(bulkchal *bc)
1081   { aead_chal *c = (aead_chal *)bc; GAEAD_DESTROY(c->k); DESTROY(c); }
1082
1083 static void aead_freealgs(bulkalgs *aa)
1084   { aead_algs *a = (aead_algs *)aa; DESTROY(a); }
1085
1086 static void aead_freectx(bulkctx *bbc)
1087 {
1088   aead_ctx *bc = (aead_ctx *)bbc;
1089   int i;
1090
1091   for (i = 0; i < NDIR; i++) { if (bc->d[i].k) GAEAD_DESTROY(bc->d[i].k); }
1092   DESTROY(bc);
1093 }
1094
1095 static void aead_fmtnonce(aead_ctx *bc, octet *n, uint32 seq, unsigned ty)
1096 {
1097   assert(bc->nsz <= AEAD_NONCEMAX); assert(ty <= 255);
1098   STORE32(n, seq);
1099   switch (bc->nsz) {
1100     case 5: STORE8(n + SEQSZ, ty); break;
1101     case 6: STORE16(n + SEQSZ, ty); break;
1102     case 7: STORE24(n + SEQSZ, ty); break;
1103     default: memset(n + 8, 0, bc->nsz - 8); /* and continue */
1104     case 8: STORE32(n + SEQSZ, ty); break;
1105   }
1106   TRACE_IV(n, bc->nsz);
1107 }
1108
1109 static int aead_encrypt(bulkctx *bbc, unsigned ty,
1110                         buf *b, buf *bb, uint32 seq)
1111 {
1112   aead_ctx *bc = (aead_ctx *)bbc;
1113   const octet *p = BCUR(b);
1114   gaead_key *k = bc->d[DIR_OUT].k;
1115   size_t sz = BLEFT(b);
1116   size_t csz = sz + k->ops->c->ohd;
1117   octet *qmac, *qseq, *qpk;
1118   octet n[AEAD_NONCEMAX];
1119   int rc;
1120
1121   assert(k);
1122
1123   if (buf_ensure(bb, bc->tsz + SEQSZ + csz)) return (0);
1124   qmac = BCUR(bb); qseq = qmac + bc->tsz; qpk = qseq + SEQSZ;
1125   STORE32(qseq, seq);
1126
1127   aead_fmtnonce(bc, n, seq, ty);
1128   rc = gaead_encrypt(k, n, bc->nsz, 0, 0, p, sz, qpk, &csz, qmac, bc->tsz);
1129   assert(!rc);
1130   BSTEP(bb, bc->tsz + SEQSZ + csz);
1131   TRACE_CT(qpk, csz);
1132   TRACE_MAC(qmac, bc->tsz);
1133
1134   return (0);
1135 }
1136
1137 static int aead_decrypt(bulkctx *bbc, unsigned ty,
1138                        buf *b, buf *bb, uint32 *seq_out)
1139 {
1140   aead_ctx *bc = (aead_ctx *)bbc;
1141   gaead_key *k = bc->d[DIR_IN].k;
1142   const octet *pmac, *pseq, *ppk;
1143   uint32 seq;
1144   size_t psz = BLEFT(b);
1145   size_t sz;
1146   octet *q = BCUR(bb);
1147   octet n[AEAD_NONCEMAX];
1148   int rc;
1149
1150   assert(k);
1151
1152   if (psz < bc->tsz + SEQSZ) {
1153     T( trace(T_KEYSET, "keyset: block too small for keyset"); )
1154     return (KSERR_MALFORMED);
1155   }
1156   sz = psz - bc->tsz - SEQSZ;
1157   pmac = BCUR(b); pseq = pmac + bc->tsz; ppk = pseq + SEQSZ;
1158   seq = LOAD32(pseq);
1159
1160   aead_fmtnonce(bc, n, seq, ty);
1161   rc = gaead_decrypt(k, n, bc->nsz, 0, 0, ppk, sz, q, &sz, pmac, bc->tsz);
1162   assert(rc >= 0);
1163   if (!rc) { TRACE_MACERR(pmac, bc->tsz); return (KSERR_DECRYPT); }
1164
1165   *seq_out = seq;
1166   BSTEP(bb, sz);
1167   return (0);
1168 }
1169
1170 /*----- The NaCl box transform --------------------------------------------*
1171  *
1172  * This transform is very similar to the NaCl `crypto_secretbox' transform
1173  * described in Bernstein, `Cryptography in NaCl', with the difference that,
1174  * rather than using XSalsa20, we use either Salsa20/r or ChaChar, because we
1175  * have no need of XSalsa20's extended nonce.  The default cipher is Salsa20.
1176  *
1177  * Salsa20 and ChaCha accept a 64-bit nonce.  The low 32 bits are the
1178  * sequence number, and the high 32 bits are the type, both big-endian.
1179  *
1180  *              +--------+--------+
1181  *              |  seq   |  type  |
1182  *              +--------+--------+
1183  *                  32       32
1184  *
1185  * A stream is generated by concatenating the raw output blocks generated
1186  * with this nonce and successive counter values starting from zero.  The
1187  * first 32 bytes of the stream are used as a key for Poly1305: the first 16
1188  * bytes are the universal hash key r, and the second 16 bytes are the mask
1189  * value s.
1190  *
1191  *              +------+------+ +------...------+
1192  *              |  r   |  s   | |   keystream   |
1193  *              +------+------+ +------...------+
1194  *                128    128           sz
1195  *
1196  * The remainder of the stream is XORed with the incoming plaintext to form a
1197  * ciphertext with the same length.  The ciphertext (only) is then tagged
1198  * using Poly1305.  The tag, sequence number, and ciphertext are concatenated
1199  * in this order, and transmitted.
1200  *
1201  *
1202  *              +---...---+------+------...------+
1203  *              |   tag   | seq  |   ciphertext  |
1204  *              +---...---+------+------...------+
1205  *                  128     32          sz
1206  *
1207  * Note that there is no need to authenticate the type separately, since it
1208  * was used to select the cipher nonce, and hence the Poly1305 key.  The
1209  * Poly1305 tag length is fixed.
1210  */
1211
1212 typedef struct naclbox_algs {
1213   aead_algs _b;
1214   const gccipher *c;
1215 } naclbox_algs;
1216
1217 static bulkalgs *naclbox_getalgs(const algswitch *asw, dstr *e,
1218                                  key_file *kf, key *k)
1219 {
1220   naclbox_algs *a = CREATE(naclbox_algs);
1221   const char *p;
1222   char *qq;
1223   unsigned long n;
1224
1225   /* --- Collect the selected cipher and check that it's supported --- */
1226
1227   p = key_getattr(kf, k, "cipher");
1228   if (!p || strcmp(p, "salsa20") == 0)
1229     { a->_b.c = &salsa20_naclbox; a->c = &salsa20; }
1230   else if (strcmp(p, "salsa20/12") == 0)
1231     { a->_b.c = &salsa2012_naclbox; a->c = &salsa2012; }
1232   else if (strcmp(p, "salsa20/8") == 0)
1233     { a->_b.c = &salsa208_naclbox; a->c = &salsa208; }
1234   else if (strcmp(p, "chacha20") == 0)
1235     { a->_b.c = &chacha20_naclbox; a->c = &chacha20; }
1236   else if (strcmp(p, "chacha12") == 0)
1237     { a->_b.c = &chacha12_naclbox; a->c = &chacha12; }
1238   else if (strcmp(p, "chacha8") == 0)
1239     { a->_b.c = &chacha8_naclbox; a->c = &chacha8; }
1240   else {
1241     a_format(e, "unknown-cipher", "%s", p, A_END);
1242     goto fail;
1243   }
1244   a->_b.nsz = 8;
1245
1246   /* --- Collect the selected MAC, and check the tag length --- */
1247
1248   p = key_getattr(kf, k, "mac");
1249   if (!p)
1250     ;
1251   else if (strncmp(p, "poly1305", 8) != 0 || (p[8] && p[8] != '/')) {
1252     a_format(e, "unknown-mac", "%s", p, A_END);
1253     goto fail;
1254   } else if (p[8] == '/') {
1255     n = strtoul(p + 9, &qq, 0);
1256     if (*qq) {
1257       a_format(e, "bad-tag-length-string", "%s", p + 9, A_END);
1258       goto fail;
1259     }
1260     if (n != 128) {
1261       a_format(e, "bad-tag-length", "%lu", n, A_END);
1262       goto fail;
1263     }
1264   }
1265   a->_b.tsz = 16;
1266
1267   return (&a->_b._b);
1268 fail:
1269   DESTROY(a);
1270   return (0);
1271 }
1272
1273 #ifndef NTRACE
1274 static void naclbox_tracealgs(const bulkalgs *aa)
1275 {
1276   const naclbox_algs *a = (const naclbox_algs *)aa;
1277
1278   trace(T_CRYPTO, "crypto: cipher = %s", a->c->name);
1279   trace(T_CRYPTO, "crypto: mac = poly1305/128");
1280 }
1281 #endif
1282
1283 #define naclbox_checkalgs aead_checkalgs
1284 #define naclbox_samealgsp aead_samealgsp
1285
1286 static void naclbox_alginfo(const bulkalgs *aa, admin *adm)
1287 {
1288   const naclbox_algs *a = (const naclbox_algs *)aa;
1289   a_info(adm, "cipher=%s", a->c->name, "cipher-keysz=32", A_END);
1290   a_info(adm, "mac=poly1305", "mac-tagsz=16", A_END);
1291 }
1292
1293 #define naclbox_overhead aead_overhead
1294 #define naclbox_expsz aead_expsz
1295 #define naclbox_genkeys aead_genkeys
1296
1297 typedef struct naclbox_chal {
1298   bulkchal _b;
1299   gcipher *c;
1300 } naclbox_chal;
1301
1302 static bulkchal *naclbox_genchal(const bulkalgs *aa)
1303 {
1304   const naclbox_algs *a = (const naclbox_algs *)aa;
1305   naclbox_chal *c = CREATE(naclbox_chal);
1306   rand_get(RAND_GLOBAL, buf_t, a->_b.ksz);
1307   c->c = GC_INIT(a->c, buf_t, a->_b.ksz);
1308   IF_TRACING(T_CHAL, {
1309     trace(T_CHAL, "chal: generated new challenge key");
1310     trace_block(T_CRYPTO, "chal: new key", buf_t, a->_b.ksz);
1311   })
1312   c->_b.tagsz = POLY1305_TAGSZ;
1313   return (&c->_b);
1314 }
1315
1316 static int naclbox_chaltag(bulkchal *bc, const void *m, size_t msz,
1317                            uint32 seq, void *t)
1318 {
1319   naclbox_chal *c = (naclbox_chal *)bc;
1320   poly1305_key pk;
1321   poly1305_ctx pm;
1322   octet b[POLY1305_KEYSZ + POLY1305_MASKSZ];
1323
1324   assert(SALSA20_NONCESZ <= sizeof(b));
1325   memset(b, 0, SALSA20_NONCESZ - 4); STORE32(b + SALSA20_NONCESZ - 4, seq);
1326   GC_SETIV(c->c, b); GC_ENCRYPT(c->c, 0, b, sizeof(b));
1327   poly1305_keyinit(&pk, b, POLY1305_KEYSZ);
1328   poly1305_macinit(&pm, &pk, b + POLY1305_KEYSZ);
1329   if (msz) poly1305_hash(&pm, m, msz);
1330   poly1305_done(&pm, t);
1331   return (0);
1332 }
1333
1334 static int naclbox_chalvrf(bulkchal *bc, const void *m, size_t msz,
1335                            uint32 seq, const void *t)
1336 {
1337   naclbox_chal *c = (naclbox_chal *)bc;
1338   poly1305_key pk;
1339   poly1305_ctx pm;
1340   octet b[POLY1305_KEYSZ + POLY1305_MASKSZ];
1341
1342   assert(SALSA20_NONCESZ <= sizeof(b));
1343   memset(b, 0, SALSA20_NONCESZ - 4); STORE32(b + SALSA20_NONCESZ - 4, seq);
1344   GC_SETIV(c->c, b); GC_ENCRYPT(c->c, 0, b, sizeof(b));
1345   poly1305_keyinit(&pk, b, POLY1305_KEYSZ);
1346   poly1305_macinit(&pm, &pk, b + POLY1305_KEYSZ);
1347   if (msz) poly1305_hash(&pm, m, msz);
1348   assert(POLY1305_TAGSZ <= sizeof(b)); poly1305_done(&pm, b);
1349   return (ct_memeq(t, b, POLY1305_TAGSZ) ? 0 : -1);
1350 }
1351
1352 static void naclbox_freechal(bulkchal *bc)
1353   { naclbox_chal *c = (naclbox_chal *)bc; GC_DESTROY(c->c); DESTROY(c); }
1354
1355 static void naclbox_freealgs(bulkalgs *aa)
1356   { naclbox_algs *a = (naclbox_algs *)aa; DESTROY(a); }
1357
1358 #define naclbox_freectx aead_freectx
1359 #define naclbox_encrypt aead_encrypt
1360 #define naclbox_decrypt aead_decrypt
1361
1362 /*----- Bulk crypto transform table ---------------------------------------*/
1363
1364 const bulkops bulktab[] = {
1365
1366 #define COMMA ,
1367
1368 #define BULK(name, pre)                                                 \
1369   { name, pre##_getalgs, T( pre##_tracealgs COMMA )                     \
1370     pre##_checkalgs, pre##_samealgsp,                                   \
1371     pre##_alginfo, pre##_overhead, pre##_expsz,                         \
1372     pre##_genkeys, pre##_genchal, pre##_freealgs,                       \
1373     pre##_encrypt, pre##_decrypt, pre##_freectx,                        \
1374     pre##_chaltag, pre##_chalvrf, pre##_freechal }
1375
1376   BULK("v0", v0),
1377   BULK("iiv", iiv),
1378   BULK("aead", aead),
1379   BULK("naclbox", naclbox),
1380
1381 #undef BULK
1382   { 0 }
1383 };
1384
1385 /*----- That's all, folks -------------------------------------------------*/