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
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * TrIPE is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 /*----- Header files ------------------------------------------------------*/
31 /*----- Brief protocol overview -------------------------------------------*
33 * Let %$G$% be a cyclic group; let %$g$% be a generator of %$G$%, and let
34 * %$q$% be the order of %$G$%; for a key %$K$%, let %$E_K(\cdot)$% denote
35 * application of the symmetric packet protocol to a message; let
36 * %$H(\cdot)$% be the random oracle. Let $\alpha \inr \{0,\ldots,q - 1\}$%
37 * be Alice's private key; let %$a = g^\alpha$% be her public key; let %$b$%
38 * be Bob's public key.
40 * At the beginning of the session, Alice chooses
42 * %$\rho_A \inr \{0, \ldots q - 1\}$%
46 * %$r_A = g^{\rho_A}$% Alice's challenge
47 * %$c_A = H(\cookie{cookie}, r_A)$% Alice's cookie
48 * %$v_A = \rho_A \xor H(\cookie{expected-reply}, a, r_A, r_B, b^{\rho_A})$%
49 * Alice's challenge check value
50 * %$r_B^\alpha = a^{\rho_B}$% Alice's reply
51 * %$K = r_B^{\rho_A} = r_B^{\rho_A} = g^{\rho_A\rho_B}$%
52 * Alice and Bob's shared secret key
53 * %$w_A = H(\cookie{switch-request}, c_A, c_B)$%
54 * Alice's switch request value
55 * %$u_A = H(\cookie{switch-confirm}, c_A, c_B)$%
56 * Alice's switch confirm value
58 * The messages are then:
60 * %$\cookie{kx-pre-challenge}, r_A$%
61 * Initial greeting. In state @KXS_CHAL@.
63 * %$\cookie{kx-challenge}, r_A, c_B, v_A$%
64 * Here's a full challenge for you to answer.
66 * %$\cookie{kx-reply}, r_A, c_B, v_A, E_K(r_B^\alpha))$%
67 * Challenge accpeted: here's the answer. Commit to my challenge. Move
70 * %$\cookie{kx-switch-rq}, c_A, c_B, E_K(r_B^\alpha, w_A))$%
71 * Reply received: here's my reply. Committed; send data; move to
74 * %$\cookie{kx-switch-ok}, E_K(u_A))$%
75 * Switch received. Committed; send data; move to @KXS_SWITCH@.
78 /*----- Tunable parameters ------------------------------------------------*/
80 #define T_VALID SEC(20) /* Challenge validity period */
81 #define T_RETRY SEC(10) /* Challenge retransmit interval */
83 #define VALIDP(kx, now) ((now) < (kx)->t_valid)
85 /*----- Static tables -----------------------------------------------------*/
87 static const char *const pkname[] = {
88 "pre-challenge", "challenge", "reply", "switch-rq", "switch-ok"
91 /*----- Various utilities -------------------------------------------------*/
95 * Arguments: @ghash *h@ = pointer to hash context
96 * @group *g@ = pointer to group
97 * @ge *x@ = pointer to group element
101 * Use: Adds the hash of a group element to the context. Corrupts
105 static void hashge(ghash *h, group *g, ge *x)
109 buf_init(&b, buf_t, sizeof(buf_t));
112 GH_HASH(h, BBASE(&b), BLEN(&b));
115 /* --- @mpmask@ --- *
117 * Arguments: @buf *b@ = output buffer
118 * @mp *x@ = the plaintext integer
119 * @size_t n@ = the expected size of the plaintext
120 * @gcipher *mgfc@ = mask-generating function to use
121 * @const octet *k@ = pointer to key material
122 * @size_t ksz@ = size of the key
124 * Returns: Pointer to the output.
126 * Use: Masks a multiprecision integer: returns %$x \xor H(k)$%, so
127 * it's a random oracle thing rather than an encryption thing.
130 static octet *mpmask(buf *b, mp *x, size_t n,
131 const gccipher *mgfc, const octet *k, size_t ksz)
136 if ((p = buf_get(b, n)) == 0)
138 mgf = GC_INIT(mgfc, k, ksz);
139 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
140 trace(T_CRYPTO, "crypto: masking index = %s", mpstr(x));
141 trace_block(T_CRYPTO, "crypto: masking key", k, ksz);
143 mp_storeb(x, buf_t, n);
144 GC_ENCRYPT(mgf, buf_t, p, n);
145 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
146 trace_block(T_CRYPTO, "crypto: index plaintext", buf_t, n);
147 trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
153 /* --- @mpunmask@ --- *
155 * Arguments: @mp *d@ = the output integer
156 * @const octet *p@ = pointer to the ciphertext
157 * @size_t n@ = the size of the ciphertext
158 * @gcipher *mgfc@ = mask-generating function to use
159 * @const octet *k@ = pointer to key material
160 * @size_t ksz@ = size of the key
162 * Returns: The decrypted integer, or null.
164 * Use: Unmasks a multiprecision integer.
167 static mp *mpunmask(mp *d, const octet *p, size_t n,
168 const gccipher *mgfc, const octet *k, size_t ksz)
172 mgf = GC_INIT(mgfc, k, ksz);
173 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
174 trace_block(T_CRYPTO, "crypto: unmasking key", k, ksz);
175 trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
177 GC_DECRYPT(mgf, p, buf_t, n);
178 d = mp_loadb(d, buf_t, n);
179 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
180 trace_block(T_CRYPTO, "crypto: index plaintext", buf_t, n);
181 trace(T_CRYPTO, "crypto: unmasked index = %s", mpstr(d));
187 /* --- @hashcheck@ --- *
189 * Arguments: @keyexch *kx@ = pointer to key-exchange block
190 * @ge *kpub@ = sender's public key
191 * @ge *cc@ = receiver's challenge
192 * @ge *c@ = sender's challenge
193 * @ge *y@ = reply to sender's challenge
195 * Returns: Pointer to the hash value (in @buf_t@)
197 * Use: Computes the check-value hash, used to mask or unmask
198 * indices to prove the validity of challenges. This computes
199 * the masking key used in challenge check values. This is
200 * really the heart of the whole thing, since it ensures that
201 * the index can be recovered from the history of hashing
202 * queries, which gives us (a) a proof that the authentication
203 * process is zero-knowledge, and (b) a proof that the whole
204 * key-exchange is deniable.
207 static const octet *hashcheck(keyexch *kx, ge *kpub, ge *cc, ge *c, ge *y)
209 ghash *h = GH_INIT(kx->kpriv->algs.h);
210 group *g = kx->kpriv->g;
212 HASH_STRING(h, "tripe-expected-reply");
218 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
219 trace(T_CRYPTO, "crypto: computing challenge check hash");
220 trace(T_CRYPTO, "crypto: public key = %s", gestr(g, kpub));
221 trace(T_CRYPTO, "crypto: receiver challenge = %s", gestr(g, cc));
222 trace(T_CRYPTO, "crypto: sender challenge = %s", gestr(g, c));
223 trace(T_CRYPTO, "crypto: sender reply = %s", gestr(g, y));
224 trace_block(T_CRYPTO, "crypto: hash output", buf_t, kx->kpriv->algs.hashsz);
230 /* --- @sendchallenge@ --- *
232 * Arguments: @keyexch *kx@ = pointer to key exchange block
233 * @buf *b@ = output buffer for challenge
234 * @ge *c@ = peer's actual challenge
235 * @const octet *hc@ = peer's challenge cookie
239 * Use: Writes a full challenge to the message buffer.
242 static void sendchallenge(keyexch *kx, buf *b, ge *c, const octet *hc)
244 G_TOBUF(kx->kpriv->g, b, kx->c);
245 buf_put(b, hc, kx->kpriv->algs.hashsz);
246 mpmask(b, kx->alpha, kx->kpriv->indexsz, kx->kpriv->algs.mgf,
247 hashcheck(kx, kx->kpriv->kpub, c, kx->c, kx->rx),
248 kx->kpriv->algs.hashsz);
253 * Arguments: @struct timeval *tv@ = the current time
254 * @void *v@ = pointer to key exchange context
258 * Use: Acts when the key exchange timer goes off.
261 static void timer(struct timeval *tv, void *v)
265 T( trace(T_KEYEXCH, "keyexch: timer has popped"); )
269 /* --- @settimer@ --- *
271 * Arguments: @keyexch *kx@ = pointer to key exchange context
272 * @time_t t@ = when to set the timer for
276 * Use: Sets the timer for the next key exchange attempt.
279 static void settimer(keyexch *kx, time_t t)
282 if (kx->f & KXF_TIMER)
286 sel_addtimer(&sel, &kx->t, &tv, timer, kx);
290 /*----- Challenge management ----------------------------------------------*/
292 /* --- Notes on challenge management --- *
294 * We may get multiple different replies to our key exchange; some will be
295 * correct, some inserted by attackers. Up until @KX_THRESH@, all challenges
296 * received will be added to the table and given a full response. After
297 * @KX_THRESH@ distinct challenges are received, we return only a `cookie':
298 * our existing challenge, followed by a hash of the sender's challenge. We
299 * do %%\emph{not}%% give a bare challenge a reply slot at this stage. All
300 * properly-formed cookies are assigned a table slot: if none is spare, a
301 * used slot is randomly selected and destroyed. A cookie always receives a
305 /* --- @kxc_destroy@ --- *
307 * Arguments: @kxchal *kxc@ = pointer to the challenge block
311 * Use: Disposes of a challenge block.
314 static void kxc_destroy(kxchal *kxc)
316 if (kxc->f & KXF_TIMER)
317 sel_rmtimer(&kxc->t);
318 G_DESTROY(kxc->kx->kpriv->g, kxc->c);
319 G_DESTROY(kxc->kx->kpriv->g, kxc->r);
324 /* --- @kxc_stoptimer@ --- *
326 * Arguments: @kxchal *kxc@ = pointer to the challenge block
330 * Use: Stops the challenge's retry timer from sending messages.
331 * Useful when the state machine is in the endgame of the
335 static void kxc_stoptimer(kxchal *kxc)
337 if (kxc->f & KXF_TIMER)
338 sel_rmtimer(&kxc->t);
339 kxc->f &= ~KXF_TIMER;
342 /* --- @kxc_new@ --- *
344 * Arguments: @keyexch *kx@ = pointer to key exchange block
346 * Returns: A pointer to the challenge block.
348 * Use: Returns a pointer to a new challenge block to fill in.
351 static kxchal *kxc_new(keyexch *kx)
356 /* --- If we're over reply threshold, discard one at random --- */
358 if (kx->nr < KX_NCHAL)
361 i = rand_global.ops->range(&rand_global, KX_NCHAL);
362 kxc_destroy(kx->r[i]);
365 /* --- Fill in the new structure --- */
367 kxc = CREATE(kxchal);
368 kxc->c = G_CREATE(kx->kpriv->g);
369 kxc->r = G_CREATE(kx->kpriv->g);
377 /* --- @kxc_bychal@ --- *
379 * Arguments: @keyexch *kx@ = pointer to key exchange block
380 * @ge *c@ = challenge from remote host
382 * Returns: Pointer to the challenge block, or null.
384 * Use: Finds a challenge block, given its challenge.
387 static kxchal *kxc_bychal(keyexch *kx, ge *c)
391 for (i = 0; i < kx->nr; i++) {
392 if (G_EQ(kx->kpriv->g, c, kx->r[i]->c))
398 /* --- @kxc_byhc@ --- *
400 * Arguments: @keyexch *kx@ = pointer to key exchange block
401 * @const octet *hc@ = challenge hash from remote host
403 * Returns: Pointer to the challenge block, or null.
405 * Use: Finds a challenge block, given a hash of its challenge.
408 static kxchal *kxc_byhc(keyexch *kx, const octet *hc)
412 for (i = 0; i < kx->nr; i++) {
413 if (memcmp(hc, kx->r[i]->hc, kx->kpriv->algs.hashsz) == 0)
419 /* --- @kxc_answer@ --- *
421 * Arguments: @keyexch *kx@ = pointer to key exchange block
422 * @kxchal *kxc@ = pointer to challenge block
426 * Use: Sends a reply to the remote host, according to the data in
427 * this challenge block.
430 static void kxc_answer(keyexch *kx, kxchal *kxc);
432 static void kxc_timer(struct timeval *tv, void *v)
435 kxc->f &= ~KXF_TIMER;
436 kxc_answer(kxc->kx, kxc);
439 static void kxc_answer(keyexch *kx, kxchal *kxc)
441 stats *st = p_stats(kx->p);
442 buf *b = p_txstart(kx->p, MSG_KEYEXCH | KX_REPLY);
446 /* --- Build the reply packet --- */
448 T( trace(T_KEYEXCH, "keyexch: sending reply to `%s'", p_name(kx->p)); )
449 sendchallenge(kx, b, kxc->c, kxc->hc);
450 buf_init(&bb, buf_i, sizeof(buf_i));
451 G_TORAW(kx->kpriv->g, &bb, kxc->r);
453 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_REPLY, &bb, b);
455 /* --- Update the statistics --- */
459 st->sz_kxout += BLEN(b);
463 /* --- Schedule another resend --- */
465 if (kxc->f & KXF_TIMER)
466 sel_rmtimer(&kxc->t);
467 gettimeofday(&tv, 0);
468 tv.tv_sec += T_RETRY;
469 sel_addtimer(&sel, &kxc->t, &tv, kxc_timer, kxc);
473 /*----- Individual message handlers ---------------------------------------*/
475 /* --- @doprechallenge@ --- *
477 * Arguments: @keyexch *kx@ = pointer to key exchange block
478 * @buf *b@ = buffer containing the packet
480 * Returns: Zero if OK, nonzero of the packet was rejected.
482 * Use: Processes a pre-challenge message.
485 static int doprechallenge(keyexch *kx, buf *b)
487 stats *st = p_stats(kx->p);
488 ge *c = G_CREATE(kx->kpriv->g);
491 /* --- Ensure that we're in a sensible state --- */
493 if (kx->s != KXS_CHAL) {
494 a_warn("KX", "?PEER", kx->p, "unexpected", "pre-challenge", A_END);
498 /* --- Unpack the packet --- */
500 if (G_FROMBUF(kx->kpriv->g, b, c) || BLEFT(b))
503 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
504 trace(T_CRYPTO, "crypto: challenge = %s", gestr(kx->kpriv->g, c));
507 /* --- Send out a full challenge by return --- */
509 b = p_txstart(kx->p, MSG_KEYEXCH | KX_CHAL);
510 h = GH_INIT(kx->kpriv->algs.h);
511 HASH_STRING(h, "tripe-cookie");
512 hashge(h, kx->kpriv->g, c);
513 sendchallenge(kx, b, c, GH_DONE(h, 0));
516 st->sz_kxout += BLEN(b);
521 G_DESTROY(kx->kpriv->g, c);
525 if (c) G_DESTROY(kx->kpriv->g, c);
529 /* --- @respond@ --- *
531 * Arguments: @keyexch *kx@ = pointer to key exchange block
532 * @unsigned msg@ = message code for this packet
533 * @buf *b@ = buffer containing the packet
535 * Returns: Key-exchange challenge block, or null.
537 * Use: Computes a response for the given challenge, entering it into
538 * a challenge block and so on.
541 static kxchal *respond(keyexch *kx, unsigned msg, buf *b)
543 group *g = kx->kpriv->g;
544 const algswitch *algs = &kx->kpriv->algs;
545 size_t ixsz = kx->kpriv->indexsz;
548 ge *cc = G_CREATE(g);
549 const octet *hc, *ck;
557 /* --- Unpack the packet --- */
559 if (G_FROMBUF(g, b, c) ||
560 (hc = buf_get(b, algs->hashsz)) == 0 ||
561 (ck = buf_get(b, ixsz)) == 0) {
562 a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
565 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
566 trace(T_CRYPTO, "crypto: challenge = %s", gestr(g, c));
567 trace_block(T_CRYPTO, "crypto: cookie", hc, algs->hashsz);
568 trace_block(T_CRYPTO, "crypto: check-value", ck, ixsz);
571 /* --- Discard a packet with an invalid cookie --- */
573 if (hc && memcmp(hc, kx->hc, algs->hashsz) != 0) {
574 a_warn("KX", "?PEER", kx->p, "incorrect", "cookie", A_END);
578 /* --- Recover the check value and verify it --- *
580 * To avoid recomputation on replays, we store a hash of the `right'
581 * value. The `correct' value is unique, so this is right.
583 * This will also find a challenge block and, if necessary, populate it.
586 if ((kxc = kxc_bychal(kx, c)) != 0) {
587 h = GH_INIT(algs->h);
588 HASH_STRING(h, "tripe-check-hash");
589 GH_HASH(h, ck, ixsz);
590 ok = !memcmp(kxc->ck, GH_DONE(h, 0), algs->hashsz);
592 if (!ok) goto badcheck;
595 /* --- Compute the reply, and check the magic --- */
597 G_EXP(g, r, c, kx->kpriv->kpriv);
598 cv = mpunmask(MP_NEW, ck, ixsz, algs->mgf,
599 hashcheck(kx, kx->kpub->kpub, kx->c, c, r),
601 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
602 trace(T_CRYPTO, "crypto: computed reply = %s", gestr(g, r));
603 trace(T_CRYPTO, "crypto: recovered log = %s", mpstr(cv));
605 if (MP_CMP(cv, >, g->r) ||
606 (G_EXP(g, cc, g->g, cv),
610 /* --- Fill in a new challenge block --- */
613 G_COPY(g, kxc->c, c);
614 G_COPY(g, kxc->r, r);
616 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-check-hash");
617 GH_HASH(h, ck, ixsz);
618 GH_DONE(h, kxc->ck); GH_DESTROY(h);
620 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-cookie");
621 hashge(h, g, kxc->c);
622 GH_DONE(h, kxc->hc); GH_DESTROY(h);
624 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
625 trace_block(T_CRYPTO, "crypto: computed cookie",
626 kxc->hc, algs->hashsz);
629 /* --- Work out the shared key --- */
631 G_EXP(g, r, c, kx->alpha);
632 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
633 trace(T_CRYPTO, "crypto: shared secret = %s", gestr(g, r));
636 /* --- Compute the switch messages --- */
638 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
639 hashge(h, g, kx->c); hashge(h, g, kxc->c);
640 GH_DONE(h, kxc->hswrq_out); GH_DESTROY(h);
641 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
642 hashge(h, g, kx->c); hashge(h, g, kxc->c);
643 GH_DONE(h, kxc->hswok_out); GH_DESTROY(h);
645 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
646 hashge(h, g, kxc->c); hashge(h, g, kx->c);
647 GH_DONE(h, kxc->hswrq_in); GH_DESTROY(h);
648 h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
649 hashge(h, g, kxc->c); hashge(h, g, kx->c);
650 GH_DONE(h, kxc->hswok_in); GH_DESTROY(h);
652 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
653 trace_block(T_CRYPTO, "crypto: outbound switch request",
654 kxc->hswrq_out, algs->hashsz);
655 trace_block(T_CRYPTO, "crypto: outbound switch confirm",
656 kxc->hswok_out, algs->hashsz);
657 trace_block(T_CRYPTO, "crypto: inbound switch request",
658 kxc->hswrq_in, algs->hashsz);
659 trace_block(T_CRYPTO, "crypto: inbound switch confirm",
660 kxc->hswok_in, algs->hashsz);
663 /* --- Create a new symmetric keyset --- */
665 buf_init(&bb, buf_o, sizeof(buf_o));
666 G_TOBUF(g, &bb, kx->c); x = BLEN(&bb);
667 G_TOBUF(g, &bb, kxc->c); y = BLEN(&bb);
668 G_TOBUF(g, &bb, r); z = BLEN(&bb);
671 kxc->ks = ks_gen(BBASE(&bb), x, y, z, kx->p);
681 a_warn("KX", "?PEER", kx->p, "bad-expected-reply-log", A_END);
691 /* --- @dochallenge@ --- *
693 * Arguments: @keyexch *kx@ = pointer to key exchange block
694 * @unsigned msg@ = message code for the packet
695 * @buf *b@ = buffer containing the packet
697 * Returns: Zero if OK, nonzero if the packet was rejected.
699 * Use: Processes a packet containing a challenge.
702 static int dochallenge(keyexch *kx, buf *b)
706 if (kx->s != KXS_CHAL) {
707 a_warn("KX", "?PEER", kx->p, "unexpected", "challenge", A_END);
710 if ((kxc = respond(kx, KX_CHAL, b)) == 0)
713 a_warn("KX", "?PEER", kx->p, "invalid", "challenge", A_END);
723 /* --- @resend@ --- *
725 * Arguments: @keyexch *kx@ = pointer to key exchange context
729 * Use: Sends the next message for a key exchange.
732 static void resend(keyexch *kx)
736 stats *st = p_stats(kx->p);
741 T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
743 b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
744 G_TOBUF(kx->kpriv->g, b, kx->c);
747 T( trace(T_KEYEXCH, "keyexch: sending switch request to `%s'",
750 b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCH);
751 buf_put(b, kx->hc, kx->kpriv->algs.hashsz);
752 buf_put(b, kxc->hc, kx->kpriv->algs.hashsz);
753 buf_init(&bb, buf_i, sizeof(buf_i));
754 G_TORAW(kx->kpriv->g, &bb, kxc->r);
755 buf_put(&bb, kxc->hswrq_out, kx->kpriv->algs.hashsz);
757 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCH, &bb, b);
760 T( trace(T_KEYEXCH, "keyexch: sending switch confirmation to `%s'",
763 b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCHOK);
764 buf_init(&bb, buf_i, sizeof(buf_i));
765 buf_put(&bb, kxc->hswok_out, kx->kpriv->algs.hashsz);
767 ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, &bb, b);
775 st->sz_kxout += BLEN(b);
779 if (kx->s < KXS_SWITCH)
780 settimer(kx, time(0) + T_RETRY);
783 /* --- @decryptrest@ --- *
785 * Arguments: @keyexch *kx@ = pointer to key exchange context
786 * @kxchal *kxc@ = pointer to challenge block
787 * @unsigned msg@ = type of incoming message
788 * @buf *b@ = encrypted remainder of the packet
790 * Returns: Zero if OK, nonzero on some kind of error.
792 * Use: Decrypts the remainder of the packet, and points @b@ at the
793 * recovered plaintext.
796 static int decryptrest(keyexch *kx, kxchal *kxc, unsigned msg, buf *b)
800 buf_init(&bb, buf_o, sizeof(buf_o));
801 if (ks_decrypt(kxc->ks, MSG_KEYEXCH | msg, b, &bb)) {
802 a_warn("KX", "?PEER", kx->p, "decrypt-failed", "%s", pkname[msg], A_END);
805 if (!BOK(&bb)) return (-1);
806 buf_init(b, BBASE(&bb), BLEN(&bb));
810 /* --- @checkresponse@ --- *
812 * Arguments: @keyexch *kx@ = pointer to key exchange context
813 * @unsigned msg@ = type of incoming message
814 * @buf *b@ = decrypted remainder of the packet
816 * Returns: Zero if OK, nonzero on some kind of error.
818 * Use: Checks a reply or switch packet, ensuring that its response
822 static int checkresponse(keyexch *kx, unsigned msg, buf *b)
824 group *g = kx->kpriv->g;
827 if (G_FROMRAW(g, b, r)) {
828 a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
831 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
832 trace(T_CRYPTO, "crypto: reply = %s", gestr(g, r));
834 if (!G_EQ(g, r, kx->rx)) {
835 a_warn("KX", "?PEER", kx->p, "incorrect", "response", A_END);
847 /* --- @commit@ --- *
849 * Arguments: @keyexch *kx@ = pointer to key exchange context
850 * @kxchal *kxc@ = pointer to challenge to commit to
854 * Use: Commits to a particular challenge as being the `right' one,
855 * since a reply has arrived for it.
858 static void commit(keyexch *kx, kxchal *kxc)
862 for (i = 0; i < kx->nr; i++) {
864 kxc_destroy(kx->r[i]);
869 ksl_link(kx->ks, kxc->ks);
872 /* --- @doreply@ --- *
874 * Arguments: @keyexch *kx@ = pointer to key exchange context
875 * @buf *b@ = buffer containing packet
877 * Returns: Zero if OK, nonzero if the packet was rejected.
879 * Use: Handles a reply packet. This doesn't handle the various
880 * switch packets: they're rather too different.
883 static int doreply(keyexch *kx, buf *b)
887 if (kx->s != KXS_CHAL && kx->s != KXS_COMMIT) {
888 a_warn("KX", "?PEER", kx->p, "unexpected", "reply", A_END);
891 if ((kxc = respond(kx, KX_REPLY, b)) == 0 ||
892 decryptrest(kx, kxc, KX_REPLY, b) ||
893 checkresponse(kx, KX_REPLY, b))
896 a_warn("KX", "?PEER", kx->p, "invalid", "reply", A_END);
899 if (kx->s == KXS_CHAL) {
910 /* --- @kxfinish@ --- *
912 * Arguments: @keyexch *kx@ = pointer to key exchange block
916 * Use: Sets everything up following a successful key exchange.
919 static void kxfinish(keyexch *kx)
921 kxchal *kxc = kx->r[0];
922 ks_activate(kxc->ks);
923 settimer(kx, ks_tregen(kxc->ks));
925 a_notify("KXDONE", "?PEER", kx->p, A_END);
926 p_stats(kx->p)->t_kx = time(0);
929 /* --- @doswitch@ --- *
931 * Arguments: @keyexch *kx@ = pointer to key exchange block
932 * @buf *b@ = pointer to buffer containing packet
934 * Returns: Zero if OK, nonzero if the packet was rejected.
936 * Use: Handles a reply with a switch request bolted onto it.
939 static int doswitch(keyexch *kx, buf *b)
941 size_t hsz = kx->kpriv->algs.hashsz;
942 const octet *hc_in, *hc_out, *hswrq;
945 if ((hc_in = buf_get(b, hsz)) == 0 ||
946 (hc_out = buf_get(b, hsz)) == 0) {
947 a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
950 IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
951 trace_block(T_CRYPTO, "crypto: challenge", hc_in, hsz);
952 trace_block(T_CRYPTO, "crypto: cookie", hc_out, hsz);
954 if ((kxc = kxc_byhc(kx, hc_in)) == 0 ||
955 memcmp(hc_out, kx->hc, hsz) != 0) {
956 a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
959 if (decryptrest(kx, kxc, KX_SWITCH, b) ||
960 checkresponse(kx, KX_SWITCH, b))
962 if ((hswrq = buf_get(b, hsz)) == 0 || BLEFT(b)) {
963 a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
966 IF_TRACING(T_KEYEXCH, {
967 trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, hsz);
969 if (memcmp(hswrq, kxc->hswrq_in, hsz) != 0) {
970 a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
973 if (kx->s == KXS_CHAL)
975 if (kx->s < KXS_SWITCH)
984 /* --- @doswitchok@ --- *
986 * Arguments: @keyexch *kx@ = pointer to key exchange block
987 * @buf *b@ = pointer to buffer containing packet
989 * Returns: Zero if OK, nonzero if the packet was rejected.
991 * Use: Handles a reply with a switch request bolted onto it.
994 static int doswitchok(keyexch *kx, buf *b)
996 size_t hsz = kx->kpriv->algs.hashsz;
1001 if (kx->s < KXS_COMMIT) {
1002 a_warn("KX", "?PEER", kx->p, "unexpected", "switch-ok", A_END);
1006 buf_init(&bb, buf_o, sizeof(buf_o));
1007 if (decryptrest(kx, kxc, KX_SWITCHOK, b))
1009 if ((hswok = buf_get(b, hsz)) == 0 || BLEFT(b)) {
1010 a_warn("KX", "?PEER", kx->p, "invalid", "switch-ok", A_END);
1013 IF_TRACING(T_KEYEXCH, {
1014 trace_block(T_CRYPTO, "crypto: switch confirmation hash",
1017 if (memcmp(hswok, kxc->hswok_in, hsz) != 0) {
1018 a_warn("KX", "?PEER", kx->p, "incorrect", "switch-ok", A_END);
1021 if (kx->s < KXS_SWITCH)
1029 /*----- Main code ---------------------------------------------------------*/
1033 * Arguments: @keyexch *kx@ = pointer to key exchange context
1037 * Use: Stops a key exchange dead in its tracks. Throws away all of
1038 * the context information. The context is left in an
1039 * inconsistent state. The only functions which understand this
1040 * state are @kx_free@ and @kx_init@ (which cause it internally
1041 * it), and @start@ (which expects it to be the prevailing
1045 static void stop(keyexch *kx)
1049 if (kx->f & KXF_DEAD)
1052 if (kx->f & KXF_TIMER)
1053 sel_rmtimer(&kx->t);
1054 for (i = 0; i < kx->nr; i++)
1055 kxc_destroy(kx->r[i]);
1057 G_DESTROY(kx->kpriv->g, kx->c);
1058 G_DESTROY(kx->kpriv->g, kx->rx);
1061 kx->f &= ~KXF_TIMER;
1064 /* --- @start@ --- *
1066 * Arguments: @keyexch *kx@ = pointer to key exchange context
1067 * @time_t now@ = the current time
1071 * Use: Starts a new key exchange with the peer. The context must be
1072 * in the bizarre state left by @stop@ or @kx_init@.
1075 static void start(keyexch *kx, time_t now)
1077 algswitch *algs = &kx->kpriv->algs;
1078 group *g = kx->kpriv->g;
1081 assert(kx->f & KXF_DEAD);
1083 kx->f &= ~(KXF_DEAD | KXF_CORK);
1085 kx->alpha = mprand_range(MP_NEW, g->r, &rand_global, 0);
1086 kx->c = G_CREATE(g); G_EXP(g, kx->c, g->g, kx->alpha);
1087 kx->rx = G_CREATE(g); G_EXP(g, kx->rx, kx->kpub->kpub, kx->alpha);
1089 kx->t_valid = now + T_VALID;
1091 h = GH_INIT(algs->h);
1092 HASH_STRING(h, "tripe-cookie");
1093 hashge(h, g, kx->c);
1097 IF_TRACING(T_KEYEXCH, {
1098 trace(T_KEYEXCH, "keyexch: creating new challenge");
1099 IF_TRACING(T_CRYPTO, {
1100 trace(T_CRYPTO, "crypto: secret = %s", mpstr(kx->alpha));
1101 trace(T_CRYPTO, "crypto: challenge = %s", gestr(g, kx->c));
1102 trace(T_CRYPTO, "crypto: expected response = %s", gestr(g, kx->rx));
1103 trace_block(T_CRYPTO, "crypto: challenge cookie",
1104 kx->hc, algs->hashsz);
1109 /* --- @checkpub@ --- *
1111 * Arguments: @keyexch *kx@ = pointer to key exchange context
1113 * Returns: Zero if OK, nonzero if the peer's public key has expired.
1115 * Use: Deactivates the key-exchange until the peer acquires a new
1119 static int checkpub(keyexch *kx)
1124 if (kx->f & KXF_DEAD)
1127 if (KEY_EXPIRED(now, kx->kpriv->t_exp)) f |= 1;
1128 if (KEY_EXPIRED(now, kx->kpub->t_exp)) f |= 2;
1131 if (f & 1) a_warn("KX", "?PEER", kx->p, "private-key-expired", A_END);
1132 if (f & 2) a_warn("KX", "?PEER", kx->p, "public-key-expired", A_END);
1133 kx->f &= ~KXF_PUBKEY;
1139 /* --- @kx_start@ --- *
1141 * Arguments: @keyexch *kx@ = pointer to key exchange context
1142 * @int forcep@ = nonzero to ignore the quiet timer
1146 * Use: Stimulates a key exchange. If a key exchage is in progress,
1147 * a new challenge is sent (unless the quiet timer forbids
1148 * this); if no exchange is in progress, one is commenced.
1151 void kx_start(keyexch *kx, int forcep)
1153 time_t now = time(0);
1157 if (forcep || !VALIDP(kx, now)) {
1160 a_notify("KXSTART", "?PEER", kx->p, A_END);
1165 /* --- @kx_message@ --- *
1167 * Arguments: @keyexch *kx@ = pointer to key exchange context
1168 * @unsigned msg@ = the message code
1169 * @buf *b@ = pointer to buffer containing the packet
1173 * Use: Reads a packet containing key exchange messages and handles
1177 void kx_message(keyexch *kx, unsigned msg, buf *b)
1179 time_t now = time(0);
1180 stats *st = p_stats(kx->p);
1184 if (kx->f & KXF_CORK) {
1186 settimer(kx, now + T_RETRY);
1187 a_notify("KXSTART", A_END);
1193 if (!VALIDP(kx, now)) {
1197 T( trace(T_KEYEXCH, "keyexch: processing %s packet from `%s'",
1198 msg < KX_NMSG ? pkname[msg] : "unknown", p_name(kx->p)); )
1202 rc = doprechallenge(kx, b);
1205 rc = dochallenge(kx, b);
1208 rc = doreply(kx, b);
1211 rc = doswitch(kx, b);
1214 rc = doswitchok(kx, b);
1217 a_warn("KX", "?PEER", kx->p, "unknown-message", "0x%02x", msg, A_END);
1230 /* --- @kx_free@ --- *
1232 * Arguments: @keyexch *kx@ = pointer to key exchange context
1236 * Use: Frees everything in a key exchange context.
1239 void kx_free(keyexch *kx)
1243 km_unref(kx->kpriv);
1246 /* --- @kx_newkeys@ --- *
1248 * Arguments: @keyexch *kx@ = pointer to key exchange context
1252 * Use: Informs the key exchange module that its keys may have
1253 * changed. If fetching the new keys fails, the peer will be
1254 * destroyed, we log messages and struggle along with the old
1258 void kx_newkeys(keyexch *kx)
1260 kdata *kpriv, *kpub;
1263 time_t now = time(0);
1265 T( trace(T_KEYEXCH, "keyexch: checking new keys for `%s'",
1268 /* --- Find out whether we can use new keys --- *
1270 * Try each available combination of new and old, public and private,
1271 * except both old (which is status quo anyway). The selection is encoded
1272 * in @i@, with bit 0 for the private key and bit 1 for public key; a set
1273 * bit means to use the old value, and a clear bit means to use the new
1276 * This means that we currently prefer `old private and new public' over
1277 * `new private and old public'. I'm not sure which way round this should
1281 for (i = 0; i < 3; i++) {
1283 /* --- Select the keys we're going to examine --- *
1285 * If we're meant to have a new key and don't, then skip this
1289 T( trace(T_KEYEXCH, "keyexch: checking %s private, %s public",
1290 i & 1 ? "old" : "new", i & 2 ? "old" : "new"); )
1292 if (i & 1) kpriv = kx->kpriv;
1293 else if (kx->kpriv->kn->kd != kx->kpriv) kpriv = kx->kpriv->kn->kd;
1295 T( trace(T_KEYEXCH, "keyexch: private key unchanged, skipping"); )
1299 if (i & 2) kpub = kx->kpub;
1300 else if (kx->kpub->kn->kd != kx->kpub) kpub = kx->kpub->kn->kd;
1302 T( trace(T_KEYEXCH, "keyexch: public key unchanged, skipping"); )
1306 /* --- Skip if either key is expired --- *
1308 * We're not going to get far with expired keys, and this simplifies the
1312 if (KEY_EXPIRED(now, kx->kpriv->t_exp) ||
1313 KEY_EXPIRED(now, kx->kpub->t_exp)) {
1314 T( trace(T_KEYEXCH, "keyexch: %s expired, skipping",
1315 !KEY_EXPIRED(now, kx->kpriv->t_exp) ? "public key" :
1316 !KEY_EXPIRED(now, kx->kpub->t_exp) ? "private key" :
1321 /* --- If the groups don't match then we can't use this pair --- */
1323 if (!km_samealgsp(kpriv, kpub)) {
1324 T( trace(T_KEYEXCH, "keyexch: peer `%s' group mismatch; "
1325 "%s priv `%s' and %s pub `%s'", p_name(kx->p),
1326 i & 1 ? "old" : "new", km_tag(kx->kpriv),
1327 i & 2 ? "old" : "new", km_tag(kx->kpub)); )
1332 T( trace(T_KEYEXCH, "keyexch: peer `%s' continuing with old keys",
1336 /* --- We've chosen new keys --- *
1338 * Switch the new ones into place. Neither of the keys we're switching to
1339 * is expired (we checked that above), so we should just crank everything
1342 * A complication arises: we don't really want to force a new key exchange
1343 * unless we have to. If the group is unchanged, and we're currently
1344 * running OK, then we should just let things lie.
1348 switchp = ((kx->f & KXF_DEAD) ||
1349 kx->s != KXS_SWITCH ||
1350 !group_samep(kx->kpriv->g, kpriv->g));
1352 T( trace(T_KEYEXCH, "keyexch: peer `%s' adopting "
1353 "%s priv `%s' and %s pub `%s'; %sforcing exchange", p_name(kx->p),
1354 i & 1 ? "old" : "new", km_tag(kx->kpriv),
1355 i & 2 ? "old" : "new", km_tag(kx->kpub),
1356 switchp ? "" : "not "); )
1358 if (switchp) stop(kx);
1359 km_ref(kpriv); km_unref(kx->kpriv); kx->kpriv = kpriv;
1360 km_ref(kpub); km_unref(kx->kpub); kx->kpub = kpub;
1361 kx->f |= KXF_PUBKEY;
1363 T( trace(T_KEYEXCH, "keyexch: restarting key negotiation with `%s'",
1370 /* --- @kx_init@ --- *
1372 * Arguments: @keyexch *kx@ = pointer to key exchange context
1373 * @peer *p@ = pointer to peer context
1374 * @keyset **ks@ = pointer to keyset list
1375 * @unsigned f@ = various useful flags
1377 * Returns: Zero if OK, nonzero if it failed.
1379 * Use: Initializes a key exchange module. The module currently
1380 * contains no keys, and will attempt to initiate a key
1384 int kx_init(keyexch *kx, peer *p, keyset **ks, unsigned f)
1386 if ((kx->kpriv = km_findpriv(p_privtag(p))) == 0) goto fail_0;
1387 if ((kx->kpub = km_findpub(p_tag(p))) == 0) goto fail_1;
1388 if (!group_samep(kx->kpriv->g, kx->kpub->g)) {
1389 a_warn("KX", "?PEER", kx->p, "group-mismatch",
1390 "local-private-key", "%s", p_privtag(p),
1391 "peer-public-key", "%s", p_tag(p),
1398 kx->f = KXF_DEAD | KXF_PUBKEY | f;
1399 if (!(kx->f & KXF_CORK)) {
1402 /* Don't notify here: the ADD message hasn't gone out yet. */
1409 km_unref(kx->kpriv);
1414 /*----- That's all, folks -------------------------------------------------*/