chiark / gitweb /
server/bulkcrypto.c: Document the procedures for producing challenges.
[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  * Challenge tags are calculated by applying the MAC to the sequence number
308  * and message, concatenated as follows.
309  *
310  *              +--------+---...---+
311  *              |  seq   |    m    |
312  *              +--------+---...---+
313  *                  32       msz
314  */
315
316 typedef struct v0_algs {
317   bulkalgs _b;
318   gencomp_algs ga;
319 } v0_algs;
320
321 typedef struct v0_ctx {
322   bulkctx _b;
323   size_t tagsz;
324   struct {
325     gcipher *c;
326     gmac *m;
327   } d[NDIR];
328 } v0_ctx;
329
330 static bulkalgs *v0_getalgs(const algswitch *asw, dstr *e,
331                             key_file *kf, key *k)
332 {
333   v0_algs *a = CREATE(v0_algs);
334   if (gencomp_getalgs(&a->ga, asw, e, kf, k)) { DESTROY(a); return (0); }
335   return (&a->_b);
336 }
337
338 #ifndef NTRACE
339 static void v0_tracealgs(const bulkalgs *aa)
340   { const v0_algs *a = (const v0_algs *)aa; gencomp_tracealgs(&a->ga); }
341 #endif
342
343 static int v0_checkalgs(bulkalgs *aa, const algswitch *asw, dstr *e)
344 {
345   v0_algs *a = (v0_algs *)aa;
346   if (gencomp_checkalgs(&a->ga, asw, e)) return (-1);
347   return (0);
348 }
349
350 static int v0_samealgsp(const bulkalgs *aa, const bulkalgs *bb)
351 {
352   const v0_algs *a = (const v0_algs *)aa, *b = (const v0_algs *)bb;
353   return (gencomp_samealgsp(&a->ga, &b->ga));
354 }
355
356 static void v0_alginfo(const bulkalgs *aa, admin *adm)
357   { const v0_algs *a = (const v0_algs *)aa; gencomp_alginfo(&a->ga, adm); }
358
359 static size_t v0_overhead(const bulkalgs *aa)
360 {
361   const v0_algs *a = (const v0_algs *)aa;
362   return (a->ga.tagsz + SEQSZ + a->ga.c->blksz);
363 }
364
365 static size_t v0_expsz(const bulkalgs *aa)
366   { const v0_algs *a = (const v0_algs *)aa; return (gencomp_expsz(&a->ga)); }
367
368 static bulkctx *v0_genkeys(const bulkalgs *aa, const deriveargs *da)
369 {
370   const v0_algs *a = (const v0_algs *)aa;
371   v0_ctx *bc = CREATE(v0_ctx);
372   octet k[MAXHASHSZ];
373   int i;
374
375   bc->tagsz = a->ga.tagsz;
376   for (i = 0; i < NDIR; i++) {
377     if (!(da->f&(1 << i))) { bc->d[i].c = 0; bc->d[i].m = 0; continue; }
378     derivekey(k, a->ga.cksz, da, i, "encryption");
379     bc->d[i].c = GC_INIT(a->ga.c, k, a->ga.cksz);
380     derivekey(k, a->ga.mksz, da, i, "integrity");
381     bc->d[i].m = GM_KEY(a->ga.m, k, a->ga.mksz);
382   }
383   return (&bc->_b);
384 }
385
386 static bulkchal *v0_genchal(const bulkalgs *aa)
387 {
388   const v0_algs *a = (const v0_algs *)aa;
389   return (gencomp_genchal(&a->ga));
390 }
391 #define v0_chaltag gencomp_chaltag
392 #define v0_chalvrf gencomp_chalvrf
393 #define v0_freechal gencomp_freechal
394
395 static void v0_freealgs(bulkalgs *aa)
396   { v0_algs *a = (v0_algs *)aa; DESTROY(a); }
397
398 static void v0_freectx(bulkctx *bbc)
399 {
400   v0_ctx *bc = (v0_ctx *)bbc;
401   int i;
402
403   for (i = 0; i < NDIR; i++) {
404     if (bc->d[i].c) GC_DESTROY(bc->d[i].c);
405     if (bc->d[i].m) GM_DESTROY(bc->d[i].m);
406   }
407   DESTROY(bc);
408 }
409
410 static int v0_encrypt(bulkctx *bbc, unsigned ty,
411                       buf *b, buf *bb, uint32 seq)
412 {
413   v0_ctx *bc = (v0_ctx *)bbc;
414   ghash *h;
415   gcipher *c = bc->d[DIR_OUT].c;
416   const octet *p = BCUR(b);
417   size_t sz = BLEFT(b);
418   octet *qmac, *qseq, *qiv, *qpk;
419   size_t ivsz;
420   size_t tagsz = bc->tagsz;
421   octet t[4];
422
423   assert(c);
424   ivsz = GC_CLASS(c)->blksz;
425
426   /* --- Determine the ciphertext layout --- */
427
428   if (buf_ensure(bb, tagsz + SEQSZ + ivsz + sz)) return (0);
429   qmac = BCUR(bb); qseq = qmac + tagsz; qiv = qseq + SEQSZ; qpk = qiv + ivsz;
430   BSTEP(bb, tagsz + SEQSZ + ivsz + sz);
431
432   /* --- Store the type --- *
433    *
434    * This isn't transmitted, but it's covered by the MAC.
435    */
436
437   STORE32(t, ty);
438
439   /* --- Store the sequence number --- */
440
441   STORE32(qseq, seq);
442
443   /* --- Establish an initialization vector if necessary --- */
444
445   if (ivsz) {
446     rand_get(RAND_GLOBAL, qiv, ivsz);
447     GC_SETIV(c, qiv);
448     TRACE_IV(qiv, ivsz);
449   }
450
451   /* --- Encrypt the packet --- */
452
453   GC_ENCRYPT(c, p, qpk, sz);
454   TRACE_CT(qpk, sz);
455
456   /* --- Compute a MAC over type, sequence number, IV, and ciphertext --- */
457
458   if (tagsz) {
459     h = GM_INIT(bc->d[DIR_OUT].m);
460     GH_HASH(h, t, sizeof(t));
461     GH_HASH(h, qseq, SEQSZ + ivsz + sz);
462     memcpy(qmac, GH_DONE(h, 0), tagsz);
463     GH_DESTROY(h);
464     TRACE_MAC(qmac, tagsz);
465   }
466
467   /* --- We're done --- */
468
469   return (0);
470 }
471
472 static int v0_decrypt(bulkctx *bbc, unsigned ty,
473                       buf *b, buf *bb, uint32 *seq)
474 {
475   v0_ctx *bc = (v0_ctx *)bbc;
476   const octet *pmac, *piv, *pseq, *ppk;
477   size_t psz = BLEFT(b);
478   size_t sz;
479   octet *q = BCUR(bb);
480   ghash *h;
481   gcipher *c = bc->d[DIR_IN].c;
482   size_t ivsz;
483   size_t tagsz = bc->tagsz;
484   octet t[4];
485
486   assert(c);
487   ivsz = GC_CLASS(c)->blksz;
488
489   /* --- Break up the packet into its components --- */
490
491   if (psz < ivsz + SEQSZ + tagsz) {
492     T( trace(T_KEYSET, "keyset: block too small for keyset"); )
493     return (KSERR_MALFORMED);
494   }
495   sz = psz - ivsz - SEQSZ - tagsz;
496   pmac = BCUR(b); pseq = pmac + tagsz; piv = pseq + SEQSZ; ppk = piv + ivsz;
497   STORE32(t, ty);
498
499   /* --- Verify the MAC on the packet --- */
500
501   if (tagsz) {
502     h = GM_INIT(bc->d[DIR_IN].m);
503     GH_HASH(h, t, sizeof(t));
504     GH_HASH(h, pseq, SEQSZ + ivsz + sz);
505     CHECK_MAC(h, pmac, tagsz);
506   }
507
508   /* --- Decrypt the packet --- */
509
510   if (ivsz) {
511     TRACE_IV(piv, ivsz);
512     GC_SETIV(c, piv);
513   }
514   GC_DECRYPT(c, ppk, q, sz);
515
516   /* --- Finished --- */
517
518   *seq = LOAD32(pseq);
519   BSTEP(bb, sz);
520   return (0);
521 }
522
523 /*----- The implicit-IV transform -----------------------------------------*
524  *
525  * The v0 transform makes everything explicit.  There's an IV because the
526  * cipher needs an IV; there's a sequence number because replay prevention
527  * needs a sequence number.
528  *
529  * This new transform works rather differently.  We make use of a block
530  * cipher to encrypt the sequence number, and use that as the IV.  We
531  * transmit the sequence number in the clear, as before.  This reduces
532  * overhead; and it's not a significant privacy leak because the adversary
533  * can see the order in which the messages are transmitted -- i.e., the
534  * sequence numbers are almost completely predictable anyway.
535  *
536  * So, a MAC is computed over
537  *
538  *              +--------+ +--------+------...------+
539  *              |  type  | |  seq   |   ciphertext  |
540  *              +--------+ +--------+------...------+
541  *                  32         32          sz
542  *
543  * and we actually transmit the following as the cryptogram.
544  *
545  *              +---...---+------+------...------+
546  *              |   tag   | seq  |   ciphertext  |
547  *              +---...---+------+------...------+
548  *                 tagsz     32         sz
549  *
550  * Challenge tags are calculated by applying the MAC to the sequence number
551  * and message, concatenated as follows.
552  *
553  *              +--------+---...---+
554  *              |  seq   |    m    |
555  *              +--------+---...---+
556  *                  32       msz
557  */
558
559 typedef struct iiv_algs {
560   bulkalgs _b;
561   gencomp_algs ga;
562   const gccipher *b; size_t bksz;
563 } iiv_algs;
564
565 typedef struct iiv_ctx {
566   bulkctx _b;
567   size_t tagsz;
568   struct {
569     gcipher *c, *b;
570     gmac *m;
571   } d[NDIR];
572 } iiv_ctx;
573
574
575 static bulkalgs *iiv_getalgs(const algswitch *asw, dstr *e,
576                             key_file *kf, key *k)
577 {
578   iiv_algs *a = CREATE(iiv_algs);
579   dstr d = DSTR_INIT, dd = DSTR_INIT;
580   const char *p;
581   char *q;
582
583   if (gencomp_getalgs(&a->ga, asw, e, kf, k)) goto fail;
584
585   if ((p = key_getattr(kf, k, "blkc")) == 0) {
586     dstr_puts(&dd, a->ga.c->name);
587     if ((q = strrchr(dd.buf, '-')) != 0) *q = 0;
588     p = dd.buf;
589   }
590   dstr_putf(&d, "%s-ecb", p);
591   if ((a->b = gcipher_byname(d.buf)) == 0) {
592     a_format(e, "unknown-blkc", "%s", p, A_END);
593     goto fail;
594   }
595
596   dstr_destroy(&d); dstr_destroy(&dd);
597   return (&a->_b);
598 fail:
599   dstr_destroy(&d); dstr_destroy(&dd);
600   DESTROY(a);
601   return (0);
602 }
603
604 #ifndef NTRACE
605 static void iiv_tracealgs(const bulkalgs *aa)
606 {
607   const iiv_algs *a = (const iiv_algs *)aa;
608
609   gencomp_tracealgs(&a->ga);
610   trace(T_CRYPTO,
611         "crypto: blkc = %.*s", (int)strlen(a->b->name) - 4, a->b->name);
612 }
613 #endif
614
615 static int iiv_checkalgs(bulkalgs *aa, const algswitch *asw, dstr *e)
616 {
617   iiv_algs *a = (iiv_algs *)aa;
618
619   if (gencomp_checkalgs(&a->ga, asw, e)) return (-1);
620
621   if ((a->bksz = keysz(asw->hashsz, a->b->keysz)) == 0) {
622     a_format(e, "blkc", "%.*s", strlen(a->b->name) - 4, a->b->name,
623              "no-key-size", "%lu", (unsigned long)asw->hashsz,
624              A_END);
625     return (-1);
626   }
627   if (a->b->blksz < a->ga.c->blksz) {
628     a_format(e, "blkc", "%.*s", strlen(a->b->name) - 4, a->b->name,
629              "blksz-insufficient", A_END);
630     return (-1);
631   }
632   return (0);
633 }
634
635 static int iiv_samealgsp(const bulkalgs *aa, const bulkalgs *bb)
636 {
637   const iiv_algs *a = (const iiv_algs *)aa, *b = (const iiv_algs *)bb;
638   return (gencomp_samealgsp(&a->ga, &b->ga) && a->b == b->b);
639 }
640
641 static void iiv_alginfo(const bulkalgs *aa, admin *adm)
642 {
643   const iiv_algs *a = (const iiv_algs *)aa;
644   gencomp_alginfo(&a->ga, adm);
645   a_info(adm,
646          "blkc=%.*s", strlen(a->b->name) - 4, a->b->name,
647          "blkc-keysz=%lu", (unsigned long)a->bksz,
648          "blkc-blksz=%lu", (unsigned long)a->b->blksz,
649          A_END);
650 }
651
652 static size_t iiv_overhead(const bulkalgs *aa)
653   { const iiv_algs *a = (const iiv_algs *)aa; return (a->ga.tagsz + SEQSZ); }
654
655 static size_t iiv_expsz(const bulkalgs *aa)
656 {
657   const iiv_algs *a = (const iiv_algs *)aa;
658   return (gencomp_expsz(&a->ga));
659 }
660
661 static bulkctx *iiv_genkeys(const bulkalgs *aa, const deriveargs *da)
662 {
663   const iiv_algs *a = (const iiv_algs *)aa;
664   iiv_ctx *bc = CREATE(iiv_ctx);
665   octet k[MAXHASHSZ];
666   int i;
667
668   bc->tagsz = a->ga.tagsz;
669   for (i = 0; i < NDIR; i++) {
670     if (!(da->f&(1 << i)))
671       { bc->d[i].c = 0; bc->d[i].b = 0; bc->d[i].m = 0; continue; }
672     derivekey(k, a->ga.cksz, da, i, "encryption");
673     bc->d[i].c = GC_INIT(a->ga.c, k, a->ga.cksz);
674     derivekey(k, a->bksz, da, i, "blkc");
675     bc->d[i].b = GC_INIT(a->b, k, a->bksz);
676     derivekey(k, a->ga.mksz, da, i, "integrity");
677     bc->d[i].m = GM_KEY(a->ga.m, k, a->ga.mksz);
678   }
679   return (&bc->_b);
680 }
681
682 static bulkchal *iiv_genchal(const bulkalgs *aa)
683 {
684   const iiv_algs *a = (const iiv_algs *)aa;
685   return (gencomp_genchal(&a->ga));
686 }
687 #define iiv_chaltag gencomp_chaltag
688 #define iiv_chalvrf gencomp_chalvrf
689 #define iiv_freechal gencomp_freechal
690
691 static void iiv_freealgs(bulkalgs *aa)
692   { iiv_algs *a = (iiv_algs *)aa; DESTROY(a); }
693
694 static void iiv_freectx(bulkctx *bbc)
695 {
696   iiv_ctx *bc = (iiv_ctx *)bbc;
697   int i;
698
699   for (i = 0; i < NDIR; i++) {
700     if (bc->d[i].c) GC_DESTROY(bc->d[i].c);
701     if (bc->d[i].b) GC_DESTROY(bc->d[i].b);
702     if (bc->d[i].m) GM_DESTROY(bc->d[i].m);
703   }
704   DESTROY(bc);
705 }
706
707 #define TRACE_PRESEQ(qseq, ivsz) do { IF_TRACING(T_KEYSET, {            \
708   trace_block(T_CRYPTO, "crypto: IV derivation input", (qseq), (ivsz)); \
709 }) } while (0)
710
711 static int iiv_encrypt(bulkctx *bbc, unsigned ty,
712                        buf *b, buf *bb, uint32 seq)
713 {
714   iiv_ctx *bc = (iiv_ctx *)bbc;
715   ghash *h;
716   gcipher *c = bc->d[DIR_OUT].c, *blkc = bc->d[DIR_OUT].b;
717   const octet *p = BCUR(b);
718   size_t sz = BLEFT(b);
719   octet *qmac, *qseq, *qpk;
720   size_t ivsz, blkcsz;
721   size_t tagsz = bc->tagsz;
722   octet t[4];
723
724   assert(c); assert(blkc);
725   ivsz = GC_CLASS(c)->blksz;
726   blkcsz = GC_CLASS(blkc)->blksz;
727
728   /* --- Determine the ciphertext layout --- */
729
730   if (buf_ensure(bb, tagsz + SEQSZ + sz)) return (0);
731   qmac = BCUR(bb); qseq = qmac + tagsz; qpk = qseq + SEQSZ;
732   BSTEP(bb, tagsz + SEQSZ + sz);
733
734   /* --- Store the type --- *
735    *
736    * This isn't transmitted, but it's covered by the MAC.
737    */
738
739   STORE32(t, ty);
740
741   /* --- Store the sequence number --- */
742
743   STORE32(qseq, seq);
744
745   /* --- Establish an initialization vector if necessary --- */
746
747   if (ivsz) {
748     memset(buf_u, 0, blkcsz - SEQSZ);
749     memcpy(buf_u + blkcsz - SEQSZ, qseq, SEQSZ);
750     TRACE_PRESEQ(buf_u, ivsz);
751     GC_ENCRYPT(blkc, buf_u, buf_u, blkcsz);
752     GC_SETIV(c, buf_u);
753     TRACE_IV(buf_u, ivsz);
754   }
755
756   /* --- Encrypt the packet --- */
757
758   GC_ENCRYPT(c, p, qpk, sz);
759   TRACE_CT(qpk, sz);
760
761   /* --- Compute a MAC over type, sequence number, and ciphertext --- */
762
763   if (tagsz) {
764     h = GM_INIT(bc->d[DIR_OUT].m);
765     GH_HASH(h, t, sizeof(t));
766     GH_HASH(h, qseq, SEQSZ + sz);
767     memcpy(qmac, GH_DONE(h, 0), tagsz);
768     GH_DESTROY(h);
769     TRACE_MAC(qmac, tagsz);
770   }
771
772   /* --- We're done --- */
773
774   return (0);
775 }
776
777 static int iiv_decrypt(bulkctx *bbc, unsigned ty,
778                        buf *b, buf *bb, uint32 *seq)
779 {
780   iiv_ctx *bc = (iiv_ctx *)bbc;
781   const octet *pmac, *pseq, *ppk;
782   size_t psz = BLEFT(b);
783   size_t sz;
784   octet *q = BCUR(bb);
785   ghash *h;
786   gcipher *c = bc->d[DIR_IN].c, *blkc = bc->d[DIR_IN].b;
787   size_t ivsz, blkcsz;
788   size_t tagsz = bc->tagsz;
789   octet t[4];
790
791   assert(c); assert(blkc);
792   ivsz = GC_CLASS(c)->blksz;
793   blkcsz = GC_CLASS(blkc)->blksz;
794
795   /* --- Break up the packet into its components --- */
796
797   if (psz < SEQSZ + tagsz) {
798     T( trace(T_KEYSET, "keyset: block too small for keyset"); )
799     return (KSERR_MALFORMED);
800   }
801   sz = psz - SEQSZ - tagsz;
802   pmac = BCUR(b); pseq = pmac + tagsz; ppk = pseq + SEQSZ;
803   STORE32(t, ty);
804
805   /* --- Verify the MAC on the packet --- */
806
807   if (tagsz) {
808     h = GM_INIT(bc->d[DIR_IN].m);
809     GH_HASH(h, t, sizeof(t));
810     GH_HASH(h, pseq, SEQSZ + sz);
811     CHECK_MAC(h, pmac, tagsz);
812   }
813
814   /* --- Decrypt the packet --- */
815
816   if (ivsz) {
817     memset(buf_u, 0, blkcsz - SEQSZ);
818     memcpy(buf_u + blkcsz - SEQSZ, pseq, SEQSZ);
819     TRACE_PRESEQ(buf_u, ivsz);
820     GC_ENCRYPT(blkc, buf_u, buf_u, blkcsz);
821     GC_SETIV(c, buf_u);
822     TRACE_IV(buf_u, ivsz);
823   }
824   GC_DECRYPT(c, ppk, q, sz);
825
826   /* --- Finished --- */
827
828   *seq = LOAD32(pseq);
829   BSTEP(bb, sz);
830   return (0);
831 }
832
833 /*----- The AEAD transform ------------------------------------------------*
834  *
835  * This transform uses a general authenticated encryption scheme.  Processing
836  * additional authenticated data isn't needed for encrypting messages, but it
837  * is required for challenge generation.  Good options include `chacha20-
838  * poly1305' or `rijndael-ocb3'; alas, `salsa20-naclbox' isn't acceptable.
839  *
840  * To be acceptable, the scheme must accept at least a 40-bit nonce.  (All of
841  * Catacomb's current AEAD schemes are suitable in this respect.)  The low 32
842  * bits are the sequence number.  The type is written to the next 8--32
843  * bytes: if the nonce size is 64 bits or more (preferred, for compatibility
844  * reasons) then the type is written as 32 bits, and the remaining space is
845  * padded with zero bytes; otherwise, the type is right-aligned in the
846  * remaining space.  Both fields are big-endian.
847  *
848  *              +--------+--+
849  *              |  seq   |ty|
850  *              +--------+--+
851  *                  32    8
852  *
853  *              +--------+----+
854  *              |  seq   | ty |
855  *              +--------+----+
856  *                  32     16
857  *
858  *              +--------+------+
859  *              |  seq   | type |
860  *              +--------+------+
861  *                  32      24
862  *
863  *              +--------+--------+---...---+
864  *              |  seq   |  type  |    0    |
865  *              +--------+--------+---...---+
866  *                  32       32     nsz - 64
867  *
868  * The ciphertext is formatted as
869  *
870  *              +---...---+--------+------...------+
871  *              |   tag   |  seq   |   ciphertext  |
872  *              +---...---+--------+------...------+
873  *                 tagsz      32          sz
874  *
875  * Challenge tags are calculated by encrypting the message, using the
876  * sequence number as a nonce (as a big-endian integer, padding with leading
877  * zeroes as needed to fill the space), and discarding the ciphertext.
878  *
879  *              +---...---+--------+ +-----...------+
880  *              |    0    |  seq   | |   message    |
881  *              +---...---+--------+ +-----...------+
882  *               nsz - 32     32           msz
883  */
884
885 #define AEAD_NONCEMAX 64
886
887 typedef struct aead_algs {
888   bulkalgs _b;
889   const gcaead *c;
890   size_t ksz, nsz, tsz;
891 } aead_algs;
892
893 typedef struct aead_ctx {
894   bulkctx _b;
895   struct { gaead_key *k; } d[NDIR];
896   size_t nsz, tsz;
897 } aead_ctx;
898
899 static bulkalgs *aead_getalgs(const algswitch *asw, dstr *e,
900                               key_file *kf, key *k)
901 {
902   aead_algs *a = CREATE(aead_algs);
903   const char *p;
904   char *qq;
905   gaead_key *kk = 0;
906   size_t ksz;
907   size_t csz = 0;
908   unsigned long n;
909
910   /* --- Collect the selected cipher and check that it's supported --- */
911
912   p = key_getattr(kf, k, "cipher"); if (!p) p = "rijndael-ocb3";
913   a->c = gaead_byname(p);
914   if (!a->c) { a_format(e, "unknown-cipher", "%s", p, A_END); goto fail; }
915   if (a->c->f&AEADF_NOAAD) {
916     a_format(e, "unsuitable-aead-cipher", "%s", p, "no-aad", A_END);
917     goto fail;
918   }
919   a->nsz = keysz_pad(8, a->c->noncesz);
920   if (!a->nsz) a->nsz = keysz_pad(5, a->c->noncesz);
921   if (!a->nsz) {
922     a_format(e, "unsuitable-aead-cipher", "%s", p, "nonce-too-small", A_END);
923     goto fail;
924   } else if (a->nsz > AEAD_NONCEMAX) {
925     a_format(e, "unsuitable-aead-cipher", "%s", p, "nonce-too-large", A_END);
926     goto fail;
927   }
928
929   /* --- Collect the selected MAC, and check the tag length --- *
930    *
931    * Of course, there isn't a separate MAC, so only accept `aead'.
932    */
933
934   p = key_getattr(kf, k, "tagsz");
935   if (!p) {
936     p = key_getattr(kf, k, "mac");
937     if (!p) ;
938     else if (strncmp(p, "aead", 4) != 0 || (p[4] && p[4] != '/'))
939       { a_format(e, "unknown-mac", "%s", p, A_END); goto fail; }
940     else if (p[4] == '/') p += 5;
941     else p = 0;
942   }
943   if (!p)
944     a->tsz = keysz(0, a->c->tagsz);
945   else {
946     n = strtoul(p, &qq, 0);
947     if (*qq) {
948       a_format(e, "bad-tag-length-string", "%s", p, A_END);
949       goto fail;
950     }
951     if (n%8 || (a->tsz = keysz(n/8, a->c->tagsz)) == 0)
952       { a_format(e, "bad-tag-length", "%lu", n, A_END); goto fail; }
953   }
954
955   /* --- Check that an empty message gives an empty ciphertext --- *
956    *
957    * This is necessary for producing challenges.  If the overhead is zero
958    * then we're fine; otherwise, we have to check the hard way.
959    */
960
961   if (a->c->ohd) {
962     ksz = keysz(0, a->c->keysz);
963     memset(buf_t, 0, ksz > a->nsz ? ksz : a->nsz);
964     kk = GAEAD_KEY(a->c, buf_t, ksz);
965     if (gaead_encrypt(kk, buf_t, a->nsz,
966                       buf_t, ksz,
967                       0, 0,
968                       buf_t, &csz,
969                       buf_t, a->tsz)) {
970       a_format(e, "unsuitable-aead-cipher", "%s", a->c->name,
971                "nonempty-ciphertext-for-empty-message", A_END);
972       goto fail;
973     }
974     GAEAD_DESTROY(kk); kk = 0;
975   }
976
977   return (&a->_b);
978 fail:
979   if (kk) GAEAD_DESTROY(kk);
980   DESTROY(a);
981   return (0);
982 }
983
984 #ifndef NTRACE
985 static void aead_tracealgs(const bulkalgs *aa)
986 {
987   const aead_algs *a = (const aead_algs *)aa;
988
989   trace(T_CRYPTO, "crypto: cipher = %s", a->c->name);
990   trace(T_CRYPTO, "crypto: noncesz = %lu", (unsigned long)a->nsz);
991   trace(T_CRYPTO, "crypto: tagsz = %lu", (unsigned long)a->tsz);
992 }
993 #endif
994
995 static int aead_checkalgs(bulkalgs *aa, const algswitch *asw, dstr *e)
996 {
997   aead_algs *a = (aead_algs *)aa;
998
999   if ((a->ksz = keysz(asw->hashsz, a->c->keysz)) == 0) {
1000     a_format(e, "cipher", "%s", a->c->name,
1001              "no-key-size", "%lu", (unsigned long)asw->hashsz,
1002              A_END);
1003     return (-1);
1004   }
1005   return (0);
1006 }
1007
1008 static int aead_samealgsp(const bulkalgs *aa, const bulkalgs *bb)
1009 {
1010   const aead_algs *a = (const aead_algs *)aa,
1011     *b = (const aead_algs *)bb;
1012   return (a->c == b->c && a->tsz == b->tsz);
1013 }
1014
1015 static void aead_alginfo(const bulkalgs *aa, admin *adm)
1016 {
1017   const aead_algs *a = (const aead_algs *)aa;
1018   a_info(adm, "cipher=%s", a->c->name,
1019          "cipher-keysz=%lu", (unsigned long)a->ksz,
1020          A_END);
1021   a_info(adm, "mac=aead", "mac-tagsz=%lu", (unsigned long)a->tsz, A_END);
1022 }
1023
1024 static size_t aead_overhead(const bulkalgs *aa)
1025 {
1026   const aead_algs *a = (const aead_algs *)aa;
1027   return (a->tsz + SEQSZ + a->c->ohd);
1028 }
1029
1030 static size_t aead_expsz(const bulkalgs *aa)
1031 {
1032   const aead_algs *a = (const aead_algs *)aa;
1033   return (a->c->blksz < 16 ? MEG(64) : MEG(2048));
1034 }
1035
1036 static bulkctx *aead_genkeys(const bulkalgs *aa, const deriveargs *da)
1037 {
1038   const aead_algs *a = (const aead_algs *)aa;
1039   aead_ctx *bc = CREATE(aead_ctx);
1040   octet k[MAXHASHSZ];
1041   int i;
1042
1043   for (i = 0; i < NDIR; i++) {
1044     if (!(da->f&(1 << i))) { bc->d[i].k = 0; continue; }
1045     derivekey(k, a->ksz, da, i, "encryption");
1046     bc->d[i].k = GAEAD_KEY(a->c, k, a->ksz);
1047   }
1048   bc->nsz = a->nsz; bc->tsz = a->tsz;
1049   return (&bc->_b);
1050 }
1051
1052 typedef struct aead_chal {
1053   bulkchal _b;
1054   gaead_key *k;
1055 } aead_chal;
1056
1057 static bulkchal *aead_genchal(const bulkalgs *aa)
1058 {
1059   const aead_algs *a = (const aead_algs *)aa;
1060   aead_chal *c = CREATE(aead_chal);
1061   rand_get(RAND_GLOBAL, buf_t, a->ksz);
1062   c->k = GAEAD_KEY(a->c, buf_t, a->ksz);
1063   IF_TRACING(T_CHAL, {
1064     trace(T_CHAL, "chal: generated new challenge key");
1065     trace_block(T_CRYPTO, "chal: new key", buf_t, a->ksz);
1066   })
1067   c->_b.tagsz = a->tsz;
1068   return (&c->_b);
1069 }
1070
1071 static int aead_chaltag(bulkchal *bc, const void *m, size_t msz,
1072                         uint32 seq, void *t)
1073 {
1074   aead_chal *c = (aead_chal *)bc;
1075   octet b[AEAD_NONCEMAX];
1076   size_t nsz = keysz_pad(4, c->k->ops->c->noncesz);
1077   size_t csz = 0;
1078   int rc;
1079
1080   assert(nsz); assert(nsz <= sizeof(b));
1081   memset(b, 0, nsz - 4); STORE32(b + nsz - 4, seq);
1082   rc = gaead_encrypt(c->k, b, nsz, m, msz, 0, 0,
1083                      buf_t, &csz, t, c->_b.tagsz);
1084   assert(!rc);
1085   return (0);
1086 }
1087
1088 static int aead_chalvrf(bulkchal *bc, const void *m, size_t msz,
1089                            uint32 seq, const void *t)
1090 {
1091   aead_chal *c = (aead_chal *)bc;
1092   octet b[AEAD_NONCEMAX];
1093   size_t nsz = keysz(4, c->k->ops->c->noncesz);
1094   size_t psz = 0;
1095   int rc;
1096
1097   assert(nsz); assert(nsz <= sizeof(b));
1098   memset(b, 0, nsz - 4); STORE32(b + nsz - 4, seq);
1099   rc = gaead_decrypt(c->k, b, nsz, m, msz, 0, 0,
1100                      buf_t, &psz, t, c->_b.tagsz);
1101   assert(rc >= 0);
1102   return (rc == 1 ? 0 : -1);
1103 }
1104
1105 static void aead_freechal(bulkchal *bc)
1106   { aead_chal *c = (aead_chal *)bc; GAEAD_DESTROY(c->k); DESTROY(c); }
1107
1108 static void aead_freealgs(bulkalgs *aa)
1109   { aead_algs *a = (aead_algs *)aa; DESTROY(a); }
1110
1111 static void aead_freectx(bulkctx *bbc)
1112 {
1113   aead_ctx *bc = (aead_ctx *)bbc;
1114   int i;
1115
1116   for (i = 0; i < NDIR; i++) { if (bc->d[i].k) GAEAD_DESTROY(bc->d[i].k); }
1117   DESTROY(bc);
1118 }
1119
1120 static void aead_fmtnonce(aead_ctx *bc, octet *n, uint32 seq, unsigned ty)
1121 {
1122   assert(bc->nsz <= AEAD_NONCEMAX); assert(ty <= 255);
1123   STORE32(n, seq);
1124   switch (bc->nsz) {
1125     case 5: STORE8(n + SEQSZ, ty); break;
1126     case 6: STORE16(n + SEQSZ, ty); break;
1127     case 7: STORE24(n + SEQSZ, ty); break;
1128     default: memset(n + 8, 0, bc->nsz - 8); /* and continue */
1129     case 8: STORE32(n + SEQSZ, ty); break;
1130   }
1131   TRACE_IV(n, bc->nsz);
1132 }
1133
1134 static int aead_encrypt(bulkctx *bbc, unsigned ty,
1135                         buf *b, buf *bb, uint32 seq)
1136 {
1137   aead_ctx *bc = (aead_ctx *)bbc;
1138   const octet *p = BCUR(b);
1139   gaead_key *k = bc->d[DIR_OUT].k;
1140   size_t sz = BLEFT(b);
1141   size_t csz = sz + k->ops->c->ohd;
1142   octet *qmac, *qseq, *qpk;
1143   octet n[AEAD_NONCEMAX];
1144   int rc;
1145
1146   assert(k);
1147
1148   if (buf_ensure(bb, bc->tsz + SEQSZ + csz)) return (0);
1149   qmac = BCUR(bb); qseq = qmac + bc->tsz; qpk = qseq + SEQSZ;
1150   STORE32(qseq, seq);
1151
1152   aead_fmtnonce(bc, n, seq, ty);
1153   rc = gaead_encrypt(k, n, bc->nsz, 0, 0, p, sz, qpk, &csz, qmac, bc->tsz);
1154   assert(!rc);
1155   BSTEP(bb, bc->tsz + SEQSZ + csz);
1156   TRACE_CT(qpk, csz);
1157   TRACE_MAC(qmac, bc->tsz);
1158
1159   return (0);
1160 }
1161
1162 static int aead_decrypt(bulkctx *bbc, unsigned ty,
1163                        buf *b, buf *bb, uint32 *seq_out)
1164 {
1165   aead_ctx *bc = (aead_ctx *)bbc;
1166   gaead_key *k = bc->d[DIR_IN].k;
1167   const octet *pmac, *pseq, *ppk;
1168   uint32 seq;
1169   size_t psz = BLEFT(b);
1170   size_t sz;
1171   octet *q = BCUR(bb);
1172   octet n[AEAD_NONCEMAX];
1173   int rc;
1174
1175   assert(k);
1176
1177   if (psz < bc->tsz + SEQSZ) {
1178     T( trace(T_KEYSET, "keyset: block too small for keyset"); )
1179     return (KSERR_MALFORMED);
1180   }
1181   sz = psz - bc->tsz - SEQSZ;
1182   pmac = BCUR(b); pseq = pmac + bc->tsz; ppk = pseq + SEQSZ;
1183   seq = LOAD32(pseq);
1184
1185   aead_fmtnonce(bc, n, seq, ty);
1186   rc = gaead_decrypt(k, n, bc->nsz, 0, 0, ppk, sz, q, &sz, pmac, bc->tsz);
1187   assert(rc >= 0);
1188   if (!rc) { TRACE_MACERR(pmac, bc->tsz); return (KSERR_DECRYPT); }
1189
1190   *seq_out = seq;
1191   BSTEP(bb, sz);
1192   return (0);
1193 }
1194
1195 /*----- The NaCl box transform --------------------------------------------*
1196  *
1197  * This transform is very similar to the NaCl `crypto_secretbox' transform
1198  * described in Bernstein, `Cryptography in NaCl', with the difference that,
1199  * rather than using XSalsa20, we use either Salsa20/r or ChaChar, because we
1200  * have no need of XSalsa20's extended nonce.  The default cipher is Salsa20.
1201  *
1202  * Salsa20 and ChaCha accept a 64-bit nonce.  The low 32 bits are the
1203  * sequence number, and the high 32 bits are the type, both big-endian.
1204  *
1205  *              +--------+--------+
1206  *              |  seq   |  type  |
1207  *              +--------+--------+
1208  *                  32       32
1209  *
1210  * A stream is generated by concatenating the raw output blocks generated
1211  * with this nonce and successive counter values starting from zero.  The
1212  * first 32 bytes of the stream are used as a key for Poly1305: the first 16
1213  * bytes are the universal hash key r, and the second 16 bytes are the mask
1214  * value s.
1215  *
1216  *              +------+------+ +------...------+
1217  *              |  r   |  s   | |   keystream   |
1218  *              +------+------+ +------...------+
1219  *                128    128           sz
1220  *
1221  * The remainder of the stream is XORed with the incoming plaintext to form a
1222  * ciphertext with the same length.  The ciphertext (only) is then tagged
1223  * using Poly1305.  The tag, sequence number, and ciphertext are concatenated
1224  * in this order, and transmitted.
1225  *
1226  *
1227  *              +---...---+------+------...------+
1228  *              |   tag   | seq  |   ciphertext  |
1229  *              +---...---+------+------...------+
1230  *                  128     32          sz
1231  *
1232  * Note that there is no need to authenticate the type separately, since it
1233  * was used to select the cipher nonce, and hence the Poly1305 key.  The
1234  * Poly1305 tag length is fixed.
1235  *
1236  * Challenge formation is rather tricky.  We can't use Poly1305 directly
1237  * because we need a random mask.  So we proceed as follows.  The challenge
1238  * generator has a Salsa20 or ChaCha key.  The sequence number is used as the
1239  * Salsa20 message number/nonce, padded at the start with zeroes to form,
1240  * effectively, a 64-bit big-endian integer.
1241  *
1242  *              +--------+--------+
1243  *              |   0    |  seq   |
1244  *              +--------+--------+
1245  *                  32       32
1246  *
1247  * 256 bits (32 bytes) of keystream are generated and used as a Poly1305 hash
1248  * key r and mask s.  These are then used to hash the message, and the
1249  * resulting tag is the challenge.
1250  */
1251
1252 typedef struct naclbox_algs {
1253   aead_algs _b;
1254   const gccipher *c;
1255 } naclbox_algs;
1256
1257 static bulkalgs *naclbox_getalgs(const algswitch *asw, dstr *e,
1258                                  key_file *kf, key *k)
1259 {
1260   naclbox_algs *a = CREATE(naclbox_algs);
1261   const char *p;
1262   char *qq;
1263   unsigned long n;
1264
1265   /* --- Collect the selected cipher and check that it's supported --- */
1266
1267   p = key_getattr(kf, k, "cipher");
1268   if (!p || strcmp(p, "salsa20") == 0)
1269     { a->_b.c = &salsa20_naclbox; a->c = &salsa20; }
1270   else if (strcmp(p, "salsa20/12") == 0)
1271     { a->_b.c = &salsa2012_naclbox; a->c = &salsa2012; }
1272   else if (strcmp(p, "salsa20/8") == 0)
1273     { a->_b.c = &salsa208_naclbox; a->c = &salsa208; }
1274   else if (strcmp(p, "chacha20") == 0)
1275     { a->_b.c = &chacha20_naclbox; a->c = &chacha20; }
1276   else if (strcmp(p, "chacha12") == 0)
1277     { a->_b.c = &chacha12_naclbox; a->c = &chacha12; }
1278   else if (strcmp(p, "chacha8") == 0)
1279     { a->_b.c = &chacha8_naclbox; a->c = &chacha8; }
1280   else {
1281     a_format(e, "unknown-cipher", "%s", p, A_END);
1282     goto fail;
1283   }
1284   a->_b.nsz = 8;
1285
1286   /* --- Collect the selected MAC, and check the tag length --- */
1287
1288   p = key_getattr(kf, k, "mac");
1289   if (!p)
1290     ;
1291   else if (strncmp(p, "poly1305", 8) != 0 || (p[8] && p[8] != '/')) {
1292     a_format(e, "unknown-mac", "%s", p, A_END);
1293     goto fail;
1294   } else if (p[8] == '/') {
1295     n = strtoul(p + 9, &qq, 0);
1296     if (*qq) {
1297       a_format(e, "bad-tag-length-string", "%s", p + 9, A_END);
1298       goto fail;
1299     }
1300     if (n != 128) {
1301       a_format(e, "bad-tag-length", "%lu", n, A_END);
1302       goto fail;
1303     }
1304   }
1305   a->_b.tsz = 16;
1306
1307   return (&a->_b._b);
1308 fail:
1309   DESTROY(a);
1310   return (0);
1311 }
1312
1313 #ifndef NTRACE
1314 static void naclbox_tracealgs(const bulkalgs *aa)
1315 {
1316   const naclbox_algs *a = (const naclbox_algs *)aa;
1317
1318   trace(T_CRYPTO, "crypto: cipher = %s", a->c->name);
1319   trace(T_CRYPTO, "crypto: mac = poly1305/128");
1320 }
1321 #endif
1322
1323 #define naclbox_checkalgs aead_checkalgs
1324 #define naclbox_samealgsp aead_samealgsp
1325
1326 static void naclbox_alginfo(const bulkalgs *aa, admin *adm)
1327 {
1328   const naclbox_algs *a = (const naclbox_algs *)aa;
1329   a_info(adm, "cipher=%s", a->c->name, "cipher-keysz=32", A_END);
1330   a_info(adm, "mac=poly1305", "mac-tagsz=16", A_END);
1331 }
1332
1333 #define naclbox_overhead aead_overhead
1334 #define naclbox_expsz aead_expsz
1335 #define naclbox_genkeys aead_genkeys
1336
1337 typedef struct naclbox_chal {
1338   bulkchal _b;
1339   gcipher *c;
1340 } naclbox_chal;
1341
1342 static bulkchal *naclbox_genchal(const bulkalgs *aa)
1343 {
1344   const naclbox_algs *a = (const naclbox_algs *)aa;
1345   naclbox_chal *c = CREATE(naclbox_chal);
1346   rand_get(RAND_GLOBAL, buf_t, a->_b.ksz);
1347   c->c = GC_INIT(a->c, buf_t, a->_b.ksz);
1348   IF_TRACING(T_CHAL, {
1349     trace(T_CHAL, "chal: generated new challenge key");
1350     trace_block(T_CRYPTO, "chal: new key", buf_t, a->_b.ksz);
1351   })
1352   c->_b.tagsz = POLY1305_TAGSZ;
1353   return (&c->_b);
1354 }
1355
1356 static int naclbox_chaltag(bulkchal *bc, const void *m, size_t msz,
1357                            uint32 seq, void *t)
1358 {
1359   naclbox_chal *c = (naclbox_chal *)bc;
1360   poly1305_key pk;
1361   poly1305_ctx pm;
1362   octet b[POLY1305_KEYSZ + POLY1305_MASKSZ];
1363
1364   STATIC_ASSERT(SALSA20_NONCESZ <= sizeof(b), "Need more space for nonce");
1365
1366   memset(b, 0, SALSA20_NONCESZ - 4); STORE32(b + SALSA20_NONCESZ - 4, seq);
1367   GC_SETIV(c->c, b); GC_ENCRYPT(c->c, 0, b, sizeof(b));
1368   poly1305_keyinit(&pk, b, POLY1305_KEYSZ);
1369   poly1305_macinit(&pm, &pk, b + POLY1305_KEYSZ);
1370   if (msz) poly1305_hash(&pm, m, msz);
1371   poly1305_done(&pm, t);
1372   return (0);
1373 }
1374
1375 static int naclbox_chalvrf(bulkchal *bc, const void *m, size_t msz,
1376                            uint32 seq, const void *t)
1377 {
1378   naclbox_chal *c = (naclbox_chal *)bc;
1379   poly1305_key pk;
1380   poly1305_ctx pm;
1381   octet b[POLY1305_KEYSZ + POLY1305_MASKSZ];
1382
1383   STATIC_ASSERT(SALSA20_NONCESZ <= sizeof(b), "Need more space for nonce");
1384   STATIC_ASSERT(POLY1305_TAGSZ <= sizeof(b), "Need more space for tag");
1385
1386   memset(b, 0, SALSA20_NONCESZ - 4); STORE32(b + SALSA20_NONCESZ - 4, seq);
1387   GC_SETIV(c->c, b); GC_ENCRYPT(c->c, 0, b, sizeof(b));
1388   poly1305_keyinit(&pk, b, POLY1305_KEYSZ);
1389   poly1305_macinit(&pm, &pk, b + POLY1305_KEYSZ);
1390   if (msz) poly1305_hash(&pm, m, msz);
1391   poly1305_done(&pm, b);
1392   return (ct_memeq(t, b, POLY1305_TAGSZ) ? 0 : -1);
1393 }
1394
1395 static void naclbox_freechal(bulkchal *bc)
1396   { naclbox_chal *c = (naclbox_chal *)bc; GC_DESTROY(c->c); DESTROY(c); }
1397
1398 static void naclbox_freealgs(bulkalgs *aa)
1399   { naclbox_algs *a = (naclbox_algs *)aa; DESTROY(a); }
1400
1401 #define naclbox_freectx aead_freectx
1402 #define naclbox_encrypt aead_encrypt
1403 #define naclbox_decrypt aead_decrypt
1404
1405 /*----- Bulk crypto transform table ---------------------------------------*/
1406
1407 const bulkops bulktab[] = {
1408
1409 #define COMMA ,
1410
1411 #define BULK(name, pre)                                                 \
1412   { name, pre##_getalgs, T( pre##_tracealgs COMMA )                     \
1413     pre##_checkalgs, pre##_samealgsp,                                   \
1414     pre##_alginfo, pre##_overhead, pre##_expsz,                         \
1415     pre##_genkeys, pre##_genchal, pre##_freealgs,                       \
1416     pre##_encrypt, pre##_decrypt, pre##_freectx,                        \
1417     pre##_chaltag, pre##_chalvrf, pre##_freechal }
1418
1419   BULK("v0", v0),
1420   BULK("iiv", iiv),
1421   BULK("aead", aead),
1422   BULK("naclbox", naclbox),
1423
1424 #undef BULK
1425   { 0 }
1426 };
1427
1428 /*----- That's all, folks -------------------------------------------------*/