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