chiark / gitweb /
d26ac787378aa6658ca0517d7f83ab73a1822174
[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  *              @group *g@ = pointer to group
101  *              @ge *x@ = pointer to group element
102  *
103  * Returns:     ---
104  *
105  * Use:         Adds the hash of a group element to the context.  Corrupts
106  *              @buf_t@.
107  */
108
109 static void hashge(ghash *h, group *g, ge *x)
110 {
111   buf b;
112
113   buf_init(&b, buf_t, sizeof(buf_t));
114   G_TOBUF(g, &b, x);
115   assert(BOK(&b));
116   GH_HASH(h, BBASE(&b), BLEN(&b));
117 }
118
119 /* --- @mpmask@ --- *
120  *
121  * Arguments:   @buf *b@ = output buffer
122  *              @mp *x@ = the plaintext integer
123  *              @size_t n@ = the expected size of the plaintext
124  *              @gcipher *mgfc@ = mask-generating function to use
125  *              @const octet *k@ = pointer to key material
126  *              @size_t ksz@ = size of the key
127  *
128  * Returns:     Pointer to the output.
129  *
130  * Use:         Masks a multiprecision integer: returns %$x \xor H(k)$%, so
131  *              it's a random oracle thing rather than an encryption thing.
132  */
133
134 static octet *mpmask(buf *b, mp *x, size_t n,
135                      const gccipher *mgfc, const octet *k, size_t ksz)
136 {
137   gcipher *mgf;
138   octet *p;
139
140   if ((p = buf_get(b, n)) == 0)
141     return (0);
142   mgf = GC_INIT(mgfc, k, ksz);
143   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
144     trace(T_CRYPTO, "crypto: masking index = %s", mpstr(x));
145     trace_block(T_CRYPTO, "crypto: masking key", k, ksz);
146   }))
147   mp_storeb(x, buf_t, n);
148   GC_ENCRYPT(mgf, buf_t, p, n);
149   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
150     trace_block(T_CRYPTO, "crypto: index plaintext", buf_t, n);
151     trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
152   }))
153   GC_DESTROY(mgf);
154   return (p);
155 }
156
157 /* --- @mpunmask@ --- *
158  *
159  * Arguments:   @mp *d@ = the output integer
160  *              @const octet *p@ = pointer to the ciphertext
161  *              @size_t n@ = the size of the ciphertext
162  *              @gcipher *mgfc@ = mask-generating function to use
163  *              @const octet *k@ = pointer to key material
164  *              @size_t ksz@ = size of the key
165  *
166  * Returns:     The decrypted integer, or null.
167  *
168  * Use:         Unmasks a multiprecision integer.
169  */
170
171 static mp *mpunmask(mp *d, const octet *p, size_t n,
172                     const gccipher *mgfc, const octet *k, size_t ksz)
173 {
174   gcipher *mgf;
175
176   mgf = GC_INIT(mgfc, k, ksz);
177   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
178     trace_block(T_CRYPTO, "crypto: unmasking key", k, ksz);
179     trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
180   }))
181   GC_DECRYPT(mgf, p, buf_t, n);
182   d = mp_loadb(d, buf_t, n);
183   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
184     trace_block(T_CRYPTO, "crypto: index plaintext", buf_t, n);
185     trace(T_CRYPTO, "crypto: unmasked index = %s", mpstr(d));
186   }))
187   GC_DESTROY(mgf);
188   return (d);
189 }
190
191 /* --- @hashcheck@ --- *
192  *
193  * Arguments:   @keyexch *kx@ = pointer to key-exchange block
194  *              @ge *kpub@ = sender's public key
195  *              @ge *cc@ = receiver's challenge
196  *              @ge *c@ = sender's challenge
197  *              @ge *y@ = reply to sender's challenge
198  *
199  * Returns:     Pointer to the hash value (in @buf_t@)
200  *
201  * Use:         Computes the check-value hash, used to mask or unmask
202  *              indices to prove the validity of challenges.  This computes
203  *              the masking key used in challenge check values.  This is
204  *              really the heart of the whole thing, since it ensures that
205  *              the index can be recovered from the history of hashing
206  *              queries, which gives us (a) a proof that the authentication
207  *              process is zero-knowledge, and (b) a proof that the whole
208  *              key-exchange is deniable.
209  */
210
211 static const octet *hashcheck(keyexch *kx, ge *kpub, ge *cc, ge *c, ge *y)
212 {
213   ghash *h = GH_INIT(kx->kpriv->algs.h);
214   group *g = kx->kpriv->g;
215
216   HASH_STRING(h, "tripe-expected-reply");
217   hashge(h, g, kpub);
218   hashge(h, g, cc);
219   hashge(h, g, c);
220   hashge(h, g, y);
221   GH_DONE(h, buf_t);
222   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
223     trace(T_CRYPTO, "crypto: computing challenge check hash");
224     trace(T_CRYPTO, "crypto: public key = %s", gestr(g, kpub));
225     trace(T_CRYPTO, "crypto: receiver challenge = %s", gestr(g, cc));
226     trace(T_CRYPTO, "crypto: sender challenge = %s", gestr(g, c));
227     trace(T_CRYPTO, "crypto: sender reply = %s", gestr(g, y));
228     trace_block(T_CRYPTO, "crypto: hash output", buf_t, kx->kpriv->algs.hashsz);
229   }))
230   GH_DESTROY(h);
231   return (buf_t);
232 }
233
234 /* --- @sendchallenge@ --- *
235  *
236  * Arguments:   @keyexch *kx@ = pointer to key exchange block
237  *              @buf *b@ = output buffer for challenge
238  *              @ge *c@ = peer's actual challenge
239  *              @const octet *hc@ = peer's challenge cookie
240  *
241  * Returns:     ---
242  *
243  * Use:         Writes a full challenge to the message buffer.
244  */
245
246 static void sendchallenge(keyexch *kx, buf *b, ge *c, const octet *hc)
247 {
248   G_TOBUF(kx->kpriv->g, b, kx->c);
249   buf_put(b, hc, kx->kpriv->algs.hashsz);
250   mpmask(b, kx->alpha, kx->kpriv->indexsz, kx->kpriv->algs.mgf,
251          hashcheck(kx, kx->kpriv->kpub, c, kx->c, kx->rx),
252          kx->kpriv->algs.hashsz);
253 }
254
255 /* --- @timer@ --- *
256  *
257  * Arguments:   @struct timeval *tv@ = the current time
258  *              @void *v@ = pointer to key exchange context
259  *
260  * Returns:     ---
261  *
262  * Use:         Acts when the key exchange timer goes off.
263  */
264
265 static void timer(struct timeval *tv, void *v)
266 {
267   keyexch *kx = v;
268   kx->f &= ~KXF_TIMER;
269   T( trace(T_KEYEXCH, "keyexch: timer has popped"); )
270   kx_start(kx, 0);
271 }
272
273 /* --- @settimer@ --- *
274  *
275  * Arguments:   @keyexch *kx@ = pointer to key exchange context
276  *              @struct timeval *tv@ = when to set the timer for
277  *
278  * Returns:     ---
279  *
280  * Use:         Sets the timer for the next key exchange attempt.
281  */
282
283 static void settimer(keyexch *kx, struct timeval *tv)
284 {
285   if (kx->f & KXF_TIMER) sel_rmtimer(&kx->t);
286   sel_addtimer(&sel, &kx->t, tv, timer, kx);
287   kx->f |= KXF_TIMER;
288 }
289
290 /* --- @f2tv@ --- *
291  *
292  * Arguments:   @struct timeval *tv@ = where to write the timeval
293  *              @double t@ = a time as a floating point number
294  *
295  * Returns:     ---
296  *
297  * Use:         Converts a floating-point time into a timeval.
298  */
299
300 static void f2tv(struct timeval *tv, double t)
301 {
302   tv->tv_sec = t;
303   tv->tv_usec = (t - tv->tv_sec)*MILLION;
304 }
305
306 /* --- @wobble@ --- *
307  *
308  * Arguments:   @double t@ = a time interval
309  *
310  * Returns:     The same time interval, with a random error applied.
311  */
312
313 static double wobble(double t)
314 {
315   uint32 r = rand_global.ops->word(&rand_global);
316   double w = (r/F_2P32) - 0.5;
317   return (t + t*w*T_WOBBLE);
318 }
319
320 /* --- @rs_time@ --- *
321  *
322  * Arguments:   @retry *rs@ = current retry state
323  *              @struct timeval *tv@ = where to write the result
324  *              @const struct timeval *now@ = current time, or null
325  *
326  * Returns:     ---
327  *
328  * Use:         Computes a time at which to retry sending a key-exchange
329  *              packet.  This algorithm is subject to change, but it's
330  *              currently a capped exponential backoff, slightly randomized
331  *              to try to keep clients from hammering a server that's only
332  *              just woken up.
333  *
334  *              If @now@ is null then the function works out the time for
335  *              itself.
336  */
337
338 static void rs_time(retry *rs, struct timeval *tv, const struct timeval *now)
339 {
340   double t;
341   struct timeval rtv;
342
343   if (!rs->t)
344     t = SEC(2);
345   else {
346     t = (rs->t * 5)/4;
347     if (t > MIN(5)) t = MIN(5);
348   }
349   rs->t = t;
350
351   if (!now) {
352     now = tv;
353     gettimeofday(tv, 0);
354   }
355   f2tv(&rtv, wobble(t));
356   TV_ADD(tv, now, &rtv);
357 }
358
359 /* --- @retry_reset@ --- *
360  *
361  * Arguments:   @retry *rs@ = retry state
362  *
363  * Returns:     --
364  *
365  * Use:         Resets a retry state to indicate that progress has been
366  *              made.  Also useful for initializing the state in the first
367  *              place.
368  */
369
370 static void rs_reset(retry *rs) { rs->t = 0; }
371
372 /*----- Challenge management ----------------------------------------------*/
373
374 /* --- Notes on challenge management --- *
375  *
376  * We may get multiple different replies to our key exchange; some will be
377  * correct, some inserted by attackers.  Up until @KX_THRESH@, all challenges
378  * received will be added to the table and given a full response.  After
379  * @KX_THRESH@ distinct challenges are received, we return only a `cookie':
380  * our existing challenge, followed by a hash of the sender's challenge.  We
381  * do %%\emph{not}%% give a bare challenge a reply slot at this stage.  All
382  * properly-formed cookies are assigned a table slot: if none is spare, a
383  * used slot is randomly selected and destroyed.  A cookie always receives a
384  * full reply.
385  */
386
387 /* --- @kxc_destroy@ --- *
388  *
389  * Arguments:   @kxchal *kxc@ = pointer to the challenge block
390  *
391  * Returns:     ---
392  *
393  * Use:         Disposes of a challenge block.
394  */
395
396 static void kxc_destroy(kxchal *kxc)
397 {
398   if (kxc->f & KXF_TIMER)
399     sel_rmtimer(&kxc->t);
400   G_DESTROY(kxc->kx->kpriv->g, kxc->c);
401   G_DESTROY(kxc->kx->kpriv->g, kxc->r);
402   ks_drop(kxc->ks);
403   DESTROY(kxc);
404 }
405
406 /* --- @kxc_stoptimer@ --- *
407  *
408  * Arguments:   @kxchal *kxc@ = pointer to the challenge block
409  *
410  * Returns:     ---
411  *
412  * Use:         Stops the challenge's retry timer from sending messages.
413  *              Useful when the state machine is in the endgame of the
414  *              exchange.
415  */
416
417 static void kxc_stoptimer(kxchal *kxc)
418 {
419   if (kxc->f & KXF_TIMER)
420     sel_rmtimer(&kxc->t);
421   kxc->f &= ~KXF_TIMER;
422 }
423
424 /* --- @kxc_new@ --- *
425  *
426  * Arguments:   @keyexch *kx@ = pointer to key exchange block
427  *
428  * Returns:     A pointer to the challenge block.
429  *
430  * Use:         Returns a pointer to a new challenge block to fill in.
431  */
432
433 static kxchal *kxc_new(keyexch *kx)
434 {
435   kxchal *kxc;
436   unsigned i;
437
438   /* --- If we're over reply threshold, discard one at random --- */
439
440   if (kx->nr < KX_NCHAL)
441     i = kx->nr++;
442   else {
443     i = rand_global.ops->range(&rand_global, KX_NCHAL);
444     kxc_destroy(kx->r[i]);
445   }
446
447   /* --- Fill in the new structure --- */
448
449   kxc = CREATE(kxchal);
450   kxc->c = G_CREATE(kx->kpriv->g);
451   kxc->r = G_CREATE(kx->kpriv->g);
452   kxc->ks = 0;
453   kxc->kx = kx;
454   kxc->f = 0;
455   kx->r[i] = kxc;
456   rs_reset(&kxc->rs);
457   return (kxc);
458 }
459
460 /* --- @kxc_bychal@ --- *
461  *
462  * Arguments:   @keyexch *kx@ = pointer to key exchange block
463  *              @ge *c@ = challenge from remote host
464  *
465  * Returns:     Pointer to the challenge block, or null.
466  *
467  * Use:         Finds a challenge block, given its challenge.
468  */
469
470 static kxchal *kxc_bychal(keyexch *kx, ge *c)
471 {
472   unsigned i;
473
474   for (i = 0; i < kx->nr; i++) {
475     if (G_EQ(kx->kpriv->g, c, kx->r[i]->c))
476       return (kx->r[i]);
477   }
478   return (0);
479 }
480
481 /* --- @kxc_byhc@ --- *
482  *
483  * Arguments:   @keyexch *kx@ = pointer to key exchange block
484  *              @const octet *hc@ = challenge hash from remote host
485  *
486  * Returns:     Pointer to the challenge block, or null.
487  *
488  * Use:         Finds a challenge block, given a hash of its challenge.
489  */
490
491 static kxchal *kxc_byhc(keyexch *kx, const octet *hc)
492 {
493   unsigned i;
494
495   for (i = 0; i < kx->nr; i++) {
496     if (memcmp(hc, kx->r[i]->hc, kx->kpriv->algs.hashsz) == 0)
497       return (kx->r[i]);
498   }
499   return (0);
500 }
501
502 /* --- @kxc_answer@ --- *
503  *
504  * Arguments:   @keyexch *kx@ = pointer to key exchange block
505  *              @kxchal *kxc@ = pointer to challenge block
506  *
507  * Returns:     ---
508  *
509  * Use:         Sends a reply to the remote host, according to the data in
510  *              this challenge block.
511  */
512
513 static void kxc_answer(keyexch *kx, kxchal *kxc);
514
515 static void kxc_timer(struct timeval *tv, void *v)
516 {
517   kxchal *kxc = v;
518   kxc->f &= ~KXF_TIMER;
519   kxc_answer(kxc->kx, kxc);
520 }
521
522 static void kxc_answer(keyexch *kx, kxchal *kxc)
523 {
524   stats *st = p_stats(kx->p);
525   buf *b = p_txstart(kx->p, MSG_KEYEXCH | KX_REPLY);
526   struct timeval tv;
527   buf bb;
528
529   /* --- Build the reply packet --- */
530
531   T( trace(T_KEYEXCH, "keyexch: sending reply to `%s'", p_name(kx->p)); )
532   sendchallenge(kx, b, kxc->c, kxc->hc);
533   buf_init(&bb, buf_i, sizeof(buf_i));
534   G_TORAW(kx->kpriv->g, &bb, kxc->r);
535   buf_flip(&bb);
536   ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_REPLY, &bb, b);
537
538   /* --- Update the statistics --- */
539
540   if (BOK(b)) {
541     st->n_kxout++;
542     st->sz_kxout += BLEN(b);
543     p_txend(kx->p);
544   }
545
546   /* --- Schedule another resend --- */
547
548   if (kxc->f & KXF_TIMER)
549     sel_rmtimer(&kxc->t);
550   gettimeofday(&tv, 0);
551   rs_time(&kxc->rs, &tv, &tv);
552   sel_addtimer(&sel, &kxc->t, &tv, kxc_timer, kxc);
553   kxc->f |= KXF_TIMER;
554 }
555
556 /*----- Individual message handlers ---------------------------------------*/
557
558 /* --- @doprechallenge@ --- *
559  *
560  * Arguments:   @keyexch *kx@ = pointer to key exchange block
561  *              @buf *b@ = buffer containing the packet
562  *
563  * Returns:     Zero if OK, nonzero of the packet was rejected.
564  *
565  * Use:         Processes a pre-challenge message.
566  */
567
568 static int doprechallenge(keyexch *kx, buf *b)
569 {
570   stats *st = p_stats(kx->p);
571   ge *c = G_CREATE(kx->kpriv->g);
572   ghash *h;
573
574   /* --- Ensure that we're in a sensible state --- */
575
576   if (kx->s != KXS_CHAL) {
577     a_warn("KX", "?PEER", kx->p, "unexpected", "pre-challenge", A_END);
578     goto bad;
579   }
580
581   /* --- Unpack the packet --- */
582
583   if (G_FROMBUF(kx->kpriv->g, b, c) || BLEFT(b))
584     goto bad;
585
586   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
587     trace(T_CRYPTO, "crypto: challenge = %s", gestr(kx->kpriv->g, c));
588   }))
589
590   /* --- Send out a full challenge by return --- */
591
592   b = p_txstart(kx->p, MSG_KEYEXCH | KX_CHAL);
593   h = GH_INIT(kx->kpriv->algs.h);
594   HASH_STRING(h, "tripe-cookie");
595   hashge(h, kx->kpriv->g, c);
596   sendchallenge(kx, b, c, GH_DONE(h, 0));
597   GH_DESTROY(h);
598   st->n_kxout++;
599   st->sz_kxout += BLEN(b);
600   p_txend(kx->p);
601
602   /* --- Done --- */
603
604   G_DESTROY(kx->kpriv->g, c);
605   return (0);
606
607 bad:
608   if (c) G_DESTROY(kx->kpriv->g, c);
609   return (-1);
610 }
611
612 /* --- @respond@ --- *
613  *
614  * Arguments:   @keyexch *kx@ = pointer to key exchange block
615  *              @unsigned msg@ = message code for this packet
616  *              @buf *b@ = buffer containing the packet
617  *
618  * Returns:     Key-exchange challenge block, or null.
619  *
620  * Use:         Computes a response for the given challenge, entering it into
621  *              a challenge block and so on.
622  */
623
624 static kxchal *respond(keyexch *kx, unsigned msg, buf *b)
625 {
626   group *g = kx->kpriv->g;
627   const algswitch *algs = &kx->kpriv->algs;
628   size_t ixsz = kx->kpriv->indexsz;
629   ge *c = G_CREATE(g);
630   ge *r = G_CREATE(g);
631   ge *cc = G_CREATE(g);
632   const octet *hc, *ck;
633   size_t x, y, z;
634   mp *cv = 0;
635   kxchal *kxc;
636   ghash *h = 0;
637   buf bb;
638   int ok;
639
640   /* --- Unpack the packet --- */
641
642   if (G_FROMBUF(g, b, c) ||
643       (hc = buf_get(b, algs->hashsz)) == 0 ||
644       (ck = buf_get(b, ixsz)) == 0) {
645     a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
646     goto bad;
647   }
648   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
649     trace(T_CRYPTO, "crypto: challenge = %s", gestr(g, c));
650     trace_block(T_CRYPTO, "crypto: cookie", hc, algs->hashsz);
651     trace_block(T_CRYPTO, "crypto: check-value", ck, ixsz);
652   }))
653
654   /* --- Discard a packet with an invalid cookie --- */
655
656   if (hc && memcmp(hc, kx->hc, algs->hashsz) != 0) {
657     a_warn("KX", "?PEER", kx->p, "incorrect", "cookie", A_END);
658     goto bad;
659   }
660
661   /* --- Recover the check value and verify it --- *
662    *
663    * To avoid recomputation on replays, we store a hash of the `right'
664    * value.  The `correct' value is unique, so this is right.
665    *
666    * This will also find a challenge block and, if necessary, populate it.
667    */
668
669   if ((kxc = kxc_bychal(kx, c)) != 0) {
670     h = GH_INIT(algs->h);
671     HASH_STRING(h, "tripe-check-hash");
672     GH_HASH(h, ck, ixsz);
673     ok = !memcmp(kxc->ck, GH_DONE(h, 0), algs->hashsz);
674     GH_DESTROY(h);
675     if (!ok) goto badcheck;
676   } else {
677
678     /* --- Compute the reply, and check the magic --- */
679
680     G_EXP(g, r, c, kx->kpriv->kpriv);
681     cv = mpunmask(MP_NEW, ck, ixsz, algs->mgf,
682                   hashcheck(kx, kx->kpub->kpub, kx->c, c, r),
683                   algs->hashsz);
684     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
685       trace(T_CRYPTO, "crypto: computed reply = %s", gestr(g, r));
686       trace(T_CRYPTO, "crypto: recovered log = %s", mpstr(cv));
687     }))
688     if (MP_CMP(cv, >, g->r) ||
689         (G_EXP(g, cc, g->g, cv),
690          !G_EQ(g, c, cc)))
691       goto badcheck;
692
693     /* --- Fill in a new challenge block --- */
694
695     kxc = kxc_new(kx);
696     G_COPY(g, kxc->c, c);
697     G_COPY(g, kxc->r, r);
698
699     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-check-hash");
700     GH_HASH(h, ck, ixsz);
701     GH_DONE(h, kxc->ck); GH_DESTROY(h);
702
703     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-cookie");
704     hashge(h, g, kxc->c);
705     GH_DONE(h, kxc->hc); GH_DESTROY(h);
706
707     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
708       trace_block(T_CRYPTO, "crypto: computed cookie",
709                   kxc->hc, algs->hashsz);
710     }))
711
712     /* --- Work out the shared key --- */
713
714     G_EXP(g, r, c, kx->alpha);
715     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
716       trace(T_CRYPTO, "crypto: shared secret = %s", gestr(g, r));
717     }))
718
719     /* --- Compute the switch messages --- */
720
721     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
722     hashge(h, g, kx->c); hashge(h, g, kxc->c);
723     GH_DONE(h, kxc->hswrq_out); GH_DESTROY(h);
724     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
725     hashge(h, g, kx->c); hashge(h, g, kxc->c);
726     GH_DONE(h, kxc->hswok_out); GH_DESTROY(h);
727
728     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
729     hashge(h, g, kxc->c); hashge(h, g, kx->c);
730     GH_DONE(h, kxc->hswrq_in); GH_DESTROY(h);
731     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
732     hashge(h, g, kxc->c); hashge(h, g, kx->c);
733     GH_DONE(h, kxc->hswok_in); GH_DESTROY(h);
734
735     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
736       trace_block(T_CRYPTO, "crypto: outbound switch request",
737                   kxc->hswrq_out, algs->hashsz);
738       trace_block(T_CRYPTO, "crypto: outbound switch confirm",
739                   kxc->hswok_out, algs->hashsz);
740       trace_block(T_CRYPTO, "crypto: inbound switch request",
741                   kxc->hswrq_in, algs->hashsz);
742       trace_block(T_CRYPTO, "crypto: inbound switch confirm",
743                   kxc->hswok_in, algs->hashsz);
744     }))
745
746     /* --- Create a new symmetric keyset --- */
747
748     buf_init(&bb, buf_o, sizeof(buf_o));
749     G_TOBUF(g, &bb, kx->c); x = BLEN(&bb);
750     G_TOBUF(g, &bb, kxc->c); y = BLEN(&bb);
751     G_TOBUF(g, &bb, r); z = BLEN(&bb);
752     assert(BOK(&bb));
753
754     kxc->ks = ks_gen(BBASE(&bb), x, y, z, kx->p);
755   }
756
757   G_DESTROY(g, c);
758   G_DESTROY(g, cc);
759   G_DESTROY(g, r);
760   mp_drop(cv);
761   return (kxc);
762
763 badcheck:
764   a_warn("KX", "?PEER", kx->p, "bad-expected-reply-log", A_END);
765   goto bad;
766 bad:
767   G_DESTROY(g, c);
768   G_DESTROY(g, cc);
769   G_DESTROY(g, r);
770   mp_drop(cv);
771   return (0);
772 }
773
774 /* --- @dochallenge@ --- *
775  *
776  * Arguments:   @keyexch *kx@ = pointer to key exchange block
777  *              @unsigned msg@ = message code for the packet
778  *              @buf *b@ = buffer containing the packet
779  *
780  * Returns:     Zero if OK, nonzero if the packet was rejected.
781  *
782  * Use:         Processes a packet containing a challenge.
783  */
784
785 static int dochallenge(keyexch *kx, buf *b)
786 {
787   kxchal *kxc;
788
789   if (kx->s != KXS_CHAL) {
790     a_warn("KX", "?PEER", kx->p, "unexpected", "challenge", A_END);
791     goto bad;
792   }
793   if ((kxc = respond(kx, KX_CHAL, b)) == 0)
794     goto bad;
795   if (BLEFT(b)) {
796     a_warn("KX", "?PEER", kx->p, "invalid", "challenge", A_END);
797     goto bad;
798   }
799   kxc_answer(kx, kxc);
800   return (0);
801
802 bad:
803   return (-1);
804 }
805
806 /* --- @resend@ --- *
807  *
808  * Arguments:   @keyexch *kx@ = pointer to key exchange context
809  *
810  * Returns:     ---
811  *
812  * Use:         Sends the next message for a key exchange.
813  */
814
815 static void resend(keyexch *kx)
816 {
817   kxchal *kxc;
818   buf bb;
819   stats *st = p_stats(kx->p);
820   struct timeval tv;
821   buf *b;
822
823   switch (kx->s) {
824     case KXS_CHAL:
825       T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
826                p_name(kx->p)); )
827       b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
828       G_TOBUF(kx->kpriv->g, b, kx->c);
829       break;
830     case KXS_COMMIT:
831       T( trace(T_KEYEXCH, "keyexch: sending switch request to `%s'",
832                p_name(kx->p)); )
833       kxc = kx->r[0];
834       b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCH);
835       buf_put(b, kx->hc, kx->kpriv->algs.hashsz);
836       buf_put(b, kxc->hc, kx->kpriv->algs.hashsz);
837       buf_init(&bb, buf_i, sizeof(buf_i));
838       G_TORAW(kx->kpriv->g, &bb, kxc->r);
839       buf_put(&bb, kxc->hswrq_out, kx->kpriv->algs.hashsz);
840       buf_flip(&bb);
841       ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCH, &bb, b);
842       break;
843     case KXS_SWITCH:
844       T( trace(T_KEYEXCH, "keyexch: sending switch confirmation to `%s'",
845                p_name(kx->p)); )
846       kxc = kx->r[0];
847       b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCHOK);
848       buf_init(&bb, buf_i, sizeof(buf_i));
849       buf_put(&bb, kxc->hswok_out, kx->kpriv->algs.hashsz);
850       buf_flip(&bb);
851       ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, &bb, b);
852       break;
853     default:
854       abort();
855   }
856
857   if (BOK(b)) {
858     st->n_kxout++;
859     st->sz_kxout += BLEN(b);
860     p_txend(kx->p);
861   }
862
863   if (kx->s < KXS_SWITCH) {
864     rs_time(&kx->rs, &tv, 0);
865     settimer(kx, &tv);
866   }
867 }
868
869 /* --- @decryptrest@ --- *
870  *
871  * Arguments:   @keyexch *kx@ = pointer to key exchange context
872  *              @kxchal *kxc@ = pointer to challenge block
873  *              @unsigned msg@ = type of incoming message
874  *              @buf *b@ = encrypted remainder of the packet
875  *
876  * Returns:     Zero if OK, nonzero on some kind of error.
877  *
878  * Use:         Decrypts the remainder of the packet, and points @b@ at the
879  *              recovered plaintext.
880  */
881
882 static int decryptrest(keyexch *kx, kxchal *kxc, unsigned msg, buf *b)
883 {
884   buf bb;
885
886   buf_init(&bb, buf_o, sizeof(buf_o));
887   if (ks_decrypt(kxc->ks, MSG_KEYEXCH | msg, b, &bb)) {
888     a_warn("KX", "?PEER", kx->p, "decrypt-failed", "%s", pkname[msg], A_END);
889     return (-1);
890   }
891   if (!BOK(&bb)) return (-1);
892   buf_init(b, BBASE(&bb), BLEN(&bb));
893   return (0);
894 }
895
896 /* --- @checkresponse@ --- *
897  *
898  * Arguments:   @keyexch *kx@ = pointer to key exchange context
899  *              @unsigned msg@ = type of incoming message
900  *              @buf *b@ = decrypted remainder of the packet
901  *
902  * Returns:     Zero if OK, nonzero on some kind of error.
903  *
904  * Use:         Checks a reply or switch packet, ensuring that its response
905  *              is correct.
906  */
907
908 static int checkresponse(keyexch *kx, unsigned msg, buf *b)
909 {
910   group *g = kx->kpriv->g;
911   ge *r = G_CREATE(g);
912
913   if (G_FROMRAW(g, b, r)) {
914     a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
915     goto bad;
916   }
917   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
918     trace(T_CRYPTO, "crypto: reply = %s", gestr(g, r));
919   }))
920   if (!G_EQ(g, r, kx->rx)) {
921     a_warn("KX", "?PEER", kx->p, "incorrect", "response", A_END);
922     goto bad;
923   }
924
925   G_DESTROY(g, r);
926   return (0);
927
928 bad:
929   G_DESTROY(g, r);
930   return (-1);
931 }
932
933 /* --- @commit@ --- *
934  *
935  * Arguments:   @keyexch *kx@ = pointer to key exchange context
936  *              @kxchal *kxc@ = pointer to challenge to commit to
937  *
938  * Returns:     ---
939  *
940  * Use:         Commits to a particular challenge as being the `right' one,
941  *              since a reply has arrived for it.
942  */
943
944 static void commit(keyexch *kx, kxchal *kxc)
945 {
946   unsigned i;
947
948   for (i = 0; i < kx->nr; i++) {
949     if (kx->r[i] != kxc)
950       kxc_destroy(kx->r[i]);
951   }
952   kx->r[0] = kxc;
953   kx->nr = 1;
954   kxc_stoptimer(kxc);
955   ksl_link(kx->ks, kxc->ks);
956 }
957
958 /* --- @doreply@ --- *
959  *
960  * Arguments:   @keyexch *kx@ = pointer to key exchange context
961  *              @buf *b@ = buffer containing packet
962  *
963  * Returns:     Zero if OK, nonzero if the packet was rejected.
964  *
965  * Use:         Handles a reply packet.  This doesn't handle the various
966  *              switch packets: they're rather too different.
967  */
968
969 static int doreply(keyexch *kx, buf *b)
970 {
971   kxchal *kxc;
972
973   if (kx->s != KXS_CHAL && kx->s != KXS_COMMIT) {
974     a_warn("KX", "?PEER", kx->p, "unexpected", "reply", A_END);
975     goto bad;
976   }
977   if ((kxc = respond(kx, KX_REPLY, b)) == 0 ||
978       decryptrest(kx, kxc, KX_REPLY, b) ||
979       checkresponse(kx, KX_REPLY, b))
980     goto bad;
981   if (BLEFT(b)) {
982     a_warn("KX", "?PEER", kx->p, "invalid", "reply", A_END);
983     goto bad;
984   }
985   if (kx->s == KXS_CHAL) {
986     commit(kx, kxc);
987     kx->s = KXS_COMMIT;
988   }
989   resend(kx);
990   return (0);
991
992 bad:
993   return (-1);
994 }
995
996 /* --- @kxfinish@ --- *
997  *
998  * Arguments:   @keyexch *kx@ = pointer to key exchange block
999  *
1000  * Returns:     ---
1001  *
1002  * Use:         Sets everything up following a successful key exchange.
1003  */
1004
1005 static void kxfinish(keyexch *kx)
1006 {
1007   kxchal *kxc = kx->r[0];
1008   struct timeval now, tv;
1009
1010   ks_activate(kxc->ks);
1011   gettimeofday(&now, 0);
1012   f2tv(&tv, wobble(T_REGEN));
1013   TV_ADD(&tv, &now, &tv);
1014   settimer(kx, &tv);
1015   kx->s = KXS_SWITCH;
1016   a_notify("KXDONE", "?PEER", kx->p, A_END);
1017   p_stats(kx->p)->t_kx = time(0);
1018 }
1019
1020 /* --- @doswitch@ --- *
1021  *
1022  * Arguments:   @keyexch *kx@ = pointer to key exchange block
1023  *              @buf *b@ = pointer to buffer containing packet
1024  *
1025  * Returns:     Zero if OK, nonzero if the packet was rejected.
1026  *
1027  * Use:         Handles a reply with a switch request bolted onto it.
1028  */
1029
1030 static int doswitch(keyexch *kx, buf *b)
1031 {
1032   size_t hsz = kx->kpriv->algs.hashsz;
1033   const octet *hc_in, *hc_out, *hswrq;
1034   kxchal *kxc;
1035
1036   if ((hc_in = buf_get(b, hsz)) == 0 ||
1037       (hc_out = buf_get(b, hsz)) == 0) {
1038     a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
1039     goto bad;
1040   }
1041   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
1042     trace_block(T_CRYPTO, "crypto: challenge", hc_in, hsz);
1043     trace_block(T_CRYPTO, "crypto: cookie", hc_out, hsz);
1044   }))
1045   if ((kxc = kxc_byhc(kx, hc_in)) == 0 ||
1046       memcmp(hc_out, kx->hc, hsz) != 0) {
1047     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
1048     goto bad;
1049   }
1050   if (decryptrest(kx, kxc, KX_SWITCH, b) ||
1051       checkresponse(kx, KX_SWITCH, b))
1052     goto bad;
1053   if ((hswrq = buf_get(b, hsz)) == 0 || BLEFT(b)) {
1054     a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
1055     goto bad;
1056   }
1057   IF_TRACING(T_KEYEXCH, {
1058     trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, hsz);
1059   })
1060   if (memcmp(hswrq, kxc->hswrq_in, hsz) != 0) {
1061     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
1062     goto bad;
1063   }
1064   if (kx->s == KXS_CHAL)
1065     commit(kx, kxc);
1066   if (kx->s < KXS_SWITCH)
1067     kxfinish(kx);
1068   resend(kx);
1069   return (0);
1070
1071 bad:
1072   return (-1);
1073 }
1074
1075 /* --- @doswitchok@ --- *
1076  *
1077  * Arguments:   @keyexch *kx@ = pointer to key exchange block
1078  *              @buf *b@ = pointer to buffer containing packet
1079  *
1080  * Returns:     Zero if OK, nonzero if the packet was rejected.
1081  *
1082  * Use:         Handles a reply with a switch request bolted onto it.
1083  */
1084
1085 static int doswitchok(keyexch *kx, buf *b)
1086 {
1087   size_t hsz = kx->kpriv->algs.hashsz;
1088   const octet *hswok;
1089   kxchal *kxc;
1090   buf bb;
1091
1092   if (kx->s < KXS_COMMIT) {
1093     a_warn("KX", "?PEER", kx->p, "unexpected", "switch-ok", A_END);
1094     goto bad;
1095   }
1096   kxc = kx->r[0];
1097   buf_init(&bb, buf_o, sizeof(buf_o));
1098   if (decryptrest(kx, kxc, KX_SWITCHOK, b))
1099     goto bad;
1100   if ((hswok = buf_get(b, hsz)) == 0 || BLEFT(b)) {
1101     a_warn("KX", "?PEER", kx->p, "invalid", "switch-ok", A_END);
1102     goto bad;
1103   }
1104   IF_TRACING(T_KEYEXCH, {
1105     trace_block(T_CRYPTO, "crypto: switch confirmation hash",
1106                 hswok, hsz);
1107   })
1108   if (memcmp(hswok, kxc->hswok_in, hsz) != 0) {
1109     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-ok", A_END);
1110     goto bad;
1111   }
1112   if (kx->s < KXS_SWITCH)
1113     kxfinish(kx);
1114   return (0);
1115
1116 bad:
1117   return (-1);
1118 }
1119
1120 /*----- Main code ---------------------------------------------------------*/
1121
1122 /* --- @stop@ --- *
1123  *
1124  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1125  *
1126  * Returns:     ---
1127  *
1128  * Use:         Stops a key exchange dead in its tracks.  Throws away all of
1129  *              the context information.  The context is left in an
1130  *              inconsistent state.  The only functions which understand this
1131  *              state are @kx_free@ and @kx_init@ (which cause it internally
1132  *              it), and @start@ (which expects it to be the prevailing
1133  *              state).
1134  */
1135
1136 static void stop(keyexch *kx)
1137 {
1138   unsigned i;
1139
1140   if (kx->f & KXF_DEAD)
1141     return;
1142
1143   if (kx->f & KXF_TIMER)
1144     sel_rmtimer(&kx->t);
1145   for (i = 0; i < kx->nr; i++)
1146     kxc_destroy(kx->r[i]);
1147   mp_drop(kx->alpha);
1148   G_DESTROY(kx->kpriv->g, kx->c);
1149   G_DESTROY(kx->kpriv->g, kx->rx);
1150   kx->t_valid = 0;
1151   kx->f |= KXF_DEAD;
1152   kx->f &= ~KXF_TIMER;
1153 }
1154
1155 /* --- @start@ --- *
1156  *
1157  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1158  *              @time_t now@ = the current time
1159  *
1160  * Returns:     ---
1161  *
1162  * Use:         Starts a new key exchange with the peer.  The context must be
1163  *              in the bizarre state left by @stop@ or @kx_init@.
1164  */
1165
1166 static void start(keyexch *kx, time_t now)
1167 {
1168   algswitch *algs = &kx->kpriv->algs;
1169   group *g = kx->kpriv->g;
1170   ghash *h;
1171
1172   assert(kx->f & KXF_DEAD);
1173
1174   kx->f &= ~(KXF_DEAD | KXF_CORK);
1175   kx->nr = 0;
1176   kx->alpha = mprand_range(MP_NEW, g->r, &rand_global, 0);
1177   kx->c = G_CREATE(g); G_EXP(g, kx->c, g->g, kx->alpha);
1178   kx->rx = G_CREATE(g); G_EXP(g, kx->rx, kx->kpub->kpub, kx->alpha);
1179   kx->s = KXS_CHAL;
1180   kx->t_valid = now + T_VALID;
1181
1182   h = GH_INIT(algs->h);
1183   HASH_STRING(h, "tripe-cookie");
1184   hashge(h, g, kx->c);
1185   GH_DONE(h, kx->hc);
1186   GH_DESTROY(h);
1187
1188   IF_TRACING(T_KEYEXCH, {
1189     trace(T_KEYEXCH, "keyexch: creating new challenge");
1190     IF_TRACING(T_CRYPTO, {
1191       trace(T_CRYPTO, "crypto: secret = %s", mpstr(kx->alpha));
1192       trace(T_CRYPTO, "crypto: challenge = %s", gestr(g, kx->c));
1193       trace(T_CRYPTO, "crypto: expected response = %s", gestr(g, kx->rx));
1194       trace_block(T_CRYPTO, "crypto: challenge cookie",
1195                   kx->hc, algs->hashsz);
1196     })
1197   })
1198 }
1199
1200 /* --- @checkpub@ --- *
1201  *
1202  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1203  *
1204  * Returns:     Zero if OK, nonzero if the peer's public key has expired.
1205  *
1206  * Use:         Deactivates the key-exchange until the peer acquires a new
1207  *              public key.
1208  */
1209
1210 static int checkpub(keyexch *kx)
1211 {
1212   time_t now;
1213   unsigned f = 0;
1214
1215   if (kx->f & KXF_DEAD)
1216     return (-1);
1217   now = time(0);
1218   if (KEY_EXPIRED(now, kx->kpriv->t_exp)) f |= 1;
1219   if (KEY_EXPIRED(now, kx->kpub->t_exp)) f |= 2;
1220   if (f) {
1221     stop(kx);
1222     if (f & 1) a_warn("KX", "?PEER", kx->p, "private-key-expired", A_END);
1223     if (f & 2) a_warn("KX", "?PEER", kx->p, "public-key-expired", A_END);
1224     kx->f &= ~KXF_PUBKEY;
1225     return (-1);
1226   }
1227   return (0);
1228 }
1229
1230 /* --- @kx_start@ --- *
1231  *
1232  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1233  *              @int forcep@ = nonzero to ignore the quiet timer
1234  *
1235  * Returns:     ---
1236  *
1237  * Use:         Stimulates a key exchange.  If a key exchage is in progress,
1238  *              a new challenge is sent (unless the quiet timer forbids
1239  *              this); if no exchange is in progress, one is commenced.
1240  */
1241
1242 void kx_start(keyexch *kx, int forcep)
1243 {
1244   time_t now = time(0);
1245
1246   if (checkpub(kx))
1247     return;
1248   if (forcep || !VALIDP(kx, now)) {
1249     stop(kx);
1250     start(kx, now);
1251     a_notify("KXSTART", "?PEER", kx->p, A_END);
1252   }
1253   resend(kx);
1254 }
1255
1256 /* --- @kx_message@ --- *
1257  *
1258  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1259  *              @unsigned msg@ = the message code
1260  *              @buf *b@ = pointer to buffer containing the packet
1261  *
1262  * Returns:     ---
1263  *
1264  * Use:         Reads a packet containing key exchange messages and handles
1265  *              it.
1266  */
1267
1268 void kx_message(keyexch *kx, unsigned msg, buf *b)
1269 {
1270   struct timeval now, tv;
1271   stats *st = p_stats(kx->p);
1272   size_t sz = BSZ(b);
1273   int rc;
1274
1275   gettimeofday(&now, 0);
1276   rs_reset(&kx->rs);
1277   if (kx->f & KXF_CORK) {
1278     start(kx, now.tv_sec);
1279     rs_time(&kx->rs, &tv, &now);
1280     settimer(kx, &tv);
1281     a_notify("KXSTART", A_END);
1282   }
1283
1284   if (checkpub(kx))
1285     return;
1286
1287   if (!VALIDP(kx, now.tv_sec)) {
1288     stop(kx);
1289     start(kx, now.tv_sec);
1290   }
1291   T( trace(T_KEYEXCH, "keyexch: processing %s packet from `%s'",
1292            msg < KX_NMSG ? pkname[msg] : "unknown", p_name(kx->p)); )
1293
1294   switch (msg) {
1295     case KX_PRECHAL:
1296       rc = doprechallenge(kx, b);
1297       break;
1298     case KX_CHAL:
1299       rc = dochallenge(kx, b);
1300       break;
1301     case KX_REPLY:
1302       rc = doreply(kx, b);
1303       break;
1304     case KX_SWITCH:
1305       rc = doswitch(kx, b);
1306       break;
1307     case KX_SWITCHOK:
1308       rc = doswitchok(kx, b);
1309       break;
1310     default:
1311       a_warn("KX", "?PEER", kx->p, "unknown-message", "0x%02x", msg, A_END);
1312       rc = -1;
1313       break;
1314   }
1315
1316   if (rc)
1317     st->n_reject++;
1318   else {
1319     st->n_kxin++;
1320     st->sz_kxin += sz;
1321   }
1322 }
1323
1324 /* --- @kx_free@ --- *
1325  *
1326  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1327  *
1328  * Returns:     ---
1329  *
1330  * Use:         Frees everything in a key exchange context.
1331  */
1332
1333 void kx_free(keyexch *kx)
1334 {
1335   stop(kx);
1336   km_unref(kx->kpub);
1337   km_unref(kx->kpriv);
1338 }
1339
1340 /* --- @kx_newkeys@ --- *
1341  *
1342  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1343  *
1344  * Returns:     ---
1345  *
1346  * Use:         Informs the key exchange module that its keys may have
1347  *              changed.  If fetching the new keys fails, the peer will be
1348  *              destroyed, we log messages and struggle along with the old
1349  *              keys.
1350  */
1351
1352 void kx_newkeys(keyexch *kx)
1353 {
1354   kdata *kpriv, *kpub;
1355   unsigned i;
1356   int switchp;
1357   time_t now = time(0);
1358
1359   T( trace(T_KEYEXCH, "keyexch: checking new keys for `%s'",
1360            p_name(kx->p)); )
1361
1362   /* --- Find out whether we can use new keys --- *
1363    *
1364    * Try each available combination of new and old, public and private,
1365    * except both old (which is status quo anyway).  The selection is encoded
1366    * in @i@, with bit 0 for the private key and bit 1 for public key; a set
1367    * bit means to use the old value, and a clear bit means to use the new
1368    * one.
1369    *
1370    * This means that we currently prefer `old private and new public' over
1371    * `new private and old public'.  I'm not sure which way round this should
1372    * actually be.
1373    */
1374
1375   for (i = 0; i < 3; i++) {
1376
1377     /* --- Select the keys we're going to examine --- *
1378      *
1379      * If we're meant to have a new key and don't, then skip this
1380      * combination.
1381      */
1382
1383     T( trace(T_KEYEXCH, "keyexch: checking %s private, %s public",
1384              i & 1 ? "old" : "new", i & 2 ? "old" : "new"); )
1385
1386     if (i & 1) kpriv = kx->kpriv;
1387     else if (kx->kpriv->kn->kd != kx->kpriv) kpriv = kx->kpriv->kn->kd;
1388     else {
1389       T( trace(T_KEYEXCH, "keyexch: private key unchanged, skipping"); )
1390       continue;
1391     }
1392
1393     if (i & 2) kpub = kx->kpub;
1394     else if (kx->kpub->kn->kd != kx->kpub) kpub = kx->kpub->kn->kd;
1395     else {
1396       T( trace(T_KEYEXCH, "keyexch: public key unchanged, skipping"); )
1397       continue;
1398     }
1399
1400     /* --- Skip if either key is expired --- *
1401      *
1402      * We're not going to get far with expired keys, and this simplifies the
1403      * logic below.
1404      */
1405
1406     if (KEY_EXPIRED(now, kx->kpriv->t_exp) ||
1407         KEY_EXPIRED(now, kx->kpub->t_exp)) {
1408       T( trace(T_KEYEXCH, "keyexch: %s expired, skipping",
1409                !KEY_EXPIRED(now, kx->kpriv->t_exp) ? "public key" :
1410                !KEY_EXPIRED(now, kx->kpub->t_exp) ? "private key" :
1411                "both keys"); )
1412       continue;
1413     }
1414
1415     /* --- If the groups don't match then we can't use this pair --- */
1416
1417     if (!km_samealgsp(kpriv, kpub)) {
1418       T( trace(T_KEYEXCH, "keyexch: peer `%s' group mismatch; "
1419                "%s priv `%s' and %s pub `%s'", p_name(kx->p),
1420                i & 1 ? "old" : "new", km_tag(kx->kpriv),
1421                i & 2 ? "old" : "new", km_tag(kx->kpub)); )
1422       continue;
1423     }
1424     goto newkeys;
1425   }
1426   T( trace(T_KEYEXCH, "keyexch: peer `%s' continuing with old keys",
1427            p_name(kx->p)); )
1428   return;
1429
1430   /* --- We've chosen new keys --- *
1431    *
1432    * Switch the new ones into place.  Neither of the keys we're switching to
1433    * is expired (we checked that above), so we should just crank everything
1434    * up.
1435    *
1436    * A complication arises: we don't really want to force a new key exchange
1437    * unless we have to.  If the group is unchanged, and we're currently
1438    * running OK, then we should just let things lie.
1439    */
1440
1441 newkeys:
1442   switchp = ((kx->f & KXF_DEAD) ||
1443              kx->s != KXS_SWITCH ||
1444              !group_samep(kx->kpriv->g, kpriv->g));
1445
1446   T( trace(T_KEYEXCH, "keyexch: peer `%s' adopting "
1447            "%s priv `%s' and %s pub `%s'; %sforcing exchange", p_name(kx->p),
1448            i & 1 ? "old" : "new", km_tag(kx->kpriv),
1449            i & 2 ? "old" : "new", km_tag(kx->kpub),
1450            switchp ? "" : "not "); )
1451
1452   if (switchp) stop(kx);
1453   km_ref(kpriv); km_unref(kx->kpriv); kx->kpriv = kpriv;
1454   km_ref(kpub);  km_unref(kx->kpub);  kx->kpub  = kpub;
1455   kx->f |= KXF_PUBKEY;
1456   if (switchp) {
1457     T( trace(T_KEYEXCH, "keyexch: restarting key negotiation with `%s'",
1458              p_name(kx->p)); )
1459     start(kx, time(0));
1460     resend(kx);
1461   }
1462 }
1463
1464 /* --- @kx_init@ --- *
1465  *
1466  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1467  *              @peer *p@ = pointer to peer context
1468  *              @keyset **ks@ = pointer to keyset list
1469  *              @unsigned f@ = various useful flags
1470  *
1471  * Returns:     Zero if OK, nonzero if it failed.
1472  *
1473  * Use:         Initializes a key exchange module.  The module currently
1474  *              contains no keys, and will attempt to initiate a key
1475  *              exchange.
1476  */
1477
1478 int kx_init(keyexch *kx, peer *p, keyset **ks, unsigned f)
1479 {
1480   if ((kx->kpriv = km_findpriv(p_privtag(p))) == 0) goto fail_0;
1481   if ((kx->kpub = km_findpub(p_tag(p))) == 0) goto fail_1;
1482   if (!group_samep(kx->kpriv->g, kx->kpub->g)) {
1483     a_warn("KX", "?PEER", kx->p, "group-mismatch",
1484            "local-private-key", "%s", p_privtag(p),
1485            "peer-public-key", "%s", p_tag(p),
1486            A_END);
1487     goto fail_2;
1488   }
1489
1490   kx->ks = ks;
1491   kx->p = p;
1492   kx->f = KXF_DEAD | KXF_PUBKEY | f;
1493   rs_reset(&kx->rs);
1494   if (!(kx->f & KXF_CORK)) {
1495     start(kx, time(0));
1496     resend(kx);
1497     /* Don't notify here: the ADD message hasn't gone out yet. */
1498   }
1499   return (0);
1500
1501 fail_2:
1502   km_unref(kx->kpub);
1503 fail_1:
1504   km_unref(kx->kpriv);
1505 fail_0:
1506   return (-1);
1507 }
1508
1509 /*----- That's all, folks -------------------------------------------------*/