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