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