server/admin.c: Remove spurious `ping' in usage message.
[tripe] / server / keyexch.c
index c27d69f..b141100 100644 (file)
@@ -9,19 +9,18 @@
  *
  * This file is part of Trivial IP Encryption (TrIPE).
  *
- * TrIPE is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
+ * TrIPE is free software: you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 3 of the License, or (at your
+ * option) any later version.
  *
- * TrIPE is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
+ * TrIPE is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with TrIPE; if not, write to the Free Software Foundation,
- * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
  */
 
 /*----- Header files ------------------------------------------------------*/
  *
  * %$\cookie{kx-switch-ok}, E_K(u_A))$%
  *     Switch received.  Committed; send data; move to @KXS_SWITCH@.
+ *
+ * %$\cookie{kx-token-request}, u, E_L(n)$%
+ *     %$L = H(u, u^\alpha)$%, and %$n$% is a string of the form
+ *     `[PEER.]KEYTAG'.  Expect %$\cookie{kx-token}$% by return.
+ *
+ * %$\cookie{kx-token}, v, E_{L'}(t)$%
+ *     %$L' = H(v, v^\alpha)$%, and %$t$% is a token associated with %$n$%
+ *     (see %$\cookie{kx-token-request}$% above).
+ *
+ * %$\cookie{kx-knock}, u, E_L(n, t), r_A$%
+ *     %$L$%, %$n$% and %$t$% are as %$\cookie{kx-token}$% and
+ *     %$\cookie{kx-token-request}$%; %$r_A$% is as in
+ *     %$\cookie{kx-pre-challenge}$%.  If the token %$t$% doesn't match
+ *     %$n$%, then warn and discard.  If a peer named PEER (or KEYTAG)
+ *     exists then proceed as for %$\cookie{kx-pre-challenge}$%.  Otherwise
+ *     issue a notification `NOTE KNOCK PEER ADDR...' and discard.
  */
 
 /*----- Static tables -----------------------------------------------------*/
 
 static const char *const pkname[] = {
-  "pre-challenge", "challenge", "reply", "switch-rq", "switch-ok"
+  "pre-challenge", "challenge", "reply", "switch-rq", "switch-ok",
+  "token-rq", "token", "knock"
 };
 
 /*----- Various utilities -------------------------------------------------*/
@@ -97,7 +113,8 @@ static const char *const pkname[] = {
 /* --- @hashge@ --- *
  *
  * Arguments:  @ghash *h@ = pointer to hash context
- *             @ge *x@ = pointer to group element
+ *             @const dhgrp *g@ = pointer to group
+ *             @const dhge *Y@ = pointer to group element
  *
  * Returns:    ---
  *
@@ -105,11 +122,12 @@ static const char *const pkname[] = {
  *             @buf_t@.
  */
 
-static void hashge(ghash *h, ge *x)
+static void hashge(ghash *h, const dhgrp *g, const dhge *Y)
 {
   buf b;
+
   buf_init(&b, buf_t, sizeof(buf_t));
-  G_TOBUF(gg, &b, x);
+  g->ops->stge(g, &b, Y, DHFMT_HASH);
   assert(BOK(&b));
   GH_HASH(h, BBASE(&b), BLEN(&b));
 }
@@ -117,78 +135,84 @@ static void hashge(ghash *h, ge *x)
 /* --- @mpmask@ --- *
  *
  * Arguments:  @buf *b@ = output buffer
- *             @mp *x@ = the plaintext integer
+ *             @const dhgrp *g@ = the group
+ *             @const dhsc *x@ = the plaintext scalar
  *             @size_t n@ = the expected size of the plaintext
+ *             @gcipher *mgfc@ = mask-generating function to use
  *             @const octet *k@ = pointer to key material
  *             @size_t ksz@ = size of the key
  *
- * Returns:    Pointer to the output.
+ * Returns:    ---
  *
- * Use:                Masks a multiprecision integer: returns %$x \xor H(k)$%, so
- *             it's a random oracle thing rather than an encryption thing.
+ * Use:                Masks a scalar: returns %$x \xor H(k)$%, so it's a random
+ *             oracle thing rather than an encryption thing.  Breaks the
+ *             output buffer on error.
  */
 
-static octet *mpmask(buf *b, mp *x, size_t n, const octet *k, size_t ksz)
+static void mpmask(buf *b, const dhgrp *g, const dhsc *x, size_t n,
+                  const gccipher *mgfc, const octet *k, size_t ksz)
 {
   gcipher *mgf;
   octet *p;
 
-  if ((p = buf_get(b, n)) == 0)
-    return (0);
-  mgf = GC_INIT(algs.mgf, k, ksz);
+  if ((p = buf_get(b, n)) == 0) return;
+  mgf = GC_INIT(mgfc, k, ksz);
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace(T_CRYPTO, "masking index = %s", mpstr(x));
-    trace_block(T_CRYPTO, "masking key", k, ksz);
+    trace(T_CRYPTO, "crypto: masking scalar = %s", g->ops->scstr(g, x));
+    trace_block(T_CRYPTO, "crypto: masking key", k, ksz);
   }))
-  mp_storeb(x, buf_t, n);
+  if (g->ops->stsc(g, buf_t, n, x)) { buf_break(b); return; }
   GC_ENCRYPT(mgf, buf_t, p, n);
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace_block(T_CRYPTO, "index plaintext", buf_t, n);
-    trace_block(T_CRYPTO, "masked ciphertext", p, n);
+    trace_block(T_CRYPTO, "crypto: scalar plaintext", buf_t, n);
+    trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
   }))
   GC_DESTROY(mgf);
-  return (p);
 }
 
 /* --- @mpunmask@ --- *
  *
- * Arguments:  @mp *d@ = the output integer
+ * Arguments:  @const dhgrp *g@ = the group
  *             @const octet *p@ = pointer to the ciphertext
  *             @size_t n@ = the size of the ciphertext
+ *             @gcipher *mgfc@ = mask-generating function to use
  *             @const octet *k@ = pointer to key material
  *             @size_t ksz@ = size of the key
  *
- * Returns:    The decrypted integer, or null.
+ * Returns:    The decrypted scalar, or null.
  *
- * Use:                Unmasks a multiprecision integer.
+ * Use:                Unmasks a scalar.
  */
 
-static mp *mpunmask(mp *d, const octet *p, size_t n,
-                   const octet *k, size_t ksz)
+static dhsc *mpunmask(const dhgrp *g, const octet *p, size_t n,
+                     const gccipher *mgfc, const octet *k, size_t ksz)
 {
   gcipher *mgf;
+  dhsc *x;
 
-  mgf = GC_INIT(algs.mgf, k, ksz);
+  mgf = GC_INIT(mgfc, k, ksz);
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace_block(T_CRYPTO, "unmasking key", k, ksz);
-    trace_block(T_CRYPTO, "masked ciphertext", p, n);
+    trace_block(T_CRYPTO, "crypto: unmasking key", k, ksz);
+    trace_block(T_CRYPTO, "crypto: masked ciphertext", p, n);
   }))
   GC_DECRYPT(mgf, p, buf_t, n);
-  d = mp_loadb(d, buf_t, n);
+  x = g->ops->ldsc(g, buf_t, n);
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace_block(T_CRYPTO, "index plaintext", buf_t, n);
-    trace(T_CRYPTO, "unmasked index = %s", mpstr(d));
+    trace_block(T_CRYPTO, "crypto: scalar plaintext", buf_t, n);
+    trace(T_CRYPTO, "crypto: unmasked scalar = %s",
+         x ? g->ops->scstr(g, x) : "<failed>");
   }))
   GC_DESTROY(mgf);
-  return (d);
+  return (x);
 }
 
 /* --- @hashcheck@ --- *
  *
- * Arguments:  @ge *kpub@ = sender's public key
- *             @ge *cc@ = receiver's challenge
- *             @ge *c@ = sender's challenge
- *             @ge *y@ = reply to sender's challenge
+ * Arguments:  @keyexch *kx@ = pointer to key-exchange block
+ *             @const dhge *K@ = sender's public key
+ *             @const dhge *CC@ = receiver's challenge
+ *             @const dhge *C@ = sender's challenge
+ *             @const dhge *Y@ = reply to sender's challenge
  *
  * Returns:    Pointer to the hash value (in @buf_t@)
  *
@@ -196,29 +220,31 @@ static mp *mpunmask(mp *d, const octet *p, size_t n,
  *             indices to prove the validity of challenges.  This computes
  *             the masking key used in challenge check values.  This is
  *             really the heart of the whole thing, since it ensures that
- *             the index can be recovered from the history of hashing
+ *             the scalar can be recovered from the history of hashing
  *             queries, which gives us (a) a proof that the authentication
  *             process is zero-knowledge, and (b) a proof that the whole
  *             key-exchange is deniable.
  */
 
-static const octet *hashcheck(ge *kpub, ge *cc, ge *c, ge *y)
+static const octet *hashcheck(keyexch *kx, const dhge *K,
+                             const dhge *CC, const dhge *C, const dhge *Y)
 {
-  ghash *h = GH_INIT(algs.h);
+  ghash *h = GH_INIT(kx->kpriv->algs.h);
+  const dhgrp *g = kx->kpriv->grp;
 
   HASH_STRING(h, "tripe-expected-reply");
-  hashge(h, kpub);
-  hashge(h, cc);
-  hashge(h, c);
-  hashge(h, y);
+  hashge(h, g, K);
+  hashge(h, g, CC);
+  hashge(h, g, C);
+  hashge(h, g, Y);
   GH_DONE(h, buf_t);
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace(T_CRYPTO, "computing challenge check hash");
-    trace(T_CRYPTO, "public key = %s", gestr(gg, kpub));
-    trace(T_CRYPTO, "receiver challenge = %s", gestr(gg, cc));
-    trace(T_CRYPTO, "sender challenge = %s", gestr(gg, c));
-    trace(T_CRYPTO, "sender reply = %s", gestr(gg, y));
-    trace_block(T_CRYPTO, "hash output", buf_t, algs.hashsz);
+    trace(T_CRYPTO, "crypto: computing challenge check hash");
+    trace(T_CRYPTO, "crypto: public key = %s", g->ops->gestr(g, K));
+    trace(T_CRYPTO, "crypto: receiver challenge = %s", g->ops->gestr(g, CC));
+    trace(T_CRYPTO, "crypto: sender challenge = %s", g->ops->gestr(g, C));
+    trace(T_CRYPTO, "crypto: sender reply = %s", g->ops->gestr(g, Y));
+    trace_block(T_CRYPTO, "crypto: hash output", buf_t, kx->kpriv->algs.hashsz);
   }))
   GH_DESTROY(h);
   return (buf_t);
@@ -228,7 +254,7 @@ static const octet *hashcheck(ge *kpub, ge *cc, ge *c, ge *y)
  *
  * Arguments:  @keyexch *kx@ = pointer to key exchange block
  *             @buf *b@ = output buffer for challenge
- *             @ge *c@ = peer's actual challenge
+ *             @const dhge *C@ = peer's actual challenge
  *             @const octet *hc@ = peer's challenge cookie
  *
  * Returns:    ---
@@ -236,12 +262,15 @@ static const octet *hashcheck(ge *kpub, ge *cc, ge *c, ge *y)
  * Use:                Writes a full challenge to the message buffer.
  */
 
-static void sendchallenge(keyexch *kx, buf *b, ge *c, const octet *hc)
+static void sendchallenge(keyexch *kx, buf *b,
+                         const dhge *C, const octet *hc)
 {
-  G_TOBUF(gg, b, kx->c);
-  buf_put(b, hc, algs.hashsz);
-  mpmask(b, kx->alpha, indexsz,
-        hashcheck(kpub, c, kx->c, kx->rx), algs.hashsz);
+  const dhgrp *g = kx->kpriv->grp;
+  g->ops->stge(g, b, kx->C, DHFMT_VAR);
+  buf_put(b, hc, kx->kpriv->algs.hashsz);
+  mpmask(b, g, kx->a, g->scsz, kx->kpriv->algs.mgf,
+        hashcheck(kx, kx->kpriv->K, C, kx->C, kx->RX),
+        kx->kpriv->algs.hashsz);
 }
 
 /* --- @timer@ --- *
@@ -279,6 +308,148 @@ static void settimer(keyexch *kx, struct timeval *tv)
   kx->f |= KXF_TIMER;
 }
 
+/* --- @f2tv@ --- *
+ *
+ * Arguments:  @struct timeval *tv@ = where to write the timeval
+ *             @double t@ = a time as a floating point number
+ *
+ * Returns:    ---
+ *
+ * Use:                Converts a floating-point time into a timeval.
+ */
+
+static void f2tv(struct timeval *tv, double t)
+{
+  tv->tv_sec = t;
+  tv->tv_usec = (t - tv->tv_sec)*MILLION;
+}
+
+/* --- @wobble@ --- *
+ *
+ * Arguments:  @double t@ = a time interval
+ *
+ * Returns:    The same time interval, with a random error applied.
+ */
+
+static double wobble(double t)
+{
+  uint32 r = rand_global.ops->word(&rand_global);
+  double w = (r/F_2P32) - 0.5;
+  return (t + t*w*T_WOBBLE);
+}
+
+/* --- @rs_time@ --- *
+ *
+ * Arguments:  @retry *rs@ = current retry state
+ *             @struct timeval *tv@ = where to write the result
+ *             @const struct timeval *now@ = current time, or null
+ *
+ * Returns:    ---
+ *
+ * Use:                Computes a time at which to retry sending a key-exchange
+ *             packet.  This algorithm is subject to change, but it's
+ *             currently a capped exponential backoff, slightly randomized
+ *             to try to keep clients from hammering a server that's only
+ *             just woken up.
+ *
+ *             If @now@ is null then the function works out the time for
+ *             itself.
+ */
+
+static void rs_time(retry *rs, struct timeval *tv, const struct timeval *now)
+{
+  double t;
+  struct timeval rtv;
+
+  if (!rs->t)
+    t = SEC(2);
+  else {
+    t = (rs->t * 5)/4;
+    if (t > MIN(5)) t = MIN(5);
+  }
+  rs->t = t;
+
+  if (!now) {
+    now = tv;
+    gettimeofday(tv, 0);
+  }
+  f2tv(&rtv, wobble(t));
+  TV_ADD(tv, now, &rtv);
+}
+
+/* --- @retry_reset@ --- *
+ *
+ * Arguments:  @retry *rs@ = retry state
+ *
+ * Returns:    --
+ *
+ * Use:                Resets a retry state to indicate that progress has been
+ *             made.  Also useful for initializing the state in the first
+ *             place.
+ */
+
+static void rs_reset(retry *rs) { rs->t = 0; }
+
+/* --- @notice_message@ --- *
+ *
+ * Arguments:  @keyexch *kx@ = pointer to key-exchange block
+ *
+ * Returns:    Zero if OK; @-1@ if the public key is in a bad state.
+ *
+ * Use:                Updates the key-exchange state following a received message.
+ *             Specifically, if there's no currently active key-exchange in
+ *             progress, and we're not in the cooling-off period, then
+ *             commence a new one; reset the retry timers; and if we're
+ *             corked then pop the cork so that we can reply.
+ */
+
+static int checkpub(keyexch *kx);
+static void stop(keyexch *kx);
+static void start(keyexch *kx, time_t now);
+
+static int notice_message(keyexch *kx)
+{
+  struct timeval now, tv;
+
+  gettimeofday(&now, 0);
+  rs_reset(&kx->rs);
+  if (kx->f & KXF_CORK) {
+    start(kx, now.tv_sec);
+    rs_time(&kx->rs, &tv, &now);
+    settimer(kx, &tv);
+    a_notify("KXSTART", "?PEER", kx->p, A_END);
+  }
+  if (checkpub(kx)) return (-1);
+  if (!VALIDP(kx, now.tv_sec)) {
+    stop(kx);
+    start(kx, now.tv_sec);
+  }
+  return (0);
+}
+
+/* --- @update_stats_tx@, @update_stats_rx@ --- *
+ *
+ * Arguments:  @keyexch *kx@ = pointer to key-exchange block
+ *             @int ok@ = nonzero if the message was valid (for @rx@)
+ *             @size_t sz@ = size of sent message
+ *
+ * Returns:    ---
+ *
+ * Use:                Records that a key-exchange message was sent to, or received
+ *             from, the peer.
+ */
+
+static void update_stats_tx(keyexch *kx, size_t sz)
+  { stats *st = p_stats(kx->p); st->n_kxout++; st->sz_kxout += sz; }
+
+static void update_stats_rx(keyexch *kx, int ok, size_t sz)
+{
+  stats *st = p_stats(kx->p);
+
+  if (!ok) st->n_reject++;
+  else { st->n_kxin++; st->sz_kxin += sz; }
+}
+
 /*----- Challenge management ----------------------------------------------*/
 
 /* --- Notes on challenge management --- *
@@ -305,10 +476,11 @@ static void settimer(keyexch *kx, struct timeval *tv)
 
 static void kxc_destroy(kxchal *kxc)
 {
+  const dhgrp *g = kxc->kx->kpriv->grp;
   if (kxc->f & KXF_TIMER)
     sel_rmtimer(&kxc->t);
-  G_DESTROY(gg, kxc->c);
-  G_DESTROY(gg, kxc->r);
+  g->ops->freege(g, kxc->C);
+  g->ops->freege(g, kxc->R);
   ks_drop(kxc->ks);
   DESTROY(kxc);
 }
@@ -338,6 +510,8 @@ static void kxc_stoptimer(kxchal *kxc)
  * Returns:    A pointer to the challenge block.
  *
  * Use:                Returns a pointer to a new challenge block to fill in.
+ *             In particular, the @c@ and @r@ members are left
+ *             uninitialized.
  */
 
 static kxchal *kxc_new(keyexch *kx)
@@ -357,31 +531,31 @@ static kxchal *kxc_new(keyexch *kx)
   /* --- Fill in the new structure --- */
 
   kxc = CREATE(kxchal);
-  kxc->c = G_CREATE(gg);
-  kxc->r = G_CREATE(gg);
   kxc->ks = 0;
   kxc->kx = kx;
   kxc->f = 0;
   kx->r[i] = kxc;
+  rs_reset(&kxc->rs);
   return (kxc);
 }
 
 /* --- @kxc_bychal@ --- *
  *
  * Arguments:  @keyexch *kx@ = pointer to key exchange block
- *             @ge *c@ = challenge from remote host
+ *             @const dhge *C@ = challenge from remote host
  *
  * Returns:    Pointer to the challenge block, or null.
  *
  * Use:                Finds a challenge block, given its challenge.
  */
 
-static kxchal *kxc_bychal(keyexch *kx, ge *c)
+static kxchal *kxc_bychal(keyexch *kx, const dhge *C)
 {
+  const dhgrp *g = kx->kpriv->grp;
   unsigned i;
 
   for (i = 0; i < kx->nr; i++) {
-    if (G_EQ(gg, c, kx->r[i]->c))
+    if (g->ops->eq(g, C, kx->r[i]->C))
       return (kx->r[i]);
   }
   return (0);
@@ -402,7 +576,7 @@ static kxchal *kxc_byhc(keyexch *kx, const octet *hc)
   unsigned i;
 
   for (i = 0; i < kx->nr; i++) {
-    if (memcmp(hc, kx->r[i]->hc, algs.hashsz) == 0)
+    if (memcmp(hc, kx->r[i]->hc, kx->kpriv->algs.hashsz) == 0)
       return (kx->r[i]);
   }
   return (0);
@@ -430,25 +604,24 @@ static void kxc_timer(struct timeval *tv, void *v)
 
 static void kxc_answer(keyexch *kx, kxchal *kxc)
 {
-  stats *st = p_stats(kx->p);
   buf *b = p_txstart(kx->p, MSG_KEYEXCH | KX_REPLY);
+  const dhgrp *g = kx->kpriv->grp;
   struct timeval tv;
   buf bb;
 
   /* --- Build the reply packet --- */
 
   T( trace(T_KEYEXCH, "keyexch: sending reply to `%s'", p_name(kx->p)); )
-  sendchallenge(kx, b, kxc->c, kxc->hc);
+  sendchallenge(kx, b, kxc->C, kxc->hc);
   buf_init(&bb, buf_i, sizeof(buf_i));
-  G_TORAW(gg, &bb, kxc->r);
+  g->ops->stge(g, &bb, kxc->R, DHFMT_STD);
   buf_flip(&bb);
   ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_REPLY, &bb, b);
 
   /* --- Update the statistics --- */
 
   if (BOK(b)) {
-    st->n_kxout++;
-    st->sz_kxout += BLEN(b);
+    update_stats_tx(kx, BLEN(b));
     p_txend(kx->p);
   }
 
@@ -457,13 +630,155 @@ static void kxc_answer(keyexch *kx, kxchal *kxc)
   if (kxc->f & KXF_TIMER)
     sel_rmtimer(&kxc->t);
   gettimeofday(&tv, 0);
-  tv.tv_sec += T_RETRY;
+  rs_time(&kxc->rs, &tv, &tv);
   sel_addtimer(&sel, &kxc->t, &tv, kxc_timer, kxc);
   kxc->f |= KXF_TIMER;
 }
 
 /*----- Individual message handlers ---------------------------------------*/
 
+static ratelim unauth_limit;
+
+/* --- @dotokenrq@ --- *
+ *
+ * Arguments:  @const addr *a@ = sender's address
+ *             @buf *b@ = buffer containing the packet
+ *
+ * Returns:    ---
+ *
+ * Use:                Processes a token-request message.
+ */
+
+static void dotokenrq(const addr *a, buf *b)
+{
+  uint32 id;
+  kdata *kpriv = 0, *kpub = 0;
+  char *pname;
+  const char *tag;
+  size_t sz;
+  buf bb, bbb;
+
+  /* --- Check if we're in danger of overloading --- */
+
+  if (ratelim_withdraw(&unauth_limit, 1)) goto done;
+
+  /* --- Start building the reply --- */
+
+  buf_init(&bbb, buf_o, sizeof(buf_o));
+  buf_putu8(&bbb, MSG_KEYEXCH | KX_TOKEN);
+
+  /* --- Fetch and copy the challenge string --- */
+
+  if (buf_getbuf16(b, &bb)) goto done;
+  buf_putmem16(&bbb, BBASE(&bb), BSZ(&bb));
+
+  /* --- Make our own challenge for the response --- */
+
+  buf_init(&bb, buf_t, sizeof(buf_t));
+  c_new(0, 0, &bb); assert(BOK(&bb)); buf_putbuf16(&bbb, &bb);
+
+  /* --- Figure out which private key I'm supposed to use --- */
+
+  if (buf_getu32(b, &id)) goto done;
+  if ((kpriv = km_findprivbyid(id)) == 0) goto done;
+
+  /* --- Decrypt the message --- */
+
+  buf_init(&bb, buf_t, sizeof(buf_t));
+  if (ies_decrypt(kpriv, MSG_KEYEXCH | KX_TOKENRQ, b, &bb) || BLEFT(b))
+    goto done;
+
+  /* --- Parse the token request and find the sender's public key --- */
+
+  assert(BOK(&bb)); buf_flip(&bb);
+  if ((pname = buf_getmem16(&bb, &sz)) == 0 || memchr(pname, 0, sz))
+    goto done;
+  assert(sz < sizeof(buf_t) - ((const octet *)pname - buf_t));
+  pname[sz] = 0;
+  if ((tag = strchr(pname, '.')) != 0) tag++;
+  else tag = pname;
+  if ((kpub = km_findpub(tag)) == 0) goto done;
+
+  /* --- Build and encrypt the token --- */
+
+  buf_init(&bb, buf_i, sizeof(buf_i));
+  c_new(pname, sz, &bb);
+  assert(BOK(&bb)); buf_flip(&bb);
+  if (ies_encrypt(kpub, MSG_KEYEXCH | KX_TOKEN, &bb, &bbb)) goto done;
+  assert(BOK(&bbb));
+
+  /* --- Send the response -- or at least give it a try --- */
+
+  p_txaddr(a, BBASE(&bbb), BLEN(&bbb));
+
+  /* --- All done --- */
+
+done:
+  if (kpriv) km_unref(kpriv);
+  if (kpub) km_unref(kpub);
+}
+
+/* --- @dotoken@ --- *
+ *
+ * Arguments:  @keyexch *kx@ = pointer to key exchange block
+ *             @buf *b@ = buffer containing the packet
+ *
+ * Returns:    Zero if OK, nonzero of the packet was rejected.
+ *
+ * Use:                Processes a token message.
+ */
+
+static int dotoken(keyexch *kx, buf *b)
+{
+  buf bb;
+  buf *bbb;
+  const dhgrp *g = kx->kpriv->grp;
+  octet *p;
+  size_t sz;
+
+  /* --- Make sure this is a sensible message to have received --- */
+
+  if (!kx->p->spec.knock) return (-1);
+
+  /* --- First, collect and verify our challenge --- */
+
+  if (buf_getbuf16(b, &bb) || c_check(0, 0, &bb) || BLEFT(&bb)) return (-1);
+
+  /* --- Start building the knock message from here --- */
+
+  bbb = p_txstart(kx->p, MSG_KEYEXCH | KX_KNOCK);
+
+  /* --- Copy the peer's challenge --- */
+
+  if (buf_getbuf16(b, &bb)) return (-1);
+  buf_putmem16(bbb, BBASE(&bb), BSZ(&bb));
+
+  /* --- Add the key indicator --- */
+
+  buf_putu32(bbb, kx->kpub->id);
+
+  /* --- Building the knock payload --- */
+
+  buf_init(&bb, buf_t, sizeof(buf_t));
+  buf_putstr16(&bb, kx->p->spec.knock);
+  sz = BLEN(&bb)%64; if (sz) sz = 64 - sz;
+  if (ies_decrypt(kx->kpriv, MSG_KEYEXCH | KX_TOKEN, b, &bb)) return (-1);
+  p = buf_get(&bb, sz); assert(p); memset(p, 0, sz);
+  assert(BOK(&bb)); buf_flip(&bb);
+  if (ies_encrypt(kx->kpub, MSG_KEYEXCH | KX_KNOCK, &bb, bbb)) return (-1);
+
+  /* --- Finally, the pre-challenge group element --- */
+
+  g->ops->stge(g, bbb, kx->C, DHFMT_VAR);
+
+  /* --- And we're done --- */
+
+  if (BBAD(bbb)) return (-1);
+  update_stats_tx(kx, BLEN(bbb));
+  p_txend(kx->p);
+  return (0);
+}
+
 /* --- @doprechallenge@ --- *
  *
  * Arguments:  @keyexch *kx@ = pointer to key exchange block
@@ -476,8 +791,8 @@ static void kxc_answer(keyexch *kx, kxchal *kxc)
 
 static int doprechallenge(keyexch *kx, buf *b)
 {
-  stats *st = p_stats(kx->p);
-  ge *c = G_CREATE(gg);
+  const dhgrp *g = kx->kpriv->grp;
+  dhge *C = 0;
   ghash *h;
 
   /* --- Ensure that we're in a sensible state --- */
@@ -489,35 +804,101 @@ static int doprechallenge(keyexch *kx, buf *b)
 
   /* --- Unpack the packet --- */
 
-  if (G_FROMBUF(gg, b, c) || BLEFT(b))
+  if ((C = g->ops->ldge(g, b, DHFMT_VAR)) == 0 || BLEFT(b))
     goto bad;
 
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace(T_CRYPTO, "crypto: challenge = %s", gestr(gg, c));
+    trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, C));
   }))
 
   /* --- Send out a full challenge by return --- */
 
   b = p_txstart(kx->p, MSG_KEYEXCH | KX_CHAL);
-  h = GH_INIT(algs.h);
+  h = GH_INIT(kx->kpriv->algs.h);
   HASH_STRING(h, "tripe-cookie");
-  hashge(h, c);
-  sendchallenge(kx, b, c, GH_DONE(h, 0));
+  hashge(h, g, C);
+  sendchallenge(kx, b, C, GH_DONE(h, 0));
   GH_DESTROY(h);
-  st->n_kxout++;
-  st->sz_kxout += BLEN(b);
+  update_stats_tx(kx, BLEN(b));
   p_txend(kx->p);
 
   /* --- Done --- */
 
-  G_DESTROY(gg, c);
+  g->ops->freege(g, C);
   return (0);
 
 bad:
-  if (c) G_DESTROY(gg, c);
+  if (C) g->ops->freege(g, C);
   return (-1);
 }
 
+/* --- @doknock@ --- *
+ *
+ * Arguments:  @const addr *a@ = sender's address
+ *             @buf *b@ = buffer containing the packet
+ *
+ * Returns:    ---
+ *
+ * Use:                Processes a knock message.
+ */
+
+static void doknock(const addr *a, buf *b)
+{
+  keyexch *kx;
+  peer *p;
+  uint32 id;
+  kdata *kpriv = 0;
+  char *pname;
+  size_t sz, msgsz = BLEN(b);
+  buf bb;
+  int rc;
+
+  /* --- Read and check the challenge --- */
+
+  buf_getbuf16(b, &bb);
+  if (c_check(0, 0, &bb)) goto done;
+
+  /* --- Figure out which private key I'm supposed to use --- */
+
+  if (buf_getu32(b, &id)) goto done;
+  if ((kpriv = km_findprivbyid(id)) == 0) goto done;
+
+  /* --- Decrypt and check the peer's name against the token --- */
+
+  buf_init(&bb, buf_t, sizeof(buf_t));
+  if (ies_decrypt(kpriv, MSG_KEYEXCH | KX_KNOCK, b, &bb)) goto done;
+  assert(BOK(&bb)); buf_flip(&bb);
+  if ((pname = buf_getmem16(&bb, &sz)) == 0 ||
+      memchr(pname, 0, sz) ||
+      c_check(pname, sz, &bb))
+    goto done;
+  assert(sz < sizeof(buf_t) - ((const octet *)pname - buf_t));
+  pname[sz] = 0;
+
+  /* --- If we can't find the peer, then issue a notification --- */
+
+  if ((p = p_find(pname)) == 0) {
+    a_notify("KNOCK", "%s", pname, "?ADDR", a, A_END);
+    goto done;
+  }
+
+  /* --- Update the peer's address --- */
+
+  kx = &p->kx;
+  p_updateaddr(kx->p, a);
+
+  /* --- Now treat the remainder of the message as a pre-challenge --- */
+
+  notice_message(kx);
+  rc = doprechallenge(kx, b);
+  update_stats_rx(kx, !rc, msgsz);
+
+  /* --- All done: clean up --- */
+
+done:
+  if (kpriv) km_unref(kpriv);
+}
+
 /* --- @respond@ --- *
  *
  * Arguments:  @keyexch *kx@ = pointer to key exchange block
@@ -532,12 +913,15 @@ bad:
 
 static kxchal *respond(keyexch *kx, unsigned msg, buf *b)
 {
-  ge *c = G_CREATE(gg);
-  ge *r = G_CREATE(gg);
-  ge *cc = G_CREATE(gg);
+  const dhgrp *g = kx->kpriv->grp;
+  const algswitch *algs = &kx->kpriv->algs;
+  size_t ixsz = g->scsz;
+  dhge *C = 0;
+  dhge *R = 0;
+  dhge *CC = 0;
+  deriveargs a;
   const octet *hc, *ck;
-  size_t x, y, z;
-  mp *cv = 0;
+  dhsc *c = 0;
   kxchal *kxc;
   ghash *h = 0;
   buf bb;
@@ -545,21 +929,21 @@ static kxchal *respond(keyexch *kx, unsigned msg, buf *b)
 
   /* --- Unpack the packet --- */
 
-  if (G_FROMBUF(gg, b, c) ||
-      (hc = buf_get(b, algs.hashsz)) == 0 ||
-      (ck = buf_get(b, indexsz)) == 0) {
+  if ((C = g->ops->ldge(g, b, DHFMT_VAR)) == 0 ||
+      (hc = buf_get(b, algs->hashsz)) == 0 ||
+      (ck = buf_get(b, ixsz)) == 0) {
     a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
     goto bad;
   }
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace(T_CRYPTO, "crypto: challenge = %s", gestr(gg, c));
-    trace_block(T_CRYPTO, "crypto: cookie", hc, algs.hashsz);
-    trace_block(T_CRYPTO, "crypto: check-value", ck, indexsz);
+    trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, C));
+    trace_block(T_CRYPTO, "crypto: cookie", hc, algs->hashsz);
+    trace_block(T_CRYPTO, "crypto: check-value", ck, ixsz);
   }))
 
   /* --- Discard a packet with an invalid cookie --- */
 
-  if (hc && memcmp(hc, kx->hc, algs.hashsz) != 0) {
+  if (hc && memcmp(hc, kx->hc, algs->hashsz) != 0) {
     a_warn("KX", "?PEER", kx->p, "incorrect", "cookie", A_END);
     goto bad;
   }
@@ -572,109 +956,107 @@ static kxchal *respond(keyexch *kx, unsigned msg, buf *b)
    * This will also find a challenge block and, if necessary, populate it.
    */
 
-  if ((kxc = kxc_bychal(kx, c)) != 0) {
-    h = GH_INIT(algs.h);
+  if ((kxc = kxc_bychal(kx, C)) != 0) {
+    h = GH_INIT(algs->h);
     HASH_STRING(h, "tripe-check-hash");
-    GH_HASH(h, ck, indexsz);
-    ok = !memcmp(kxc->ck, GH_DONE(h, 0), algs.hashsz);
+    GH_HASH(h, ck, ixsz);
+    ok = !memcmp(kxc->ck, GH_DONE(h, 0), algs->hashsz);
     GH_DESTROY(h);
     if (!ok) goto badcheck;
   } else {
 
     /* --- Compute the reply, and check the magic --- */
 
-    G_EXP(gg, r, c, kpriv);
-    cv = mpunmask(MP_NEW, ck, indexsz,
-                 hashcheck(kx->kpub, kx->c, c, r), algs.hashsz);
+    R = g->ops->mul(g, kx->kpriv->k, C);
+    if ((c = mpunmask(g, ck, ixsz, algs->mgf,
+                     hashcheck(kx, kx->kpub->K, kx->C, C, R),
+                     algs->hashsz)) == 0)
+      goto badcheck;
     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-      trace(T_CRYPTO, "crypto: computed reply = %s", gestr(gg, r));
-      trace(T_CRYPTO, "crypto: recovered log = %s", mpstr(cv));
+      trace(T_CRYPTO, "crypto: computed reply = %s", g->ops->gestr(g, R));
+      trace(T_CRYPTO, "crypto: recovered log = %s", g->ops->scstr(g, c));
     }))
-    if (MP_CMP(cv, >, gg->r) ||
-       (G_EXP(gg, cc, gg->g, cv), !G_EQ(gg, c, cc)))
-      goto badcheck;
+    CC = g->ops->mul(g, c, 0);
+    if (!g->ops->eq(g, CC, C)) goto badcheck;
 
     /* --- Fill in a new challenge block --- */
 
     kxc = kxc_new(kx);
-    G_COPY(gg, kxc->c, c);
-    G_COPY(gg, kxc->r, r);
+    kxc->C = C; C = 0;
+    kxc->R = R; R = 0;
 
-    h = GH_INIT(algs.h);
-    HASH_STRING(h, "tripe-check-hash");
-    GH_HASH(h, ck, indexsz);
-    GH_DONE(h, kxc->ck);
-    GH_DESTROY(h);
+    h = GH_INIT(algs->h); HASH_STRING(h, "tripe-check-hash");
+    GH_HASH(h, ck, ixsz);
+    GH_DONE(h, kxc->ck); GH_DESTROY(h);
 
-    h = GH_INIT(algs.h);
-    HASH_STRING(h, "tripe-cookie");
-    hashge(h, kxc->c);
-    GH_DONE(h, kxc->hc);
-    GH_DESTROY(h);
+    h = GH_INIT(algs->h); HASH_STRING(h, "tripe-cookie");
+    hashge(h, g, kxc->C);
+    GH_DONE(h, kxc->hc); GH_DESTROY(h);
 
     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-      trace_block(T_CRYPTO, "crypto: computed cookie", kxc->hc, algs.hashsz);
+      trace_block(T_CRYPTO, "crypto: computed cookie",
+                 kxc->hc, algs->hashsz);
     }))
 
     /* --- Work out the shared key --- */
 
-    G_EXP(gg, r, c, kx->alpha);
+    R = g->ops->mul(g, kx->a, kxc->C);
     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-      trace(T_CRYPTO, "crypto: shared secret = %s", gestr(gg, r));
+      trace(T_CRYPTO, "crypto: shared secret = %s", g->ops->gestr(g, R));
     }))
 
     /* --- Compute the switch messages --- */
 
-    h = GH_INIT(algs.h); HASH_STRING(h, "tripe-switch-request");
-    hashge(h, kx->c); hashge(h, kxc->c);
+    h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
+    hashge(h, g, kx->C); hashge(h, g, kxc->C);
     GH_DONE(h, kxc->hswrq_out); GH_DESTROY(h);
-    h = GH_INIT(algs.h); HASH_STRING(h, "tripe-switch-confirm");
-    hashge(h, kx->c); hashge(h, kxc->c);
+    h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
+    hashge(h, g, kx->C); hashge(h, g, kxc->C);
     GH_DONE(h, kxc->hswok_out); GH_DESTROY(h);
 
-    h = GH_INIT(algs.h); HASH_STRING(h, "tripe-switch-request");
-    hashge(h, kxc->c); hashge(h, kx->c);
+    h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-request");
+    hashge(h, g, kxc->C); hashge(h, g, kx->C);
     GH_DONE(h, kxc->hswrq_in); GH_DESTROY(h);
-    h = GH_INIT(algs.h); HASH_STRING(h, "tripe-switch-confirm");
-    hashge(h, kxc->c); hashge(h, kx->c);
+    h = GH_INIT(algs->h); HASH_STRING(h, "tripe-switch-confirm");
+    hashge(h, g, kxc->C); hashge(h, g, kx->C);
     GH_DONE(h, kxc->hswok_in); GH_DESTROY(h);
 
     IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
       trace_block(T_CRYPTO, "crypto: outbound switch request",
-                 kxc->hswrq_out, algs.hashsz);
+                 kxc->hswrq_out, algs->hashsz);
       trace_block(T_CRYPTO, "crypto: outbound switch confirm",
-                 kxc->hswok_out, algs.hashsz);
+                 kxc->hswok_out, algs->hashsz);
       trace_block(T_CRYPTO, "crypto: inbound switch request",
-                 kxc->hswrq_in, algs.hashsz);
+                 kxc->hswrq_in, algs->hashsz);
       trace_block(T_CRYPTO, "crypto: inbound switch confirm",
-                 kxc->hswok_in, algs.hashsz);
+                 kxc->hswok_in, algs->hashsz);
     }))
 
     /* --- Create a new symmetric keyset --- */
 
-    buf_init(&bb, buf_o, sizeof(buf_o));
-    G_TOBUF(gg, &bb, kx->c); x = BLEN(&bb);
-    G_TOBUF(gg, &bb, kxc->c); y = BLEN(&bb);
-    G_TOBUF(gg, &bb, r); z = BLEN(&bb);
+    buf_init(&bb, buf_o, sizeof(buf_o)); a.k = BBASE(&bb);
+    g->ops->stge(g, &bb, kx->C, DHFMT_HASH); a.x = BLEN(&bb);
+    g->ops->stge(g, &bb, kxc->C, DHFMT_HASH); a.y = BLEN(&bb);
+    g->ops->stge(g, &bb, R, DHFMT_HASH); a.z = BLEN(&bb);
     assert(BOK(&bb));
 
-    kxc->ks = ks_gen(BBASE(&bb), x, y, z, kx->p);
+    kxc->ks = ks_gen(&a, kx->p);
   }
 
-  G_DESTROY(gg, c);
-  G_DESTROY(gg, cc);
-  G_DESTROY(gg, r);
-  mp_drop(cv);
+  if (C) g->ops->freege(g, C);
+  if (CC) g->ops->freege(g, CC);
+  if (R) g->ops->freege(g, R);
+  if (c) g->ops->freesc(g, c);
   return (kxc);
 
 badcheck:
   a_warn("KX", "?PEER", kx->p, "bad-expected-reply-log", A_END);
   goto bad;
 bad:
-  G_DESTROY(gg, c);
-  G_DESTROY(gg, cc);
-  G_DESTROY(gg, r);
-  mp_drop(cv);
+  if (C) g->ops->freege(g, C);
+  if (CC) g->ops->freege(g, CC);
+  if (R) g->ops->freege(g, R);
+  if (c) g->ops->freesc(g, c);
   return (0);
 }
 
@@ -723,27 +1105,48 @@ static void resend(keyexch *kx)
 {
   kxchal *kxc;
   buf bb;
-  stats *st = p_stats(kx->p);
   struct timeval tv;
+  const dhgrp *g = kx->kpriv->grp;
+  octet *p;
+  size_t sz;
   buf *b;
 
   switch (kx->s) {
     case KXS_CHAL:
-      T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
-              p_name(kx->p)); )
-      b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
-      G_TOBUF(gg, b, kx->c);
+      if (!kx->p->spec.knock) {
+       T( trace(T_KEYEXCH, "keyexch: sending prechallenge to `%s'",
+                p_name(kx->p)); )
+       b = p_txstart(kx->p, MSG_KEYEXCH | KX_PRECHAL);
+       g->ops->stge(g, b, kx->C, DHFMT_VAR);
+      } else {
+       T( trace(T_KEYEXCH, "keyexch: sending token-request to `%s'",
+                p_name(kx->p)); )
+       b = p_txstart(kx->p, MSG_KEYEXCH | KX_TOKENRQ);
+
+       buf_init(&bb, buf_t, sizeof(buf_t));
+       c_new(0, 0, &bb); assert(BOK(&bb)); buf_putbuf16(b, &bb);
+
+       buf_putu32(b, kx->kpub->id);
+
+       buf_init(&bb, buf_t, sizeof(buf_t));
+       buf_putstr16(&bb, kx->p->spec.knock);
+       sz = BLEN(&bb)%64; if (sz) sz = 64 - sz;
+       p = buf_get(&bb, sz); assert(p); memset(p, 0, sz);
+       assert(BOK(&bb)); buf_flip(&bb);
+       if (ies_encrypt(kx->kpub, MSG_KEYEXCH | KX_TOKENRQ, &bb, b))
+         buf_break(b);
+      }
       break;
     case KXS_COMMIT:
       T( trace(T_KEYEXCH, "keyexch: sending switch request to `%s'",
               p_name(kx->p)); )
       kxc = kx->r[0];
       b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCH);
-      buf_put(b, kx->hc, algs.hashsz);
-      buf_put(b, kxc->hc, algs.hashsz);
+      buf_put(b, kx->hc, kx->kpriv->algs.hashsz);
+      buf_put(b, kxc->hc, kx->kpriv->algs.hashsz);
       buf_init(&bb, buf_i, sizeof(buf_i));
-      G_TORAW(gg, &bb, kxc->r);
-      buf_put(&bb, kxc->hswrq_out, algs.hashsz);
+      g->ops->stge(g, &bb, kxc->R, DHFMT_STD);
+      buf_put(&bb, kxc->hswrq_out, kx->kpriv->algs.hashsz);
       buf_flip(&bb);
       ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCH, &bb, b);
       break;
@@ -753,7 +1156,7 @@ static void resend(keyexch *kx)
       kxc = kx->r[0];
       b = p_txstart(kx->p, MSG_KEYEXCH | KX_SWITCHOK);
       buf_init(&bb, buf_i, sizeof(buf_i));
-      buf_put(&bb, kxc->hswok_out, algs.hashsz);
+      buf_put(&bb, kxc->hswok_out, kx->kpriv->algs.hashsz);
       buf_flip(&bb);
       ks_encrypt(kxc->ks, MSG_KEYEXCH | KX_SWITCHOK, &bb, b);
       break;
@@ -762,14 +1165,12 @@ static void resend(keyexch *kx)
   }
 
   if (BOK(b)) {
-    st->n_kxout++;
-    st->sz_kxout += BLEN(b);
+    update_stats_tx(kx, BLEN(b));
     p_txend(kx->p);
   }
 
   if (kx->s < KXS_SWITCH) {
-    gettimeofday(&tv, 0);
-    tv.tv_sec += T_RETRY;
+    rs_time(&kx->rs, &tv, 0);
     settimer(kx, &tv);
   }
 }
@@ -815,25 +1216,26 @@ static int decryptrest(keyexch *kx, kxchal *kxc, unsigned msg, buf *b)
 
 static int checkresponse(keyexch *kx, unsigned msg, buf *b)
 {
-  ge *r = G_CREATE(gg);
+  const dhgrp *g = kx->kpriv->grp;
+  dhge *R;
 
-  if (G_FROMRAW(gg, b, r)) {
+  if ((R = g->ops->ldge(g, b, DHFMT_STD)) == 0) {
     a_warn("KX", "?PEER", kx->p, "invalid", "%s", pkname[msg], A_END);
     goto bad;
   }
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace(T_CRYPTO, "crypto: reply = %s", gestr(gg, r));
+    trace(T_CRYPTO, "crypto: reply = %s", g->ops->gestr(g, R));
   }))
-  if (!G_EQ(gg, r, kx->rx)) {
+  if (!g->ops->eq(g, R, kx->RX)) {
     a_warn("KX", "?PEER", kx->p, "incorrect", "response", A_END);
     goto bad;
   }
 
-  G_DESTROY(gg, r);
+  g->ops->freege(g, R);
   return (0);
 
 bad:
-  G_DESTROY(gg, r);
+  if (R) g->ops->freege(g, R);
   return (-1);
 }
 
@@ -912,11 +1314,12 @@ bad:
 static void kxfinish(keyexch *kx)
 {
   kxchal *kxc = kx->r[0];
-  struct timeval tv;
+  struct timeval now, tv;
 
   ks_activate(kxc->ks);
-  gettimeofday(&tv, 0);
-  tv.tv_sec += T_REGEN;
+  gettimeofday(&now, 0);
+  f2tv(&tv, wobble(T_REGEN));
+  TV_ADD(&tv, &now, &tv);
   settimer(kx, &tv);
   kx->s = KXS_SWITCH;
   a_notify("KXDONE", "?PEER", kx->p, A_END);
@@ -935,34 +1338,35 @@ static void kxfinish(keyexch *kx)
 
 static int doswitch(keyexch *kx, buf *b)
 {
+  size_t hsz = kx->kpriv->algs.hashsz;
   const octet *hc_in, *hc_out, *hswrq;
   kxchal *kxc;
 
-  if ((hc_in = buf_get(b, algs.hashsz)) == 0 ||
-      (hc_out = buf_get(b, algs.hashsz)) == 0) {
+  if ((hc_in = buf_get(b, hsz)) == 0 ||
+      (hc_out = buf_get(b, hsz)) == 0) {
     a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
     goto bad;
   }
   IF_TRACING(T_KEYEXCH, IF_TRACING(T_CRYPTO, {
-    trace_block(T_CRYPTO, "crypto: challenge", hc_in, algs.hashsz);
-    trace_block(T_CRYPTO, "crypto: cookie", hc_out, algs.hashsz);
+    trace_block(T_CRYPTO, "crypto: challenge", hc_in, hsz);
+    trace_block(T_CRYPTO, "crypto: cookie", hc_out, hsz);
   }))
   if ((kxc = kxc_byhc(kx, hc_in)) == 0 ||
-      memcmp(hc_out, kx->hc, algs.hashsz) != 0) {
+      memcmp(hc_out, kx->hc, hsz) != 0) {
     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
     goto bad;
   }
   if (decryptrest(kx, kxc, KX_SWITCH, b) ||
       checkresponse(kx, KX_SWITCH, b))
     goto bad;
-  if ((hswrq = buf_get(b, algs.hashsz)) == 0 || BLEFT(b)) {
+  if ((hswrq = buf_get(b, hsz)) == 0 || BLEFT(b)) {
     a_warn("KX", "?PEER", kx->p, "invalid", "switch-rq", A_END);
     goto bad;
   }
   IF_TRACING(T_KEYEXCH, {
-    trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, algs.hashsz);
+    trace_block(T_CRYPTO, "crypto: switch request hash", hswrq, hsz);
   })
-  if (memcmp(hswrq, kxc->hswrq_in, algs.hashsz) != 0) {
+  if (memcmp(hswrq, kxc->hswrq_in, hsz) != 0) {
     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-rq", A_END);
     goto bad;
   }
@@ -989,6 +1393,7 @@ bad:
 
 static int doswitchok(keyexch *kx, buf *b)
 {
+  size_t hsz = kx->kpriv->algs.hashsz;
   const octet *hswok;
   kxchal *kxc;
   buf bb;
@@ -1001,15 +1406,15 @@ static int doswitchok(keyexch *kx, buf *b)
   buf_init(&bb, buf_o, sizeof(buf_o));
   if (decryptrest(kx, kxc, KX_SWITCHOK, b))
     goto bad;
-  if ((hswok = buf_get(b, algs.hashsz)) == 0 || BLEFT(b)) {
+  if ((hswok = buf_get(b, hsz)) == 0 || BLEFT(b)) {
     a_warn("KX", "?PEER", kx->p, "invalid", "switch-ok", A_END);
     goto bad;
   }
   IF_TRACING(T_KEYEXCH, {
     trace_block(T_CRYPTO, "crypto: switch confirmation hash",
-               hswok, algs.hashsz);
+               hswok, hsz);
   })
-  if (memcmp(hswok, kxc->hswok_in, algs.hashsz) != 0) {
+  if (memcmp(hswok, kxc->hswok_in, hsz) != 0) {
     a_warn("KX", "?PEER", kx->p, "incorrect", "switch-ok", A_END);
     goto bad;
   }
@@ -1039,6 +1444,7 @@ bad:
 
 static void stop(keyexch *kx)
 {
+  const dhgrp *g = kx->kpriv->grp;
   unsigned i;
 
   if (kx->f & KXF_DEAD)
@@ -1048,9 +1454,9 @@ static void stop(keyexch *kx)
     sel_rmtimer(&kx->t);
   for (i = 0; i < kx->nr; i++)
     kxc_destroy(kx->r[i]);
-  mp_drop(kx->alpha);
-  G_DESTROY(gg, kx->c);
-  G_DESTROY(gg, kx->rx);
+  g->ops->freesc(g, kx->a);
+  g->ops->freege(g, kx->C);
+  g->ops->freege(g, kx->RX);
   kx->t_valid = 0;
   kx->f |= KXF_DEAD;
   kx->f &= ~KXF_TIMER;
@@ -1069,31 +1475,35 @@ static void stop(keyexch *kx)
 
 static void start(keyexch *kx, time_t now)
 {
+  algswitch *algs = &kx->kpriv->algs;
+  const dhgrp *g = kx->kpriv->grp;
   ghash *h;
 
   assert(kx->f & KXF_DEAD);
 
   kx->f &= ~(KXF_DEAD | KXF_CORK);
   kx->nr = 0;
-  kx->alpha = mprand_range(MP_NEW, gg->r, &rand_global, 0);
-  kx->c = G_CREATE(gg); G_EXP(gg, kx->c, gg->g, kx->alpha);
-  kx->rx = G_CREATE(gg); G_EXP(gg, kx->rx, kx->kpub, kx->alpha);
+  kx->a = g->ops->randsc(g);
+  kx->C = g->ops->mul(g, kx->a, 0);
+  kx->RX = g->ops->mul(g, kx->a, kx->kpub->K);
   kx->s = KXS_CHAL;
   kx->t_valid = now + T_VALID;
 
-  h = GH_INIT(algs.h);
+  h = GH_INIT(algs->h);
   HASH_STRING(h, "tripe-cookie");
-  hashge(h, kx->c);
+  hashge(h, g, kx->C);
   GH_DONE(h, kx->hc);
   GH_DESTROY(h);
 
   IF_TRACING(T_KEYEXCH, {
     trace(T_KEYEXCH, "keyexch: creating new challenge");
     IF_TRACING(T_CRYPTO, {
-      trace(T_CRYPTO, "crypto: secret = %s", mpstr(kx->alpha));
-      trace(T_CRYPTO, "crypto: challenge = %s", gestr(gg, kx->c));
-      trace(T_CRYPTO, "crypto: expected response = %s", gestr(gg, kx->rx));
-      trace_block(T_CRYPTO, "crypto: challenge cookie", kx->hc, algs.hashsz);
+      trace(T_CRYPTO, "crypto: secret = %s", g->ops->scstr(g, kx->a));
+      trace(T_CRYPTO, "crypto: challenge = %s", g->ops->gestr(g, kx->C));
+      trace(T_CRYPTO, "crypto: expected response = %s",
+           g->ops->gestr(g, kx->RX));
+      trace_block(T_CRYPTO, "crypto: challenge cookie",
+                 kx->hc, algs->hashsz);
     })
   })
 }
@@ -1111,13 +1521,17 @@ static void start(keyexch *kx, time_t now)
 static int checkpub(keyexch *kx)
 {
   time_t now;
+  unsigned f = 0;
+
   if (kx->f & KXF_DEAD)
     return (-1);
   now = time(0);
-  if (KEY_EXPIRED(now, kx->texp_kpub)) {
+  if (KEY_EXPIRED(now, kx->kpriv->t_exp)) f |= 1;
+  if (KEY_EXPIRED(now, kx->kpub->t_exp)) f |= 2;
+  if (f) {
     stop(kx);
-    a_warn("KX", "?PEER", kx->p, "public-key-expired", A_END);
-    G_COPY(gg, kx->kpub, gg->i);
+    if (f & 1) a_warn("KX", "?PEER", kx->p, "private-key-expired", A_END);
+    if (f & 2) a_warn("KX", "?PEER", kx->p, "public-key-expired", A_END);
     kx->f &= ~KXF_PUBKEY;
     return (-1);
   }
@@ -1153,68 +1567,48 @@ void kx_start(keyexch *kx, int forcep)
 /* --- @kx_message@ --- *
  *
  * Arguments:  @keyexch *kx@ = pointer to key exchange context
+ *             @const addr *a@ = sender's IP address and port
  *             @unsigned msg@ = the message code
  *             @buf *b@ = pointer to buffer containing the packet
  *
- * Returns:    ---
+ * Returns:    Nonzero if the sender's address was unknown.
  *
  * Use:                Reads a packet containing key exchange messages and handles
  *             it.
  */
 
-void kx_message(keyexch *kx, unsigned msg, buf *b)
+int kx_message(keyexch *kx, const addr *a, unsigned msg, buf *b)
 {
-  struct timeval now, tv;
-  stats *st = p_stats(kx->p);
   size_t sz = BSZ(b);
   int rc;
 
-  gettimeofday(&now, 0);
-  if (kx->f & KXF_CORK) {
-    start(kx, now.tv_sec);
-    TV_ADDL(&tv, &now, T_RETRY, 0);
-    settimer(kx, &tv);
-    a_notify("KXSTART", A_END);
-  }
+  T( trace(T_KEYEXCH, "keyexch: processing %s packet from %c%s%c",
+          msg < KX_NMSG ? pkname[msg] : "unknown",
+          kx ? '`' : '<', kx ? p_name(kx->p) : "nil", kx ? '\'' : '>'); )
 
-  if (checkpub(kx))
-    return;
-
-  if (!VALIDP(kx, now.tv_sec)) {
-    stop(kx);
-    start(kx, now.tv_sec);
+  switch (msg) {
+    case KX_TOKENRQ: dotokenrq(a, b); return (0);
+    case KX_KNOCK: doknock(a, b); return (0);
   }
-  T( trace(T_KEYEXCH, "keyexch: processing %s packet from `%s'",
-          msg < KX_NMSG ? pkname[msg] : "unknown", p_name(kx->p)); )
+
+  if (!kx) return (-1);
+  if (notice_message(kx)) return (0);
 
   switch (msg) {
-    case KX_PRECHAL:
-      rc = doprechallenge(kx, b);
-      break;
-    case KX_CHAL:
-      rc = dochallenge(kx, b);
-      break;
-    case KX_REPLY:
-      rc = doreply(kx, b);
-      break;
-    case KX_SWITCH:
-      rc = doswitch(kx, b);
-      break;
-    case KX_SWITCHOK:
-      rc = doswitchok(kx, b);
-      break;
+    case KX_TOKEN: rc = dotoken(kx, b); break;
+    case KX_PRECHAL: rc = doprechallenge(kx, b); break;
+    case KX_CHAL: rc = dochallenge(kx, b); break;
+    case KX_REPLY: rc = doreply(kx, b); break;
+    case KX_SWITCH: rc = doswitch(kx, b); break;
+    case KX_SWITCHOK: rc = doswitchok(kx, b); break;
     default:
       a_warn("KX", "?PEER", kx->p, "unknown-message", "0x%02x", msg, A_END);
       rc = -1;
       break;
   }
 
-  if (rc)
-    st->n_reject++;
-  else {
-    st->n_kxin++;
-    st->sz_kxin += sz;
-  }
+  update_stats_rx(kx, !rc, sz);
+  return (0);
 }
 
 /* --- @kx_free@ --- *
@@ -1229,7 +1623,8 @@ void kx_message(keyexch *kx, unsigned msg, buf *b)
 void kx_free(keyexch *kx)
 {
   stop(kx);
-  G_DESTROY(gg, kx->kpub);
+  km_unref(kx->kpub);
+  km_unref(kx->kpriv);
 }
 
 /* --- @kx_newkeys@ --- *
@@ -1246,19 +1641,118 @@ void kx_free(keyexch *kx)
 
 void kx_newkeys(keyexch *kx)
 {
-  if (km_getpubkey(p_tag(kx->p), kx->kpub, &kx->texp_kpub))
-    return;
+  kdata *kpriv, *kpub;
+  unsigned i;
+  int switchp;
+  time_t now = time(0);
+
+  T( trace(T_KEYEXCH, "keyexch: checking new keys for `%s'",
+          p_name(kx->p)); )
+
+  /* --- Find out whether we can use new keys --- *
+   *
+   * Try each available combination of new and old, public and private,
+   * except both old (which is status quo anyway).  The selection is encoded
+   * in @i@, with bit 0 for the private key and bit 1 for public key; a set
+   * bit means to use the old value, and a clear bit means to use the new
+   * one.
+   *
+   * This means that we currently prefer `old private and new public' over
+   * `new private and old public'.  I'm not sure which way round this should
+   * actually be.
+   */
+
+  for (i = 0; i < 3; i++) {
+
+    /* --- Select the keys we're going to examine --- *
+     *
+     * If we're meant to have a new key and don't, then skip this
+     * combination.
+     */
+
+    T( trace(T_KEYEXCH, "keyexch: checking %s private, %s public",
+            i & 1 ? "old" : "new", i & 2 ? "old" : "new"); )
+
+    if (i & 1) kpriv = kx->kpriv;
+    else if (kx->kpriv->kn->kd != kx->kpriv) kpriv = kx->kpriv->kn->kd;
+    else {
+      T( trace(T_KEYEXCH, "keyexch: private key unchanged, skipping"); )
+      continue;
+    }
+
+    if (i & 2) kpub = kx->kpub;
+    else if (kx->kpub->kn->kd != kx->kpub) kpub = kx->kpub->kn->kd;
+    else {
+      T( trace(T_KEYEXCH, "keyexch: public key unchanged, skipping"); )
+      continue;
+    }
+
+    /* --- Skip if either key is expired --- *
+     *
+     * We're not going to get far with expired keys, and this simplifies the
+     * logic below.
+     */
+
+    if (KEY_EXPIRED(now, kx->kpriv->t_exp) ||
+       KEY_EXPIRED(now, kx->kpub->t_exp)) {
+      T( trace(T_KEYEXCH, "keyexch: %s expired, skipping",
+              !KEY_EXPIRED(now, kx->kpriv->t_exp) ? "public key" :
+              !KEY_EXPIRED(now, kx->kpub->t_exp) ? "private key" :
+              "both keys"); )
+      continue;
+    }
+
+    /* --- If the groups don't match then we can't use this pair --- */
+
+    if (!km_samealgsp(kpriv, kpub)) {
+      T( trace(T_KEYEXCH, "keyexch: peer `%s' group mismatch; "
+              "%s priv `%s' and %s pub `%s'", p_name(kx->p),
+              i & 1 ? "old" : "new", km_tag(kx->kpriv),
+              i & 2 ? "old" : "new", km_tag(kx->kpub)); )
+      continue;
+    }
+    goto newkeys;
+  }
+  T( trace(T_KEYEXCH, "keyexch: peer `%s' continuing with old keys",
+          p_name(kx->p)); )
+  return;
+
+  /* --- We've chosen new keys --- *
+   *
+   * Switch the new ones into place.  Neither of the keys we're switching to
+   * is expired (we checked that above), so we should just crank everything
+   * up.
+   *
+   * A complication arises: we don't really want to force a new key exchange
+   * unless we have to.  If the group is unchanged, and we're currently
+   * running OK, then we should just let things lie.
+   */
+
+newkeys:
+  switchp = ((kx->f & KXF_DEAD) ||
+            kx->s != KXS_SWITCH ||
+            kpriv->grp->ops != kx->kpriv->grp->ops ||
+            !kpriv->grp->ops->samegrpp(kpriv->grp, kx->kpriv->grp));
+
+  T( trace(T_KEYEXCH, "keyexch: peer `%s' adopting "
+          "%s priv `%s' and %s pub `%s'; %sforcing exchange", p_name(kx->p),
+          i & 1 ? "old" : "new", km_tag(kx->kpriv),
+          i & 2 ? "old" : "new", km_tag(kx->kpub),
+          switchp ? "" : "not "); )
+
+  if (switchp) stop(kx);
+  km_ref(kpriv); km_unref(kx->kpriv); kx->kpriv = kpriv;
+  km_ref(kpub);  km_unref(kx->kpub);  kx->kpub  = kpub;
   kx->f |= KXF_PUBKEY;
-  if ((kx->f & KXF_DEAD) || kx->s != KXS_SWITCH) {
+  if (switchp) {
     T( trace(T_KEYEXCH, "keyexch: restarting key negotiation with `%s'",
             p_name(kx->p)); )
-    stop(kx);
     start(kx, time(0));
     resend(kx);
   }
 }
 
-/* --- @kx_init@ --- *
+/* --- @kx_setup@ --- *
  *
  * Arguments:  @keyexch *kx@ = pointer to key exchange context
  *             @peer *p@ = pointer to peer context
@@ -1272,22 +1766,47 @@ void kx_newkeys(keyexch *kx)
  *             exchange.
  */
 
-int kx_init(keyexch *kx, peer *p, keyset **ks, unsigned f)
+int kx_setup(keyexch *kx, peer *p, keyset **ks, unsigned f)
 {
+  if ((kx->kpriv = km_findpriv(p_privtag(p))) == 0) goto fail_0;
+  if ((kx->kpub = km_findpub(p_tag(p))) == 0) goto fail_1;
+  if (!km_samealgsp(kx->kpriv, kx->kpub)) {
+    a_warn("KX", "?PEER", p, "group-mismatch",
+          "local-private-key", "%s", p_privtag(p),
+          "peer-public-key", "%s", p_tag(p),
+          A_END);
+    goto fail_2;
+  }
+
   kx->ks = ks;
   kx->p = p;
-  kx->kpub = G_CREATE(gg);
-  if (km_getpubkey(p_tag(p), kx->kpub, &kx->texp_kpub)) {
-    G_DESTROY(gg, kx->kpub);
-    return (-1);
-  }
   kx->f = KXF_DEAD | KXF_PUBKEY | f;
+  rs_reset(&kx->rs);
   if (!(kx->f & KXF_CORK)) {
     start(kx, time(0));
     resend(kx);
     /* Don't notify here: the ADD message hasn't gone out yet. */
   }
   return (0);
+
+fail_2:
+  km_unref(kx->kpub);
+fail_1:
+  km_unref(kx->kpriv);
+fail_0:
+  return (-1);
 }
 
+/* --- @kx_init@ --- *
+ *
+ * Arguments:  ---
+ *
+ * Returns:    ---
+ *
+ * Use:                Initializes the key-exchange logic.
+ */
+
+void kx_init(void)
+  { ratelim_init(&unauth_limit, 20, 500); }
+
 /*----- That's all, folks -------------------------------------------------*/