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