chiark / gitweb /
Merge branch '1.0.0pre19.x'
[tripe] / server / keyexch.c
1 /* -*-c-*-
2  *
3  * Key exchange protocol
4  *
5  * (c) 2001 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Trivial IP Encryption (TrIPE).
11  *
12  * TrIPE is free software: you can redistribute it and/or modify it under
13  * the terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your
15  * option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20  * for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
24  */
25
26 /*----- Header files ------------------------------------------------------*/
27
28 #include "tripe.h"
29
30 /*----- Brief protocol overview -------------------------------------------*
31  *
32  * Let %$G$% be a cyclic group; let %$g$% be a generator of %$G$%, and let
33  * %$q$% be the order of %$G$%; for a key %$K$%, let %$E_K(\cdot)$% denote
34  * application of the symmetric packet protocol to a message; let
35  * %$H(\cdot)$% be the random oracle.  Let $\alpha \inr \{0,\ldots,q - 1\}$%
36  * be Alice's private key; let %$a = g^\alpha$% be her public key; let %$b$%
37  * be Bob's public key.
38  *
39  * At the beginning of the session, Alice chooses
40  *
41  *   %$\rho_A \inr \{0, \ldots q - 1\}$%
42  *
43  * We also have:
44  *
45  * %$r_A = g^{\rho_A}$%                 Alice's challenge
46  * %$c_A = H(\cookie{cookie}, r_A)$%    Alice's cookie
47  * %$v_A = \rho_A \xor H(\cookie{expected-reply}, a, r_A, r_B, b^{\rho_A})$%
48  *                                      Alice's challenge check value
49  * %$r_B^\alpha = a^{\rho_B}$%          Alice's reply
50  * %$K = r_B^{\rho_A} = r_B^{\rho_A} = g^{\rho_A\rho_B}$%
51  *                                      Alice and Bob's shared secret key
52  * %$w_A = H(\cookie{switch-request}, c_A, c_B)$%
53  *                                      Alice's switch request value
54  * %$u_A = H(\cookie{switch-confirm}, c_A, c_B)$%
55  *                                      Alice's switch confirm value
56  *
57  * The messages are then:
58  *
59  * %$\cookie{kx-pre-challenge}, r_A$%
60  *      Initial greeting.  In state @KXS_CHAL@.
61  *
62  * %$\cookie{kx-challenge}, r_A, c_B, v_A$%
63  *      Here's a full challenge for you to answer.
64  *
65  * %$\cookie{kx-reply}, r_A, c_B, v_A, E_K(r_B^\alpha))$%
66  *      Challenge accpeted: here's the answer.  Commit to my challenge.  Move
67  *      to @KXS_COMMIT@.
68  *
69  * %$\cookie{kx-switch-rq}, c_A, c_B, E_K(r_B^\alpha, w_A))$%
70  *      Reply received: here's my reply.  Committed; send data; move to
71  *      @KXS_SWITCH@.
72  *
73  * %$\cookie{kx-switch-ok}, E_K(u_A))$%
74  *      Switch received.  Committed; send data; move to @KXS_SWITCH@.
75  *
76  * %$\cookie{kx-token-request}, u, E_L(n)$%
77  *      %$L = H(u, u^\alpha)$%, and %$n$% is a string of the form
78  *      `[PEER.]KEYTAG'.  Expect %$\cookie{kx-token}$% by return.
79  *
80  * %$\cookie{kx-token}, v, E_{L'}(t)$%
81  *      %$L' = H(v, v^\alpha)$%, and %$t$% is a token associated with %$n$%
82  *      (see %$\cookie{kx-token-request}$% above).
83  *
84  * %$\cookie{kx-knock}, u, E_L(n, t), r_A$%
85  *      %$L$%, %$n$% and %$t$% are as %$\cookie{kx-token}$% and
86  *      %$\cookie{kx-token-request}$%; %$r_A$% is as in
87  *      %$\cookie{kx-pre-challenge}$%.  If the token %$t$% doesn't match
88  *      %$n$%, then warn and discard.  If a peer named PEER (or KEYTAG)
89  *      exists then proceed as for %$\cookie{kx-pre-challenge}$%.  Otherwise
90  *      issue a notification `NOTE KNOCK PEER ADDR...' and discard.
91  */
92
93 /*----- Static tables -----------------------------------------------------*/
94
95 static const char *const pkname[] = {
96   "pre-challenge", "challenge", "reply", "switch-rq", "switch-ok",
97   "token-rq", "token", "knock"
98 };
99
100 /*----- Various utilities -------------------------------------------------*/
101
102 /* --- @VALIDP@ --- *
103  *
104  * Arguments:   @const keyexch *kx@ = key exchange state
105  *              @time_t now@ = current time in seconds
106  *
107  * Returns:     Whether the challenge in the key-exchange state is still
108  *              valid or should be regenerated.
109  */
110
111 #define VALIDP(kx, now) ((now) < (kx)->t_valid)
112
113 /* --- @hashge@ --- *
114  *
115  * Arguments:   @ghash *h@ = pointer to hash context
116  *              @const dhgrp *g@ = pointer to group
117  *              @const dhge *Y@ = pointer to group element
118  *
119  * Returns:     ---
120  *
121  * Use:         Adds the hash of a group element to the context.  Corrupts
122  *              @buf_t@.
123  */
124
125 static void hashge(ghash *h, const dhgrp *g, const dhge *Y)
126 {
127   buf b;
128
129   buf_init(&b, buf_t, sizeof(buf_t));
130   g->ops->stge(g, &b, Y, DHFMT_HASH);
131   assert(BOK(&b));
132   GH_HASH(h, BBASE(&b), BLEN(&b));
133 }
134
135 /* --- @mpmask@ --- *
136  *
137  * Arguments:   @buf *b@ = output buffer
138  *              @const dhgrp *g@ = the group
139  *              @const dhsc *x@ = the plaintext scalar
140  *              @size_t n@ = the expected size of the plaintext
141  *              @gcipher *mgfc@ = mask-generating function to use
142  *              @const octet *k@ = pointer to key material
143  *              @size_t ksz@ = size of the key
144  *
145  * Returns:     ---
146  *
147  * Use:         Masks a scalar: returns %$x \xor H(k)$%, so it's a random
148  *              oracle thing rather than an encryption thing.  Breaks the
149  *              output buffer on error.
150  */
151
152 static void mpmask(buf *b, const dhgrp *g, const dhsc *x, size_t n,
153                    const gccipher *mgfc, const octet *k, size_t ksz)
154 {
155   gcipher *mgf;
156   octet *p;
157
158   if ((p = buf_get(b, n)) == 0) return;
159   mgf = GC_INIT(mgfc, k, ksz);
160   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
161     trace(T_CRYPTO, "crypto: masking scalar = %s", g->ops->scstr(g, x));
162     trace_block(T_CRYPTO, "crypto: masking key", k, ksz);
163   }))
164   if (g->ops->stsc(g, buf_t, n, x)) { buf_break(b); return; }
165   GC_ENCRYPT(mgf, buf_t, p, n);
166   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
167     trace_block(T_CRYPTO, "crypto: scalar plaintext", buf_t, n);
168     trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
169   }))
170   GC_DESTROY(mgf);
171 }
172
173 /* --- @mpunmask@ --- *
174  *
175  * Arguments:   @const dhgrp *g@ = the group
176  *              @const octet *p@ = pointer to the ciphertext
177  *              @size_t n@ = the size of the ciphertext
178  *              @gcipher *mgfc@ = mask-generating function to use
179  *              @const octet *k@ = pointer to key material
180  *              @size_t ksz@ = size of the key
181  *
182  * Returns:     The decrypted scalar, or null.
183  *
184  * Use:         Unmasks a scalar.
185  */
186
187 static dhsc *mpunmask(const dhgrp *g, const octet *p, size_t n,
188                       const gccipher *mgfc, const octet *k, size_t ksz)
189 {
190   gcipher *mgf;
191   dhsc *x;
192
193   mgf = GC_INIT(mgfc, k, ksz);
194   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
195     trace_block(T_CRYPTO, "crypto: unmasking key", k, ksz);
196     trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
197   }))
198   GC_DECRYPT(mgf, p, buf_t, n);
199   x = g->ops->ldsc(g, buf_t, n);
200   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
201     trace_block(T_CRYPTO, "crypto: scalar plaintext", buf_t, n);
202     trace(T_CRYPTO, "crypto: unmasked scalar = %s",
203           x ? g->ops->scstr(g, x) : "<failed>");
204   }))
205   GC_DESTROY(mgf);
206   return (x);
207 }
208
209 /* --- @hashcheck@ --- *
210  *
211  * Arguments:   @keyexch *kx@ = pointer to key-exchange block
212  *              @const dhge *K@ = sender's public key
213  *              @const dhge *CC@ = receiver's challenge
214  *              @const dhge *C@ = sender's challenge
215  *              @const dhge *Y@ = reply to sender's challenge
216  *
217  * Returns:     Pointer to the hash value (in @buf_t@)
218  *
219  * Use:         Computes the check-value hash, used to mask or unmask
220  *              indices to prove the validity of challenges.  This computes
221  *              the masking key used in challenge check values.  This is
222  *              really the heart of the whole thing, since it ensures that
223  *              the scalar can be recovered from the history of hashing
224  *              queries, which gives us (a) a proof that the authentication
225  *              process is zero-knowledge, and (b) a proof that the whole
226  *              key-exchange is deniable.
227  */
228
229 static const octet *hashcheck(keyexch *kx, const dhge *K,
230                               const dhge *CC, const dhge *C, const dhge *Y)
231 {
232   ghash *h = GH_INIT(kx->kpriv->algs.h);
233   const dhgrp *g = kx->kpriv->grp;
234
235   HASH_STRING(h, "tripe-expected-reply");
236   hashge(h, g, K);
237   hashge(h, g, CC);
238   hashge(h, g, C);
239   hashge(h, g, Y);
240   GH_DONE(h, buf_t);
241   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
242     trace(T_CRYPTO, "crypto: computing challenge check hash");
243     trace(T_CRYPTO, "crypto: public key = %s", g->ops->gestr(g, K));
244     trace(T_CRYPTO, "crypto: receiver challenge = %s", g->ops->gestr(g, CC));
245     trace(T_CRYPTO, "crypto: sender challenge = %s", g->ops->gestr(g, C));
246     trace(T_CRYPTO, "crypto: sender reply = %s", g->ops->gestr(g, Y));
247     trace_block(T_CRYPTO, "crypto: hash output", buf_t, kx->kpriv->algs.hashsz);
248   }))
249   GH_DESTROY(h);
250   return (buf_t);
251 }
252
253 /* --- @sendchallenge@ --- *
254  *
255  * Arguments:   @keyexch *kx@ = pointer to key exchange block
256  *              @buf *b@ = output buffer for challenge
257  *              @const dhge *C@ = peer's actual challenge
258  *              @const octet *hc@ = peer's challenge cookie
259  *
260  * Returns:     ---
261  *
262  * Use:         Writes a full challenge to the message buffer.
263  */
264
265 static void sendchallenge(keyexch *kx, buf *b,
266                           const dhge *C, const octet *hc)
267 {
268   const dhgrp *g = kx->kpriv->grp;
269   g->ops->stge(g, b, kx->C, DHFMT_VAR);
270   buf_put(b, hc, kx->kpriv->algs.hashsz);
271   mpmask(b, g, kx->a, g->scsz, kx->kpriv->algs.mgf,
272          hashcheck(kx, kx->kpriv->K, C, kx->C, kx->RX),
273          kx->kpriv->algs.hashsz);
274 }
275
276 /* --- @timer@ --- *
277  *
278  * Arguments:   @struct timeval *tv@ = the current time
279  *              @void *v@ = pointer to key exchange context
280  *
281  * Returns:     ---
282  *
283  * Use:         Acts when the key exchange timer goes off.
284  */
285
286 static void timer(struct timeval *tv, void *v)
287 {
288   keyexch *kx = v;
289   kx->f &= ~KXF_TIMER;
290   T( trace(T_KEYEXCH, "keyexch: timer has popped"); )
291   kx_start(kx, 0);
292 }
293
294 /* --- @settimer@ --- *
295  *
296  * Arguments:   @keyexch *kx@ = pointer to key exchange context
297  *              @struct timeval *tv@ = when to set the timer for
298  *
299  * Returns:     ---
300  *
301  * Use:         Sets the timer for the next key exchange attempt.
302  */
303
304 static void settimer(keyexch *kx, struct timeval *tv)
305 {
306   if (kx->f & KXF_TIMER) sel_rmtimer(&kx->t);
307   sel_addtimer(&sel, &kx->t, tv, timer, kx);
308   kx->f |= KXF_TIMER;
309 }
310
311 /* --- @f2tv@ --- *
312  *
313  * Arguments:   @struct timeval *tv@ = where to write the timeval
314  *              @double t@ = a time as a floating point number
315  *
316  * Returns:     ---
317  *
318  * Use:         Converts a floating-point time into a timeval.
319  */
320
321 static void f2tv(struct timeval *tv, double t)
322 {
323   tv->tv_sec = t;
324   tv->tv_usec = (t - tv->tv_sec)*MILLION;
325 }
326
327 /* --- @wobble@ --- *
328  *
329  * Arguments:   @double t@ = a time interval
330  *
331  * Returns:     The same time interval, with a random error applied.
332  */
333
334 static double wobble(double t)
335 {
336   uint32 r = rand_global.ops->word(&rand_global);
337   double w = (r/F_2P32) - 0.5;
338   return (t + t*w*T_WOBBLE);
339 }
340
341 /* --- @rs_time@ --- *
342  *
343  * Arguments:   @retry *rs@ = current retry state
344  *              @struct timeval *tv@ = where to write the result
345  *              @const struct timeval *now@ = current time, or null
346  *
347  * Returns:     ---
348  *
349  * Use:         Computes a time at which to retry sending a key-exchange
350  *              packet.  This algorithm is subject to change, but it's
351  *              currently a capped exponential backoff, slightly randomized
352  *              to try to keep clients from hammering a server that's only
353  *              just woken up.
354  *
355  *              If @now@ is null then the function works out the time for
356  *              itself.
357  */
358
359 static void rs_time(retry *rs, struct timeval *tv, const struct timeval *now)
360 {
361   double t;
362   struct timeval rtv;
363
364   if (!rs->t)
365     t = SEC(2);
366   else {
367     t = (rs->t * 5)/4;
368     if (t > MIN(5)) t = MIN(5);
369   }
370   rs->t = t;
371
372   if (!now) {
373     now = tv;
374     gettimeofday(tv, 0);
375   }
376   f2tv(&rtv, wobble(t));
377   TV_ADD(tv, now, &rtv);
378 }
379
380 /* --- @retry_reset@ --- *
381  *
382  * Arguments:   @retry *rs@ = retry state
383  *
384  * Returns:     --
385  *
386  * Use:         Resets a retry state to indicate that progress has been
387  *              made.  Also useful for initializing the state in the first
388  *              place.
389  */
390
391 static void rs_reset(retry *rs) { rs->t = 0; }
392
393 /* --- @notice_message@ --- *
394  *
395  * Arguments:   @keyexch *kx@ = pointer to key-exchange block
396  *
397  * Returns:     Zero if OK; @-1@ if the public key is in a bad state.
398  *
399  * Use:         Updates the key-exchange state following a received message.
400  *              Specifically, if there's no currently active key-exchange in
401  *              progress, and we're not in the cooling-off period, then
402  *              commence a new one; reset the retry timers; and if we're
403  *              corked then pop the cork so that we can reply.
404  */
405
406 static int checkpub(keyexch *kx);
407 static void stop(keyexch *kx);
408 static void start(keyexch *kx, time_t now);
409
410 static int notice_message(keyexch *kx)
411 {
412   struct timeval now, tv;
413
414   gettimeofday(&now, 0);
415   rs_reset(&kx->rs);
416   if (kx->f & KXF_CORK) {
417     start(kx, now.tv_sec);
418     rs_time(&kx->rs, &tv, &now);
419     settimer(kx, &tv);
420     a_notify("KXSTART", "?PEER", kx->p, A_END);
421   }
422   if (checkpub(kx)) return (-1);
423   if (!VALIDP(kx, now.tv_sec)) {
424     stop(kx);
425     start(kx, now.tv_sec);
426   }
427   return (0);
428 }
429
430 /* --- @update_stats_tx@, @update_stats_rx@ --- *
431  *
432  * Arguments:   @keyexch *kx@ = pointer to key-exchange block
433  *              @int ok@ = nonzero if the message was valid (for @rx@)
434  *              @size_t sz@ = size of sent message
435  *
436  * Returns:     ---
437  *
438  * Use:         Records that a key-exchange message was sent to, or received
439  *              from, the peer.
440  */
441
442 static void update_stats_tx(keyexch *kx, size_t sz)
443   { stats *st = p_stats(kx->p); st->n_kxout++; st->sz_kxout += sz; }
444
445 static void update_stats_rx(keyexch *kx, int ok, size_t sz)
446 {
447   stats *st = p_stats(kx->p);
448
449   if (!ok) st->n_reject++;
450   else { st->n_kxin++; st->sz_kxin += sz; }
451 }
452
453 /*----- Challenge management ----------------------------------------------*/
454
455 /* --- Notes on challenge management --- *
456  *
457  * We may get multiple different replies to our key exchange; some will be
458  * correct, some inserted by attackers.  Up until @KX_THRESH@, all challenges
459  * received will be added to the table and given a full response.  After
460  * @KX_THRESH@ distinct challenges are received, we return only a `cookie':
461  * our existing challenge, followed by a hash of the sender's challenge.  We
462  * do %%\emph{not}%% give a bare challenge a reply slot at this stage.  All
463  * properly-formed cookies are assigned a table slot: if none is spare, a
464  * used slot is randomly selected and destroyed.  A cookie always receives a
465  * full reply.
466  */
467
468 /* --- @kxc_destroy@ --- *
469  *
470  * Arguments:   @kxchal *kxc@ = pointer to the challenge block
471  *
472  * Returns:     ---
473  *
474  * Use:         Disposes of a challenge block.
475  */
476
477 static void kxc_destroy(kxchal *kxc)
478 {
479   const dhgrp *g = kxc->kx->kpriv->grp;
480   if (kxc->f & KXF_TIMER)
481     sel_rmtimer(&kxc->t);
482   g->ops->freege(g, kxc->C);
483   g->ops->freege(g, kxc->R);
484   ks_drop(kxc->ks);
485   DESTROY(kxc);
486 }
487
488 /* --- @kxc_stoptimer@ --- *
489  *
490  * Arguments:   @kxchal *kxc@ = pointer to the challenge block
491  *
492  * Returns:     ---
493  *
494  * Use:         Stops the challenge's retry timer from sending messages.
495  *              Useful when the state machine is in the endgame of the
496  *              exchange.
497  */
498
499 static void kxc_stoptimer(kxchal *kxc)
500 {
501   if (kxc->f & KXF_TIMER)
502     sel_rmtimer(&kxc->t);
503   kxc->f &= ~KXF_TIMER;
504 }
505
506 /* --- @kxc_new@ --- *
507  *
508  * Arguments:   @keyexch *kx@ = pointer to key exchange block
509  *
510  * Returns:     A pointer to the challenge block.
511  *
512  * Use:         Returns a pointer to a new challenge block to fill in.
513  *              In particular, the @c@ and @r@ members are left
514  *              uninitialized.
515  */
516
517 static kxchal *kxc_new(keyexch *kx)
518 {
519   kxchal *kxc;
520   unsigned i;
521
522   /* --- If we're over reply threshold, discard one at random --- */
523
524   if (kx->nr < KX_NCHAL)
525     i = kx->nr++;
526   else {
527     i = rand_global.ops->range(&rand_global, KX_NCHAL);
528     kxc_destroy(kx->r[i]);
529   }
530
531   /* --- Fill in the new structure --- */
532
533   kxc = CREATE(kxchal);
534   kxc->ks = 0;
535   kxc->kx = kx;
536   kxc->f = 0;
537   kx->r[i] = kxc;
538   rs_reset(&kxc->rs);
539   return (kxc);
540 }
541
542 /* --- @kxc_bychal@ --- *
543  *
544  * Arguments:   @keyexch *kx@ = pointer to key exchange block
545  *              @const dhge *C@ = challenge from remote host
546  *
547  * Returns:     Pointer to the challenge block, or null.
548  *
549  * Use:         Finds a challenge block, given its challenge.
550  */
551
552 static kxchal *kxc_bychal(keyexch *kx, const dhge *C)
553 {
554   const dhgrp *g = kx->kpriv->grp;
555   unsigned i;
556
557   for (i = 0; i < kx->nr; i++) {
558     if (g->ops->eq(g, C, kx->r[i]->C))
559       return (kx->r[i]);
560   }
561   return (0);
562 }
563
564 /* --- @kxc_byhc@ --- *
565  *
566  * Arguments:   @keyexch *kx@ = pointer to key exchange block
567  *              @const octet *hc@ = challenge hash from remote host
568  *
569  * Returns:     Pointer to the challenge block, or null.
570  *
571  * Use:         Finds a challenge block, given a hash of its challenge.
572  */
573
574 static kxchal *kxc_byhc(keyexch *kx, const octet *hc)
575 {
576   unsigned i;
577
578   for (i = 0; i < kx->nr; i++) {
579     if (memcmp(hc, kx->r[i]->hc, kx->kpriv->algs.hashsz) == 0)
580       return (kx->r[i]);
581   }
582   return (0);
583 }
584
585 /* --- @kxc_answer@ --- *
586  *
587  * Arguments:   @keyexch *kx@ = pointer to key exchange block
588  *              @kxchal *kxc@ = pointer to challenge block
589  *
590  * Returns:     ---
591  *
592  * Use:         Sends a reply to the remote host, according to the data in
593  *              this challenge block.
594  */
595
596 static void kxc_answer(keyexch *kx, kxchal *kxc);
597
598 static void kxc_timer(struct timeval *tv, void *v)
599 {
600   kxchal *kxc = v;
601   kxc->f &= ~KXF_TIMER;
602   kxc_answer(kxc->kx, kxc);
603 }
604
605 static void kxc_answer(keyexch *kx, kxchal *kxc)
606 {
607   buf *b = p_txstart(kx->p, MSG_KEYEXCH | KX_REPLY);
608   const dhgrp *g = kx->kpriv->grp;
609   struct timeval tv;
610   buf bb;
611
612   /* --- Build the reply packet --- */
613
614   T( trace(T_KEYEXCH, "keyexch: sending reply to `%s'", p_name(kx->p)); )
615   sendchallenge(kx, b, kxc->C, kxc->hc);
616   buf_init(&bb, buf_i, sizeof(buf_i));
617   g->ops->stge(g, &bb, kxc->R, DHFMT_STD);
618   buf_flip(&bb);
619   ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_REPLY, &bb, b);
620
621   /* --- Update the statistics --- */
622
623   if (BOK(b)) {
624     update_stats_tx(kx, BLEN(b));
625     p_txend(kx->p);
626   }
627
628   /* --- Schedule another resend --- */
629
630   if (kxc->f & KXF_TIMER)
631     sel_rmtimer(&kxc->t);
632   gettimeofday(&tv, 0);
633   rs_time(&kxc->rs, &tv, &tv);
634   sel_addtimer(&sel, &kxc->t, &tv, kxc_timer, kxc);
635   kxc->f |= KXF_TIMER;
636 }
637
638 /*----- Individual message handlers ---------------------------------------*/
639
640 static ratelim unauth_limit;
641
642 /* --- @dotokenrq@ --- *
643  *
644  * Arguments:   @const addr *a@ = sender's address
645  *              @buf *b@ = buffer containing the packet
646  *
647  * Returns:     ---
648  *
649  * Use:         Processes a token-request message.
650  */
651
652 static void dotokenrq(const addr *a, buf *b)
653 {
654   uint32 id;
655   kdata *kpriv = 0, *kpub = 0;
656   char *pname;
657   const char *tag;
658   size_t sz;
659   buf bb, bbb;
660
661   /* --- Check if we're in danger of overloading --- */
662
663   if (ratelim_withdraw(&unauth_limit, 1)) goto done;
664
665   /* --- Start building the reply --- */
666
667   buf_init(&bbb, buf_o, sizeof(buf_o));
668   buf_putu8(&bbb, MSG_KEYEXCH | KX_TOKEN);
669
670   /* --- Fetch and copy the challenge string --- */
671
672   if (buf_getbuf16(b, &bb)) goto done;
673   buf_putmem16(&bbb, BBASE(&bb), BSZ(&bb));
674
675   /* --- Make our own challenge for the response --- */
676
677   buf_init(&bb, buf_t, sizeof(buf_t));
678   c_new(0, 0, &bb); assert(BOK(&bb)); buf_putbuf16(&bbb, &bb);
679
680   /* --- Figure out which private key I'm supposed to use --- */
681
682   if (buf_getu32(b, &id)) goto done;
683   if ((kpriv = km_findprivbyid(id)) == 0) goto done;
684
685   /* --- Decrypt the message --- */
686
687   buf_init(&bb, buf_t, sizeof(buf_t));
688   if (ies_decrypt(kpriv, MSG_KEYEXCH | KX_TOKENRQ, b, &bb) || BLEFT(b))
689     goto done;
690
691   /* --- Parse the token request and find the sender's public key --- */
692
693   assert(BOK(&bb)); buf_flip(&bb);
694   if ((pname = buf_getmem16(&bb, &sz)) == 0 || memchr(pname, 0, sz))
695     goto done;
696   assert(sz < sizeof(buf_t) - ((const octet *)pname - buf_t));
697   pname[sz] = 0;
698   if ((tag = strchr(pname, '.')) != 0) tag++;
699   else tag = pname;
700   if ((kpub = km_findpub(tag)) == 0) goto done;
701
702   /* --- Build and encrypt the token --- */
703
704   buf_init(&bb, buf_i, sizeof(buf_i));
705   c_new(pname, sz, &bb);
706   assert(BOK(&bb)); buf_flip(&bb);
707   if (ies_encrypt(kpub, MSG_KEYEXCH | KX_TOKEN, &bb, &bbb)) goto done;
708   assert(BOK(&bbb));
709
710   /* --- Send the response -- or at least give it a try --- */
711
712   p_txaddr(a, BBASE(&bbb), BLEN(&bbb));
713
714   /* --- All done --- */
715
716 done:
717   if (kpriv) km_unref(kpriv);
718   if (kpub) km_unref(kpub);
719 }
720
721 /* --- @dotoken@ --- *
722  *
723  * Arguments:   @keyexch *kx@ = pointer to key exchange block
724  *              @buf *b@ = buffer containing the packet
725  *
726  * Returns:     Zero if OK, nonzero of the packet was rejected.
727  *
728  * Use:         Processes a token message.
729  */
730
731 static int dotoken(keyexch *kx, buf *b)
732 {
733   buf bb;
734   buf *bbb;
735   const dhgrp *g = kx->kpriv->grp;
736   octet *p;
737   size_t sz;
738
739   /* --- Make sure this is a sensible message to have received --- */
740
741   if (!kx->p->spec.knock) return (-1);
742
743   /* --- First, collect and verify our challenge --- */
744
745   if (buf_getbuf16(b, &bb) || c_check(0, 0, &bb) || BLEFT(&bb)) return (-1);
746
747   /* --- Start building the knock message from here --- */
748
749   bbb = p_txstart(kx->p, MSG_KEYEXCH | KX_KNOCK);
750
751   /* --- Copy the peer's challenge --- */
752
753   if (buf_getbuf16(b, &bb)) return (-1);
754   buf_putmem16(bbb, BBASE(&bb), BSZ(&bb));
755
756   /* --- Add the key indicator --- */
757
758   buf_putu32(bbb, kx->kpub->id);
759
760   /* --- Building the knock payload --- */
761
762   buf_init(&bb, buf_t, sizeof(buf_t));
763   buf_putstr16(&bb, kx->p->spec.knock);
764   sz = BLEN(&bb)%64; if (sz) sz = 64 - sz;
765   if (ies_decrypt(kx->kpriv, MSG_KEYEXCH | KX_TOKEN, b, &bb)) return (-1);
766   p = buf_get(&bb, sz); assert(p); memset(p, 0, sz);
767   assert(BOK(&bb)); buf_flip(&bb);
768   if (ies_encrypt(kx->kpub, MSG_KEYEXCH | KX_KNOCK, &bb, bbb)) return (-1);
769
770   /* --- Finally, the pre-challenge group element --- */
771
772   g->ops->stge(g, bbb, kx->C, DHFMT_VAR);
773
774   /* --- And we're done --- */
775
776   if (BBAD(bbb)) return (-1);
777   update_stats_tx(kx, BLEN(bbb));
778   p_txend(kx->p);
779   return (0);
780 }
781
782 /* --- @doprechallenge@ --- *
783  *
784  * Arguments:   @keyexch *kx@ = pointer to key exchange block
785  *              @buf *b@ = buffer containing the packet
786  *
787  * Returns:     Zero if OK, nonzero of the packet was rejected.
788  *
789  * Use:         Processes a pre-challenge message.
790  */
791
792 static int doprechallenge(keyexch *kx, buf *b)
793 {
794   const dhgrp *g = kx->kpriv->grp;
795   dhge *C = 0;
796   ghash *h;
797
798   /* --- Ensure that we're in a sensible state --- */
799
800   if (kx->s != KXS_CHAL) {
801     a_warn("KX", "?PEER", kx->p, "unexpected", "pre-challenge", A_END);
802     goto bad;
803   }
804
805   /* --- Unpack the packet --- */
806
807   if ((C = g->ops->ldge(g, b, DHFMT_VAR)) == 0 || BLEFT(b))
808     goto bad;
809
810   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
811     trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, C));
812   }))
813
814   /* --- Send out a full challenge by return --- */
815
816   b = p_txstart(kx->p, MSG_KEYEXCH | KX_CHAL);
817   h = GH_INIT(kx->kpriv->algs.h);
818   HASH_STRING(h, "tripe-cookie");
819   hashge(h, g, C);
820   sendchallenge(kx, b, C, GH_DONE(h, 0));
821   GH_DESTROY(h);
822   update_stats_tx(kx, BLEN(b));
823   p_txend(kx->p);
824
825   /* --- Done --- */
826
827   g->ops->freege(g, C);
828   return (0);
829
830 bad:
831   if (C) g->ops->freege(g, C);
832   return (-1);
833 }
834
835 /* --- @doknock@ --- *
836  *
837  * Arguments:   @const addr *a@ = sender's address
838  *              @buf *b@ = buffer containing the packet
839  *
840  * Returns:     ---
841  *
842  * Use:         Processes a knock message.
843  */
844
845 static void doknock(const addr *a, buf *b)
846 {
847   keyexch *kx;
848   peer *p;
849   uint32 id;
850   kdata *kpriv = 0;
851   char *pname;
852   size_t sz, msgsz = BLEN(b);
853   buf bb;
854   int rc;
855
856   /* --- Read and check the challenge --- */
857
858   buf_getbuf16(b, &bb);
859   if (c_check(0, 0, &bb)) goto done;
860
861   /* --- Figure out which private key I'm supposed to use --- */
862
863   if (buf_getu32(b, &id)) goto done;
864   if ((kpriv = km_findprivbyid(id)) == 0) goto done;
865
866   /* --- Decrypt and check the peer's name against the token --- */
867
868   buf_init(&bb, buf_t, sizeof(buf_t));
869   if (ies_decrypt(kpriv, MSG_KEYEXCH | KX_KNOCK, b, &bb)) goto done;
870   assert(BOK(&bb)); buf_flip(&bb);
871   if ((pname = buf_getmem16(&bb, &sz)) == 0 ||
872       memchr(pname, 0, sz) ||
873       c_check(pname, sz, &bb))
874     goto done;
875   assert(sz < sizeof(buf_t) - ((const octet *)pname - buf_t));
876   pname[sz] = 0;
877
878   /* --- If we can't find the peer, then issue a notification --- */
879
880   if ((p = p_find(pname)) == 0) {
881     a_notify("KNOCK", "%s", pname, "?ADDR", a, A_END);
882     goto done;
883   }
884
885   /* --- Update the peer's address --- */
886
887   kx = &p->kx;
888   p_updateaddr(kx->p, a);
889
890   /* --- Now treat the remainder of the message as a pre-challenge --- */
891
892   notice_message(kx);
893   rc = doprechallenge(kx, b);
894   update_stats_rx(kx, !rc, msgsz);
895
896   /* --- All done: clean up --- */
897
898 done:
899   if (kpriv) km_unref(kpriv);
900 }
901
902 /* --- @respond@ --- *
903  *
904  * Arguments:   @keyexch *kx@ = pointer to key exchange block
905  *              @unsigned msg@ = message code for this packet
906  *              @buf *b@ = buffer containing the packet
907  *
908  * Returns:     Key-exchange challenge block, or null.
909  *
910  * Use:         Computes a response for the given challenge, entering it into
911  *              a challenge block and so on.
912  */
913
914 static kxchal *respond(keyexch *kx, unsigned msg, buf *b)
915 {
916   const dhgrp *g = kx->kpriv->grp;
917   const algswitch *algs = &kx->kpriv->algs;
918   size_t ixsz = g->scsz;
919   dhge *C = 0;
920   dhge *R = 0;
921   dhge *CC = 0;
922   deriveargs a;
923   const octet *hc, *ck;
924   dhsc *c = 0;
925   kxchal *kxc;
926   ghash *h = 0;
927   buf bb;
928   int ok;
929
930   /* --- Unpack the packet --- */
931
932   if ((C = g->ops->ldge(g, b, DHFMT_VAR)) == 0 ||
933       (hc = buf_get(b, algs->hashsz)) == 0 ||
934       (ck = buf_get(b, ixsz)) == 0) {
935     a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
936     goto bad;
937   }
938   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
939     trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, C));
940     trace_block(T_CRYPTO, "crypto: cookie", hc, algs->hashsz);
941     trace_block(T_CRYPTO, "crypto: check-value", ck, ixsz);
942   }))
943
944   /* --- Discard a packet with an invalid cookie --- */
945
946   if (hc && memcmp(hc, kx->hc, algs->hashsz) != 0) {
947     a_warn("KX", "?PEER", kx->p, "incorrect", "cookie", A_END);
948     goto bad;
949   }
950
951   /* --- Recover the check value and verify it --- *
952    *
953    * To avoid recomputation on replays, we store a hash of the `right'
954    * value.  The `correct' value is unique, so this is right.
955    *
956    * This will also find a challenge block and, if necessary, populate it.
957    */
958
959   if ((kxc = kxc_bychal(kx, C)) != 0) {
960     h = GH_INIT(algs->h);
961     HASH_STRING(h, "tripe-check-hash");
962     GH_HASH(h, ck, ixsz);
963     ok = !memcmp(kxc->ck, GH_DONE(h, 0), algs->hashsz);
964     GH_DESTROY(h);
965     if (!ok) goto badcheck;
966   } else {
967
968     /* --- Compute the reply, and check the magic --- */
969
970     R = g->ops->mul(g, kx->kpriv->k, C);
971     if ((c = mpunmask(g, ck, ixsz, algs->mgf,
972                       hashcheck(kx, kx->kpub->K, kx->C, C, R),
973                       algs->hashsz)) == 0)
974       goto badcheck;
975     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
976       trace(T_CRYPTO, "crypto: computed reply = %s", g->ops->gestr(g, R));
977       trace(T_CRYPTO, "crypto: recovered log = %s", g->ops->scstr(g, c));
978     }))
979     CC = g->ops->mul(g, c, 0);
980     if (!g->ops->eq(g, CC, C)) goto badcheck;
981
982     /* --- Fill in a new challenge block --- */
983
984     kxc = kxc_new(kx);
985     kxc->C = C; C = 0;
986     kxc->R = R; R = 0;
987
988     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-check-hash");
989     GH_HASH(h, ck, ixsz);
990     GH_DONE(h, kxc->ck); GH_DESTROY(h);
991
992     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-cookie");
993     hashge(h, g, kxc->C);
994     GH_DONE(h, kxc->hc); GH_DESTROY(h);
995
996     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
997       trace_block(T_CRYPTO, "crypto: computed cookie",
998                   kxc->hc, algs->hashsz);
999     }))
1000
1001     /* --- Work out the shared key --- */
1002
1003     R = g->ops->mul(g, kx->a, kxc->C);
1004     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
1005       trace(T_CRYPTO, "crypto: shared secret = %s", g->ops->gestr(g, R));
1006     }))
1007
1008     /* --- Compute the switch messages --- */
1009
1010     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
1011     hashge(h, g, kx->C); hashge(h, g, kxc->C);
1012     GH_DONE(h, kxc->hswrq_out); GH_DESTROY(h);
1013     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
1014     hashge(h, g, kx->C); hashge(h, g, kxc->C);
1015     GH_DONE(h, kxc->hswok_out); GH_DESTROY(h);
1016
1017     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
1018     hashge(h, g, kxc->C); hashge(h, g, kx->C);
1019     GH_DONE(h, kxc->hswrq_in); GH_DESTROY(h);
1020     h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
1021     hashge(h, g, kxc->C); hashge(h, g, kx->C);
1022     GH_DONE(h, kxc->hswok_in); GH_DESTROY(h);
1023
1024     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
1025       trace_block(T_CRYPTO, "crypto: outbound switch request",
1026                   kxc->hswrq_out, algs->hashsz);
1027       trace_block(T_CRYPTO, "crypto: outbound switch confirm",
1028                   kxc->hswok_out, algs->hashsz);
1029       trace_block(T_CRYPTO, "crypto: inbound switch request",
1030                   kxc->hswrq_in, algs->hashsz);
1031       trace_block(T_CRYPTO, "crypto: inbound switch confirm",
1032                   kxc->hswok_in, algs->hashsz);
1033     }))
1034
1035     /* --- Create a new symmetric keyset --- */
1036
1037     buf_init(&bb, buf_o, sizeof(buf_o)); a.k = BBASE(&bb);
1038     g->ops->stge(g, &bb, kx->C, DHFMT_HASH); a.x = BLEN(&bb);
1039     g->ops->stge(g, &bb, kxc->C, DHFMT_HASH); a.y = BLEN(&bb);
1040     g->ops->stge(g, &bb, R, DHFMT_HASH); a.z = BLEN(&bb);
1041     assert(BOK(&bb));
1042
1043     kxc->ks = ks_gen(&a, kx->p);
1044   }
1045
1046   if (C) g->ops->freege(g, C);
1047   if (CC) g->ops->freege(g, CC);
1048   if (R) g->ops->freege(g, R);
1049   if (c) g->ops->freesc(g, c);
1050   return (kxc);
1051
1052 badcheck:
1053   a_warn("KX", "?PEER", kx->p, "bad-expected-reply-log", A_END);
1054   goto bad;
1055 bad:
1056   if (C) g->ops->freege(g, C);
1057   if (CC) g->ops->freege(g, CC);
1058   if (R) g->ops->freege(g, R);
1059   if (c) g->ops->freesc(g, c);
1060   return (0);
1061 }
1062
1063 /* --- @dochallenge@ --- *
1064  *
1065  * Arguments:   @keyexch *kx@ = pointer to key exchange block
1066  *              @unsigned msg@ = message code for the packet
1067  *              @buf *b@ = buffer containing the packet
1068  *
1069  * Returns:     Zero if OK, nonzero if the packet was rejected.
1070  *
1071  * Use:         Processes a packet containing a challenge.
1072  */
1073
1074 static int dochallenge(keyexch *kx, buf *b)
1075 {
1076   kxchal *kxc;
1077
1078   if (kx->s != KXS_CHAL) {
1079     a_warn("KX", "?PEER", kx->p, "unexpected", "challenge", A_END);
1080     goto bad;
1081   }
1082   if ((kxc = respond(kx, KX_CHAL, b)) == 0)
1083     goto bad;
1084   if (BLEFT(b)) {
1085     a_warn("KX", "?PEER", kx->p, "invalid", "challenge", A_END);
1086     goto bad;
1087   }
1088   kxc_answer(kx, kxc);
1089   return (0);
1090
1091 bad:
1092   return (-1);
1093 }
1094
1095 /* --- @resend@ --- *
1096  *
1097  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1098  *
1099  * Returns:     ---
1100  *
1101  * Use:         Sends the next message for a key exchange.
1102  */
1103
1104 static void resend(keyexch *kx)
1105 {
1106   kxchal *kxc;
1107   buf bb;
1108   struct timeval tv;
1109   const dhgrp *g = kx->kpriv->grp;
1110   octet *p;
1111   size_t sz;
1112   buf *b;
1113
1114   switch (kx->s) {
1115     case KXS_CHAL:
1116       if (!kx->p->spec.knock) {
1117         T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
1118                  p_name(kx->p)); )
1119         b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
1120         g->ops->stge(g, b, kx->C, DHFMT_VAR);
1121       } else {
1122         T( trace(T_KEYEXCH, "keyexch: sending token-request to `%s'",
1123                  p_name(kx->p)); )
1124         b = p_txstart(kx->p, MSG_KEYEXCH | KX_TOKENRQ);
1125
1126         buf_init(&bb, buf_t, sizeof(buf_t));
1127         c_new(0, 0, &bb); assert(BOK(&bb)); buf_putbuf16(b, &bb);
1128
1129         buf_putu32(b, kx->kpub->id);
1130
1131         buf_init(&bb, buf_t, sizeof(buf_t));
1132         buf_putstr16(&bb, kx->p->spec.knock);
1133         sz = BLEN(&bb)%64; if (sz) sz = 64 - sz;
1134         p = buf_get(&bb, sz); assert(p); memset(p, 0, sz);
1135         assert(BOK(&bb)); buf_flip(&bb);
1136         if (ies_encrypt(kx->kpub, MSG_KEYEXCH | KX_TOKENRQ, &bb, b))
1137           buf_break(b);
1138       }
1139       break;
1140     case KXS_COMMIT:
1141       T( trace(T_KEYEXCH, "keyexch: sending switch request to `%s'",
1142                p_name(kx->p)); )
1143       kxc = kx->r[0];
1144       b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCH);
1145       buf_put(b, kx->hc, kx->kpriv->algs.hashsz);
1146       buf_put(b, kxc->hc, kx->kpriv->algs.hashsz);
1147       buf_init(&bb, buf_i, sizeof(buf_i));
1148       g->ops->stge(g, &bb, kxc->R, DHFMT_STD);
1149       buf_put(&bb, kxc->hswrq_out, kx->kpriv->algs.hashsz);
1150       buf_flip(&bb);
1151       ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCH, &bb, b);
1152       break;
1153     case KXS_SWITCH:
1154       T( trace(T_KEYEXCH, "keyexch: sending switch confirmation to `%s'",
1155                p_name(kx->p)); )
1156       kxc = kx->r[0];
1157       b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCHOK);
1158       buf_init(&bb, buf_i, sizeof(buf_i));
1159       buf_put(&bb, kxc->hswok_out, kx->kpriv->algs.hashsz);
1160       buf_flip(&bb);
1161       ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, &bb, b);
1162       break;
1163     default:
1164       abort();
1165   }
1166
1167   if (BOK(b)) {
1168     update_stats_tx(kx, BLEN(b));
1169     p_txend(kx->p);
1170   }
1171
1172   if (kx->s < KXS_SWITCH) {
1173     rs_time(&kx->rs, &tv, 0);
1174     settimer(kx, &tv);
1175   }
1176 }
1177
1178 /* --- @decryptrest@ --- *
1179  *
1180  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1181  *              @kxchal *kxc@ = pointer to challenge block
1182  *              @unsigned msg@ = type of incoming message
1183  *              @buf *b@ = encrypted remainder of the packet
1184  *
1185  * Returns:     Zero if OK, nonzero on some kind of error.
1186  *
1187  * Use:         Decrypts the remainder of the packet, and points @b@ at the
1188  *              recovered plaintext.
1189  */
1190
1191 static int decryptrest(keyexch *kx, kxchal *kxc, unsigned msg, buf *b)
1192 {
1193   buf bb;
1194
1195   buf_init(&bb, buf_o, sizeof(buf_o));
1196   if (ks_decrypt(kxc->ks, MSG_KEYEXCH | msg, b, &bb)) {
1197     a_warn("KX", "?PEER", kx->p, "decrypt-failed", "%s", pkname[msg], A_END);
1198     return (-1);
1199   }
1200   if (!BOK(&bb)) return (-1);
1201   buf_init(b, BBASE(&bb), BLEN(&bb));
1202   return (0);
1203 }
1204
1205 /* --- @checkresponse@ --- *
1206  *
1207  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1208  *              @unsigned msg@ = type of incoming message
1209  *              @buf *b@ = decrypted remainder of the packet
1210  *
1211  * Returns:     Zero if OK, nonzero on some kind of error.
1212  *
1213  * Use:         Checks a reply or switch packet, ensuring that its response
1214  *              is correct.
1215  */
1216
1217 static int checkresponse(keyexch *kx, unsigned msg, buf *b)
1218 {
1219   const dhgrp *g = kx->kpriv->grp;
1220   dhge *R;
1221
1222   if ((R = g->ops->ldge(g, b, DHFMT_STD)) == 0) {
1223     a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
1224     goto bad;
1225   }
1226   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
1227     trace(T_CRYPTO, "crypto: reply = %s", g->ops->gestr(g, R));
1228   }))
1229   if (!g->ops->eq(g, R, kx->RX)) {
1230     a_warn("KX", "?PEER", kx->p, "incorrect", "response", A_END);
1231     goto bad;
1232   }
1233
1234   g->ops->freege(g, R);
1235   return (0);
1236
1237 bad:
1238   if (R) g->ops->freege(g, R);
1239   return (-1);
1240 }
1241
1242 /* --- @commit@ --- *
1243  *
1244  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1245  *              @kxchal *kxc@ = pointer to challenge to commit to
1246  *
1247  * Returns:     ---
1248  *
1249  * Use:         Commits to a particular challenge as being the `right' one,
1250  *              since a reply has arrived for it.
1251  */
1252
1253 static void commit(keyexch *kx, kxchal *kxc)
1254 {
1255   unsigned i;
1256
1257   for (i = 0; i < kx->nr; i++) {
1258     if (kx->r[i] != kxc)
1259       kxc_destroy(kx->r[i]);
1260   }
1261   kx->r[0] = kxc;
1262   kx->nr = 1;
1263   kxc_stoptimer(kxc);
1264   ksl_link(kx->ks, kxc->ks);
1265 }
1266
1267 /* --- @doreply@ --- *
1268  *
1269  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1270  *              @buf *b@ = buffer containing packet
1271  *
1272  * Returns:     Zero if OK, nonzero if the packet was rejected.
1273  *
1274  * Use:         Handles a reply packet.  This doesn't handle the various
1275  *              switch packets: they're rather too different.
1276  */
1277
1278 static int doreply(keyexch *kx, buf *b)
1279 {
1280   kxchal *kxc;
1281
1282   if (kx->s != KXS_CHAL && kx->s != KXS_COMMIT) {
1283     a_warn("KX", "?PEER", kx->p, "unexpected", "reply", A_END);
1284     goto bad;
1285   }
1286   if ((kxc = respond(kx, KX_REPLY, b)) == 0 ||
1287       decryptrest(kx, kxc, KX_REPLY, b) ||
1288       checkresponse(kx, KX_REPLY, b))
1289     goto bad;
1290   if (BLEFT(b)) {
1291     a_warn("KX", "?PEER", kx->p, "invalid", "reply", A_END);
1292     goto bad;
1293   }
1294   if (kx->s == KXS_CHAL) {
1295     commit(kx, kxc);
1296     kx->s = KXS_COMMIT;
1297   }
1298   resend(kx);
1299   return (0);
1300
1301 bad:
1302   return (-1);
1303 }
1304
1305 /* --- @kxfinish@ --- *
1306  *
1307  * Arguments:   @keyexch *kx@ = pointer to key exchange block
1308  *
1309  * Returns:     ---
1310  *
1311  * Use:         Sets everything up following a successful key exchange.
1312  */
1313
1314 static void kxfinish(keyexch *kx)
1315 {
1316   kxchal *kxc = kx->r[0];
1317   struct timeval now, tv;
1318
1319   ks_activate(kxc->ks);
1320   gettimeofday(&now, 0);
1321   f2tv(&tv, wobble(T_REGEN));
1322   TV_ADD(&tv, &now, &tv);
1323   settimer(kx, &tv);
1324   kx->s = KXS_SWITCH;
1325   a_notify("KXDONE", "?PEER", kx->p, A_END);
1326   p_stats(kx->p)->t_kx = time(0);
1327 }
1328
1329 /* --- @doswitch@ --- *
1330  *
1331  * Arguments:   @keyexch *kx@ = pointer to key exchange block
1332  *              @buf *b@ = pointer to buffer containing packet
1333  *
1334  * Returns:     Zero if OK, nonzero if the packet was rejected.
1335  *
1336  * Use:         Handles a reply with a switch request bolted onto it.
1337  */
1338
1339 static int doswitch(keyexch *kx, buf *b)
1340 {
1341   size_t hsz = kx->kpriv->algs.hashsz;
1342   const octet *hc_in, *hc_out, *hswrq;
1343   kxchal *kxc;
1344
1345   if ((hc_in = buf_get(b, hsz)) == 0 ||
1346       (hc_out = buf_get(b, hsz)) == 0) {
1347     a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
1348     goto bad;
1349   }
1350   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
1351     trace_block(T_CRYPTO, "crypto: challenge", hc_in, hsz);
1352     trace_block(T_CRYPTO, "crypto: cookie", hc_out, hsz);
1353   }))
1354   if ((kxc = kxc_byhc(kx, hc_in)) == 0 ||
1355       memcmp(hc_out, kx->hc, hsz) != 0) {
1356     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
1357     goto bad;
1358   }
1359   if (decryptrest(kx, kxc, KX_SWITCH, b) ||
1360       checkresponse(kx, KX_SWITCH, b))
1361     goto bad;
1362   if ((hswrq = buf_get(b, hsz)) == 0 || BLEFT(b)) {
1363     a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
1364     goto bad;
1365   }
1366   IF_TRACING(T_KEYEXCH, {
1367     trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, hsz);
1368   })
1369   if (memcmp(hswrq, kxc->hswrq_in, hsz) != 0) {
1370     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
1371     goto bad;
1372   }
1373   if (kx->s == KXS_CHAL)
1374     commit(kx, kxc);
1375   if (kx->s < KXS_SWITCH)
1376     kxfinish(kx);
1377   resend(kx);
1378   return (0);
1379
1380 bad:
1381   return (-1);
1382 }
1383
1384 /* --- @doswitchok@ --- *
1385  *
1386  * Arguments:   @keyexch *kx@ = pointer to key exchange block
1387  *              @buf *b@ = pointer to buffer containing packet
1388  *
1389  * Returns:     Zero if OK, nonzero if the packet was rejected.
1390  *
1391  * Use:         Handles a reply with a switch request bolted onto it.
1392  */
1393
1394 static int doswitchok(keyexch *kx, buf *b)
1395 {
1396   size_t hsz = kx->kpriv->algs.hashsz;
1397   const octet *hswok;
1398   kxchal *kxc;
1399   buf bb;
1400
1401   if (kx->s < KXS_COMMIT) {
1402     a_warn("KX", "?PEER", kx->p, "unexpected", "switch-ok", A_END);
1403     goto bad;
1404   }
1405   kxc = kx->r[0];
1406   buf_init(&bb, buf_o, sizeof(buf_o));
1407   if (decryptrest(kx, kxc, KX_SWITCHOK, b))
1408     goto bad;
1409   if ((hswok = buf_get(b, hsz)) == 0 || BLEFT(b)) {
1410     a_warn("KX", "?PEER", kx->p, "invalid", "switch-ok", A_END);
1411     goto bad;
1412   }
1413   IF_TRACING(T_KEYEXCH, {
1414     trace_block(T_CRYPTO, "crypto: switch confirmation hash",
1415                 hswok, hsz);
1416   })
1417   if (memcmp(hswok, kxc->hswok_in, hsz) != 0) {
1418     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-ok", A_END);
1419     goto bad;
1420   }
1421   if (kx->s < KXS_SWITCH)
1422     kxfinish(kx);
1423   return (0);
1424
1425 bad:
1426   return (-1);
1427 }
1428
1429 /*----- Main code ---------------------------------------------------------*/
1430
1431 /* --- @stop@ --- *
1432  *
1433  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1434  *
1435  * Returns:     ---
1436  *
1437  * Use:         Stops a key exchange dead in its tracks.  Throws away all of
1438  *              the context information.  The context is left in an
1439  *              inconsistent state.  The only functions which understand this
1440  *              state are @kx_free@ and @kx_init@ (which cause it internally
1441  *              it), and @start@ (which expects it to be the prevailing
1442  *              state).
1443  */
1444
1445 static void stop(keyexch *kx)
1446 {
1447   const dhgrp *g = kx->kpriv->grp;
1448   unsigned i;
1449
1450   if (kx->f & KXF_DEAD)
1451     return;
1452
1453   if (kx->f & KXF_TIMER)
1454     sel_rmtimer(&kx->t);
1455   for (i = 0; i < kx->nr; i++)
1456     kxc_destroy(kx->r[i]);
1457   g->ops->freesc(g, kx->a);
1458   g->ops->freege(g, kx->C);
1459   g->ops->freege(g, kx->RX);
1460   kx->t_valid = 0;
1461   kx->f |= KXF_DEAD;
1462   kx->f &= ~KXF_TIMER;
1463 }
1464
1465 /* --- @start@ --- *
1466  *
1467  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1468  *              @time_t now@ = the current time
1469  *
1470  * Returns:     ---
1471  *
1472  * Use:         Starts a new key exchange with the peer.  The context must be
1473  *              in the bizarre state left by @stop@ or @kx_init@.
1474  */
1475
1476 static void start(keyexch *kx, time_t now)
1477 {
1478   algswitch *algs = &kx->kpriv->algs;
1479   const dhgrp *g = kx->kpriv->grp;
1480   ghash *h;
1481
1482   assert(kx->f & KXF_DEAD);
1483
1484   kx->f &= ~(KXF_DEAD | KXF_CORK);
1485   kx->nr = 0;
1486   kx->a = g->ops->randsc(g);
1487   kx->C = g->ops->mul(g, kx->a, 0);
1488   kx->RX = g->ops->mul(g, kx->a, kx->kpub->K);
1489   kx->s = KXS_CHAL;
1490   kx->t_valid = now + T_VALID;
1491
1492   h = GH_INIT(algs->h);
1493   HASH_STRING(h, "tripe-cookie");
1494   hashge(h, g, kx->C);
1495   GH_DONE(h, kx->hc);
1496   GH_DESTROY(h);
1497
1498   IF_TRACING(T_KEYEXCH, {
1499     trace(T_KEYEXCH, "keyexch: creating new challenge");
1500     IF_TRACING(T_CRYPTO, {
1501       trace(T_CRYPTO, "crypto: secret = %s", g->ops->scstr(g, kx->a));
1502       trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, kx->C));
1503       trace(T_CRYPTO, "crypto: expected response = %s",
1504             g->ops->gestr(g, kx->RX));
1505       trace_block(T_CRYPTO, "crypto: challenge cookie",
1506                   kx->hc, algs->hashsz);
1507     })
1508   })
1509 }
1510
1511 /* --- @checkpub@ --- *
1512  *
1513  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1514  *
1515  * Returns:     Zero if OK, nonzero if the peer's public key has expired.
1516  *
1517  * Use:         Deactivates the key-exchange until the peer acquires a new
1518  *              public key.
1519  */
1520
1521 static int checkpub(keyexch *kx)
1522 {
1523   time_t now;
1524   unsigned f = 0;
1525
1526   if (kx->f & KXF_DEAD)
1527     return (-1);
1528   now = time(0);
1529   if (KEY_EXPIRED(now, kx->kpriv->t_exp)) f |= 1;
1530   if (KEY_EXPIRED(now, kx->kpub->t_exp)) f |= 2;
1531   if (f) {
1532     stop(kx);
1533     if (f & 1) a_warn("KX", "?PEER", kx->p, "private-key-expired", A_END);
1534     if (f & 2) a_warn("KX", "?PEER", kx->p, "public-key-expired", A_END);
1535     kx->f &= ~KXF_PUBKEY;
1536     return (-1);
1537   }
1538   return (0);
1539 }
1540
1541 /* --- @kx_start@ --- *
1542  *
1543  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1544  *              @int forcep@ = nonzero to ignore the quiet timer
1545  *
1546  * Returns:     ---
1547  *
1548  * Use:         Stimulates a key exchange.  If a key exchage is in progress,
1549  *              a new challenge is sent (unless the quiet timer forbids
1550  *              this); if no exchange is in progress, one is commenced.
1551  */
1552
1553 void kx_start(keyexch *kx, int forcep)
1554 {
1555   time_t now = time(0);
1556
1557   if (checkpub(kx))
1558     return;
1559   if (forcep || !VALIDP(kx, now)) {
1560     stop(kx);
1561     start(kx, now);
1562     a_notify("KXSTART", "?PEER", kx->p, A_END);
1563   }
1564   resend(kx);
1565 }
1566
1567 /* --- @kx_message@ --- *
1568  *
1569  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1570  *              @const addr *a@ = sender's IP address and port
1571  *              @unsigned msg@ = the message code
1572  *              @buf *b@ = pointer to buffer containing the packet
1573  *
1574  * Returns:     Nonzero if the sender's address was unknown.
1575  *
1576  * Use:         Reads a packet containing key exchange messages and handles
1577  *              it.
1578  */
1579
1580 int kx_message(keyexch *kx, const addr *a, unsigned msg, buf *b)
1581 {
1582   size_t sz = BSZ(b);
1583   int rc;
1584
1585   T( trace(T_KEYEXCH, "keyexch: processing %s packet from %c%s%c",
1586            msg < KX_NMSG ? pkname[msg] : "unknown",
1587            kx ? '`' : '<', kx ? p_name(kx->p) : "nil", kx ? '\'' : '>'); )
1588
1589   switch (msg) {
1590     case KX_TOKENRQ: dotokenrq(a, b); return (0);
1591     case KX_KNOCK: doknock(a, b); return (0);
1592   }
1593
1594   if (!kx) return (-1);
1595   if (notice_message(kx)) return (0);
1596
1597   switch (msg) {
1598     case KX_TOKEN: rc = dotoken(kx, b); break;
1599     case KX_PRECHAL: rc = doprechallenge(kx, b); break;
1600     case KX_CHAL: rc = dochallenge(kx, b); break;
1601     case KX_REPLY: rc = doreply(kx, b); break;
1602     case KX_SWITCH: rc = doswitch(kx, b); break;
1603     case KX_SWITCHOK: rc = doswitchok(kx, b); break;
1604     default:
1605       a_warn("KX", "?PEER", kx->p, "unknown-message", "0x%02x", msg, A_END);
1606       rc = -1;
1607       break;
1608   }
1609
1610   update_stats_rx(kx, !rc, sz);
1611   return (0);
1612 }
1613
1614 /* --- @kx_free@ --- *
1615  *
1616  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1617  *
1618  * Returns:     ---
1619  *
1620  * Use:         Frees everything in a key exchange context.
1621  */
1622
1623 void kx_free(keyexch *kx)
1624 {
1625   stop(kx);
1626   km_unref(kx->kpub);
1627   km_unref(kx->kpriv);
1628 }
1629
1630 /* --- @kx_newkeys@ --- *
1631  *
1632  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1633  *
1634  * Returns:     ---
1635  *
1636  * Use:         Informs the key exchange module that its keys may have
1637  *              changed.  If fetching the new keys fails, the peer will be
1638  *              destroyed, we log messages and struggle along with the old
1639  *              keys.
1640  */
1641
1642 void kx_newkeys(keyexch *kx)
1643 {
1644   kdata *kpriv, *kpub;
1645   unsigned i;
1646   int switchp;
1647   time_t now = time(0);
1648
1649   T( trace(T_KEYEXCH, "keyexch: checking new keys for `%s'",
1650            p_name(kx->p)); )
1651
1652   /* --- Find out whether we can use new keys --- *
1653    *
1654    * Try each available combination of new and old, public and private,
1655    * except both old (which is status quo anyway).  The selection is encoded
1656    * in @i@, with bit 0 for the private key and bit 1 for public key; a set
1657    * bit means to use the old value, and a clear bit means to use the new
1658    * one.
1659    *
1660    * This means that we currently prefer `old private and new public' over
1661    * `new private and old public'.  I'm not sure which way round this should
1662    * actually be.
1663    */
1664
1665   for (i = 0; i < 3; i++) {
1666
1667     /* --- Select the keys we're going to examine --- *
1668      *
1669      * If we're meant to have a new key and don't, then skip this
1670      * combination.
1671      */
1672
1673     T( trace(T_KEYEXCH, "keyexch: checking %s private, %s public",
1674              i & 1 ? "old" : "new", i & 2 ? "old" : "new"); )
1675
1676     if (i & 1) kpriv = kx->kpriv;
1677     else if (kx->kpriv->kn->kd != kx->kpriv) kpriv = kx->kpriv->kn->kd;
1678     else {
1679       T( trace(T_KEYEXCH, "keyexch: private key unchanged, skipping"); )
1680       continue;
1681     }
1682
1683     if (i & 2) kpub = kx->kpub;
1684     else if (kx->kpub->kn->kd != kx->kpub) kpub = kx->kpub->kn->kd;
1685     else {
1686       T( trace(T_KEYEXCH, "keyexch: public key unchanged, skipping"); )
1687       continue;
1688     }
1689
1690     /* --- Skip if either key is expired --- *
1691      *
1692      * We're not going to get far with expired keys, and this simplifies the
1693      * logic below.
1694      */
1695
1696     if (KEY_EXPIRED(now, kx->kpriv->t_exp) ||
1697         KEY_EXPIRED(now, kx->kpub->t_exp)) {
1698       T( trace(T_KEYEXCH, "keyexch: %s expired, skipping",
1699                !KEY_EXPIRED(now, kx->kpriv->t_exp) ? "public key" :
1700                !KEY_EXPIRED(now, kx->kpub->t_exp) ? "private key" :
1701                "both keys"); )
1702       continue;
1703     }
1704
1705     /* --- If the groups don't match then we can't use this pair --- */
1706
1707     if (!km_samealgsp(kpriv, kpub)) {
1708       T( trace(T_KEYEXCH, "keyexch: peer `%s' group mismatch; "
1709                "%s priv `%s' and %s pub `%s'", p_name(kx->p),
1710                i & 1 ? "old" : "new", km_tag(kx->kpriv),
1711                i & 2 ? "old" : "new", km_tag(kx->kpub)); )
1712       continue;
1713     }
1714     goto newkeys;
1715   }
1716   T( trace(T_KEYEXCH, "keyexch: peer `%s' continuing with old keys",
1717            p_name(kx->p)); )
1718   return;
1719
1720   /* --- We've chosen new keys --- *
1721    *
1722    * Switch the new ones into place.  Neither of the keys we're switching to
1723    * is expired (we checked that above), so we should just crank everything
1724    * up.
1725    *
1726    * A complication arises: we don't really want to force a new key exchange
1727    * unless we have to.  If the group is unchanged, and we're currently
1728    * running OK, then we should just let things lie.
1729    */
1730
1731 newkeys:
1732   switchp = ((kx->f & KXF_DEAD) ||
1733              kx->s != KXS_SWITCH ||
1734              kpriv->grp->ops != kx->kpriv->grp->ops ||
1735              !kpriv->grp->ops->samegrpp(kpriv->grp, kx->kpriv->grp));
1736
1737   T( trace(T_KEYEXCH, "keyexch: peer `%s' adopting "
1738            "%s priv `%s' and %s pub `%s'; %sforcing exchange", p_name(kx->p),
1739            i & 1 ? "old" : "new", km_tag(kx->kpriv),
1740            i & 2 ? "old" : "new", km_tag(kx->kpub),
1741            switchp ? "" : "not "); )
1742
1743   if (switchp) stop(kx);
1744   km_ref(kpriv); km_unref(kx->kpriv); kx->kpriv = kpriv;
1745   km_ref(kpub);  km_unref(kx->kpub);  kx->kpub  = kpub;
1746   kx->f |= KXF_PUBKEY;
1747   if (switchp) {
1748     T( trace(T_KEYEXCH, "keyexch: restarting key negotiation with `%s'",
1749              p_name(kx->p)); )
1750     start(kx, time(0));
1751     resend(kx);
1752   }
1753 }
1754
1755 /* --- @kx_setup@ --- *
1756  *
1757  * Arguments:   @keyexch *kx@ = pointer to key exchange context
1758  *              @peer *p@ = pointer to peer context
1759  *              @keyset **ks@ = pointer to keyset list
1760  *              @unsigned f@ = various useful flags
1761  *
1762  * Returns:     Zero if OK, nonzero if it failed.
1763  *
1764  * Use:         Initializes a key exchange module.  The module currently
1765  *              contains no keys, and will attempt to initiate a key
1766  *              exchange.
1767  */
1768
1769 int kx_setup(keyexch *kx, peer *p, keyset **ks, unsigned f)
1770 {
1771   if ((kx->kpriv = km_findpriv(p_privtag(p))) == 0) goto fail_0;
1772   if ((kx->kpub = km_findpub(p_tag(p))) == 0) goto fail_1;
1773   if (!km_samealgsp(kx->kpriv, kx->kpub)) {
1774     a_warn("KX", "?PEER", p, "group-mismatch",
1775            "local-private-key", "%s", p_privtag(p),
1776            "peer-public-key", "%s", p_tag(p),
1777            A_END);
1778     goto fail_2;
1779   }
1780
1781   kx->ks = ks;
1782   kx->p = p;
1783   kx->f = KXF_DEAD | KXF_PUBKEY | f;
1784   rs_reset(&kx->rs);
1785   if (!(kx->f & KXF_CORK)) {
1786     start(kx, time(0));
1787     resend(kx);
1788     /* Don't notify here: the ADD message hasn't gone out yet. */
1789   }
1790   return (0);
1791
1792 fail_2:
1793   km_unref(kx->kpub);
1794 fail_1:
1795   km_unref(kx->kpriv);
1796 fail_0:
1797   return (-1);
1798 }
1799
1800 /* --- @kx_init@ --- *
1801  *
1802  * Arguments:   ---
1803  *
1804  * Returns:     ---
1805  *
1806  * Use:         Initializes the key-exchange logic.
1807  */
1808
1809 void kx_init(void)
1810   { ratelim_init(&unauth_limit, 20, 500); }
1811
1812 /*----- That's all, folks -------------------------------------------------*/