3 * Key exchange protocol
5 * (c) 2001 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Trivial IP Encryption (TrIPE).
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.
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
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/>.
26 /*----- Header files ------------------------------------------------------*/
30 /*----- Brief protocol overview -------------------------------------------*
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.
39 * At the beginning of the session, Alice chooses
41 * %$\rho_A \inr \{0, \ldots q - 1\}$%
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
57 * The messages are then:
59 * %$\cookie{kx-pre-challenge}, r_A$%
60 * Initial greeting. In state @KXS_CHAL@.
62 * %$\cookie{kx-challenge}, r_A, c_B, v_A$%
63 * Here's a full challenge for you to answer.
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
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
73 * %$\cookie{kx-switch-ok}, E_K(u_A))$%
74 * Switch received. Committed; send data; move to @KXS_SWITCH@.
77 /*----- Static tables -----------------------------------------------------*/
79 static const char *const pkname[] = {
80 "pre-challenge", "challenge", "reply", "switch-rq", "switch-ok"
83 /*----- Various utilities -------------------------------------------------*/
87 * Arguments: @const keyexch *kx@ = key exchange state
88 * @time_t now@ = current time in seconds
90 * Returns: Whether the challenge in the key-exchange state is still
91 * valid or should be regenerated.
94 #define VALIDP(kx, now) ((now) < (kx)->t_valid)
98 * Arguments: @ghash *h@ = pointer to hash context
99 * @const dhgrp *g@ = pointer to group
100 * @const dhge *Y@ = pointer to group element
104 * Use: Adds the hash of a group element to the context. Corrupts
108 static void hashge(ghash *h, const dhgrp *g, const dhge *Y)
112 buf_init(&b, buf_t, sizeof(buf_t));
113 g->ops->stge(g, &b, Y, DHFMT_HASH);
115 GH_HASH(h, BBASE(&b), BLEN(&b));
118 /* --- @mpmask@ --- *
120 * Arguments: @buf *b@ = output buffer
121 * @const dhgrp *g@ = the group
122 * @const dhsc *x@ = the plaintext scalar
123 * @size_t n@ = the expected size of the plaintext
124 * @gcipher *mgfc@ = mask-generating function to use
125 * @const octet *k@ = pointer to key material
126 * @size_t ksz@ = size of the key
130 * Use: Masks a scalar: returns %$x \xor H(k)$%, so it's a random
131 * oracle thing rather than an encryption thing. Breaks the
132 * output buffer on error.
135 static void mpmask(buf *b, const dhgrp *g, const dhsc *x, size_t n,
136 const gccipher *mgfc, const octet *k, size_t ksz)
141 if ((p = buf_get(b, n)) == 0) return;
142 mgf = GC_INIT(mgfc, k, ksz);
143 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
144 trace(T_CRYPTO, "crypto: masking scalar = %s", g->ops->scstr(g, x));
145 trace_block(T_CRYPTO, "crypto: masking key", k, ksz);
147 if (g->ops->stsc(g, buf_t, n, x)) { buf_break(b); return; }
148 GC_ENCRYPT(mgf, buf_t, p, n);
149 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
150 trace_block(T_CRYPTO, "crypto: scalar plaintext", buf_t, n);
151 trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
156 /* --- @mpunmask@ --- *
158 * Arguments: @const dhgrp *g@ = the group
159 * @const octet *p@ = pointer to the ciphertext
160 * @size_t n@ = the size of the ciphertext
161 * @gcipher *mgfc@ = mask-generating function to use
162 * @const octet *k@ = pointer to key material
163 * @size_t ksz@ = size of the key
165 * Returns: The decrypted scalar, or null.
167 * Use: Unmasks a scalar.
170 static dhsc *mpunmask(const dhgrp *g, const octet *p, size_t n,
171 const gccipher *mgfc, const octet *k, size_t ksz)
176 mgf = GC_INIT(mgfc, k, ksz);
177 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
178 trace_block(T_CRYPTO, "crypto: unmasking key", k, ksz);
179 trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
181 GC_DECRYPT(mgf, p, buf_t, n);
182 x = g->ops->ldsc(g, buf_t, n);
183 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
184 trace_block(T_CRYPTO, "crypto: scalar plaintext", buf_t, n);
185 trace(T_CRYPTO, "crypto: unmasked scalar = %s",
186 x ? g->ops->scstr(g, x) : "<failed>");
192 /* --- @hashcheck@ --- *
194 * Arguments: @keyexch *kx@ = pointer to key-exchange block
195 * @const dhge *K@ = sender's public key
196 * @const dhge *CC@ = receiver's challenge
197 * @const dhge *C@ = sender's challenge
198 * @const dhge *Y@ = reply to sender's challenge
200 * Returns: Pointer to the hash value (in @buf_t@)
202 * Use: Computes the check-value hash, used to mask or unmask
203 * indices to prove the validity of challenges. This computes
204 * the masking key used in challenge check values. This is
205 * really the heart of the whole thing, since it ensures that
206 * the scalar can be recovered from the history of hashing
207 * queries, which gives us (a) a proof that the authentication
208 * process is zero-knowledge, and (b) a proof that the whole
209 * key-exchange is deniable.
212 static const octet *hashcheck(keyexch *kx, const dhge *K,
213 const dhge *CC, const dhge *C, const dhge *Y)
215 ghash *h = GH_INIT(kx->kpriv->algs.h);
216 const dhgrp *g = kx->kpriv->grp;
218 HASH_STRING(h, "tripe-expected-reply");
224 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
225 trace(T_CRYPTO, "crypto: computing challenge check hash");
226 trace(T_CRYPTO, "crypto: public key = %s", g->ops->gestr(g, K));
227 trace(T_CRYPTO, "crypto: receiver challenge = %s", g->ops->gestr(g, CC));
228 trace(T_CRYPTO, "crypto: sender challenge = %s", g->ops->gestr(g, C));
229 trace(T_CRYPTO, "crypto: sender reply = %s", g->ops->gestr(g, Y));
230 trace_block(T_CRYPTO, "crypto: hash output", buf_t, kx->kpriv->algs.hashsz);
236 /* --- @sendchallenge@ --- *
238 * Arguments: @keyexch *kx@ = pointer to key exchange block
239 * @buf *b@ = output buffer for challenge
240 * @const dhge *C@ = peer's actual challenge
241 * @const octet *hc@ = peer's challenge cookie
245 * Use: Writes a full challenge to the message buffer.
248 static void sendchallenge(keyexch *kx, buf *b,
249 const dhge *C, const octet *hc)
251 const dhgrp *g = kx->kpriv->grp;
252 g->ops->stge(g, b, kx->C, DHFMT_VAR);
253 buf_put(b, hc, kx->kpriv->algs.hashsz);
254 mpmask(b, g, kx->a, g->scsz, kx->kpriv->algs.mgf,
255 hashcheck(kx, kx->kpriv->K, C, kx->C, kx->RX),
256 kx->kpriv->algs.hashsz);
261 * Arguments: @struct timeval *tv@ = the current time
262 * @void *v@ = pointer to key exchange context
266 * Use: Acts when the key exchange timer goes off.
269 static void timer(struct timeval *tv, void *v)
273 T( trace(T_KEYEXCH, "keyexch: timer has popped"); )
277 /* --- @settimer@ --- *
279 * Arguments: @keyexch *kx@ = pointer to key exchange context
280 * @struct timeval *tv@ = when to set the timer for
284 * Use: Sets the timer for the next key exchange attempt.
287 static void settimer(keyexch *kx, struct timeval *tv)
289 if (kx->f & KXF_TIMER) sel_rmtimer(&kx->t);
290 sel_addtimer(&sel, &kx->t, tv, timer, kx);
296 * Arguments: @struct timeval *tv@ = where to write the timeval
297 * @double t@ = a time as a floating point number
301 * Use: Converts a floating-point time into a timeval.
304 static void f2tv(struct timeval *tv, double t)
307 tv->tv_usec = (t - tv->tv_sec)*MILLION;
310 /* --- @wobble@ --- *
312 * Arguments: @double t@ = a time interval
314 * Returns: The same time interval, with a random error applied.
317 static double wobble(double t)
319 uint32 r = rand_global.ops->word(&rand_global);
320 double w = (r/F_2P32) - 0.5;
321 return (t + t*w*T_WOBBLE);
324 /* --- @rs_time@ --- *
326 * Arguments: @retry *rs@ = current retry state
327 * @struct timeval *tv@ = where to write the result
328 * @const struct timeval *now@ = current time, or null
332 * Use: Computes a time at which to retry sending a key-exchange
333 * packet. This algorithm is subject to change, but it's
334 * currently a capped exponential backoff, slightly randomized
335 * to try to keep clients from hammering a server that's only
338 * If @now@ is null then the function works out the time for
342 static void rs_time(retry *rs, struct timeval *tv, const struct timeval *now)
351 if (t > MIN(5)) t = MIN(5);
359 f2tv(&rtv, wobble(t));
360 TV_ADD(tv, now, &rtv);
363 /* --- @retry_reset@ --- *
365 * Arguments: @retry *rs@ = retry state
369 * Use: Resets a retry state to indicate that progress has been
370 * made. Also useful for initializing the state in the first
374 static void rs_reset(retry *rs) { rs->t = 0; }
376 /* --- @notice_message@ --- *
378 * Arguments: @keyexch *kx@ = pointer to key-exchange block
380 * Returns: Zero if OK; @-1@ if the public key is in a bad state.
382 * Use: Updates the key-exchange state following a received message.
383 * Specifically, if there's no currently active key-exchange in
384 * progress, and we're not in the cooling-off period, then
385 * commence a new one; reset the retry timers; and if we're
386 * corked then pop the cork so that we can reply.
389 static int checkpub(keyexch *kx);
390 static void stop(keyexch *kx);
391 static void start(keyexch *kx, time_t now);
393 static int notice_message(keyexch *kx)
395 struct timeval now, tv;
397 gettimeofday(&now, 0);
399 if (kx->f & KXF_CORK) {
400 start(kx, now.tv_sec);
401 rs_time(&kx->rs, &tv, &now);
403 a_notify("KXSTART", "?PEER", kx->p, A_END);
405 if (checkpub(kx)) return (-1);
406 if (!VALIDP(kx, now.tv_sec)) {
408 start(kx, now.tv_sec);
413 /* --- @update_stats_tx@, @update_stats_rx@ --- *
415 * Arguments: @keyexch *kx@ = pointer to key-exchange block
416 * @int ok@ = nonzero if the message was valid (for @rx@)
417 * @size_t sz@ = size of sent message
421 * Use: Records that a key-exchange message was sent to, or received
425 static void update_stats_tx(keyexch *kx, size_t sz)
426 { stats *st = p_stats(kx->p); st->n_kxout++; st->sz_kxout += sz; }
428 static void update_stats_rx(keyexch *kx, int ok, size_t sz)
430 stats *st = p_stats(kx->p);
432 if (!ok) st->n_reject++;
433 else { st->n_kxin++; st->sz_kxin += sz; }
436 /*----- Challenge management ----------------------------------------------*/
438 /* --- Notes on challenge management --- *
440 * We may get multiple different replies to our key exchange; some will be
441 * correct, some inserted by attackers. Up until @KX_THRESH@, all challenges
442 * received will be added to the table and given a full response. After
443 * @KX_THRESH@ distinct challenges are received, we return only a `cookie':
444 * our existing challenge, followed by a hash of the sender's challenge. We
445 * do %%\emph{not}%% give a bare challenge a reply slot at this stage. All
446 * properly-formed cookies are assigned a table slot: if none is spare, a
447 * used slot is randomly selected and destroyed. A cookie always receives a
451 /* --- @kxc_destroy@ --- *
453 * Arguments: @kxchal *kxc@ = pointer to the challenge block
457 * Use: Disposes of a challenge block.
460 static void kxc_destroy(kxchal *kxc)
462 const dhgrp *g = kxc->kx->kpriv->grp;
463 if (kxc->f & KXF_TIMER)
464 sel_rmtimer(&kxc->t);
465 g->ops->freege(g, kxc->C);
466 g->ops->freege(g, kxc->R);
471 /* --- @kxc_stoptimer@ --- *
473 * Arguments: @kxchal *kxc@ = pointer to the challenge block
477 * Use: Stops the challenge's retry timer from sending messages.
478 * Useful when the state machine is in the endgame of the
482 static void kxc_stoptimer(kxchal *kxc)
484 if (kxc->f & KXF_TIMER)
485 sel_rmtimer(&kxc->t);
486 kxc->f &= ~KXF_TIMER;
489 /* --- @kxc_new@ --- *
491 * Arguments: @keyexch *kx@ = pointer to key exchange block
493 * Returns: A pointer to the challenge block.
495 * Use: Returns a pointer to a new challenge block to fill in.
496 * In particular, the @c@ and @r@ members are left
500 static kxchal *kxc_new(keyexch *kx)
505 /* --- If we're over reply threshold, discard one at random --- */
507 if (kx->nr < KX_NCHAL)
510 i = rand_global.ops->range(&rand_global, KX_NCHAL);
511 kxc_destroy(kx->r[i]);
514 /* --- Fill in the new structure --- */
516 kxc = CREATE(kxchal);
525 /* --- @kxc_bychal@ --- *
527 * Arguments: @keyexch *kx@ = pointer to key exchange block
528 * @const dhge *C@ = challenge from remote host
530 * Returns: Pointer to the challenge block, or null.
532 * Use: Finds a challenge block, given its challenge.
535 static kxchal *kxc_bychal(keyexch *kx, const dhge *C)
537 const dhgrp *g = kx->kpriv->grp;
540 for (i = 0; i < kx->nr; i++) {
541 if (g->ops->eq(g, C, kx->r[i]->C))
547 /* --- @kxc_byhc@ --- *
549 * Arguments: @keyexch *kx@ = pointer to key exchange block
550 * @const octet *hc@ = challenge hash from remote host
552 * Returns: Pointer to the challenge block, or null.
554 * Use: Finds a challenge block, given a hash of its challenge.
557 static kxchal *kxc_byhc(keyexch *kx, const octet *hc)
561 for (i = 0; i < kx->nr; i++) {
562 if (memcmp(hc, kx->r[i]->hc, kx->kpriv->algs.hashsz) == 0)
568 /* --- @kxc_answer@ --- *
570 * Arguments: @keyexch *kx@ = pointer to key exchange block
571 * @kxchal *kxc@ = pointer to challenge block
575 * Use: Sends a reply to the remote host, according to the data in
576 * this challenge block.
579 static void kxc_answer(keyexch *kx, kxchal *kxc);
581 static void kxc_timer(struct timeval *tv, void *v)
584 kxc->f &= ~KXF_TIMER;
585 kxc_answer(kxc->kx, kxc);
588 static void kxc_answer(keyexch *kx, kxchal *kxc)
590 buf *b = p_txstart(kx->p, MSG_KEYEXCH | KX_REPLY);
591 const dhgrp *g = kx->kpriv->grp;
595 /* --- Build the reply packet --- */
597 T( trace(T_KEYEXCH, "keyexch: sending reply to `%s'", p_name(kx->p)); )
598 sendchallenge(kx, b, kxc->C, kxc->hc);
599 buf_init(&bb, buf_i, sizeof(buf_i));
600 g->ops->stge(g, &bb, kxc->R, DHFMT_STD);
602 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_REPLY, &bb, b);
604 /* --- Update the statistics --- */
607 update_stats_tx(kx, BLEN(b));
611 /* --- Schedule another resend --- */
613 if (kxc->f & KXF_TIMER)
614 sel_rmtimer(&kxc->t);
615 gettimeofday(&tv, 0);
616 rs_time(&kxc->rs, &tv, &tv);
617 sel_addtimer(&sel, &kxc->t, &tv, kxc_timer, kxc);
621 /*----- Individual message handlers ---------------------------------------*/
623 /* --- @doprechallenge@ --- *
625 * Arguments: @keyexch *kx@ = pointer to key exchange block
626 * @buf *b@ = buffer containing the packet
628 * Returns: Zero if OK, nonzero of the packet was rejected.
630 * Use: Processes a pre-challenge message.
633 static int doprechallenge(keyexch *kx, buf *b)
635 const dhgrp *g = kx->kpriv->grp;
639 /* --- Ensure that we're in a sensible state --- */
641 if (kx->s != KXS_CHAL) {
642 a_warn("KX", "?PEER", kx->p, "unexpected", "pre-challenge", A_END);
646 /* --- Unpack the packet --- */
648 if ((C = g->ops->ldge(g, b, DHFMT_VAR)) == 0 || BLEFT(b))
651 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
652 trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, C));
655 /* --- Send out a full challenge by return --- */
657 b = p_txstart(kx->p, MSG_KEYEXCH | KX_CHAL);
658 h = GH_INIT(kx->kpriv->algs.h);
659 HASH_STRING(h, "tripe-cookie");
661 sendchallenge(kx, b, C, GH_DONE(h, 0));
663 update_stats_tx(kx, BLEN(b));
668 g->ops->freege(g, C);
672 if (C) g->ops->freege(g, C);
676 /* --- @respond@ --- *
678 * Arguments: @keyexch *kx@ = pointer to key exchange block
679 * @unsigned msg@ = message code for this packet
680 * @buf *b@ = buffer containing the packet
682 * Returns: Key-exchange challenge block, or null.
684 * Use: Computes a response for the given challenge, entering it into
685 * a challenge block and so on.
688 static kxchal *respond(keyexch *kx, unsigned msg, buf *b)
690 const dhgrp *g = kx->kpriv->grp;
691 const algswitch *algs = &kx->kpriv->algs;
692 size_t ixsz = g->scsz;
697 const octet *hc, *ck;
704 /* --- Unpack the packet --- */
706 if ((C = g->ops->ldge(g, b, DHFMT_VAR)) == 0 ||
707 (hc = buf_get(b, algs->hashsz)) == 0 ||
708 (ck = buf_get(b, ixsz)) == 0) {
709 a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
712 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
713 trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, C));
714 trace_block(T_CRYPTO, "crypto: cookie", hc, algs->hashsz);
715 trace_block(T_CRYPTO, "crypto: check-value", ck, ixsz);
718 /* --- Discard a packet with an invalid cookie --- */
720 if (hc && memcmp(hc, kx->hc, algs->hashsz) != 0) {
721 a_warn("KX", "?PEER", kx->p, "incorrect", "cookie", A_END);
725 /* --- Recover the check value and verify it --- *
727 * To avoid recomputation on replays, we store a hash of the `right'
728 * value. The `correct' value is unique, so this is right.
730 * This will also find a challenge block and, if necessary, populate it.
733 if ((kxc = kxc_bychal(kx, C)) != 0) {
734 h = GH_INIT(algs->h);
735 HASH_STRING(h, "tripe-check-hash");
736 GH_HASH(h, ck, ixsz);
737 ok = !memcmp(kxc->ck, GH_DONE(h, 0), algs->hashsz);
739 if (!ok) goto badcheck;
742 /* --- Compute the reply, and check the magic --- */
744 R = g->ops->mul(g, kx->kpriv->k, C);
745 if ((c = mpunmask(g, ck, ixsz, algs->mgf,
746 hashcheck(kx, kx->kpub->K, kx->C, C, R),
749 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
750 trace(T_CRYPTO, "crypto: computed reply = %s", g->ops->gestr(g, R));
751 trace(T_CRYPTO, "crypto: recovered log = %s", g->ops->scstr(g, c));
753 CC = g->ops->mul(g, c, 0);
754 if (!g->ops->eq(g, CC, C)) goto badcheck;
756 /* --- Fill in a new challenge block --- */
762 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-check-hash");
763 GH_HASH(h, ck, ixsz);
764 GH_DONE(h, kxc->ck); GH_DESTROY(h);
766 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-cookie");
767 hashge(h, g, kxc->C);
768 GH_DONE(h, kxc->hc); GH_DESTROY(h);
770 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
771 trace_block(T_CRYPTO, "crypto: computed cookie",
772 kxc->hc, algs->hashsz);
775 /* --- Work out the shared key --- */
777 R = g->ops->mul(g, kx->a, kxc->C);
778 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
779 trace(T_CRYPTO, "crypto: shared secret = %s", g->ops->gestr(g, R));
782 /* --- Compute the switch messages --- */
784 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
785 hashge(h, g, kx->C); hashge(h, g, kxc->C);
786 GH_DONE(h, kxc->hswrq_out); GH_DESTROY(h);
787 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
788 hashge(h, g, kx->C); hashge(h, g, kxc->C);
789 GH_DONE(h, kxc->hswok_out); GH_DESTROY(h);
791 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
792 hashge(h, g, kxc->C); hashge(h, g, kx->C);
793 GH_DONE(h, kxc->hswrq_in); GH_DESTROY(h);
794 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
795 hashge(h, g, kxc->C); hashge(h, g, kx->C);
796 GH_DONE(h, kxc->hswok_in); GH_DESTROY(h);
798 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
799 trace_block(T_CRYPTO, "crypto: outbound switch request",
800 kxc->hswrq_out, algs->hashsz);
801 trace_block(T_CRYPTO, "crypto: outbound switch confirm",
802 kxc->hswok_out, algs->hashsz);
803 trace_block(T_CRYPTO, "crypto: inbound switch request",
804 kxc->hswrq_in, algs->hashsz);
805 trace_block(T_CRYPTO, "crypto: inbound switch confirm",
806 kxc->hswok_in, algs->hashsz);
809 /* --- Create a new symmetric keyset --- */
811 buf_init(&bb, buf_o, sizeof(buf_o)); a.k = BBASE(&bb);
812 g->ops->stge(g, &bb, kx->C, DHFMT_HASH); a.x = BLEN(&bb);
813 g->ops->stge(g, &bb, kxc->C, DHFMT_HASH); a.y = BLEN(&bb);
814 g->ops->stge(g, &bb, R, DHFMT_HASH); a.z = BLEN(&bb);
817 kxc->ks = ks_gen(&a, kx->p);
820 if (C) g->ops->freege(g, C);
821 if (CC) g->ops->freege(g, CC);
822 if (R) g->ops->freege(g, R);
823 if (c) g->ops->freesc(g, c);
827 a_warn("KX", "?PEER", kx->p, "bad-expected-reply-log", A_END);
830 if (C) g->ops->freege(g, C);
831 if (CC) g->ops->freege(g, CC);
832 if (R) g->ops->freege(g, R);
833 if (c) g->ops->freesc(g, c);
837 /* --- @dochallenge@ --- *
839 * Arguments: @keyexch *kx@ = pointer to key exchange block
840 * @unsigned msg@ = message code for the packet
841 * @buf *b@ = buffer containing the packet
843 * Returns: Zero if OK, nonzero if the packet was rejected.
845 * Use: Processes a packet containing a challenge.
848 static int dochallenge(keyexch *kx, buf *b)
852 if (kx->s != KXS_CHAL) {
853 a_warn("KX", "?PEER", kx->p, "unexpected", "challenge", A_END);
856 if ((kxc = respond(kx, KX_CHAL, b)) == 0)
859 a_warn("KX", "?PEER", kx->p, "invalid", "challenge", A_END);
869 /* --- @resend@ --- *
871 * Arguments: @keyexch *kx@ = pointer to key exchange context
875 * Use: Sends the next message for a key exchange.
878 static void resend(keyexch *kx)
883 const dhgrp *g = kx->kpriv->grp;
888 T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
890 b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
891 g->ops->stge(g, b, kx->C, DHFMT_VAR);
894 T( trace(T_KEYEXCH, "keyexch: sending switch request to `%s'",
897 b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCH);
898 buf_put(b, kx->hc, kx->kpriv->algs.hashsz);
899 buf_put(b, kxc->hc, kx->kpriv->algs.hashsz);
900 buf_init(&bb, buf_i, sizeof(buf_i));
901 g->ops->stge(g, &bb, kxc->R, DHFMT_STD);
902 buf_put(&bb, kxc->hswrq_out, kx->kpriv->algs.hashsz);
904 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCH, &bb, b);
907 T( trace(T_KEYEXCH, "keyexch: sending switch confirmation to `%s'",
910 b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCHOK);
911 buf_init(&bb, buf_i, sizeof(buf_i));
912 buf_put(&bb, kxc->hswok_out, kx->kpriv->algs.hashsz);
914 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, &bb, b);
921 update_stats_tx(kx, BLEN(b));
925 if (kx->s < KXS_SWITCH) {
926 rs_time(&kx->rs, &tv, 0);
931 /* --- @decryptrest@ --- *
933 * Arguments: @keyexch *kx@ = pointer to key exchange context
934 * @kxchal *kxc@ = pointer to challenge block
935 * @unsigned msg@ = type of incoming message
936 * @buf *b@ = encrypted remainder of the packet
938 * Returns: Zero if OK, nonzero on some kind of error.
940 * Use: Decrypts the remainder of the packet, and points @b@ at the
941 * recovered plaintext.
944 static int decryptrest(keyexch *kx, kxchal *kxc, unsigned msg, buf *b)
948 buf_init(&bb, buf_o, sizeof(buf_o));
949 if (ks_decrypt(kxc->ks, MSG_KEYEXCH | msg, b, &bb)) {
950 a_warn("KX", "?PEER", kx->p, "decrypt-failed", "%s", pkname[msg], A_END);
953 if (!BOK(&bb)) return (-1);
954 buf_init(b, BBASE(&bb), BLEN(&bb));
958 /* --- @checkresponse@ --- *
960 * Arguments: @keyexch *kx@ = pointer to key exchange context
961 * @unsigned msg@ = type of incoming message
962 * @buf *b@ = decrypted remainder of the packet
964 * Returns: Zero if OK, nonzero on some kind of error.
966 * Use: Checks a reply or switch packet, ensuring that its response
970 static int checkresponse(keyexch *kx, unsigned msg, buf *b)
972 const dhgrp *g = kx->kpriv->grp;
975 if ((R = g->ops->ldge(g, b, DHFMT_STD)) == 0) {
976 a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
979 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
980 trace(T_CRYPTO, "crypto: reply = %s", g->ops->gestr(g, R));
982 if (!g->ops->eq(g, R, kx->RX)) {
983 a_warn("KX", "?PEER", kx->p, "incorrect", "response", A_END);
987 g->ops->freege(g, R);
991 if (R) g->ops->freege(g, R);
995 /* --- @commit@ --- *
997 * Arguments: @keyexch *kx@ = pointer to key exchange context
998 * @kxchal *kxc@ = pointer to challenge to commit to
1002 * Use: Commits to a particular challenge as being the `right' one,
1003 * since a reply has arrived for it.
1006 static void commit(keyexch *kx, kxchal *kxc)
1010 for (i = 0; i < kx->nr; i++) {
1011 if (kx->r[i] != kxc)
1012 kxc_destroy(kx->r[i]);
1017 ksl_link(kx->ks, kxc->ks);
1020 /* --- @doreply@ --- *
1022 * Arguments: @keyexch *kx@ = pointer to key exchange context
1023 * @buf *b@ = buffer containing packet
1025 * Returns: Zero if OK, nonzero if the packet was rejected.
1027 * Use: Handles a reply packet. This doesn't handle the various
1028 * switch packets: they're rather too different.
1031 static int doreply(keyexch *kx, buf *b)
1035 if (kx->s != KXS_CHAL && kx->s != KXS_COMMIT) {
1036 a_warn("KX", "?PEER", kx->p, "unexpected", "reply", A_END);
1039 if ((kxc = respond(kx, KX_REPLY, b)) == 0 ||
1040 decryptrest(kx, kxc, KX_REPLY, b) ||
1041 checkresponse(kx, KX_REPLY, b))
1044 a_warn("KX", "?PEER", kx->p, "invalid", "reply", A_END);
1047 if (kx->s == KXS_CHAL) {
1058 /* --- @kxfinish@ --- *
1060 * Arguments: @keyexch *kx@ = pointer to key exchange block
1064 * Use: Sets everything up following a successful key exchange.
1067 static void kxfinish(keyexch *kx)
1069 kxchal *kxc = kx->r[0];
1070 struct timeval now, tv;
1072 ks_activate(kxc->ks);
1073 gettimeofday(&now, 0);
1074 f2tv(&tv, wobble(T_REGEN));
1075 TV_ADD(&tv, &now, &tv);
1078 a_notify("KXDONE", "?PEER", kx->p, A_END);
1079 p_stats(kx->p)->t_kx = time(0);
1082 /* --- @doswitch@ --- *
1084 * Arguments: @keyexch *kx@ = pointer to key exchange block
1085 * @buf *b@ = pointer to buffer containing packet
1087 * Returns: Zero if OK, nonzero if the packet was rejected.
1089 * Use: Handles a reply with a switch request bolted onto it.
1092 static int doswitch(keyexch *kx, buf *b)
1094 size_t hsz = kx->kpriv->algs.hashsz;
1095 const octet *hc_in, *hc_out, *hswrq;
1098 if ((hc_in = buf_get(b, hsz)) == 0 ||
1099 (hc_out = buf_get(b, hsz)) == 0) {
1100 a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
1103 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
1104 trace_block(T_CRYPTO, "crypto: challenge", hc_in, hsz);
1105 trace_block(T_CRYPTO, "crypto: cookie", hc_out, hsz);
1107 if ((kxc = kxc_byhc(kx, hc_in)) == 0 ||
1108 memcmp(hc_out, kx->hc, hsz) != 0) {
1109 a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
1112 if (decryptrest(kx, kxc, KX_SWITCH, b) ||
1113 checkresponse(kx, KX_SWITCH, b))
1115 if ((hswrq = buf_get(b, hsz)) == 0 || BLEFT(b)) {
1116 a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
1119 IF_TRACING(T_KEYEXCH, {
1120 trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, hsz);
1122 if (memcmp(hswrq, kxc->hswrq_in, hsz) != 0) {
1123 a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
1126 if (kx->s == KXS_CHAL)
1128 if (kx->s < KXS_SWITCH)
1137 /* --- @doswitchok@ --- *
1139 * Arguments: @keyexch *kx@ = pointer to key exchange block
1140 * @buf *b@ = pointer to buffer containing packet
1142 * Returns: Zero if OK, nonzero if the packet was rejected.
1144 * Use: Handles a reply with a switch request bolted onto it.
1147 static int doswitchok(keyexch *kx, buf *b)
1149 size_t hsz = kx->kpriv->algs.hashsz;
1154 if (kx->s < KXS_COMMIT) {
1155 a_warn("KX", "?PEER", kx->p, "unexpected", "switch-ok", A_END);
1159 buf_init(&bb, buf_o, sizeof(buf_o));
1160 if (decryptrest(kx, kxc, KX_SWITCHOK, b))
1162 if ((hswok = buf_get(b, hsz)) == 0 || BLEFT(b)) {
1163 a_warn("KX", "?PEER", kx->p, "invalid", "switch-ok", A_END);
1166 IF_TRACING(T_KEYEXCH, {
1167 trace_block(T_CRYPTO, "crypto: switch confirmation hash",
1170 if (memcmp(hswok, kxc->hswok_in, hsz) != 0) {
1171 a_warn("KX", "?PEER", kx->p, "incorrect", "switch-ok", A_END);
1174 if (kx->s < KXS_SWITCH)
1182 /*----- Main code ---------------------------------------------------------*/
1186 * Arguments: @keyexch *kx@ = pointer to key exchange context
1190 * Use: Stops a key exchange dead in its tracks. Throws away all of
1191 * the context information. The context is left in an
1192 * inconsistent state. The only functions which understand this
1193 * state are @kx_free@ and @kx_init@ (which cause it internally
1194 * it), and @start@ (which expects it to be the prevailing
1198 static void stop(keyexch *kx)
1200 const dhgrp *g = kx->kpriv->grp;
1203 if (kx->f & KXF_DEAD)
1206 if (kx->f & KXF_TIMER)
1207 sel_rmtimer(&kx->t);
1208 for (i = 0; i < kx->nr; i++)
1209 kxc_destroy(kx->r[i]);
1210 g->ops->freesc(g, kx->a);
1211 g->ops->freege(g, kx->C);
1212 g->ops->freege(g, kx->RX);
1215 kx->f &= ~KXF_TIMER;
1218 /* --- @start@ --- *
1220 * Arguments: @keyexch *kx@ = pointer to key exchange context
1221 * @time_t now@ = the current time
1225 * Use: Starts a new key exchange with the peer. The context must be
1226 * in the bizarre state left by @stop@ or @kx_init@.
1229 static void start(keyexch *kx, time_t now)
1231 algswitch *algs = &kx->kpriv->algs;
1232 const dhgrp *g = kx->kpriv->grp;
1235 assert(kx->f & KXF_DEAD);
1237 kx->f &= ~(KXF_DEAD | KXF_CORK);
1239 kx->a = g->ops->randsc(g);
1240 kx->C = g->ops->mul(g, kx->a, 0);
1241 kx->RX = g->ops->mul(g, kx->a, kx->kpub->K);
1243 kx->t_valid = now + T_VALID;
1245 h = GH_INIT(algs->h);
1246 HASH_STRING(h, "tripe-cookie");
1247 hashge(h, g, kx->C);
1251 IF_TRACING(T_KEYEXCH, {
1252 trace(T_KEYEXCH, "keyexch: creating new challenge");
1253 IF_TRACING(T_CRYPTO, {
1254 trace(T_CRYPTO, "crypto: secret = %s", g->ops->scstr(g, kx->a));
1255 trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, kx->C));
1256 trace(T_CRYPTO, "crypto: expected response = %s",
1257 g->ops->gestr(g, kx->RX));
1258 trace_block(T_CRYPTO, "crypto: challenge cookie",
1259 kx->hc, algs->hashsz);
1264 /* --- @checkpub@ --- *
1266 * Arguments: @keyexch *kx@ = pointer to key exchange context
1268 * Returns: Zero if OK, nonzero if the peer's public key has expired.
1270 * Use: Deactivates the key-exchange until the peer acquires a new
1274 static int checkpub(keyexch *kx)
1279 if (kx->f & KXF_DEAD)
1282 if (KEY_EXPIRED(now, kx->kpriv->t_exp)) f |= 1;
1283 if (KEY_EXPIRED(now, kx->kpub->t_exp)) f |= 2;
1286 if (f & 1) a_warn("KX", "?PEER", kx->p, "private-key-expired", A_END);
1287 if (f & 2) a_warn("KX", "?PEER", kx->p, "public-key-expired", A_END);
1288 kx->f &= ~KXF_PUBKEY;
1294 /* --- @kx_start@ --- *
1296 * Arguments: @keyexch *kx@ = pointer to key exchange context
1297 * @int forcep@ = nonzero to ignore the quiet timer
1301 * Use: Stimulates a key exchange. If a key exchage is in progress,
1302 * a new challenge is sent (unless the quiet timer forbids
1303 * this); if no exchange is in progress, one is commenced.
1306 void kx_start(keyexch *kx, int forcep)
1308 time_t now = time(0);
1312 if (forcep || !VALIDP(kx, now)) {
1315 a_notify("KXSTART", "?PEER", kx->p, A_END);
1320 /* --- @kx_message@ --- *
1322 * Arguments: @keyexch *kx@ = pointer to key exchange context
1323 * @const addr *a@ = sender's IP address and port
1324 * @unsigned msg@ = the message code
1325 * @buf *b@ = pointer to buffer containing the packet
1327 * Returns: Nonzero if the sender's address was unknown.
1329 * Use: Reads a packet containing key exchange messages and handles
1333 int kx_message(keyexch *kx, const addr *a, unsigned msg, buf *b)
1338 T( trace(T_KEYEXCH, "keyexch: processing %s packet from %c%s%c",
1339 msg < KX_NMSG ? pkname[msg] : "unknown",
1340 kx ? '`' : '<', kx ? p_name(kx->p) : "nil", kx ? '\'' : '>'); )
1342 if (!kx) return (-1);
1343 if (notice_message(kx)) return (0);
1346 case KX_PRECHAL: rc = doprechallenge(kx, b); break;
1347 case KX_CHAL: rc = dochallenge(kx, b); break;
1348 case KX_REPLY: rc = doreply(kx, b); break;
1349 case KX_SWITCH: rc = doswitch(kx, b); break;
1350 case KX_SWITCHOK: rc = doswitchok(kx, b); break;
1352 a_warn("KX", "?PEER", kx->p, "unknown-message", "0x%02x", msg, A_END);
1357 update_stats_rx(kx, !rc, sz);
1361 /* --- @kx_free@ --- *
1363 * Arguments: @keyexch *kx@ = pointer to key exchange context
1367 * Use: Frees everything in a key exchange context.
1370 void kx_free(keyexch *kx)
1374 km_unref(kx->kpriv);
1377 /* --- @kx_newkeys@ --- *
1379 * Arguments: @keyexch *kx@ = pointer to key exchange context
1383 * Use: Informs the key exchange module that its keys may have
1384 * changed. If fetching the new keys fails, the peer will be
1385 * destroyed, we log messages and struggle along with the old
1389 void kx_newkeys(keyexch *kx)
1391 kdata *kpriv, *kpub;
1394 time_t now = time(0);
1396 T( trace(T_KEYEXCH, "keyexch: checking new keys for `%s'",
1399 /* --- Find out whether we can use new keys --- *
1401 * Try each available combination of new and old, public and private,
1402 * except both old (which is status quo anyway). The selection is encoded
1403 * in @i@, with bit 0 for the private key and bit 1 for public key; a set
1404 * bit means to use the old value, and a clear bit means to use the new
1407 * This means that we currently prefer `old private and new public' over
1408 * `new private and old public'. I'm not sure which way round this should
1412 for (i = 0; i < 3; i++) {
1414 /* --- Select the keys we're going to examine --- *
1416 * If we're meant to have a new key and don't, then skip this
1420 T( trace(T_KEYEXCH, "keyexch: checking %s private, %s public",
1421 i & 1 ? "old" : "new", i & 2 ? "old" : "new"); )
1423 if (i & 1) kpriv = kx->kpriv;
1424 else if (kx->kpriv->kn->kd != kx->kpriv) kpriv = kx->kpriv->kn->kd;
1426 T( trace(T_KEYEXCH, "keyexch: private key unchanged, skipping"); )
1430 if (i & 2) kpub = kx->kpub;
1431 else if (kx->kpub->kn->kd != kx->kpub) kpub = kx->kpub->kn->kd;
1433 T( trace(T_KEYEXCH, "keyexch: public key unchanged, skipping"); )
1437 /* --- Skip if either key is expired --- *
1439 * We're not going to get far with expired keys, and this simplifies the
1443 if (KEY_EXPIRED(now, kx->kpriv->t_exp) ||
1444 KEY_EXPIRED(now, kx->kpub->t_exp)) {
1445 T( trace(T_KEYEXCH, "keyexch: %s expired, skipping",
1446 !KEY_EXPIRED(now, kx->kpriv->t_exp) ? "public key" :
1447 !KEY_EXPIRED(now, kx->kpub->t_exp) ? "private key" :
1452 /* --- If the groups don't match then we can't use this pair --- */
1454 if (!km_samealgsp(kpriv, kpub)) {
1455 T( trace(T_KEYEXCH, "keyexch: peer `%s' group mismatch; "
1456 "%s priv `%s' and %s pub `%s'", p_name(kx->p),
1457 i & 1 ? "old" : "new", km_tag(kx->kpriv),
1458 i & 2 ? "old" : "new", km_tag(kx->kpub)); )
1463 T( trace(T_KEYEXCH, "keyexch: peer `%s' continuing with old keys",
1467 /* --- We've chosen new keys --- *
1469 * Switch the new ones into place. Neither of the keys we're switching to
1470 * is expired (we checked that above), so we should just crank everything
1473 * A complication arises: we don't really want to force a new key exchange
1474 * unless we have to. If the group is unchanged, and we're currently
1475 * running OK, then we should just let things lie.
1479 switchp = ((kx->f & KXF_DEAD) ||
1480 kx->s != KXS_SWITCH ||
1481 kpriv->grp->ops != kx->kpriv->grp->ops ||
1482 !kpriv->grp->ops->samegrpp(kpriv->grp, kx->kpriv->grp));
1484 T( trace(T_KEYEXCH, "keyexch: peer `%s' adopting "
1485 "%s priv `%s' and %s pub `%s'; %sforcing exchange", p_name(kx->p),
1486 i & 1 ? "old" : "new", km_tag(kx->kpriv),
1487 i & 2 ? "old" : "new", km_tag(kx->kpub),
1488 switchp ? "" : "not "); )
1490 if (switchp) stop(kx);
1491 km_ref(kpriv); km_unref(kx->kpriv); kx->kpriv = kpriv;
1492 km_ref(kpub); km_unref(kx->kpub); kx->kpub = kpub;
1493 kx->f |= KXF_PUBKEY;
1495 T( trace(T_KEYEXCH, "keyexch: restarting key negotiation with `%s'",
1502 /* --- @kx_setup@ --- *
1504 * Arguments: @keyexch *kx@ = pointer to key exchange context
1505 * @peer *p@ = pointer to peer context
1506 * @keyset **ks@ = pointer to keyset list
1507 * @unsigned f@ = various useful flags
1509 * Returns: Zero if OK, nonzero if it failed.
1511 * Use: Initializes a key exchange module. The module currently
1512 * contains no keys, and will attempt to initiate a key
1516 int kx_setup(keyexch *kx, peer *p, keyset **ks, unsigned f)
1518 if ((kx->kpriv = km_findpriv(p_privtag(p))) == 0) goto fail_0;
1519 if ((kx->kpub = km_findpub(p_tag(p))) == 0) goto fail_1;
1520 if (!km_samealgsp(kx->kpriv, kx->kpub)) {
1521 a_warn("KX", "?PEER", p, "group-mismatch",
1522 "local-private-key", "%s", p_privtag(p),
1523 "peer-public-key", "%s", p_tag(p),
1530 kx->f = KXF_DEAD | KXF_PUBKEY | f;
1532 if (!(kx->f & KXF_CORK)) {
1535 /* Don't notify here: the ADD message hasn't gone out yet. */
1542 km_unref(kx->kpriv);
1547 /*----- That's all, folks -------------------------------------------------*/