3 * $Id: keyexch.c,v 1.9 2003/07/13 11:53:14 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.9 2003/07/13 11:53:14 mdw
33 * Add protocol commentary.
35 * Revision 1.8 2003/07/13 11:19:49 mdw
36 * Incopatible protocol fix! Include message type code under MAC tag to prevent
37 * cut-and-paste from key-exchange messages to general packet transport.
39 * Revision 1.7 2003/05/17 11:01:28 mdw
40 * Handle flags on challenge timers correctly to prevent confusing the event
43 * Revision 1.6 2003/04/06 10:26:35 mdw
44 * Report peer name on decrypt errors.
46 * Revision 1.5 2002/01/13 14:54:40 mdw
47 * Patch up zero-knowledge property by passing an encrypted log with a
48 * challenge, so that the prover can verify that the challenge is good.
50 * Revision 1.4 2001/06/22 19:40:36 mdw
51 * Support expiry of other peers' public keys.
53 * Revision 1.3 2001/06/19 22:07:09 mdw
56 * Revision 1.2 2001/02/16 21:24:27 mdw
57 * Rewrite for new key exchange protocol.
59 * Revision 1.1 2001/02/03 20:26:37 mdw
64 /*----- Header files ------------------------------------------------------*/
68 /*----- Brief protocol overview -------------------------------------------*
70 * Let %$G$% be a cyclic group; let %$g$% be a generator of %$G$%, and let
71 * %$q$% be the order of %$G$%; for a key %$K$%, let %$E_K(\cdot)$% denote
72 * application of the symmetric packet protocol to a message; let
73 * %$H(\cdot)$% be the random oracle. Let $\alpha \inr \{0,\ldots,q - 1\}$%
74 * be Alice's private key; let %$a = g^\alpha$% be her public key; let %$b$%
75 * be Bob's public key.
77 * At the beginning of the session, Alice chooses
79 * %$\rho_A \inr \{0, \ldots q - 1\}$%
83 * %$r_A = g^{\rho_A}$% Alice's challenge
84 * %$c_A = H(\cookie{cookie}, r_A)$% Alice's cookie
85 * %$v_A = \rho_A \xor H(\cookie{expected-reply}, r_A, r_B, b^{\rho_A})$%
86 * Alice's challenge check value
87 * %$r_B^\alpha = a^{\rho_B}$% Alice's reply
88 * %$K = r_B^{\rho_A} = r_B^{\rho_A} = g^{\rho_A\rho_B}$%
89 * Alice and Bob's shared secret key
90 * %$w_A = H(\cookie{switch-request}, c_A, c_B)$%
91 * Alice's switch request value
92 * %$u_A = H(\cookie{switch-confirm}, c_A, c_B)$%
93 * Alice's switch confirm value
95 * The messages are then:
97 * %$\cookie{kx-pre-challenge}, r_A$%
98 * Initial greeting. In state @KXS_CHAL@.
100 * %$\cookie{kx-cookie}, r_A, c_B$%
101 * My table is full but I got your message.
103 * %$\cookie{kx-challenge}, r_A, c_B, v_A$%
104 * Here's a full challenge for you to answer.
106 * %$\cookie{kx-reply}, c_A, c_B, v_A, E_K(r_B^\alpha))$%
107 * Challenge accpeted: here's the answer. Commit to my challenge. Move
110 * %$\cookie{kx-switch}, c_A, c_B, E_K(r_B^\alpha, w_A))$%
111 * Reply received: here's my reply. Committed; send data; move to
114 * %$\cookie{kx-switch-ok}, E_K(u_A))$%
115 * Switch received. Committed; send data; move to @KXS_SWITCH@.
118 /*----- Tunable parameters ------------------------------------------------*/
120 #define T_VALID MIN(2) /* Challenge validity period */
121 #define T_RETRY SEC(10) /* Challenge retransmit interval */
123 #define ISVALID(kx, now) ((now) < (kx)->t_valid)
125 /*----- Various utilities -------------------------------------------------*/
127 /* --- @hashmp@ --- *
129 * Arguments: @HASH_CTX *r@ = pointer to hash context
130 * @mp *m@ = pointer to multiprecision integer
134 * Use: Adds the hash of a multiprecision integer to the context.
138 static void hashmp(HASH_CTX *r, mp *m)
141 buf_init(&b, buf_t, sizeof(buf_t));
144 HASH(r, BBASE(&b), BLEN(&b));
147 /* --- @mpcrypt@ --- *
149 * Arguments: @mp *d@ = the destination integer
150 * @mp *x@ = the plaintext/ciphertext integer
151 * @size_t sz@ = the expected size of the plaintext
152 * @const octet *k@ = pointer to key material
153 * @size_t ksz@ = size of the key
155 * Returns: The encrypted/decrypted integer.
157 * Use: Encrypts (or decrypts) a multiprecision integer using another
158 * multiprecision integer as the key. This is a slightly grotty
159 * way to do this, but it's easier than the alternatives.
162 static mp *mpcrypt(mp *d, mp *x, size_t sz, const octet *k, size_t ksz)
166 MGF_INIT(&m, k, ksz, 0);
167 mp_storeb(x, buf_t, sz);
168 MGF_CRYPT(&m, buf_t, buf_t, sz);
169 return (mp_loadb(d, buf_t, sz));
174 * Arguments: @struct timeval *tv@ = the current time
175 * @void *v@ = pointer to key exchange context
179 * Use: Acts when the key exchange timer goes off.
182 static void timer(struct timeval *tv, void *v)
186 T( trace(T_KEYEXCH, "keyexch: timer has popped"); )
190 /* --- @settimer@ --- *
192 * Arguments: @keyexch *kx@ = pointer to key exchange context
193 * @time_t t@ = when to set the timer for
197 * Use: Sets the timer for the next key exchange attempt.
200 static void settimer(keyexch *kx, time_t t)
203 if (kx->f & KXF_TIMER)
207 sel_addtimer(&sel, &kx->t, &tv, timer, kx);
211 /*----- Challenge management ----------------------------------------------*/
213 /* --- Notes on challenge management --- *
215 * We may get multiple different replies to our key exchange; some will be
216 * correct, some inserted by attackers. Up until @KX_THRESH@, all challenges
217 * received will be added to the table and given a full response. After
218 * @KX_THRESH@ distinct challenges are received, we return only a `cookie':
219 * our existing challenge, followed by a hash of the sender's challenge. We
220 * do %%\emph{not}%% give a bare challenge a reply slot at this stage. All
221 * properly-formed cookies are assigned a table slot: if none is spare, a
222 * used slot is randomly selected and destroyed. A cookie always receives a
226 /* --- @kxc_destroy@ --- *
228 * Arguments: @kxchal *kxc@ = pointer to the challenge block
232 * Use: Disposes of a challenge block.
235 static void kxc_destroy(kxchal *kxc)
237 if (kxc->f & KXF_TIMER)
238 sel_rmtimer(&kxc->t);
246 /* --- @kxc_stoptimer@ --- *
248 * Arguments: @kxchal *kxc@ = pointer to the challenge block
252 * Use: Stops the challenge's retry timer from sending messages.
253 * Useful when the state machine is in the endgame of the
257 static void kxc_stoptimer(kxchal *kxc)
259 if (kxc->f & KXF_TIMER)
260 sel_rmtimer(&kxc->t);
261 kxc->f &= ~KXF_TIMER;
264 /* --- @kxc_new@ --- *
266 * Arguments: @keyexch *kx@ = pointer to key exchange block
268 * Returns: A pointer to the challenge block.
270 * Use: Returns a pointer to a new challenge block to fill in.
273 static kxchal *kxc_new(keyexch *kx)
278 /* --- If we're over reply threshold, discard one at random --- */
280 if (kx->nr < KX_NCHAL)
283 i = rand_global.ops->range(&rand_global, KX_NCHAL);
284 kxc_destroy(kx->r[i]);
287 /* --- Fill in the new structure --- */
289 kxc = CREATE(kxchal);
300 /* --- @kxc_bychal@ --- *
302 * Arguments: @keyexch *kx@ = pointer to key exchange block
303 * @mp *c@ = challenge from remote host
305 * Returns: Pointer to the challenge block, or null.
307 * Use: Finds a challenge block, given its challenge.
310 static kxchal *kxc_bychal(keyexch *kx, mp *c)
314 for (i = 0; i < kx->nr; i++) {
315 if (MP_EQ(c, kx->r[i]->c))
321 /* --- @kxc_byhc@ --- *
323 * Arguments: @keyexch *kx@ = pointer to key exchange block
324 * @const octet *hc@ = challenge hash from remote host
326 * Returns: Pointer to the challenge block, or null.
328 * Use: Finds a challenge block, given a hash of its challenge.
331 static kxchal *kxc_byhc(keyexch *kx, const octet *hc)
335 for (i = 0; i < kx->nr; i++) {
336 if (memcmp(hc, kx->r[i]->hc, HASHSZ) == 0)
342 /* --- @kxc_answer@ --- *
344 * Arguments: @keyexch *kx@ = pointer to key exchange block
345 * @kxchal *kxc@ = pointer to challenge block
349 * Use: Sends a reply to the remote host, according to the data in
350 * this challenge block.
353 static void kxc_answer(keyexch *kx, kxchal *kxc);
355 static void kxc_timer(struct timeval *tv, void *v)
358 kxc->f &= ~KXF_TIMER;
359 kxc_answer(kxc->kx, kxc);
362 static void kxc_answer(keyexch *kx, kxchal *kxc)
364 stats *st = p_stats(kx->p);
365 buf *b = p_txstart(kx->p, MSG_KEYEXCH | (kxc->r ? KX_REPLY : KX_CHAL));
369 /* --- Build the reply packet --- */
374 buf_put(b, kx->hc, HASHSZ);
375 buf_put(b, kxc->hc, HASHSZ);
376 buf_putmp(b, kxc->ck);
378 /* --- Maybe send an actual reply, if we have one --- */
381 T( trace(T_KEYEXCH, "keyexch: resending challenge to `%s'",
384 T( trace(T_KEYEXCH, "keyexch: sending reply to `%s'", p_name(kx->p)); )
385 buf_init(&bb, buf_i, sizeof(buf_i));
386 buf_putmp(&bb, kxc->r);
388 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_REPLY, &bb, b);
391 /* --- Update the statistics --- */
395 st->sz_kxout += BLEN(b);
399 /* --- Schedule another resend --- */
401 if (kxc->f & KXF_TIMER)
402 sel_rmtimer(&kxc->t);
403 gettimeofday(&tv, 0);
404 tv.tv_sec += T_RETRY;
405 sel_addtimer(&sel, &kxc->t, &tv, kxc_timer, kxc);
409 /*----- Individual message handlers ---------------------------------------*/
411 /* --- @getreply@ --- *
413 * Arguments: @keyexch *kx@ = pointer to key exchange context
414 * @mp *c@ = a challenge
415 * @mp *ck@ = the supplied expected-reply check value
417 * Returns: A pointer to the reply, or null if the reply-hash was wrong.
419 * Use: Computes replies to challenges.
422 static mp *getreply(keyexch *kx, mp *c, mp *ck)
424 mp *r = mpmont_exp(&mg, MP_NEW, c, kpriv.x);
431 HASH_STRING(&h, "tripe-expected-reply");
437 a = mpcrypt(MP_NEW, ck, mp_octets(kpriv.dp.q), buf, sizeof(buf));
438 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
439 trace(T_CRYPTO, "crypto: computed reply = %s", mpstr(r));
440 trace_block(T_CRYPTO, "crypto: computed reply hash", buf, HASHSZ);
441 trace(T_CRYPTO, "crypto: recovered log = %s", mpstr(a));
443 a = mpmont_exp(&mg, a, kpriv.dp.g, a);
446 a_warn("invalid expected-reply check from `%s'", p_name(kx->p));
447 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
448 trace(T_CRYPTO, "crypto: computed challenge = %s", mpstr(a));
456 /* --- @dochallenge@ --- *
458 * Arguments: @keyexch *kx@ = pointer to key exchange block
459 * @unsigned msg@ = message code for the packet
460 * @buf *b@ = buffer containing the packet
462 * Returns: Zero if OK, nonzero if the packet was rejected.
464 * Use: Processes a packet containing a challenge.
467 static int dochallenge(keyexch *kx, unsigned msg, buf *b)
475 /* --- Ensure that we're in a sensible state --- */
477 if (kx->s != KXS_CHAL) {
478 a_warn("unexpected challenge from `%s'", p_name(kx->p));
482 /* --- Unpack the packet --- */
484 if ((c = buf_getmp(b)) == 0 ||
485 (msg >= KX_COOKIE && (hc = buf_get(b, HASHSZ)) == 0) ||
486 (msg >= KX_CHAL && (ck = buf_getmp(b)) == 0) ||
488 a_warn("malformed packet from `%s'", p_name(kx->p));
492 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
493 trace(T_CRYPTO, "crypto: challenge = %s", mpstr(c));
494 if (hc) trace_block(T_CRYPTO, "crypto: cookie", hc, HASHSZ);
495 if (ck) trace(T_CRYPTO, "crypto: check value = %s", mpstr(ck));
498 /* --- First, handle a bare challenge --- *
500 * If the table is heavily loaded, just emit a cookie and return.
503 if (!hc && kx->nr >= KX_THRESH) {
504 T( trace(T_KEYEXCH, "keyexch: too many challenges -- sending cookie"); )
505 b = p_txstart(kx->p, MSG_KEYEXCH | KX_COOKIE);
508 HASH_STRING(&h, "tripe-cookie");
510 HASH_DONE(&h, buf_get(b, HASHSZ));
515 /* --- Discard a packet with an invalid cookie --- */
517 if (hc && memcmp(hc, kx->hc, HASHSZ) != 0) {
518 a_warn("incorrect cookie from `%s'", p_name(kx->p));
522 /* --- Find a challenge block for this packet --- *
524 * If there isn't one already, create a new one.
527 if ((kxc = kxc_bychal(kx, c)) == 0) {
531 /* --- Be careful here --- *
533 * If this is a full challenge, and it's the first time I've seen it, I
534 * want to be able to throw it away before committing a table entry to
541 if ((r = getreply(kx, c, ck)) == 0)
548 /* --- Work out the cookie for this challenge --- */
551 HASH_STRING(&h, "tripe-cookie");
553 HASH_DONE(&h, kxc->hc);
555 /* --- Compute the expected-reply hash --- */
558 HASH_STRING(&h, "tripe-expected-reply");
563 kxc->ck = mpcrypt(MP_NEW, kx->alpha, mp_octets(kpriv.dp.q),
566 /* --- Work out the shared key --- */
568 trace(T_CRYPTO, "debug: c = %s", mpstr(c));
569 trace(T_CRYPTO, "debug: alpha = %s", mpstr(kx->alpha));
570 r = mpmont_exp(&mg, MP_NEW, c, kx->alpha);
571 trace(T_CRYPTO, "debug: r = %s", mpstr(r));
573 /* --- Compute the switch messages --- */
575 HASH_INIT(&h); HASH_STRING(&h, "tripe-switch-request");
576 hashmp(&h, kx->c); hashmp(&h, kxc->c);
577 HASH_DONE(&h, kxc->hswrq_out);
578 HASH_INIT(&h); HASH_STRING(&h, "tripe-switch-confirm");
579 hashmp(&h, kx->c); hashmp(&h, kxc->c);
580 HASH_DONE(&h, kxc->hswok_out);
582 HASH_INIT(&h); HASH_STRING(&h, "tripe-switch-request");
583 hashmp(&h, kxc->c); hashmp(&h, kx->c);
584 HASH_DONE(&h, kxc->hswrq_in);
585 HASH_INIT(&h); HASH_STRING(&h, "tripe-switch-confirm");
586 hashmp(&h, kxc->c); hashmp(&h, kx->c);
587 HASH_DONE(&h, kxc->hswok_in);
589 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
590 trace_block(T_CRYPTO, "crypto: computed cookie", kxc->hc, HASHSZ);
591 trace_block(T_CRYPTO, "crypto: expected-reply hash",
593 trace(T_CRYPTO, "crypto: my reply check = %s", mpstr(kxc->ck));
594 trace(T_CRYPTO, "crypto: shared secret = %s", mpstr(r));
595 trace_block(T_CRYPTO, "crypto: outbound switch request",
596 kxc->hswrq_out, HASHSZ);
597 trace_block(T_CRYPTO, "crypto: outbound switch confirm",
598 kxc->hswok_out, HASHSZ);
599 trace_block(T_CRYPTO, "crypto: inbound switch request",
600 kxc->hswrq_in, HASHSZ);
601 trace_block(T_CRYPTO, "crypto: inbound switch confirm",
602 kxc->hswok_in, HASHSZ);
605 /* --- Create a new symmetric keyset --- */
607 buf_init(b, buf_o, sizeof(buf_o));
608 buf_putmp(b, kx->c); x = BLEN(b);
609 buf_putmp(b, kxc->c); y = BLEN(b);
610 buf_putmp(b, r); z = BLEN(b);
613 kxc->ks = ks_gen(BBASE(b), x, y, z, kx->p);
617 /* --- Answer the challenge if we need to --- */
621 if ((r = getreply(kx, c, ck)) == 0)
628 /* --- Tidy up and go home --- */
641 /* --- @resend@ --- *
643 * Arguments: @keyexch *kx@ = pointer to key exchange context
647 * Use: Sends the next message for a key exchange.
650 static void resend(keyexch *kx)
654 stats *st = p_stats(kx->p);
659 T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
661 b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
665 T( trace(T_KEYEXCH, "keyexch: sending switch request to `%s'",
668 b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCH);
669 buf_put(b, kx->hc, HASHSZ);
670 buf_put(b, kxc->hc, HASHSZ);
671 buf_init(&bb, buf_i, sizeof(buf_i));
672 buf_putmp(&bb, kxc->r);
673 buf_put(&bb, kxc->hswrq_out, HASHSZ);
675 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCH, &bb, b);
678 T( trace(T_KEYEXCH, "keyexch: sending switch confirmation to `%s'",
681 b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCHOK);
682 buf_init(&bb, buf_i, sizeof(buf_i));
683 buf_put(&bb, kxc->hswok_out, HASHSZ);
685 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, &bb, b);
693 st->sz_kxout += BLEN(b);
697 if (kx->s < KXS_SWITCH)
698 settimer(kx, time(0) + T_RETRY);
701 /* --- @matchreply@ --- *
703 * Arguments: @keyexch *kx@ = pointer to key exchange context
704 * @unsigned ty@ = type of incoming message
705 * @const octet *hc_in@ = a hash of his challenge
706 * @const octet *hc_out@ = a hash of my challenge (cookie)
707 * @mp *ck@ = his expected-reply hash (optional)
708 * @buf *b@ = encrypted remainder of the packet
710 * Returns: A pointer to the challenge block if OK, or null on failure.
712 * Use: Checks a reply or switch packet, ensuring that its contents
713 * are sensible and correct. If they are, @*b@ is set to point
714 * to the remainder of the encrypted data, and the correct
715 * challenge is returned.
718 static kxchal *matchreply(keyexch *kx, unsigned ty, const octet *hc_in,
719 const octet *hc_out, mp *ck, buf *b)
725 /* --- Check the plaintext portions of the data --- */
727 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
728 trace_block(T_CRYPTO, "crypto: challenge", hc_in, HASHSZ);
729 trace_block(T_CRYPTO, "crypto: cookie", hc_out, HASHSZ);
730 if (ck) trace(T_CRYPTO, "crypto: check value = %s", mpstr(ck));
732 if (memcmp(hc_out, kx->hc, HASHSZ) != 0) {
733 a_warn("incorrect cookie from `%s'", p_name(kx->p));
736 if ((kxc = kxc_byhc(kx, hc_in)) == 0) {
737 a_warn("received reply for unknown challenge from `%s'", p_name(kx->p));
741 /* --- Maybe compute a reply for the challenge --- */
745 a_warn("unexpected switch request from `%s'", p_name(kx->p));
748 if ((r = getreply(kx, kxc->c, ck)) == 0)
754 /* --- Decrypt the rest of the packet --- */
756 buf_init(&bb, buf_o, sizeof(buf_o));
757 if (ks_decrypt(kxc->ks, ty, b, &bb)) {
758 a_warn("failed to decrypt reply from `%s'", p_name(kx->p));
761 buf_init(b, BBASE(&bb), BLEN(&bb));
762 if ((r = buf_getmp(b)) == 0) {
763 a_warn("invalid reply packet from `%s'", p_name(kx->p));
766 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
767 trace(T_CRYPTO, "crypto: reply = %s", mpstr(r));
769 if (!mp_eq(r, kx->rx)) {
770 a_warn("incorrect reply from `%s'", p_name(kx->p));
784 /* --- @commit@ --- *
786 * Arguments: @keyexch *kx@ = pointer to key exchange context
787 * @kxchal *kxc@ = pointer to challenge to commit to
791 * Use: Commits to a particular challenge as being the `right' one,
792 * since a reply has arrived for it.
795 static void commit(keyexch *kx, kxchal *kxc)
799 for (i = 0; i < kx->nr; i++) {
801 kxc_destroy(kx->r[i]);
806 ksl_link(kx->ks, kxc->ks);
809 /* --- @doreply@ --- *
811 * Arguments: @keyexch *kx@ = pointer to key exchange context
812 * @buf *b@ = buffer containing packet
814 * Returns: Zero if OK, nonzero if the packet was rejected.
816 * Use: Handles a reply packet. This doesn't handle the various
817 * switch packets: they're rather too different.
820 static int doreply(keyexch *kx, buf *b)
822 const octet *hc_in, *hc_out;
826 if (kx->s != KXS_CHAL && kx->s != KXS_COMMIT) {
827 a_warn("unexpected reply from `%s'", p_name(kx->p));
830 if ((hc_in = buf_get(b, HASHSZ)) == 0 ||
831 (hc_out = buf_get(b, HASHSZ)) == 0 ||
832 (ck = buf_getmp(b)) == 0) {
833 a_warn("invalid reply packet from `%s'", p_name(kx->p));
836 if ((kxc = matchreply(kx, MSG_KEYEXCH | KX_REPLY,
837 hc_in, hc_out, ck, b)) == 0)
840 a_warn("invalid reply packet from `%s'", p_name(kx->p));
843 if (kx->s == KXS_CHAL) {
855 /* --- @doswitch@ --- *
857 * Arguments: @keyexch *kx@ = pointer to key exchange block
858 * @buf *b@ = pointer to buffer containing packet
860 * Returns: Zero if OK, nonzero if the packet was rejected.
862 * Use: Handles a reply with a switch request bolted onto it.
865 static int doswitch(keyexch *kx, buf *b)
867 const octet *hc_in, *hc_out, *hswrq;
870 if ((hc_in = buf_get(b, HASHSZ)) == 0 ||
871 (hc_out = buf_get(b, HASHSZ)) == 0) {
872 a_warn("invalid switch request from `%s'", p_name(kx->p));
875 if ((kxc = matchreply(kx, MSG_KEYEXCH | KX_SWITCH,
876 hc_in, hc_out, 0, b)) == 0)
878 if ((hswrq = buf_get(b, HASHSZ)) == 0 || BLEFT(b)) {
879 a_warn("invalid switch request from `%s'", p_name(kx->p));
882 IF_TRACING(T_KEYEXCH, {
883 trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, HASHSZ);
885 if (memcmp(hswrq, kxc->hswrq_in, HASHSZ) != 0) {
886 a_warn("incorrect switch request hash from `%s'", p_name(kx->p));
893 ks_activate(kxc->ks);
894 settimer(kx, ks_tregen(kxc->ks));
905 /* --- @doswitchok@ --- *
907 * Arguments: @keyexch *kx@ = pointer to key exchange block
908 * @buf *b@ = pointer to buffer containing packet
910 * Returns: Zero if OK, nonzero if the packet was rejected.
912 * Use: Handles a reply with a switch request bolted onto it.
915 static int doswitchok(keyexch *kx, buf *b)
921 if (kx->s < KXS_COMMIT) {
922 a_warn("unexpected switch confirmation from `%s'", p_name(kx->p));
926 buf_init(&bb, buf_o, sizeof(buf_o));
927 if (ks_decrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, b, &bb)) {
928 a_warn("failed to decrypt switch confirmation from `%s'", p_name(kx->p));
931 buf_init(b, BBASE(&bb), BLEN(&bb));
932 if ((hswok = buf_get(b, HASHSZ)) == 0 || BLEFT(b)) {
933 a_warn("invalid switch confirmation from `%s'", p_name(kx->p));
936 IF_TRACING(T_KEYEXCH, {
937 trace_block(T_CRYPTO, "crypto: switch confirmation hash", hswok, HASHSZ);
939 if (memcmp(hswok, kxc->hswok_in, HASHSZ) != 0) {
940 a_warn("incorrect switch confirmation hash from `%s'", p_name(kx->p));
943 if (kx->s < KXS_SWITCH) {
944 ks_activate(kxc->ks);
945 settimer(kx, ks_tregen(kxc->ks));
954 /*----- Main code ---------------------------------------------------------*/
958 * Arguments: @keyexch *kx@ = pointer to key exchange context
962 * Use: Stops a key exchange dead in its tracks. Throws away all of
963 * the context information. The context is left in an
964 * inconsistent state. The only functions which understand this
965 * state are @kx_free@ and @kx_init@ (which cause it internally
966 * it), and @start@ (which expects it to be the prevailing
970 static void stop(keyexch *kx)
974 if (kx->f & KXF_DEAD)
977 if (kx->f & KXF_TIMER)
979 for (i = 0; i < kx->nr; i++)
980 kxc_destroy(kx->r[i]);
991 * Arguments: @keyexch *kx@ = pointer to key exchange context
992 * @time_t now@ = the current time
996 * Use: Starts a new key exchange with the peer. The context must be
997 * in the bizarre state left by @stop@ or @kx_init@.
1000 static void start(keyexch *kx, time_t now)
1004 assert(kx->f & KXF_DEAD);
1008 kx->alpha = mprand_range(MP_NEW, kpriv.dp.q, &rand_global, 0);
1009 kx->c = mpmont_exp(&mg, MP_NEW, kpriv.dp.g, kx->alpha);
1010 kx->rx = mpmont_exp(&mg, MP_NEW, kx->kpub.y, kx->alpha);
1012 kx->t_valid = now + T_VALID;
1015 HASH_STRING(&h, "tripe-cookie");
1017 HASH_DONE(&h, kx->hc);
1019 IF_TRACING(T_KEYEXCH, {
1020 trace(T_KEYEXCH, "keyexch: creating new challenge");
1021 IF_TRACING(T_CRYPTO, {
1022 trace(T_CRYPTO, "crypto: secret = %s", mpstr(kx->alpha));
1023 trace(T_CRYPTO, "crypto: challenge = %s", mpstr(kx->c));
1024 trace(T_CRYPTO, "crypto: expected response = %s", mpstr(kx->rx));
1025 trace_block(T_CRYPTO, "crypto: challenge cookie", kx->hc, HASHSZ);
1030 /* --- @checkpub@ --- *
1032 * Arguments: @keyexch *kx@ = pointer to key exchange context
1034 * Returns: Zero if OK, nonzero if the peer's public key has expired.
1036 * Use: Deactivates the key-exchange until the peer acquires a new
1040 static int checkpub(keyexch *kx)
1043 if (kx->f & KXF_DEAD)
1046 if (KEY_EXPIRED(now, kx->texp_kpub)) {
1048 a_warn("public key for `%s' has expired", p_name(kx->p));
1049 dh_pubfree(&kx->kpub);
1050 kx->f &= ~KXF_PUBKEY;
1056 /* --- @kx_start@ --- *
1058 * Arguments: @keyexch *kx@ = pointer to key exchange context
1062 * Use: Stimulates a key exchange. If a key exchage is in progress,
1063 * a new challenge is sent (unless the quiet timer forbids
1064 * this); if no exchange is in progress, one is commenced.
1067 void kx_start(keyexch *kx)
1069 time_t now = time(0);
1073 if (!ISVALID(kx, now)) {
1080 /* --- @kx_message@ --- *
1082 * Arguments: @keyexch *kx@ = pointer to key exchange context
1083 * @unsigned msg@ = the message code
1084 * @buf *b@ = pointer to buffer containing the packet
1088 * Use: Reads a packet containing key exchange messages and handles
1092 void kx_message(keyexch *kx, unsigned msg, buf *b)
1094 time_t now = time(0);
1095 stats *st = p_stats(kx->p);
1100 static const char *const pkname[] = {
1101 "prechallenge", "cookie", "challenge",
1102 "reply", "switch request", "switch confirmation"
1109 if (!ISVALID(kx, now)) {
1114 T( trace(T_KEYEXCH, "keyexch: processing %s packet from `%s'",
1115 msg < KX_NMSG ? pkname[msg] : "unknown", p_name(kx->p)); )
1121 rc = dochallenge(kx, msg, b);
1124 rc = doreply(kx, b);
1127 rc = doswitch(kx, b);
1130 rc = doswitchok(kx, b);
1133 a_warn("unexpected key exchange message type %u from `%p'",
1147 /* --- @kx_free@ --- *
1149 * Arguments: @keyexch *kx@ = pointer to key exchange context
1153 * Use: Frees everything in a key exchange context.
1156 void kx_free(keyexch *kx)
1159 if (kx->f & KXF_PUBKEY)
1160 dh_pubfree(&kx->kpub);
1163 /* --- @kx_newkeys@ --- *
1165 * Arguments: @keyexch *kx@ = pointer to key exchange context
1169 * Use: Informs the key exchange module that its keys may have
1170 * changed. If fetching the new keys fails, the peer will be
1171 * destroyed, we log messages and struggle along with the old
1175 void kx_newkeys(keyexch *kx)
1179 if (km_getpubkey(p_name(kx->p), &dp, &kx->texp_kpub))
1181 if (kx->f & KXF_PUBKEY)
1182 dh_pubfree(&kx->kpub);
1184 kx->f |= KXF_PUBKEY;
1185 if ((kx->f & KXF_DEAD) || kx->s != KXS_SWITCH) {
1186 T( trace(T_KEYEXCH, "keyexch: restarting key negotiation with `%s'",
1194 /* --- @kx_init@ --- *
1196 * Arguments: @keyexch *kx@ = pointer to key exchange context
1197 * @peer *p@ = pointer to peer context
1198 * @keyset **ks@ = pointer to keyset list
1200 * Returns: Zero if OK, nonzero if it failed.
1202 * Use: Initializes a key exchange module. The module currently
1203 * contains no keys, and will attempt to initiate a key
1207 int kx_init(keyexch *kx, peer *p, keyset **ks)
1211 if (km_getpubkey(p_name(p), &kx->kpub, &kx->texp_kpub))
1213 kx->f = KXF_DEAD | KXF_PUBKEY;
1219 /*----- That's all, folks -------------------------------------------------*/