chiark / gitweb /
c27d69fd7cff61df15db5c9c9ef7d58afb8551d0
[tripe] / server / keyexch.c
1 /* -*-c-*-
2  *
3  * Key exchange protocol
4  *
5  * (c) 2001 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Trivial IP Encryption (TrIPE).
11  *
12  * TrIPE is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "tripe.h"
30
31 /*----- Brief protocol overview -------------------------------------------*
32  *
33  * Let %$G$% be a cyclic group; let %$g$% be a generator of %$G$%, and let
34  * %$q$% be the order of %$G$%; for a key %$K$%, let %$E_K(\cdot)$% denote
35  * application of the symmetric packet protocol to a message; let
36  * %$H(\cdot)$% be the random oracle.  Let $\alpha \inr \{0,\ldots,q - 1\}$%
37  * be Alice's private key; let %$a = g^\alpha$% be her public key; let %$b$%
38  * be Bob's public key.
39  *
40  * At the beginning of the session, Alice chooses
41  *
42  *   %$\rho_A \inr \{0, \ldots q - 1\}$%
43  *
44  * We also have:
45  *
46  * %$r_A = g^{\rho_A}$%                 Alice's challenge
47  * %$c_A = H(\cookie{cookie}, r_A)$%    Alice's cookie
48  * %$v_A = \rho_A \xor H(\cookie{expected-reply}, a, r_A, r_B, b^{\rho_A})$%
49  *                                      Alice's challenge check value
50  * %$r_B^\alpha = a^{\rho_B}$%          Alice's reply
51  * %$K = r_B^{\rho_A} = r_B^{\rho_A} = g^{\rho_A\rho_B}$%
52  *                                      Alice and Bob's shared secret key
53  * %$w_A = H(\cookie{switch-request}, c_A, c_B)$%
54  *                                      Alice's switch request value
55  * %$u_A = H(\cookie{switch-confirm}, c_A, c_B)$%
56  *                                      Alice's switch confirm value
57  *
58  * The messages are then:
59  *
60  * %$\cookie{kx-pre-challenge}, r_A$%
61  *      Initial greeting.  In state @KXS_CHAL@.
62  *
63  * %$\cookie{kx-challenge}, r_A, c_B, v_A$%
64  *      Here's a full challenge for you to answer.
65  *
66  * %$\cookie{kx-reply}, r_A, c_B, v_A, E_K(r_B^\alpha))$%
67  *      Challenge accpeted: here's the answer.  Commit to my challenge.  Move
68  *      to @KXS_COMMIT@.
69  *
70  * %$\cookie{kx-switch-rq}, c_A, c_B, E_K(r_B^\alpha, w_A))$%
71  *      Reply received: here's my reply.  Committed; send data; move to
72  *      @KXS_SWITCH@.
73  *
74  * %$\cookie{kx-switch-ok}, E_K(u_A))$%
75  *      Switch received.  Committed; send data; move to @KXS_SWITCH@.
76  */
77
78 /*----- Static tables -----------------------------------------------------*/
79
80 static const char *const pkname[] = {
81   "pre-challenge", "challenge", "reply", "switch-rq", "switch-ok"
82 };
83
84 /*----- Various utilities -------------------------------------------------*/
85
86 /* --- @VALIDP@ --- *
87  *
88  * Arguments:   @const keyexch *kx@ = key exchange state
89  *              @time_t now@ = current time in seconds
90  *
91  * Returns:     Whether the challenge in the key-exchange state is still
92  *              valid or should be regenerated.
93  */
94
95 #define VALIDP(kx, now) ((now) < (kx)->t_valid)
96
97 /* --- @hashge@ --- *
98  *
99  * Arguments:   @ghash *h@ = pointer to hash context
100  *              @ge *x@ = pointer to group element
101  *
102  * Returns:     ---
103  *
104  * Use:         Adds the hash of a group element to the context.  Corrupts
105  *              @buf_t@.
106  */
107
108 static void hashge(ghash *h, ge *x)
109 {
110   buf b;
111   buf_init(&b, buf_t, sizeof(buf_t));
112   G_TOBUF(gg, &b, x);
113   assert(BOK(&b));
114   GH_HASH(h, BBASE(&b), BLEN(&b));
115 }
116
117 /* --- @mpmask@ --- *
118  *
119  * Arguments:   @buf *b@ = output buffer
120  *              @mp *x@ = the plaintext integer
121  *              @size_t n@ = the expected size of the plaintext
122  *              @const octet *k@ = pointer to key material
123  *              @size_t ksz@ = size of the key
124  *
125  * Returns:     Pointer to the output.
126  *
127  * Use:         Masks a multiprecision integer: returns %$x \xor H(k)$%, so
128  *              it's a random oracle thing rather than an encryption thing.
129  */
130
131 static octet *mpmask(buf *b, mp *x, size_t n, const octet *k, size_t ksz)
132 {
133   gcipher *mgf;
134   octet *p;
135
136   if ((p = buf_get(b, n)) == 0)
137     return (0);
138   mgf = GC_INIT(algs.mgf, k, ksz);
139   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
140     trace(T_CRYPTO, "masking index = %s", mpstr(x));
141     trace_block(T_CRYPTO, "masking key", k, ksz);
142   }))
143   mp_storeb(x, buf_t, n);
144   GC_ENCRYPT(mgf, buf_t, p, n);
145   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
146     trace_block(T_CRYPTO, "index plaintext", buf_t, n);
147     trace_block(T_CRYPTO, "masked ciphertext", p, n);
148   }))
149   GC_DESTROY(mgf);
150   return (p);
151 }
152
153 /* --- @mpunmask@ --- *
154  *
155  * Arguments:   @mp *d@ = the output integer
156  *              @const octet *p@ = pointer to the ciphertext
157  *              @size_t n@ = the size of the ciphertext
158  *              @const octet *k@ = pointer to key material
159  *              @size_t ksz@ = size of the key
160  *
161  * Returns:     The decrypted integer, or null.
162  *
163  * Use:         Unmasks a multiprecision integer.
164  */
165
166 static mp *mpunmask(mp *d, const octet *p, size_t n,
167                     const octet *k, size_t ksz)
168 {
169   gcipher *mgf;
170
171   mgf = GC_INIT(algs.mgf, k, ksz);
172   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
173     trace_block(T_CRYPTO, "unmasking key", k, ksz);
174     trace_block(T_CRYPTO, "masked ciphertext", p, n);
175   }))
176   GC_DECRYPT(mgf, p, buf_t, n);
177   d = mp_loadb(d, buf_t, n);
178   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
179     trace_block(T_CRYPTO, "index plaintext", buf_t, n);
180     trace(T_CRYPTO, "unmasked index = %s", mpstr(d));
181   }))
182   GC_DESTROY(mgf);
183   return (d);
184 }
185
186 /* --- @hashcheck@ --- *
187  *
188  * Arguments:   @ge *kpub@ = sender's public key
189  *              @ge *cc@ = receiver's challenge
190  *              @ge *c@ = sender's challenge
191  *              @ge *y@ = reply to sender's challenge
192  *
193  * Returns:     Pointer to the hash value (in @buf_t@)
194  *
195  * Use:         Computes the check-value hash, used to mask or unmask
196  *              indices to prove the validity of challenges.  This computes
197  *              the masking key used in challenge check values.  This is
198  *              really the heart of the whole thing, since it ensures that
199  *              the index can be recovered from the history of hashing
200  *              queries, which gives us (a) a proof that the authentication
201  *              process is zero-knowledge, and (b) a proof that the whole
202  *              key-exchange is deniable.
203  */
204
205 static const octet *hashcheck(ge *kpub, ge *cc, ge *c, ge *y)
206 {
207   ghash *h = GH_INIT(algs.h);
208
209   HASH_STRING(h, "tripe-expected-reply");
210   hashge(h, kpub);
211   hashge(h, cc);
212   hashge(h, c);
213   hashge(h, y);
214   GH_DONE(h, buf_t);
215   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
216     trace(T_CRYPTO, "computing challenge check hash");
217     trace(T_CRYPTO, "public key = %s", gestr(gg, kpub));
218     trace(T_CRYPTO, "receiver challenge = %s", gestr(gg, cc));
219     trace(T_CRYPTO, "sender challenge = %s", gestr(gg, c));
220     trace(T_CRYPTO, "sender reply = %s", gestr(gg, y));
221     trace_block(T_CRYPTO, "hash output", buf_t, algs.hashsz);
222   }))
223   GH_DESTROY(h);
224   return (buf_t);
225 }
226
227 /* --- @sendchallenge@ --- *
228  *
229  * Arguments:   @keyexch *kx@ = pointer to key exchange block
230  *              @buf *b@ = output buffer for challenge
231  *              @ge *c@ = peer's actual challenge
232  *              @const octet *hc@ = peer's challenge cookie
233  *
234  * Returns:     ---
235  *
236  * Use:         Writes a full challenge to the message buffer.
237  */
238
239 static void sendchallenge(keyexch *kx, buf *b, ge *c, const octet *hc)
240 {
241   G_TOBUF(gg, b, kx->c);
242   buf_put(b, hc, algs.hashsz);
243   mpmask(b, kx->alpha, indexsz,
244          hashcheck(kpub, c, kx->c, kx->rx), algs.hashsz);
245 }
246
247 /* --- @timer@ --- *
248  *
249  * Arguments:   @struct timeval *tv@ = the current time
250  *              @void *v@ = pointer to key exchange context
251  *
252  * Returns:     ---
253  *
254  * Use:         Acts when the key exchange timer goes off.
255  */
256
257 static void timer(struct timeval *tv, void *v)
258 {
259   keyexch *kx = v;
260   kx->f &= ~KXF_TIMER;
261   T( trace(T_KEYEXCH, "keyexch: timer has popped"); )
262   kx_start(kx, 0);
263 }
264
265 /* --- @settimer@ --- *
266  *
267  * Arguments:   @keyexch *kx@ = pointer to key exchange context
268  *              @struct timeval *tv@ = when to set the timer for
269  *
270  * Returns:     ---
271  *
272  * Use:         Sets the timer for the next key exchange attempt.
273  */
274
275 static void settimer(keyexch *kx, struct timeval *tv)
276 {
277   if (kx->f & KXF_TIMER) sel_rmtimer(&kx->t);
278   sel_addtimer(&sel, &kx->t, tv, timer, kx);
279   kx->f |= KXF_TIMER;
280 }
281
282 /*----- Challenge management ----------------------------------------------*/
283
284 /* --- Notes on challenge management --- *
285  *
286  * We may get multiple different replies to our key exchange; some will be
287  * correct, some inserted by attackers.  Up until @KX_THRESH@, all challenges
288  * received will be added to the table and given a full response.  After
289  * @KX_THRESH@ distinct challenges are received, we return only a `cookie':
290  * our existing challenge, followed by a hash of the sender's challenge.  We
291  * do %%\emph{not}%% give a bare challenge a reply slot at this stage.  All
292  * properly-formed cookies are assigned a table slot: if none is spare, a
293  * used slot is randomly selected and destroyed.  A cookie always receives a
294  * full reply.
295  */
296
297 /* --- @kxc_destroy@ --- *
298  *
299  * Arguments:   @kxchal *kxc@ = pointer to the challenge block
300  *
301  * Returns:     ---
302  *
303  * Use:         Disposes of a challenge block.
304  */
305
306 static void kxc_destroy(kxchal *kxc)
307 {
308   if (kxc->f & KXF_TIMER)
309     sel_rmtimer(&kxc->t);
310   G_DESTROY(gg, kxc->c);
311   G_DESTROY(gg, kxc->r);
312   ks_drop(kxc->ks);
313   DESTROY(kxc);
314 }
315
316 /* --- @kxc_stoptimer@ --- *
317  *
318  * Arguments:   @kxchal *kxc@ = pointer to the challenge block
319  *
320  * Returns:     ---
321  *
322  * Use:         Stops the challenge's retry timer from sending messages.
323  *              Useful when the state machine is in the endgame of the
324  *              exchange.
325  */
326
327 static void kxc_stoptimer(kxchal *kxc)
328 {
329   if (kxc->f & KXF_TIMER)
330     sel_rmtimer(&kxc->t);
331   kxc->f &= ~KXF_TIMER;
332 }
333
334 /* --- @kxc_new@ --- *
335  *
336  * Arguments:   @keyexch *kx@ = pointer to key exchange block
337  *
338  * Returns:     A pointer to the challenge block.
339  *
340  * Use:         Returns a pointer to a new challenge block to fill in.
341  */
342
343 static kxchal *kxc_new(keyexch *kx)
344 {
345   kxchal *kxc;
346   unsigned i;
347
348   /* --- If we're over reply threshold, discard one at random --- */
349
350   if (kx->nr < KX_NCHAL)
351     i = kx->nr++;
352   else {
353     i = rand_global.ops->range(&rand_global, KX_NCHAL);
354     kxc_destroy(kx->r[i]);
355   }
356
357   /* --- Fill in the new structure --- */
358
359   kxc = CREATE(kxchal);
360   kxc->c = G_CREATE(gg);
361   kxc->r = G_CREATE(gg);
362   kxc->ks = 0;
363   kxc->kx = kx;
364   kxc->f = 0;
365   kx->r[i] = kxc;
366   return (kxc);
367 }
368
369 /* --- @kxc_bychal@ --- *
370  *
371  * Arguments:   @keyexch *kx@ = pointer to key exchange block
372  *              @ge *c@ = challenge from remote host
373  *
374  * Returns:     Pointer to the challenge block, or null.
375  *
376  * Use:         Finds a challenge block, given its challenge.
377  */
378
379 static kxchal *kxc_bychal(keyexch *kx, ge *c)
380 {
381   unsigned i;
382
383   for (i = 0; i < kx->nr; i++) {
384     if (G_EQ(gg, c, kx->r[i]->c))
385       return (kx->r[i]);
386   }
387   return (0);
388 }
389
390 /* --- @kxc_byhc@ --- *
391  *
392  * Arguments:   @keyexch *kx@ = pointer to key exchange block
393  *              @const octet *hc@ = challenge hash from remote host
394  *
395  * Returns:     Pointer to the challenge block, or null.
396  *
397  * Use:         Finds a challenge block, given a hash of its challenge.
398  */
399
400 static kxchal *kxc_byhc(keyexch *kx, const octet *hc)
401 {
402   unsigned i;
403
404   for (i = 0; i < kx->nr; i++) {
405     if (memcmp(hc, kx->r[i]->hc, algs.hashsz) == 0)
406       return (kx->r[i]);
407   }
408   return (0);
409 }
410
411 /* --- @kxc_answer@ --- *
412  *
413  * Arguments:   @keyexch *kx@ = pointer to key exchange block
414  *              @kxchal *kxc@ = pointer to challenge block
415  *
416  * Returns:     ---
417  *
418  * Use:         Sends a reply to the remote host, according to the data in
419  *              this challenge block.
420  */
421
422 static void kxc_answer(keyexch *kx, kxchal *kxc);
423
424 static void kxc_timer(struct timeval *tv, void *v)
425 {
426   kxchal *kxc = v;
427   kxc->f &= ~KXF_TIMER;
428   kxc_answer(kxc->kx, kxc);
429 }
430
431 static void kxc_answer(keyexch *kx, kxchal *kxc)
432 {
433   stats *st = p_stats(kx->p);
434   buf *b = p_txstart(kx->p, MSG_KEYEXCH | KX_REPLY);
435   struct timeval tv;
436   buf bb;
437
438   /* --- Build the reply packet --- */
439
440   T( trace(T_KEYEXCH, "keyexch: sending reply to `%s'", p_name(kx->p)); )
441   sendchallenge(kx, b, kxc->c, kxc->hc);
442   buf_init(&bb, buf_i, sizeof(buf_i));
443   G_TORAW(gg, &bb, kxc->r);
444   buf_flip(&bb);
445   ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_REPLY, &bb, b);
446
447   /* --- Update the statistics --- */
448
449   if (BOK(b)) {
450     st->n_kxout++;
451     st->sz_kxout += BLEN(b);
452     p_txend(kx->p);
453   }
454
455   /* --- Schedule another resend --- */
456
457   if (kxc->f & KXF_TIMER)
458     sel_rmtimer(&kxc->t);
459   gettimeofday(&tv, 0);
460   tv.tv_sec += T_RETRY;
461   sel_addtimer(&sel, &kxc->t, &tv, kxc_timer, kxc);
462   kxc->f |= KXF_TIMER;
463 }
464
465 /*----- Individual message handlers ---------------------------------------*/
466
467 /* --- @doprechallenge@ --- *
468  *
469  * Arguments:   @keyexch *kx@ = pointer to key exchange block
470  *              @buf *b@ = buffer containing the packet
471  *
472  * Returns:     Zero if OK, nonzero of the packet was rejected.
473  *
474  * Use:         Processes a pre-challenge message.
475  */
476
477 static int doprechallenge(keyexch *kx, buf *b)
478 {
479   stats *st = p_stats(kx->p);
480   ge *c = G_CREATE(gg);
481   ghash *h;
482
483   /* --- Ensure that we're in a sensible state --- */
484
485   if (kx->s != KXS_CHAL) {
486     a_warn("KX", "?PEER", kx->p, "unexpected", "pre-challenge", A_END);
487     goto bad;
488   }
489
490   /* --- Unpack the packet --- */
491
492   if (G_FROMBUF(gg, b, c) || BLEFT(b))
493     goto bad;
494
495   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
496     trace(T_CRYPTO, "crypto: challenge = %s", gestr(gg, c));
497   }))
498
499   /* --- Send out a full challenge by return --- */
500
501   b = p_txstart(kx->p, MSG_KEYEXCH | KX_CHAL);
502   h = GH_INIT(algs.h);
503   HASH_STRING(h, "tripe-cookie");
504   hashge(h, c);
505   sendchallenge(kx, b, c, GH_DONE(h, 0));
506   GH_DESTROY(h);
507   st->n_kxout++;
508   st->sz_kxout += BLEN(b);
509   p_txend(kx->p);
510
511   /* --- Done --- */
512
513   G_DESTROY(gg, c);
514   return (0);
515
516 bad:
517   if (c) G_DESTROY(gg, c);
518   return (-1);
519 }
520
521 /* --- @respond@ --- *
522  *
523  * Arguments:   @keyexch *kx@ = pointer to key exchange block
524  *              @unsigned msg@ = message code for this packet
525  *              @buf *b@ = buffer containing the packet
526  *
527  * Returns:     Key-exchange challenge block, or null.
528  *
529  * Use:         Computes a response for the given challenge, entering it into
530  *              a challenge block and so on.
531  */
532
533 static kxchal *respond(keyexch *kx, unsigned msg, buf *b)
534 {
535   ge *c = G_CREATE(gg);
536   ge *r = G_CREATE(gg);
537   ge *cc = G_CREATE(gg);
538   const octet *hc, *ck;
539   size_t x, y, z;
540   mp *cv = 0;
541   kxchal *kxc;
542   ghash *h = 0;
543   buf bb;
544   int ok;
545
546   /* --- Unpack the packet --- */
547
548   if (G_FROMBUF(gg, b, c) ||
549       (hc = buf_get(b, algs.hashsz)) == 0 ||
550       (ck = buf_get(b, indexsz)) == 0) {
551     a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
552     goto bad;
553   }
554   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
555     trace(T_CRYPTO, "crypto: challenge = %s", gestr(gg, c));
556     trace_block(T_CRYPTO, "crypto: cookie", hc, algs.hashsz);
557     trace_block(T_CRYPTO, "crypto: check-value", ck, indexsz);
558   }))
559
560   /* --- Discard a packet with an invalid cookie --- */
561
562   if (hc && memcmp(hc, kx->hc, algs.hashsz) != 0) {
563     a_warn("KX", "?PEER", kx->p, "incorrect", "cookie", A_END);
564     goto bad;
565   }
566
567   /* --- Recover the check value and verify it --- *
568    *
569    * To avoid recomputation on replays, we store a hash of the `right'
570    * value.  The `correct' value is unique, so this is right.
571    *
572    * This will also find a challenge block and, if necessary, populate it.
573    */
574
575   if ((kxc = kxc_bychal(kx, c)) != 0) {
576     h = GH_INIT(algs.h);
577     HASH_STRING(h, "tripe-check-hash");
578     GH_HASH(h, ck, indexsz);
579     ok = !memcmp(kxc->ck, GH_DONE(h, 0), algs.hashsz);
580     GH_DESTROY(h);
581     if (!ok) goto badcheck;
582   } else {
583
584     /* --- Compute the reply, and check the magic --- */
585
586     G_EXP(gg, r, c, kpriv);
587     cv = mpunmask(MP_NEW, ck, indexsz,
588                   hashcheck(kx->kpub, kx->c, c, r), algs.hashsz);
589     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
590       trace(T_CRYPTO, "crypto: computed reply = %s", gestr(gg, r));
591       trace(T_CRYPTO, "crypto: recovered log = %s", mpstr(cv));
592     }))
593     if (MP_CMP(cv, >, gg->r) ||
594         (G_EXP(gg, cc, gg->g, cv), !G_EQ(gg, c, cc)))
595       goto badcheck;
596
597     /* --- Fill in a new challenge block --- */
598
599     kxc = kxc_new(kx);
600     G_COPY(gg, kxc->c, c);
601     G_COPY(gg, kxc->r, r);
602
603     h = GH_INIT(algs.h);
604     HASH_STRING(h, "tripe-check-hash");
605     GH_HASH(h, ck, indexsz);
606     GH_DONE(h, kxc->ck);
607     GH_DESTROY(h);
608
609     h = GH_INIT(algs.h);
610     HASH_STRING(h, "tripe-cookie");
611     hashge(h, kxc->c);
612     GH_DONE(h, kxc->hc);
613     GH_DESTROY(h);
614
615     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
616       trace_block(T_CRYPTO, "crypto: computed cookie", kxc->hc, algs.hashsz);
617     }))
618
619     /* --- Work out the shared key --- */
620
621     G_EXP(gg, r, c, kx->alpha);
622     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
623       trace(T_CRYPTO, "crypto: shared secret = %s", gestr(gg, r));
624     }))
625
626     /* --- Compute the switch messages --- */
627
628     h = GH_INIT(algs.h); HASH_STRING(h, "tripe-switch-request");
629     hashge(h, kx->c); hashge(h, kxc->c);
630     GH_DONE(h, kxc->hswrq_out); GH_DESTROY(h);
631     h = GH_INIT(algs.h); HASH_STRING(h, "tripe-switch-confirm");
632     hashge(h, kx->c); hashge(h, kxc->c);
633     GH_DONE(h, kxc->hswok_out); GH_DESTROY(h);
634
635     h = GH_INIT(algs.h); HASH_STRING(h, "tripe-switch-request");
636     hashge(h, kxc->c); hashge(h, kx->c);
637     GH_DONE(h, kxc->hswrq_in); GH_DESTROY(h);
638     h = GH_INIT(algs.h); HASH_STRING(h, "tripe-switch-confirm");
639     hashge(h, kxc->c); hashge(h, kx->c);
640     GH_DONE(h, kxc->hswok_in); GH_DESTROY(h);
641
642     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
643       trace_block(T_CRYPTO, "crypto: outbound switch request",
644                   kxc->hswrq_out, algs.hashsz);
645       trace_block(T_CRYPTO, "crypto: outbound switch confirm",
646                   kxc->hswok_out, algs.hashsz);
647       trace_block(T_CRYPTO, "crypto: inbound switch request",
648                   kxc->hswrq_in, algs.hashsz);
649       trace_block(T_CRYPTO, "crypto: inbound switch confirm",
650                   kxc->hswok_in, algs.hashsz);
651     }))
652
653     /* --- Create a new symmetric keyset --- */
654
655     buf_init(&bb, buf_o, sizeof(buf_o));
656     G_TOBUF(gg, &bb, kx->c); x = BLEN(&bb);
657     G_TOBUF(gg, &bb, kxc->c); y = BLEN(&bb);
658     G_TOBUF(gg, &bb, r); z = BLEN(&bb);
659     assert(BOK(&bb));
660
661     kxc->ks = ks_gen(BBASE(&bb), x, y, z, kx->p);
662   }
663
664   G_DESTROY(gg, c);
665   G_DESTROY(gg, cc);
666   G_DESTROY(gg, r);
667   mp_drop(cv);
668   return (kxc);
669
670 badcheck:
671   a_warn("KX", "?PEER", kx->p, "bad-expected-reply-log", A_END);
672   goto bad;
673 bad:
674   G_DESTROY(gg, c);
675   G_DESTROY(gg, cc);
676   G_DESTROY(gg, r);
677   mp_drop(cv);
678   return (0);
679 }
680
681 /* --- @dochallenge@ --- *
682  *
683  * Arguments:   @keyexch *kx@ = pointer to key exchange block
684  *              @unsigned msg@ = message code for the packet
685  *              @buf *b@ = buffer containing the packet
686  *
687  * Returns:     Zero if OK, nonzero if the packet was rejected.
688  *
689  * Use:         Processes a packet containing a challenge.
690  */
691
692 static int dochallenge(keyexch *kx, buf *b)
693 {
694   kxchal *kxc;
695
696   if (kx->s != KXS_CHAL) {
697     a_warn("KX", "?PEER", kx->p, "unexpected", "challenge", A_END);
698     goto bad;
699   }
700   if ((kxc = respond(kx, KX_CHAL, b)) == 0)
701     goto bad;
702   if (BLEFT(b)) {
703     a_warn("KX", "?PEER", kx->p, "invalid", "challenge", A_END);
704     goto bad;
705   }
706   kxc_answer(kx, kxc);
707   return (0);
708
709 bad:
710   return (-1);
711 }
712
713 /* --- @resend@ --- *
714  *
715  * Arguments:   @keyexch *kx@ = pointer to key exchange context
716  *
717  * Returns:     ---
718  *
719  * Use:         Sends the next message for a key exchange.
720  */
721
722 static void resend(keyexch *kx)
723 {
724   kxchal *kxc;
725   buf bb;
726   stats *st = p_stats(kx->p);
727   struct timeval tv;
728   buf *b;
729
730   switch (kx->s) {
731     case KXS_CHAL:
732       T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
733                p_name(kx->p)); )
734       b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
735       G_TOBUF(gg, b, kx->c);
736       break;
737     case KXS_COMMIT:
738       T( trace(T_KEYEXCH, "keyexch: sending switch request to `%s'",
739                p_name(kx->p)); )
740       kxc = kx->r[0];
741       b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCH);
742       buf_put(b, kx->hc, algs.hashsz);
743       buf_put(b, kxc->hc, algs.hashsz);
744       buf_init(&bb, buf_i, sizeof(buf_i));
745       G_TORAW(gg, &bb, kxc->r);
746       buf_put(&bb, kxc->hswrq_out, algs.hashsz);
747       buf_flip(&bb);
748       ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCH, &bb, b);
749       break;
750     case KXS_SWITCH:
751       T( trace(T_KEYEXCH, "keyexch: sending switch confirmation to `%s'",
752                p_name(kx->p)); )
753       kxc = kx->r[0];
754       b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCHOK);
755       buf_init(&bb, buf_i, sizeof(buf_i));
756       buf_put(&bb, kxc->hswok_out, algs.hashsz);
757       buf_flip(&bb);
758       ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, &bb, b);
759       break;
760     default:
761       abort();
762   }
763
764   if (BOK(b)) {
765     st->n_kxout++;
766     st->sz_kxout += BLEN(b);
767     p_txend(kx->p);
768   }
769
770   if (kx->s < KXS_SWITCH) {
771     gettimeofday(&tv, 0);
772     tv.tv_sec += T_RETRY;
773     settimer(kx, &tv);
774   }
775 }
776
777 /* --- @decryptrest@ --- *
778  *
779  * Arguments:   @keyexch *kx@ = pointer to key exchange context
780  *              @kxchal *kxc@ = pointer to challenge block
781  *              @unsigned msg@ = type of incoming message
782  *              @buf *b@ = encrypted remainder of the packet
783  *
784  * Returns:     Zero if OK, nonzero on some kind of error.
785  *
786  * Use:         Decrypts the remainder of the packet, and points @b@ at the
787  *              recovered plaintext.
788  */
789
790 static int decryptrest(keyexch *kx, kxchal *kxc, unsigned msg, buf *b)
791 {
792   buf bb;
793
794   buf_init(&bb, buf_o, sizeof(buf_o));
795   if (ks_decrypt(kxc->ks, MSG_KEYEXCH | msg, b, &bb)) {
796     a_warn("KX", "?PEER", kx->p, "decrypt-failed", "%s", pkname[msg], A_END);
797     return (-1);
798   }
799   if (!BOK(&bb)) return (-1);
800   buf_init(b, BBASE(&bb), BLEN(&bb));
801   return (0);
802 }
803
804 /* --- @checkresponse@ --- *
805  *
806  * Arguments:   @keyexch *kx@ = pointer to key exchange context
807  *              @unsigned msg@ = type of incoming message
808  *              @buf *b@ = decrypted remainder of the packet
809  *
810  * Returns:     Zero if OK, nonzero on some kind of error.
811  *
812  * Use:         Checks a reply or switch packet, ensuring that its response
813  *              is correct.
814  */
815
816 static int checkresponse(keyexch *kx, unsigned msg, buf *b)
817 {
818   ge *r = G_CREATE(gg);
819
820   if (G_FROMRAW(gg, b, r)) {
821     a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
822     goto bad;
823   }
824   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
825     trace(T_CRYPTO, "crypto: reply = %s", gestr(gg, r));
826   }))
827   if (!G_EQ(gg, r, kx->rx)) {
828     a_warn("KX", "?PEER", kx->p, "incorrect", "response", A_END);
829     goto bad;
830   }
831
832   G_DESTROY(gg, r);
833   return (0);
834
835 bad:
836   G_DESTROY(gg, r);
837   return (-1);
838 }
839
840 /* --- @commit@ --- *
841  *
842  * Arguments:   @keyexch *kx@ = pointer to key exchange context
843  *              @kxchal *kxc@ = pointer to challenge to commit to
844  *
845  * Returns:     ---
846  *
847  * Use:         Commits to a particular challenge as being the `right' one,
848  *              since a reply has arrived for it.
849  */
850
851 static void commit(keyexch *kx, kxchal *kxc)
852 {
853   unsigned i;
854
855   for (i = 0; i < kx->nr; i++) {
856     if (kx->r[i] != kxc)
857       kxc_destroy(kx->r[i]);
858   }
859   kx->r[0] = kxc;
860   kx->nr = 1;
861   kxc_stoptimer(kxc);
862   ksl_link(kx->ks, kxc->ks);
863 }
864
865 /* --- @doreply@ --- *
866  *
867  * Arguments:   @keyexch *kx@ = pointer to key exchange context
868  *              @buf *b@ = buffer containing packet
869  *
870  * Returns:     Zero if OK, nonzero if the packet was rejected.
871  *
872  * Use:         Handles a reply packet.  This doesn't handle the various
873  *              switch packets: they're rather too different.
874  */
875
876 static int doreply(keyexch *kx, buf *b)
877 {
878   kxchal *kxc;
879
880   if (kx->s != KXS_CHAL && kx->s != KXS_COMMIT) {
881     a_warn("KX", "?PEER", kx->p, "unexpected", "reply", A_END);
882     goto bad;
883   }
884   if ((kxc = respond(kx, KX_REPLY, b)) == 0 ||
885       decryptrest(kx, kxc, KX_REPLY, b) ||
886       checkresponse(kx, KX_REPLY, b))
887     goto bad;
888   if (BLEFT(b)) {
889     a_warn("KX", "?PEER", kx->p, "invalid", "reply", A_END);
890     goto bad;
891   }
892   if (kx->s == KXS_CHAL) {
893     commit(kx, kxc);
894     kx->s = KXS_COMMIT;
895   }
896   resend(kx);
897   return (0);
898
899 bad:
900   return (-1);
901 }
902
903 /* --- @kxfinish@ --- *
904  *
905  * Arguments:   @keyexch *kx@ = pointer to key exchange block
906  *
907  * Returns:     ---
908  *
909  * Use:         Sets everything up following a successful key exchange.
910  */
911
912 static void kxfinish(keyexch *kx)
913 {
914   kxchal *kxc = kx->r[0];
915   struct timeval tv;
916
917   ks_activate(kxc->ks);
918   gettimeofday(&tv, 0);
919   tv.tv_sec += T_REGEN;
920   settimer(kx, &tv);
921   kx->s = KXS_SWITCH;
922   a_notify("KXDONE", "?PEER", kx->p, A_END);
923   p_stats(kx->p)->t_kx = time(0);
924 }
925
926 /* --- @doswitch@ --- *
927  *
928  * Arguments:   @keyexch *kx@ = pointer to key exchange block
929  *              @buf *b@ = pointer to buffer containing packet
930  *
931  * Returns:     Zero if OK, nonzero if the packet was rejected.
932  *
933  * Use:         Handles a reply with a switch request bolted onto it.
934  */
935
936 static int doswitch(keyexch *kx, buf *b)
937 {
938   const octet *hc_in, *hc_out, *hswrq;
939   kxchal *kxc;
940
941   if ((hc_in = buf_get(b, algs.hashsz)) == 0 ||
942       (hc_out = buf_get(b, algs.hashsz)) == 0) {
943     a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
944     goto bad;
945   }
946   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
947     trace_block(T_CRYPTO, "crypto: challenge", hc_in, algs.hashsz);
948     trace_block(T_CRYPTO, "crypto: cookie", hc_out, algs.hashsz);
949   }))
950   if ((kxc = kxc_byhc(kx, hc_in)) == 0 ||
951       memcmp(hc_out, kx->hc, algs.hashsz) != 0) {
952     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
953     goto bad;
954   }
955   if (decryptrest(kx, kxc, KX_SWITCH, b) ||
956       checkresponse(kx, KX_SWITCH, b))
957     goto bad;
958   if ((hswrq = buf_get(b, algs.hashsz)) == 0 || BLEFT(b)) {
959     a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
960     goto bad;
961   }
962   IF_TRACING(T_KEYEXCH, {
963     trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, algs.hashsz);
964   })
965   if (memcmp(hswrq, kxc->hswrq_in, algs.hashsz) != 0) {
966     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
967     goto bad;
968   }
969   if (kx->s == KXS_CHAL)
970     commit(kx, kxc);
971   if (kx->s < KXS_SWITCH)
972     kxfinish(kx);
973   resend(kx);
974   return (0);
975
976 bad:
977   return (-1);
978 }
979
980 /* --- @doswitchok@ --- *
981  *
982  * Arguments:   @keyexch *kx@ = pointer to key exchange block
983  *              @buf *b@ = pointer to buffer containing packet
984  *
985  * Returns:     Zero if OK, nonzero if the packet was rejected.
986  *
987  * Use:         Handles a reply with a switch request bolted onto it.
988  */
989
990 static int doswitchok(keyexch *kx, buf *b)
991 {
992   const octet *hswok;
993   kxchal *kxc;
994   buf bb;
995
996   if (kx->s < KXS_COMMIT) {
997     a_warn("KX", "?PEER", kx->p, "unexpected", "switch-ok", A_END);
998     goto bad;
999   }
1000   kxc = kx->r[0];
1001   buf_init(&bb, buf_o, sizeof(buf_o));
1002   if (decryptrest(kx, kxc, KX_SWITCHOK, b))
1003     goto bad;
1004   if ((hswok = buf_get(b, algs.hashsz)) == 0 || BLEFT(b)) {
1005     a_warn("KX", "?PEER", kx->p, "invalid", "switch-ok", A_END);
1006     goto bad;
1007   }
1008   IF_TRACING(T_KEYEXCH, {
1009     trace_block(T_CRYPTO, "crypto: switch confirmation hash",
1010                 hswok, algs.hashsz);
1011   })
1012   if (memcmp(hswok, kxc->hswok_in, algs.hashsz) != 0) {
1013     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-ok", A_END);
1014     goto bad;
1015   }
1016   if (kx->s < KXS_SWITCH)
1017     kxfinish(kx);
1018   return (0);
1019
1020 bad:
1021   return (-1);
1022 }
1023
1024 /*----- Main code ---------------------------------------------------------*/
1025
1026 /* --- @stop@ --- *
1027  *
1028  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1029  *
1030  * Returns:     ---
1031  *
1032  * Use:         Stops a key exchange dead in its tracks.  Throws away all of
1033  *              the context information.  The context is left in an
1034  *              inconsistent state.  The only functions which understand this
1035  *              state are @kx_free@ and @kx_init@ (which cause it internally
1036  *              it), and @start@ (which expects it to be the prevailing
1037  *              state).
1038  */
1039
1040 static void stop(keyexch *kx)
1041 {
1042   unsigned i;
1043
1044   if (kx->f & KXF_DEAD)
1045     return;
1046
1047   if (kx->f & KXF_TIMER)
1048     sel_rmtimer(&kx->t);
1049   for (i = 0; i < kx->nr; i++)
1050     kxc_destroy(kx->r[i]);
1051   mp_drop(kx->alpha);
1052   G_DESTROY(gg, kx->c);
1053   G_DESTROY(gg, kx->rx);
1054   kx->t_valid = 0;
1055   kx->f |= KXF_DEAD;
1056   kx->f &= ~KXF_TIMER;
1057 }
1058
1059 /* --- @start@ --- *
1060  *
1061  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1062  *              @time_t now@ = the current time
1063  *
1064  * Returns:     ---
1065  *
1066  * Use:         Starts a new key exchange with the peer.  The context must be
1067  *              in the bizarre state left by @stop@ or @kx_init@.
1068  */
1069
1070 static void start(keyexch *kx, time_t now)
1071 {
1072   ghash *h;
1073
1074   assert(kx->f & KXF_DEAD);
1075
1076   kx->f &= ~(KXF_DEAD | KXF_CORK);
1077   kx->nr = 0;
1078   kx->alpha = mprand_range(MP_NEW, gg->r, &rand_global, 0);
1079   kx->c = G_CREATE(gg); G_EXP(gg, kx->c, gg->g, kx->alpha);
1080   kx->rx = G_CREATE(gg); G_EXP(gg, kx->rx, kx->kpub, kx->alpha);
1081   kx->s = KXS_CHAL;
1082   kx->t_valid = now + T_VALID;
1083
1084   h = GH_INIT(algs.h);
1085   HASH_STRING(h, "tripe-cookie");
1086   hashge(h, kx->c);
1087   GH_DONE(h, kx->hc);
1088   GH_DESTROY(h);
1089
1090   IF_TRACING(T_KEYEXCH, {
1091     trace(T_KEYEXCH, "keyexch: creating new challenge");
1092     IF_TRACING(T_CRYPTO, {
1093       trace(T_CRYPTO, "crypto: secret = %s", mpstr(kx->alpha));
1094       trace(T_CRYPTO, "crypto: challenge = %s", gestr(gg, kx->c));
1095       trace(T_CRYPTO, "crypto: expected response = %s", gestr(gg, kx->rx));
1096       trace_block(T_CRYPTO, "crypto: challenge cookie", kx->hc, algs.hashsz);
1097     })
1098   })
1099 }
1100
1101 /* --- @checkpub@ --- *
1102  *
1103  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1104  *
1105  * Returns:     Zero if OK, nonzero if the peer's public key has expired.
1106  *
1107  * Use:         Deactivates the key-exchange until the peer acquires a new
1108  *              public key.
1109  */
1110
1111 static int checkpub(keyexch *kx)
1112 {
1113   time_t now;
1114   if (kx->f & KXF_DEAD)
1115     return (-1);
1116   now = time(0);
1117   if (KEY_EXPIRED(now, kx->texp_kpub)) {
1118     stop(kx);
1119     a_warn("KX", "?PEER", kx->p, "public-key-expired", A_END);
1120     G_COPY(gg, kx->kpub, gg->i);
1121     kx->f &= ~KXF_PUBKEY;
1122     return (-1);
1123   }
1124   return (0);
1125 }
1126
1127 /* --- @kx_start@ --- *
1128  *
1129  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1130  *              @int forcep@ = nonzero to ignore the quiet timer
1131  *
1132  * Returns:     ---
1133  *
1134  * Use:         Stimulates a key exchange.  If a key exchage is in progress,
1135  *              a new challenge is sent (unless the quiet timer forbids
1136  *              this); if no exchange is in progress, one is commenced.
1137  */
1138
1139 void kx_start(keyexch *kx, int forcep)
1140 {
1141   time_t now = time(0);
1142
1143   if (checkpub(kx))
1144     return;
1145   if (forcep || !VALIDP(kx, now)) {
1146     stop(kx);
1147     start(kx, now);
1148     a_notify("KXSTART", "?PEER", kx->p, A_END);
1149   }
1150   resend(kx);
1151 }
1152
1153 /* --- @kx_message@ --- *
1154  *
1155  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1156  *              @unsigned msg@ = the message code
1157  *              @buf *b@ = pointer to buffer containing the packet
1158  *
1159  * Returns:     ---
1160  *
1161  * Use:         Reads a packet containing key exchange messages and handles
1162  *              it.
1163  */
1164
1165 void kx_message(keyexch *kx, unsigned msg, buf *b)
1166 {
1167   struct timeval now, tv;
1168   stats *st = p_stats(kx->p);
1169   size_t sz = BSZ(b);
1170   int rc;
1171
1172   gettimeofday(&now, 0);
1173   if (kx->f & KXF_CORK) {
1174     start(kx, now.tv_sec);
1175     TV_ADDL(&tv, &now, T_RETRY, 0);
1176     settimer(kx, &tv);
1177     a_notify("KXSTART", A_END);
1178   }
1179
1180   if (checkpub(kx))
1181     return;
1182
1183   if (!VALIDP(kx, now.tv_sec)) {
1184     stop(kx);
1185     start(kx, now.tv_sec);
1186   }
1187   T( trace(T_KEYEXCH, "keyexch: processing %s packet from `%s'",
1188            msg < KX_NMSG ? pkname[msg] : "unknown", p_name(kx->p)); )
1189
1190   switch (msg) {
1191     case KX_PRECHAL:
1192       rc = doprechallenge(kx, b);
1193       break;
1194     case KX_CHAL:
1195       rc = dochallenge(kx, b);
1196       break;
1197     case KX_REPLY:
1198       rc = doreply(kx, b);
1199       break;
1200     case KX_SWITCH:
1201       rc = doswitch(kx, b);
1202       break;
1203     case KX_SWITCHOK:
1204       rc = doswitchok(kx, b);
1205       break;
1206     default:
1207       a_warn("KX", "?PEER", kx->p, "unknown-message", "0x%02x", msg, A_END);
1208       rc = -1;
1209       break;
1210   }
1211
1212   if (rc)
1213     st->n_reject++;
1214   else {
1215     st->n_kxin++;
1216     st->sz_kxin += sz;
1217   }
1218 }
1219
1220 /* --- @kx_free@ --- *
1221  *
1222  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1223  *
1224  * Returns:     ---
1225  *
1226  * Use:         Frees everything in a key exchange context.
1227  */
1228
1229 void kx_free(keyexch *kx)
1230 {
1231   stop(kx);
1232   G_DESTROY(gg, kx->kpub);
1233 }
1234
1235 /* --- @kx_newkeys@ --- *
1236  *
1237  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1238  *
1239  * Returns:     ---
1240  *
1241  * Use:         Informs the key exchange module that its keys may have
1242  *              changed.  If fetching the new keys fails, the peer will be
1243  *              destroyed, we log messages and struggle along with the old
1244  *              keys.
1245  */
1246
1247 void kx_newkeys(keyexch *kx)
1248 {
1249   if (km_getpubkey(p_tag(kx->p), kx->kpub, &kx->texp_kpub))
1250     return;
1251   kx->f |= KXF_PUBKEY;
1252   if ((kx->f & KXF_DEAD) || kx->s != KXS_SWITCH) {
1253     T( trace(T_KEYEXCH, "keyexch: restarting key negotiation with `%s'",
1254              p_name(kx->p)); )
1255     stop(kx);
1256     start(kx, time(0));
1257     resend(kx);
1258   }
1259 }
1260
1261 /* --- @kx_init@ --- *
1262  *
1263  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1264  *              @peer *p@ = pointer to peer context
1265  *              @keyset **ks@ = pointer to keyset list
1266  *              @unsigned f@ = various useful flags
1267  *
1268  * Returns:     Zero if OK, nonzero if it failed.
1269  *
1270  * Use:         Initializes a key exchange module.  The module currently
1271  *              contains no keys, and will attempt to initiate a key
1272  *              exchange.
1273  */
1274
1275 int kx_init(keyexch *kx, peer *p, keyset **ks, unsigned f)
1276 {
1277   kx->ks = ks;
1278   kx->p = p;
1279   kx->kpub = G_CREATE(gg);
1280   if (km_getpubkey(p_tag(p), kx->kpub, &kx->texp_kpub)) {
1281     G_DESTROY(gg, kx->kpub);
1282     return (-1);
1283   }
1284   kx->f = KXF_DEAD | KXF_PUBKEY | f;
1285   if (!(kx->f & KXF_CORK)) {
1286     start(kx, time(0));
1287     resend(kx);
1288     /* Don't notify here: the ADD message hasn't gone out yet. */
1289   }
1290   return (0);
1291 }
1292
1293 /*----- That's all, folks -------------------------------------------------*/