3 * $Id: keyexch.c,v 1.10 2003/10/15 09:29:38 mdw Exp $
5 * Key exchange protocol
7 * (c) 2001 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of Trivial IP Encryption (TrIPE).
14 * TrIPE is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * TrIPE is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with TrIPE; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 /*----- Revision history --------------------------------------------------*
32 * Revision 1.10 2003/10/15 09:29:38 mdw
33 * Cosmetic fix to changelog comment.
35 * Revision 1.9 2003/07/13 11:53:14 mdw
36 * Add protocol commentary.
38 * Revision 1.8 2003/07/13 11:19:49 mdw
39 * Incompatible protocol fix! Include message type code under MAC tag to
40 * prevent cut-and-paste from key-exchange messages to general packet
43 * Revision 1.7 2003/05/17 11:01:28 mdw
44 * Handle flags on challenge timers correctly to prevent confusing the event
47 * Revision 1.6 2003/04/06 10:26:35 mdw
48 * Report peer name on decrypt errors.
50 * Revision 1.5 2002/01/13 14:54:40 mdw
51 * Patch up zero-knowledge property by passing an encrypted log with a
52 * challenge, so that the prover can verify that the challenge is good.
54 * Revision 1.4 2001/06/22 19:40:36 mdw
55 * Support expiry of other peers' public keys.
57 * Revision 1.3 2001/06/19 22:07:09 mdw
60 * Revision 1.2 2001/02/16 21:24:27 mdw
61 * Rewrite for new key exchange protocol.
63 * Revision 1.1 2001/02/03 20:26:37 mdw
68 /*----- Header files ------------------------------------------------------*/
72 /*----- Brief protocol overview -------------------------------------------*
74 * Let %$G$% be a cyclic group; let %$g$% be a generator of %$G$%, and let
75 * %$q$% be the order of %$G$%; for a key %$K$%, let %$E_K(\cdot)$% denote
76 * application of the symmetric packet protocol to a message; let
77 * %$H(\cdot)$% be the random oracle. Let $\alpha \inr \{0,\ldots,q - 1\}$%
78 * be Alice's private key; let %$a = g^\alpha$% be her public key; let %$b$%
79 * be Bob's public key.
81 * At the beginning of the session, Alice chooses
83 * %$\rho_A \inr \{0, \ldots q - 1\}$%
87 * %$r_A = g^{\rho_A}$% Alice's challenge
88 * %$c_A = H(\cookie{cookie}, r_A)$% Alice's cookie
89 * %$v_A = \rho_A \xor H(\cookie{expected-reply}, r_A, r_B, b^{\rho_A})$%
90 * Alice's challenge check value
91 * %$r_B^\alpha = a^{\rho_B}$% Alice's reply
92 * %$K = r_B^{\rho_A} = r_B^{\rho_A} = g^{\rho_A\rho_B}$%
93 * Alice and Bob's shared secret key
94 * %$w_A = H(\cookie{switch-request}, c_A, c_B)$%
95 * Alice's switch request value
96 * %$u_A = H(\cookie{switch-confirm}, c_A, c_B)$%
97 * Alice's switch confirm value
99 * The messages are then:
101 * %$\cookie{kx-pre-challenge}, r_A$%
102 * Initial greeting. In state @KXS_CHAL@.
104 * %$\cookie{kx-cookie}, r_A, c_B$%
105 * My table is full but I got your message.
107 * %$\cookie{kx-challenge}, r_A, c_B, v_A$%
108 * Here's a full challenge for you to answer.
110 * %$\cookie{kx-reply}, c_A, c_B, v_A, E_K(r_B^\alpha))$%
111 * Challenge accpeted: here's the answer. Commit to my challenge. Move
114 * %$\cookie{kx-switch}, c_A, c_B, E_K(r_B^\alpha, w_A))$%
115 * Reply received: here's my reply. Committed; send data; move to
118 * %$\cookie{kx-switch-ok}, E_K(u_A))$%
119 * Switch received. Committed; send data; move to @KXS_SWITCH@.
122 /*----- Tunable parameters ------------------------------------------------*/
124 #define T_VALID MIN(2) /* Challenge validity period */
125 #define T_RETRY SEC(10) /* Challenge retransmit interval */
127 #define ISVALID(kx, now) ((now) < (kx)->t_valid)
129 /*----- Various utilities -------------------------------------------------*/
131 /* --- @hashmp@ --- *
133 * Arguments: @HASH_CTX *r@ = pointer to hash context
134 * @mp *m@ = pointer to multiprecision integer
138 * Use: Adds the hash of a multiprecision integer to the context.
142 static void hashmp(HASH_CTX *r, mp *m)
145 buf_init(&b, buf_t, sizeof(buf_t));
148 HASH(r, BBASE(&b), BLEN(&b));
151 /* --- @mpcrypt@ --- *
153 * Arguments: @mp *d@ = the destination integer
154 * @mp *x@ = the plaintext/ciphertext integer
155 * @size_t sz@ = the expected size of the plaintext
156 * @const octet *k@ = pointer to key material
157 * @size_t ksz@ = size of the key
159 * Returns: The encrypted/decrypted integer.
161 * Use: Encrypts (or decrypts) a multiprecision integer using another
162 * multiprecision integer as the key. This is a slightly grotty
163 * way to do this, but it's easier than the alternatives.
166 static mp *mpcrypt(mp *d, mp *x, size_t sz, const octet *k, size_t ksz)
170 MGF_INIT(&m, k, ksz, 0);
171 mp_storeb(x, buf_t, sz);
172 MGF_CRYPT(&m, buf_t, buf_t, sz);
173 return (mp_loadb(d, buf_t, sz));
178 * Arguments: @struct timeval *tv@ = the current time
179 * @void *v@ = pointer to key exchange context
183 * Use: Acts when the key exchange timer goes off.
186 static void timer(struct timeval *tv, void *v)
190 T( trace(T_KEYEXCH, "keyexch: timer has popped"); )
194 /* --- @settimer@ --- *
196 * Arguments: @keyexch *kx@ = pointer to key exchange context
197 * @time_t t@ = when to set the timer for
201 * Use: Sets the timer for the next key exchange attempt.
204 static void settimer(keyexch *kx, time_t t)
207 if (kx->f & KXF_TIMER)
211 sel_addtimer(&sel, &kx->t, &tv, timer, kx);
215 /*----- Challenge management ----------------------------------------------*/
217 /* --- Notes on challenge management --- *
219 * We may get multiple different replies to our key exchange; some will be
220 * correct, some inserted by attackers. Up until @KX_THRESH@, all challenges
221 * received will be added to the table and given a full response. After
222 * @KX_THRESH@ distinct challenges are received, we return only a `cookie':
223 * our existing challenge, followed by a hash of the sender's challenge. We
224 * do %%\emph{not}%% give a bare challenge a reply slot at this stage. All
225 * properly-formed cookies are assigned a table slot: if none is spare, a
226 * used slot is randomly selected and destroyed. A cookie always receives a
230 /* --- @kxc_destroy@ --- *
232 * Arguments: @kxchal *kxc@ = pointer to the challenge block
236 * Use: Disposes of a challenge block.
239 static void kxc_destroy(kxchal *kxc)
241 if (kxc->f & KXF_TIMER)
242 sel_rmtimer(&kxc->t);
250 /* --- @kxc_stoptimer@ --- *
252 * Arguments: @kxchal *kxc@ = pointer to the challenge block
256 * Use: Stops the challenge's retry timer from sending messages.
257 * Useful when the state machine is in the endgame of the
261 static void kxc_stoptimer(kxchal *kxc)
263 if (kxc->f & KXF_TIMER)
264 sel_rmtimer(&kxc->t);
265 kxc->f &= ~KXF_TIMER;
268 /* --- @kxc_new@ --- *
270 * Arguments: @keyexch *kx@ = pointer to key exchange block
272 * Returns: A pointer to the challenge block.
274 * Use: Returns a pointer to a new challenge block to fill in.
277 static kxchal *kxc_new(keyexch *kx)
282 /* --- If we're over reply threshold, discard one at random --- */
284 if (kx->nr < KX_NCHAL)
287 i = rand_global.ops->range(&rand_global, KX_NCHAL);
288 kxc_destroy(kx->r[i]);
291 /* --- Fill in the new structure --- */
293 kxc = CREATE(kxchal);
304 /* --- @kxc_bychal@ --- *
306 * Arguments: @keyexch *kx@ = pointer to key exchange block
307 * @mp *c@ = challenge from remote host
309 * Returns: Pointer to the challenge block, or null.
311 * Use: Finds a challenge block, given its challenge.
314 static kxchal *kxc_bychal(keyexch *kx, mp *c)
318 for (i = 0; i < kx->nr; i++) {
319 if (MP_EQ(c, kx->r[i]->c))
325 /* --- @kxc_byhc@ --- *
327 * Arguments: @keyexch *kx@ = pointer to key exchange block
328 * @const octet *hc@ = challenge hash from remote host
330 * Returns: Pointer to the challenge block, or null.
332 * Use: Finds a challenge block, given a hash of its challenge.
335 static kxchal *kxc_byhc(keyexch *kx, const octet *hc)
339 for (i = 0; i < kx->nr; i++) {
340 if (memcmp(hc, kx->r[i]->hc, HASHSZ) == 0)
346 /* --- @kxc_answer@ --- *
348 * Arguments: @keyexch *kx@ = pointer to key exchange block
349 * @kxchal *kxc@ = pointer to challenge block
353 * Use: Sends a reply to the remote host, according to the data in
354 * this challenge block.
357 static void kxc_answer(keyexch *kx, kxchal *kxc);
359 static void kxc_timer(struct timeval *tv, void *v)
362 kxc->f &= ~KXF_TIMER;
363 kxc_answer(kxc->kx, kxc);
366 static void kxc_answer(keyexch *kx, kxchal *kxc)
368 stats *st = p_stats(kx->p);
369 buf *b = p_txstart(kx->p, MSG_KEYEXCH | (kxc->r ? KX_REPLY : KX_CHAL));
373 /* --- Build the reply packet --- */
378 buf_put(b, kx->hc, HASHSZ);
379 buf_put(b, kxc->hc, HASHSZ);
380 buf_putmp(b, kxc->ck);
382 /* --- Maybe send an actual reply, if we have one --- */
385 T( trace(T_KEYEXCH, "keyexch: resending challenge to `%s'",
388 T( trace(T_KEYEXCH, "keyexch: sending reply to `%s'", p_name(kx->p)); )
389 buf_init(&bb, buf_i, sizeof(buf_i));
390 buf_putmp(&bb, kxc->r);
392 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_REPLY, &bb, b);
395 /* --- Update the statistics --- */
399 st->sz_kxout += BLEN(b);
403 /* --- Schedule another resend --- */
405 if (kxc->f & KXF_TIMER)
406 sel_rmtimer(&kxc->t);
407 gettimeofday(&tv, 0);
408 tv.tv_sec += T_RETRY;
409 sel_addtimer(&sel, &kxc->t, &tv, kxc_timer, kxc);
413 /*----- Individual message handlers ---------------------------------------*/
415 /* --- @getreply@ --- *
417 * Arguments: @keyexch *kx@ = pointer to key exchange context
418 * @mp *c@ = a challenge
419 * @mp *ck@ = the supplied expected-reply check value
421 * Returns: A pointer to the reply, or null if the reply-hash was wrong.
423 * Use: Computes replies to challenges.
426 static mp *getreply(keyexch *kx, mp *c, mp *ck)
428 mp *r = mpmont_exp(&mg, MP_NEW, c, kpriv.x);
435 HASH_STRING(&h, "tripe-expected-reply");
441 a = mpcrypt(MP_NEW, ck, mp_octets(kpriv.dp.q), buf, sizeof(buf));
442 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
443 trace(T_CRYPTO, "crypto: computed reply = %s", mpstr(r));
444 trace_block(T_CRYPTO, "crypto: computed reply hash", buf, HASHSZ);
445 trace(T_CRYPTO, "crypto: recovered log = %s", mpstr(a));
447 a = mpmont_exp(&mg, a, kpriv.dp.g, a);
450 a_warn("invalid expected-reply check from `%s'", p_name(kx->p));
451 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
452 trace(T_CRYPTO, "crypto: computed challenge = %s", mpstr(a));
460 /* --- @dochallenge@ --- *
462 * Arguments: @keyexch *kx@ = pointer to key exchange block
463 * @unsigned msg@ = message code for the packet
464 * @buf *b@ = buffer containing the packet
466 * Returns: Zero if OK, nonzero if the packet was rejected.
468 * Use: Processes a packet containing a challenge.
471 static int dochallenge(keyexch *kx, unsigned msg, buf *b)
479 /* --- Ensure that we're in a sensible state --- */
481 if (kx->s != KXS_CHAL) {
482 a_warn("unexpected challenge from `%s'", p_name(kx->p));
486 /* --- Unpack the packet --- */
488 if ((c = buf_getmp(b)) == 0 ||
489 (msg >= KX_COOKIE && (hc = buf_get(b, HASHSZ)) == 0) ||
490 (msg >= KX_CHAL && (ck = buf_getmp(b)) == 0) ||
492 a_warn("malformed packet from `%s'", p_name(kx->p));
496 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
497 trace(T_CRYPTO, "crypto: challenge = %s", mpstr(c));
498 if (hc) trace_block(T_CRYPTO, "crypto: cookie", hc, HASHSZ);
499 if (ck) trace(T_CRYPTO, "crypto: check value = %s", mpstr(ck));
502 /* --- First, handle a bare challenge --- *
504 * If the table is heavily loaded, just emit a cookie and return.
507 if (!hc && kx->nr >= KX_THRESH) {
508 T( trace(T_KEYEXCH, "keyexch: too many challenges -- sending cookie"); )
509 b = p_txstart(kx->p, MSG_KEYEXCH | KX_COOKIE);
512 HASH_STRING(&h, "tripe-cookie");
514 HASH_DONE(&h, buf_get(b, HASHSZ));
519 /* --- Discard a packet with an invalid cookie --- */
521 if (hc && memcmp(hc, kx->hc, HASHSZ) != 0) {
522 a_warn("incorrect cookie from `%s'", p_name(kx->p));
526 /* --- Find a challenge block for this packet --- *
528 * If there isn't one already, create a new one.
531 if ((kxc = kxc_bychal(kx, c)) == 0) {
535 /* --- Be careful here --- *
537 * If this is a full challenge, and it's the first time I've seen it, I
538 * want to be able to throw it away before committing a table entry to
545 if ((r = getreply(kx, c, ck)) == 0)
552 /* --- Work out the cookie for this challenge --- */
555 HASH_STRING(&h, "tripe-cookie");
557 HASH_DONE(&h, kxc->hc);
559 /* --- Compute the expected-reply hash --- */
562 HASH_STRING(&h, "tripe-expected-reply");
567 kxc->ck = mpcrypt(MP_NEW, kx->alpha, mp_octets(kpriv.dp.q),
570 /* --- Work out the shared key --- */
572 trace(T_CRYPTO, "debug: c = %s", mpstr(c));
573 trace(T_CRYPTO, "debug: alpha = %s", mpstr(kx->alpha));
574 r = mpmont_exp(&mg, MP_NEW, c, kx->alpha);
575 trace(T_CRYPTO, "debug: r = %s", mpstr(r));
577 /* --- Compute the switch messages --- */
579 HASH_INIT(&h); HASH_STRING(&h, "tripe-switch-request");
580 hashmp(&h, kx->c); hashmp(&h, kxc->c);
581 HASH_DONE(&h, kxc->hswrq_out);
582 HASH_INIT(&h); HASH_STRING(&h, "tripe-switch-confirm");
583 hashmp(&h, kx->c); hashmp(&h, kxc->c);
584 HASH_DONE(&h, kxc->hswok_out);
586 HASH_INIT(&h); HASH_STRING(&h, "tripe-switch-request");
587 hashmp(&h, kxc->c); hashmp(&h, kx->c);
588 HASH_DONE(&h, kxc->hswrq_in);
589 HASH_INIT(&h); HASH_STRING(&h, "tripe-switch-confirm");
590 hashmp(&h, kxc->c); hashmp(&h, kx->c);
591 HASH_DONE(&h, kxc->hswok_in);
593 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
594 trace_block(T_CRYPTO, "crypto: computed cookie", kxc->hc, HASHSZ);
595 trace_block(T_CRYPTO, "crypto: expected-reply hash",
597 trace(T_CRYPTO, "crypto: my reply check = %s", mpstr(kxc->ck));
598 trace(T_CRYPTO, "crypto: shared secret = %s", mpstr(r));
599 trace_block(T_CRYPTO, "crypto: outbound switch request",
600 kxc->hswrq_out, HASHSZ);
601 trace_block(T_CRYPTO, "crypto: outbound switch confirm",
602 kxc->hswok_out, HASHSZ);
603 trace_block(T_CRYPTO, "crypto: inbound switch request",
604 kxc->hswrq_in, HASHSZ);
605 trace_block(T_CRYPTO, "crypto: inbound switch confirm",
606 kxc->hswok_in, HASHSZ);
609 /* --- Create a new symmetric keyset --- */
611 buf_init(b, buf_o, sizeof(buf_o));
612 buf_putmp(b, kx->c); x = BLEN(b);
613 buf_putmp(b, kxc->c); y = BLEN(b);
614 buf_putmp(b, r); z = BLEN(b);
617 kxc->ks = ks_gen(BBASE(b), x, y, z, kx->p);
621 /* --- Answer the challenge if we need to --- */
625 if ((r = getreply(kx, c, ck)) == 0)
632 /* --- Tidy up and go home --- */
645 /* --- @resend@ --- *
647 * Arguments: @keyexch *kx@ = pointer to key exchange context
651 * Use: Sends the next message for a key exchange.
654 static void resend(keyexch *kx)
658 stats *st = p_stats(kx->p);
663 T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
665 b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
669 T( trace(T_KEYEXCH, "keyexch: sending switch request to `%s'",
672 b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCH);
673 buf_put(b, kx->hc, HASHSZ);
674 buf_put(b, kxc->hc, HASHSZ);
675 buf_init(&bb, buf_i, sizeof(buf_i));
676 buf_putmp(&bb, kxc->r);
677 buf_put(&bb, kxc->hswrq_out, HASHSZ);
679 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCH, &bb, b);
682 T( trace(T_KEYEXCH, "keyexch: sending switch confirmation to `%s'",
685 b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCHOK);
686 buf_init(&bb, buf_i, sizeof(buf_i));
687 buf_put(&bb, kxc->hswok_out, HASHSZ);
689 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, &bb, b);
697 st->sz_kxout += BLEN(b);
701 if (kx->s < KXS_SWITCH)
702 settimer(kx, time(0) + T_RETRY);
705 /* --- @matchreply@ --- *
707 * Arguments: @keyexch *kx@ = pointer to key exchange context
708 * @unsigned ty@ = type of incoming message
709 * @const octet *hc_in@ = a hash of his challenge
710 * @const octet *hc_out@ = a hash of my challenge (cookie)
711 * @mp *ck@ = his expected-reply hash (optional)
712 * @buf *b@ = encrypted remainder of the packet
714 * Returns: A pointer to the challenge block if OK, or null on failure.
716 * Use: Checks a reply or switch packet, ensuring that its contents
717 * are sensible and correct. If they are, @*b@ is set to point
718 * to the remainder of the encrypted data, and the correct
719 * challenge is returned.
722 static kxchal *matchreply(keyexch *kx, unsigned ty, const octet *hc_in,
723 const octet *hc_out, mp *ck, buf *b)
729 /* --- Check the plaintext portions of the data --- */
731 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
732 trace_block(T_CRYPTO, "crypto: challenge", hc_in, HASHSZ);
733 trace_block(T_CRYPTO, "crypto: cookie", hc_out, HASHSZ);
734 if (ck) trace(T_CRYPTO, "crypto: check value = %s", mpstr(ck));
736 if (memcmp(hc_out, kx->hc, HASHSZ) != 0) {
737 a_warn("incorrect cookie from `%s'", p_name(kx->p));
740 if ((kxc = kxc_byhc(kx, hc_in)) == 0) {
741 a_warn("received reply for unknown challenge from `%s'", p_name(kx->p));
745 /* --- Maybe compute a reply for the challenge --- */
749 a_warn("unexpected switch request from `%s'", p_name(kx->p));
752 if ((r = getreply(kx, kxc->c, ck)) == 0)
758 /* --- Decrypt the rest of the packet --- */
760 buf_init(&bb, buf_o, sizeof(buf_o));
761 if (ks_decrypt(kxc->ks, ty, b, &bb)) {
762 a_warn("failed to decrypt reply from `%s'", p_name(kx->p));
765 buf_init(b, BBASE(&bb), BLEN(&bb));
766 if ((r = buf_getmp(b)) == 0) {
767 a_warn("invalid reply packet from `%s'", p_name(kx->p));
770 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
771 trace(T_CRYPTO, "crypto: reply = %s", mpstr(r));
773 if (!mp_eq(r, kx->rx)) {
774 a_warn("incorrect reply from `%s'", p_name(kx->p));
788 /* --- @commit@ --- *
790 * Arguments: @keyexch *kx@ = pointer to key exchange context
791 * @kxchal *kxc@ = pointer to challenge to commit to
795 * Use: Commits to a particular challenge as being the `right' one,
796 * since a reply has arrived for it.
799 static void commit(keyexch *kx, kxchal *kxc)
803 for (i = 0; i < kx->nr; i++) {
805 kxc_destroy(kx->r[i]);
810 ksl_link(kx->ks, kxc->ks);
813 /* --- @doreply@ --- *
815 * Arguments: @keyexch *kx@ = pointer to key exchange context
816 * @buf *b@ = buffer containing packet
818 * Returns: Zero if OK, nonzero if the packet was rejected.
820 * Use: Handles a reply packet. This doesn't handle the various
821 * switch packets: they're rather too different.
824 static int doreply(keyexch *kx, buf *b)
826 const octet *hc_in, *hc_out;
830 if (kx->s != KXS_CHAL && kx->s != KXS_COMMIT) {
831 a_warn("unexpected reply from `%s'", p_name(kx->p));
834 if ((hc_in = buf_get(b, HASHSZ)) == 0 ||
835 (hc_out = buf_get(b, HASHSZ)) == 0 ||
836 (ck = buf_getmp(b)) == 0) {
837 a_warn("invalid reply packet from `%s'", p_name(kx->p));
840 if ((kxc = matchreply(kx, MSG_KEYEXCH | KX_REPLY,
841 hc_in, hc_out, ck, b)) == 0)
844 a_warn("invalid reply packet from `%s'", p_name(kx->p));
847 if (kx->s == KXS_CHAL) {
859 /* --- @doswitch@ --- *
861 * Arguments: @keyexch *kx@ = pointer to key exchange block
862 * @buf *b@ = pointer to buffer containing packet
864 * Returns: Zero if OK, nonzero if the packet was rejected.
866 * Use: Handles a reply with a switch request bolted onto it.
869 static int doswitch(keyexch *kx, buf *b)
871 const octet *hc_in, *hc_out, *hswrq;
874 if ((hc_in = buf_get(b, HASHSZ)) == 0 ||
875 (hc_out = buf_get(b, HASHSZ)) == 0) {
876 a_warn("invalid switch request from `%s'", p_name(kx->p));
879 if ((kxc = matchreply(kx, MSG_KEYEXCH | KX_SWITCH,
880 hc_in, hc_out, 0, b)) == 0)
882 if ((hswrq = buf_get(b, HASHSZ)) == 0 || BLEFT(b)) {
883 a_warn("invalid switch request from `%s'", p_name(kx->p));
886 IF_TRACING(T_KEYEXCH, {
887 trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, HASHSZ);
889 if (memcmp(hswrq, kxc->hswrq_in, HASHSZ) != 0) {
890 a_warn("incorrect switch request hash from `%s'", p_name(kx->p));
897 ks_activate(kxc->ks);
898 settimer(kx, ks_tregen(kxc->ks));
909 /* --- @doswitchok@ --- *
911 * Arguments: @keyexch *kx@ = pointer to key exchange block
912 * @buf *b@ = pointer to buffer containing packet
914 * Returns: Zero if OK, nonzero if the packet was rejected.
916 * Use: Handles a reply with a switch request bolted onto it.
919 static int doswitchok(keyexch *kx, buf *b)
925 if (kx->s < KXS_COMMIT) {
926 a_warn("unexpected switch confirmation from `%s'", p_name(kx->p));
930 buf_init(&bb, buf_o, sizeof(buf_o));
931 if (ks_decrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, b, &bb)) {
932 a_warn("failed to decrypt switch confirmation from `%s'", p_name(kx->p));
935 buf_init(b, BBASE(&bb), BLEN(&bb));
936 if ((hswok = buf_get(b, HASHSZ)) == 0 || BLEFT(b)) {
937 a_warn("invalid switch confirmation from `%s'", p_name(kx->p));
940 IF_TRACING(T_KEYEXCH, {
941 trace_block(T_CRYPTO, "crypto: switch confirmation hash", hswok, HASHSZ);
943 if (memcmp(hswok, kxc->hswok_in, HASHSZ) != 0) {
944 a_warn("incorrect switch confirmation hash from `%s'", p_name(kx->p));
947 if (kx->s < KXS_SWITCH) {
948 ks_activate(kxc->ks);
949 settimer(kx, ks_tregen(kxc->ks));
958 /*----- Main code ---------------------------------------------------------*/
962 * Arguments: @keyexch *kx@ = pointer to key exchange context
966 * Use: Stops a key exchange dead in its tracks. Throws away all of
967 * the context information. The context is left in an
968 * inconsistent state. The only functions which understand this
969 * state are @kx_free@ and @kx_init@ (which cause it internally
970 * it), and @start@ (which expects it to be the prevailing
974 static void stop(keyexch *kx)
978 if (kx->f & KXF_DEAD)
981 if (kx->f & KXF_TIMER)
983 for (i = 0; i < kx->nr; i++)
984 kxc_destroy(kx->r[i]);
995 * Arguments: @keyexch *kx@ = pointer to key exchange context
996 * @time_t now@ = the current time
1000 * Use: Starts a new key exchange with the peer. The context must be
1001 * in the bizarre state left by @stop@ or @kx_init@.
1004 static void start(keyexch *kx, time_t now)
1008 assert(kx->f & KXF_DEAD);
1012 kx->alpha = mprand_range(MP_NEW, kpriv.dp.q, &rand_global, 0);
1013 kx->c = mpmont_exp(&mg, MP_NEW, kpriv.dp.g, kx->alpha);
1014 kx->rx = mpmont_exp(&mg, MP_NEW, kx->kpub.y, kx->alpha);
1016 kx->t_valid = now + T_VALID;
1019 HASH_STRING(&h, "tripe-cookie");
1021 HASH_DONE(&h, kx->hc);
1023 IF_TRACING(T_KEYEXCH, {
1024 trace(T_KEYEXCH, "keyexch: creating new challenge");
1025 IF_TRACING(T_CRYPTO, {
1026 trace(T_CRYPTO, "crypto: secret = %s", mpstr(kx->alpha));
1027 trace(T_CRYPTO, "crypto: challenge = %s", mpstr(kx->c));
1028 trace(T_CRYPTO, "crypto: expected response = %s", mpstr(kx->rx));
1029 trace_block(T_CRYPTO, "crypto: challenge cookie", kx->hc, HASHSZ);
1034 /* --- @checkpub@ --- *
1036 * Arguments: @keyexch *kx@ = pointer to key exchange context
1038 * Returns: Zero if OK, nonzero if the peer's public key has expired.
1040 * Use: Deactivates the key-exchange until the peer acquires a new
1044 static int checkpub(keyexch *kx)
1047 if (kx->f & KXF_DEAD)
1050 if (KEY_EXPIRED(now, kx->texp_kpub)) {
1052 a_warn("public key for `%s' has expired", p_name(kx->p));
1053 dh_pubfree(&kx->kpub);
1054 kx->f &= ~KXF_PUBKEY;
1060 /* --- @kx_start@ --- *
1062 * Arguments: @keyexch *kx@ = pointer to key exchange context
1066 * Use: Stimulates a key exchange. If a key exchage is in progress,
1067 * a new challenge is sent (unless the quiet timer forbids
1068 * this); if no exchange is in progress, one is commenced.
1071 void kx_start(keyexch *kx)
1073 time_t now = time(0);
1077 if (!ISVALID(kx, now)) {
1084 /* --- @kx_message@ --- *
1086 * Arguments: @keyexch *kx@ = pointer to key exchange context
1087 * @unsigned msg@ = the message code
1088 * @buf *b@ = pointer to buffer containing the packet
1092 * Use: Reads a packet containing key exchange messages and handles
1096 void kx_message(keyexch *kx, unsigned msg, buf *b)
1098 time_t now = time(0);
1099 stats *st = p_stats(kx->p);
1104 static const char *const pkname[] = {
1105 "prechallenge", "cookie", "challenge",
1106 "reply", "switch request", "switch confirmation"
1113 if (!ISVALID(kx, now)) {
1118 T( trace(T_KEYEXCH, "keyexch: processing %s packet from `%s'",
1119 msg < KX_NMSG ? pkname[msg] : "unknown", p_name(kx->p)); )
1125 rc = dochallenge(kx, msg, b);
1128 rc = doreply(kx, b);
1131 rc = doswitch(kx, b);
1134 rc = doswitchok(kx, b);
1137 a_warn("unexpected key exchange message type %u from `%p'",
1151 /* --- @kx_free@ --- *
1153 * Arguments: @keyexch *kx@ = pointer to key exchange context
1157 * Use: Frees everything in a key exchange context.
1160 void kx_free(keyexch *kx)
1163 if (kx->f & KXF_PUBKEY)
1164 dh_pubfree(&kx->kpub);
1167 /* --- @kx_newkeys@ --- *
1169 * Arguments: @keyexch *kx@ = pointer to key exchange context
1173 * Use: Informs the key exchange module that its keys may have
1174 * changed. If fetching the new keys fails, the peer will be
1175 * destroyed, we log messages and struggle along with the old
1179 void kx_newkeys(keyexch *kx)
1183 if (km_getpubkey(p_name(kx->p), &dp, &kx->texp_kpub))
1185 if (kx->f & KXF_PUBKEY)
1186 dh_pubfree(&kx->kpub);
1188 kx->f |= KXF_PUBKEY;
1189 if ((kx->f & KXF_DEAD) || kx->s != KXS_SWITCH) {
1190 T( trace(T_KEYEXCH, "keyexch: restarting key negotiation with `%s'",
1198 /* --- @kx_init@ --- *
1200 * Arguments: @keyexch *kx@ = pointer to key exchange context
1201 * @peer *p@ = pointer to peer context
1202 * @keyset **ks@ = pointer to keyset list
1204 * Returns: Zero if OK, nonzero if it failed.
1206 * Use: Initializes a key exchange module. The module currently
1207 * contains no keys, and will attempt to initiate a key
1211 int kx_init(keyexch *kx, peer *p, keyset **ks)
1215 if (km_getpubkey(p_name(p), &kx->kpub, &kx->texp_kpub))
1217 kx->f = KXF_DEAD | KXF_PUBKEY;
1223 /*----- That's all, folks -------------------------------------------------*/