chiark / gitweb /
More documentation.
[tripe] / keyset.c
index 4dd2c596609d10a92f7dd610ebacb6c2026c6658..cf0414992f1b5c1674b119d9a849e2f538dcffdb 100644 (file)
--- a/keyset.c
+++ b/keyset.c
@@ -1,6 +1,6 @@
 /* -*-c-*-
  *
- * $Id: keyset.c,v 1.2 2001/02/05 19:53:23 mdw Exp $
+ * $Id: keyset.c,v 1.3 2001/02/16 21:39:55 mdw Exp $
  *
  * Handling of symmetric keysets
  *
 /*----- Revision history --------------------------------------------------* 
  *
  * $Log: keyset.c,v $
+ * Revision 1.3  2001/02/16 21:39:55  mdw
+ * Major overhaul.  Separate functions for manipulating keysets from
+ * functions for manipulating keyset lists.  Introduce a concept of
+ * listening-only keys.
+ *
  * Revision 1.2  2001/02/05 19:53:23  mdw
  * Add sequence number protection.
  *
 
 /*----- Tunable parameters ------------------------------------------------*/
 
-#define KEY_EXPTIME MIN(60)            /* Expiry time for a key */
-#define KEY_REGENTIME MIN(45)          /* Regeneration time for a key */
-#define KEY_EXPSZ MEG(512)             /* Expiry data size for a key */
-#define KEY_REGENSZ MEG(256)           /* Data size threshold for regen */
+#define T_EXP MIN(60)                  /* Expiry time for a key */
+#define T_REGEN MIN(45)                        /* Regeneration time for a key */
+#define SZ_EXP MEG(64)                 /* Expiry data size for a key */
+#define SZ_REGEN MEG(32)               /* Data size threshold for regen */
 
 /*----- Handy macros ------------------------------------------------------*/
 
 #define KEYOK(ks, now) ((ks)->sz_exp > 0 && (ks)->t_exp > now)
 
-/*----- Main code ---------------------------------------------------------*/
+/*----- Low-level packet encryption and decryption ------------------------*/
 
-/* --- @freeks@ --- *
+/* --- @doencrypt@ --- *
  *
- * Arguments:  @keyset *ks@ = pointer to a keyset
+ * Arguments:  @keyset *ks@ = pointer to keyset to use
+ *             @buf *b@ = pointer to an input buffer
+ *             @buf *bb@ = pointer to an output buffer
  *
- * Returns:    ---
+ * Returns:    Zero if OK, nonzero if a new key is required.
  *
- * Use:                Frees a keyset.
+ * Use:                Encrypts a message with the given key.  We assume that the
+ *             keyset is OK to use.
  */
 
-static void freeks(keyset *ks)
+static int doencrypt(keyset *ks, buf *b, buf *bb)
 {
-  ks->c->ops->destroy(ks->c);
-  ks->m->ops->destroy(ks->m);
-  DESTROY(ks);
+  ghash *h;
+  gcipher *c;
+  size_t ivsz;
+  const octet *p = BCUR(b);
+  size_t sz = BLEFT(b);
+  octet *qiv, *qseq, *qpk;
+  uint32 oseq;
+  size_t osz, nsz;
+  int rc = 0;
+
+  /* --- Allocate the required buffer space --- */
+
+  c = ks->cout;
+  ivsz = c->ops->c->blksz;
+  if (buf_ensure(bb, ivsz + 4 + sz))
+    return (0); /* Caution! */
+  qiv = BCUR(bb); qseq = qiv + ivsz; qpk = qseq + 4;
+  BSTEP(bb, ivsz + 4 + sz);
+
+  /* --- MAC and encrypt the packet --- */
+
+  oseq = ks->oseq++; STORE32(qseq, oseq);
+  h = ks->mout->ops->init(ks->mout);
+  h->ops->hash(h, qseq, 4);
+  h->ops->hash(h, p, sz);
+  memcpy(qiv, h->ops->done(h, 0), ivsz);
+  h->ops->destroy(h);
+  IF_TRACING(T_KEYSET, {
+    trace(T_KEYSET, "keyset: encrypting packet %lu using keyset %u",
+         (unsigned long)oseq, ks->seq);
+    trace_block(T_CRYPTO, "crypto: computed MAC", qiv, ivsz);
+  })
+  c->ops->setiv(c, qiv);
+  c->ops->encrypt(c, p, qpk, sz);
+  IF_TRACING(T_KEYSET, {
+    trace_block(T_CRYPTO, "crypto: encrypted packet", qpk, sz);
+  })
+
+  /* --- Deduct the packet size from the key's data life --- */
+
+  osz = ks->sz_exp;
+  if (osz > sz)
+    nsz = osz - sz;
+  else
+    nsz = 0;
+  if (osz >= SZ_REGEN && nsz < SZ_REGEN) {
+    T( trace(T_KEYSET, "keyset: keyset %u data regen limit exceeded -- "
+            "forcing exchange", ks->seq); )
+    rc = -1;
+  }
+  ks->sz_exp = nsz;
+  return (rc);  
 }
 
-/* --- @ks_free@ --- *
+/* --- @dodecrypt@ --- *
  *
- * Arguments:  @keyset **ksroot@ = pointer to keyset list head
+ * Arguments:  @keyset *ks@ = pointer to keyset to use
+ *             @buf *b@ = pointer to an input buffer
+ *             @buf *bb@ = pointer to an output buffer
+ *             @uint32 *seq@ = where to store the sequence number
  *
- * Returns:    ---
+ * Returns:    Zero if OK, nonzero if it failed.
  *
- * Use:                Frees all of the keys in a keyset.
+ * Use:                Attempts to decrypt a message with the given key.  No other
+ *             checking (e.g., sequence number checks) is performed.  We
+ *             assume that the keyset is OK to use, and that there is
+ *             sufficient output buffer space reserved.  If the decryption
+ *             is successful, the buffer pointer is moved past the decrypted
+ *             packet, and the packet's sequence number is stored in @*seq@.
  */
 
-void ks_free(keyset **ksroot)
+static int dodecrypt(keyset *ks, buf *b, buf *bb, uint32 *seq)
 {
-  keyset *ks, *ksn;
-  for (ks = *ksroot; ks; ks = ksn) {
-    ksn = ks->next;
-    freeks(ks);
+  const octet *piv, *pseq, *ppk;
+  size_t psz = BLEFT(b);
+  size_t sz;
+  octet *q = BCUR(bb);
+  ghash *h;
+  gcipher *c = ks->cin;
+  size_t ivsz = c->ops->c->blksz;
+  octet *mac;
+  int eq;
+
+  /* --- Break up the packet into its components --- */
+
+  if (psz < ivsz + 4) {
+    T( trace(T_KEYSET, "keyset: block too small for keyset %u", ks->seq); )
+    return (-1);
   }
+  sz = psz - ivsz - 4;
+  piv = BCUR(b); pseq = piv + ivsz; ppk = pseq + 4;
+
+  /* --- Attempt to decrypt the packet --- */
+
+  c->ops->setiv(c, piv);
+  c->ops->decrypt(c, ppk, q, sz);
+  h = ks->min->ops->init(ks->min);
+  h->ops->hash(h, pseq, 4);
+  h->ops->hash(h, q, sz);
+  mac = h->ops->done(h, 0);
+  eq = !memcmp(mac, piv, ivsz);
+  IF_TRACING(T_KEYSET, {
+    trace(T_KEYSET, "keyset: decrypting using keyset %u", ks->seq);
+    trace_block(T_CRYPTO, "crypto: computed MAC", mac, ivsz);
+  })
+  h->ops->destroy(h);
+  if (!eq) {
+    IF_TRACING(T_KEYSET, {
+      trace(T_KEYSET, "keyset: decryption failed");
+      trace_block(T_CRYPTO, "crypto: expected MAC", piv, ivsz);
+      trace_block(T_CRYPTO, "crypto: invalid packet", q, sz);
+    })
+    return (-1);
+  }
+  if (seq)
+    *seq = LOAD32(pseq);
+  IF_TRACING(T_KEYSET, {
+    trace(T_KEYSET, "keyset: decrypted OK (sequence = %lu)",
+         (unsigned long)LOAD32(pseq));
+    trace_block(T_CRYPTO, "crypto: decrypted packet", q, sz);
+  })
+  BSTEP(bb, sz);
+  return (0);
 }
 
-/* --- @ks_prune@ --- *
+/* --- @dosequence@ --- *
  *
- * Arguments:  @keyset **ksroot@ = pointer to keyset list head
+ * Arguments:  @keyset *ks@ = pointer to a keyset
+ *             @uint32 seq@ = a sequence number from a packet
  *
- * Returns:    ---
+ * Returns:    Zero if the sequence number is OK, nonzero if it's not.
  *
- * Use:                Prunes the keyset list by removing keys which mustn't be used
- *             any more.
+ * Use:                Checks a sequence number.  The data in the keyset which keeps
+ *             track of valid sequence numbers is updated if the sequence
+ *             number given is good.  It's assumed that the sequence number
+ *             has already been checked for authenticity.
  */
 
-void ks_prune(keyset **ksroot)
+static int dosequence(keyset *ks, uint32 seq)
 {
-  time_t now = time(0);
+  uint32 seqbit;
+  uint32 n;
 
-  while (*ksroot) {
-    keyset *ks = *ksroot;
-    if (ks->t_exp <= now) {
-      T( trace(T_KEYSET, "keyset: expiring keyset %u (time limit reached)",
-              ks->seq); )
-      *ksroot = ks->next;
-      freeks(ks);
-    } else if (ks->sz_exp == 0) {
-      T( trace(T_KEYSET, "keyset: expiring keyset %u (data limit reached)",
-              ks->seq); )
-      *ksroot = ks->next;
-      freeks(ks);
-    } else
-      ksroot = &ks->next;
+  if (seq < ks->iseq) {
+    a_warn("received packet has old sequence number (possible replay)");
+    return (-1);
   }
+  if (seq >= ks->iseq + KS_SEQWINSZ) {
+    n = seq - (ks->iseq + KS_SEQWINSZ - 1);
+    if (n < KS_SEQWINSZ)
+      ks->iwin >>= n;
+    else
+      ks->iwin = 0;
+    ks->iseq += n;
+  }
+  seqbit = 1 << (seq - ks->iseq);
+  if (ks->iwin & seqbit) {
+    a_warn("received packet repeats old sequence number");
+    return (-1);
+  }
+  ks->iwin |= seqbit;
+  return (0);
+}
+
+/*----- Operations on a single keyset -------------------------------------*/
+
+/* --- @ks_drop@ --- *
+ *
+ * Arguments:  @keyset *ks@ = pointer to a keyset
+ *
+ * Returns:    ---
+ *
+ * Use:                Decrements a keyset's reference counter.  If the counter hits
+ *             zero, the keyset is freed.
+ */
+
+void ks_drop(keyset *ks)
+{
+  if (--ks->ref)
+    return;
+  ks->cin->ops->destroy(ks->cin);
+  ks->cout->ops->destroy(ks->cout);
+  ks->min->ops->destroy(ks->min);
+  ks->mout->ops->destroy(ks->mout);
+  DESTROY(ks);
 }
 
 /* --- @ks_gen@ --- *
  *
- * Arguments:  @keyset **ksroot@ = pointer to keyset list head
- *             @const void *k@ = pointer to key material
- *             @size_t sz@ = size of the key material
+ * Arguments:  @const void *k@ = pointer to key material
+ *             @size_t x, y, z@ = offsets into key material (see below)
  *
- * Returns:    The regeneration time for the new key.
+ * Returns:    A pointer to the new keyset.
  *
- * Use:                Derives a keyset from the given key material and adds it to
- *             the list.
+ * Use:                Derives a new keyset from the given key material.  The
+ *             offsets @x@, @y@ and @z@ separate the key material into three
+ *             parts.  Between the @k@ and @k + x@ is `my' contribution to
+ *             the key material; between @k + x@ and @k + y@ is `your'
+ *             contribution; and between @k + y@ and @k + z@ is a shared
+ *             value we made together.  These are used to construct two
+ *             pairs of symmetric keys.  Each pair consists of an encryption
+ *             key and a message authentication key.  One pair is used for
+ *             outgoing messages, the other for incoming messages.
+ *
+ *             The new key is marked so that it won't be selected for output
+ *             by @ksl_encrypt@.  You can still encrypt data with it by
+ *             calling @ks_encrypt@ directly.
  */
 
-time_t ks_gen(keyset **ksroot, const void *k, size_t sz)
+keyset *ks_gen(const void *k, size_t x, size_t y, size_t z)
 {
-  rmd160_ctx r;
-  octet buf[RMD160_HASHSZ];
+  HASH_CTX h;
+  octet buf[HASHSZ];
   keyset *ks = CREATE(keyset);
   time_t now = time(0);
+  const octet *p = k;
   T( static unsigned seq = 0; )
 
   T( trace(T_KEYSET, "keyset: adding new keyset %u", seq); )
 
-#define GETHASH(str) do {                                              \
-  rmd160_init(&r);                                                     \
-  rmd160_hash(&r, str, sizeof(str) - 1);                               \
-  rmd160_hash(&r, k, sz);                                              \
-  rmd160_done(&r, buf);                                                        \
+  /* --- Construct the various keys --- *
+   *
+   * This is done with macros, because it's quite tedious.
+   */
+
+#define MINE HASH(&h, p, x)
+#define YOURS HASH(&h, p + x, y - x)
+#define OURS HASH(&h, p + y, z - y)
+
+#define IN MINE; YOURS; OURS
+#define OUT YOURS; MINE; OURS
+#define STR_IN "incoming"
+#define STR_OUT "outgoing"
+
+#define GETHASH(str, dir) do {                                         \
+  HASH_INIT(&h);                                                       \
+  HASH_STRING(&h, "tripe-" str);                                       \
+  dir;                                                                 \
+  HASH_DONE(&h, buf);                                                  \
   IF_TRACING(T_KEYSET, {                                               \
-    trace_block(T_CRYPTO, "crypto: key " str, buf, sizeof(buf));       \
+    trace_block(T_CRYPTO, "crypto: " STR_##dir " key " str,            \
+               buf, sizeof(buf));                                      \
   })                                                                   \
 } while (0)
 
-  GETHASH("tripe-encryption "); ks->c = blowfish_cbc.init(buf, sizeof(buf));
-  GETHASH("tripe-integrity "); ks->m = rmd160_hmac.key(buf, sizeof(buf));
-
+  GETHASH("encryption", IN); ks->cin = CIPHER->init(buf, sizeof(buf));
+  GETHASH("integrity", IN); ks->min = MAC->key(buf, sizeof(buf));
+  GETHASH("encryption", OUT); ks->cout = CIPHER->init(buf, sizeof(buf));
+  GETHASH("integrity", OUT); ks->mout = MAC->key(buf, sizeof(buf));
+
+#undef MINE
+#undef YOURS
+#undef OURS
+#undef IN
+#undef OUT
+#undef STR_IN
+#undef STR_OUT
 #undef GETHASH
 
   T( ks->seq = seq++; )
-  ks->t_exp = now + KEY_EXPTIME;
-  ks->sz_exp = KEY_EXPSZ;
+  ks->t_exp = now + T_EXP;
+  ks->sz_exp = SZ_EXP;
   ks->oseq = ks->iseq = 0;
   ks->iwin = 0;
-  ks->next = *ksroot;
-  *ksroot = ks;
+  ks->next = 0;
+  ks->f = KSF_LISTEN;
   BURN(buf);
-  return (now + KEY_REGENTIME);
+  return (ks);
+}
+
+/* --- @ks_tregen@ --- *
+ *
+ * Arguments:  @keyset *ks@ = pointer to a keyset
+ *
+ * Returns:    The time at which moves ought to be made to replace this key.
+ */
+
+time_t ks_tregen(keyset *ks) { return (ks->t_exp - T_EXP + T_REGEN); }
+
+/* --- @ks_activate@ --- *
+ *
+ * Arguments:  @keyset *ks@ = pointer to a keyset
+ *
+ * Returns:    ---
+ *
+ * Use:                Activates a keyset, so that it can be used for encrypting
+ *             outgoing messages.
+ */
+
+void ks_activate(keyset *ks)
+{
+  if (ks->f & KSF_LISTEN) {
+    T( trace(T_KEYSET, "keyset: activating keyset %u", ks->seq); )
+    ks->f &= ~KSF_LISTEN;
+  }
 }
 
 /* --- @ks_encrypt@ --- *
+ *
+ * Arguments:  @keyset *ks@ = pointer to a keyset
+ *             @buf *b@ = pointer to input buffer
+ *             @buf *bb@ = pointer to output buffer
+ *
+ * Returns:    Zero if OK, nonzero if the key needs replacing.  If the
+ *             encryption failed, the output buffer is broken and zero is
+ *             returned.
+ *
+ * Use:                Encrypts a block of data using the key.  Note that the `key
+ *             ought to be replaced' notification is only ever given once
+ *             for each key.  Also note that this call forces a keyset to be
+ *             used even if it's marked as not for data output.
+ */
+
+int ks_encrypt(keyset *ks, buf *b, buf *bb)
+{
+  time_t now = time(0);
+
+  if (!KEYOK(ks, now)) {
+    buf_break(bb);
+    return (0);
+  }
+  return (doencrypt(ks, b, bb));
+}
+
+/* --- @ks_decrypt@ --- *
+ *
+ * Arguments:  @keyset *ks@ = pointer to a keyset
+ *             @buf *b@ = pointer to an input buffer
+ *             @buf *bb@ = pointer to an output buffer
+ *
+ * Returns:    Zero on success, or nonzero if there was some problem.
+ *
+ * Use:                Attempts to decrypt a message using a given key.  Note that
+ *             requesting decryption with a key directly won't clear a
+ *             marking that it's not for encryption.
+ */
+
+int ks_decrypt(keyset *ks, buf *b, buf *bb)
+{
+  time_t now = time(0);
+  uint32 seq;
+
+  if (!KEYOK(ks, now) ||
+      buf_ensure(bb, BLEN(b)) ||
+      dodecrypt(ks, b, bb, &seq) ||
+      dosequence(ks, seq))
+    return (-1);
+  return (0);
+}
+
+/*----- Keyset list handling ----------------------------------------------*/
+
+/* --- @ksl_free@ --- *
+ *
+ * Arguments:  @keyset **ksroot@ = pointer to keyset list head
+ *
+ * Returns:    ---
+ *
+ * Use:                Frees (releases references to) all of the keys in a keyset.
+ */
+
+void ksl_free(keyset **ksroot)
+{
+  keyset *ks, *ksn;
+  for (ks = *ksroot; ks; ks = ksn) {
+    ksn = ks->next;
+    ks->f &= ~KSF_LINK;
+    ks_drop(ks);
+  }
+}
+
+/* --- @ksl_link@ --- *
+ *
+ * Arguments:  @keyset **ksroot@ = pointer to keyset list head
+ *             @keyset *ks@ = pointer to a keyset
+ *
+ * Returns:    ---
+ *
+ * Use:                Links a keyset into a list.  A keyset can only be on one list
+ *             at a time.  Bad things happen otherwise.
+ */
+
+void ksl_link(keyset **ksroot, keyset *ks)
+{
+  assert(!(ks->f & KSF_LINK));
+  ks->next = *ksroot;
+  *ksroot = ks;
+  ks->f |= KSF_LINK;
+  ks->ref++;
+}
+
+/* --- @ksl_prune@ --- *
+ *
+ * Arguments:  @keyset **ksroot@ = pointer to keyset list head
+ *
+ * Returns:    ---
+ *
+ * Use:                Prunes the keyset list by removing keys which mustn't be used
+ *             any more.
+ */
+
+void ksl_prune(keyset **ksroot)
+{
+  time_t now = time(0);
+
+  while (*ksroot) {
+    keyset *ks = *ksroot;
+
+    if (ks->t_exp <= now) {
+      T( trace(T_KEYSET, "keyset: expiring keyset %u (time limit reached)",
+              ks->seq); )
+      goto kill;
+    } else if (ks->sz_exp == 0) {
+      T( trace(T_KEYSET, "keyset: expiring keyset %u (data limit reached)",
+              ks->seq); )
+      goto kill;
+    } else {
+      ksroot = &ks->next;
+      continue;
+    }
+
+  kill:
+    *ksroot = ks->next;
+    ks->f &= ~KSF_LINK;
+    ks_drop(ks);
+  }
+}
+
+/* --- @ksl_encrypt@ --- *
  *
  * Arguments:  @keyset **ksroot@ = pointer to keyset list head
  *             @buf *b@ = pointer to input buffer
@@ -178,78 +512,26 @@ time_t ks_gen(keyset **ksroot, const void *k, size_t sz)
  * Use:                Encrypts a packet.
  */
 
-int ks_encrypt(keyset **ksroot, buf *b, buf *bb)
+int ksl_encrypt(keyset **ksroot, buf *b, buf *bb)
 {
   time_t now = time(0);
-  keyset *ks;
-  ghash *h;
-  gcipher *c;
-  size_t ivsz;
-  const octet *p = BCUR(b);
-  size_t sz = BLEFT(b);
-  octet *qiv, *qseq, *qpk;
-  uint32 oseq;
-  size_t osz, nsz;
-  int rc = 0;
-
-  /* --- Get the latest valid key --- */
+  keyset *ks = *ksroot;
 
-  ks = *ksroot;
   for (;;) {
     if (!ks) {
-      T( trace(T_KEYSET, "keyset: no active keys -- forcing exchange"); )
+      T( trace(T_KEYSET, "keyset: no suitable keysets found"); )
       buf_break(bb);
       return (-1);
     }
-    if (KEYOK(ks, now))
+    if (KEYOK(ks, now) && !(ks->f & KSF_LISTEN))
       break;
     ks = ks->next;
   }
 
-  /* --- Allocate the required buffer space --- */
-
-  c = ks->c;
-  ivsz = c->ops->c->blksz;
-  if (buf_ensure(bb, ivsz + 4 + sz)) return (0);
-  qiv = BCUR(bb); qseq = qiv + ivsz; qpk = qseq + 4;
-  BSTEP(bb, ivsz + 4 + sz);
-
-  /* --- MAC and encrypt the packet --- */
-
-  oseq = ks->oseq++; STORE32(qseq, oseq);
-  h = ks->m->ops->init(ks->m);
-  h->ops->hash(h, qseq, 4);
-  h->ops->hash(h, p, sz);
-  memcpy(qiv, h->ops->done(h, 0), ivsz);
-  h->ops->destroy(h);
-  IF_TRACING(T_KEYSET, {
-    trace(T_KEYSET, "keyset: encrypting packet %lu using keyset %u",
-         (unsigned long)oseq, ks->seq);
-    trace_block(T_CRYPTO, "crypto: computed MAC", qiv, ivsz);
-  })
-  c->ops->setiv(c, qiv);
-  c->ops->encrypt(c, p, qpk, sz);
-  IF_TRACING(T_KEYSET, {
-    trace_block(T_CRYPTO, "crypto: encrypted packet", qpk, sz);
-  })
-
-  /* --- Deduct the packet size from the key's data life --- */
-
-  osz = ks->sz_exp;
-  if (osz > sz)
-    nsz = osz - sz;
-  else
-    nsz = 0;
-  if (osz >= KEY_REGENSZ && nsz < KEY_REGENSZ) {
-    T( trace(T_KEYSET, "keyset: keyset %u data regen limit exceeded -- "
-            "forcing exchange", ks->seq); )
-    rc = 1;
-  }
-  ks->sz_exp = nsz;
-  return (rc);
+  return (doencrypt(ks, b, bb));
 }
 
-/* --- @ks_decrypt@ --- *
+/* --- @ksl_decrypt@ --- *
  *
  * Arguments:  @keyset **ksroot@ = pointer to keyset list head
  *             @buf *b@ = pointer to input buffer
@@ -260,98 +542,29 @@ int ks_encrypt(keyset **ksroot, buf *b, buf *bb)
  * Use:                Decrypts a packet.
  */
 
-int ks_decrypt(keyset **ksroot, buf *b, buf *bb)
+int ksl_decrypt(keyset **ksroot, buf *b, buf *bb)
 {
   time_t now = time(0);
-  const octet *piv, *pseq, *ppk;
-  size_t psz = BLEFT(b);
-  size_t sz;
-  octet *q = BCUR(bb);
-  uint32 iseq;
-  unsigned seqbit;
   keyset *ks;
+  uint32 seq;
 
-  /* --- Allocate space in the output buffer --- */
-
-  T( trace(T_KEYSET, "keyset: attempting to decrypt packet"); )
-  if (buf_ensure(bb, psz))
+  if (buf_ensure(bb, BLEN(b)))
     return (-1);
 
-  /* --- Try all of the valid keys --- */
-
   for (ks = *ksroot; ks; ks = ks->next) {
-    ghash *h;
-    gcipher *c = ks->c;
-    size_t ivsz = c->ops->c->blksz;
-    octet *mac;
-    int eq;
-
-    /* --- Break up the packet into its components --- */
-
     if (!KEYOK(ks, now))
       continue;
-    if (psz < ivsz + 4) {
-      T( trace(T_KEYSET, "keyset: block too small for keyset %u", ks->seq); )
-      continue;
+    if (!dodecrypt(ks, b, bb, &seq)) {
+      if (ks->f & KSF_LISTEN) {
+       T( trace(T_KEYSET, "keyset: implicitly activating keyset %u",
+                ks->seq); )
+       ks->f &= ~KSF_LISTEN;
+      }
+      return (dosequence(ks, seq));
     }
-    sz = psz - ivsz - 4;
-    piv = BCUR(b); pseq = piv + ivsz; ppk = pseq + 4;
-
-    /* --- Attempt to decrypt the packet --- */
-
-    c->ops->setiv(c, piv);
-    c->ops->decrypt(c, ppk, q, sz);
-    h = ks->m->ops->init(ks->m);
-    h->ops->hash(h, pseq, 4);
-    h->ops->hash(h, q, sz);
-    mac = h->ops->done(h, 0);
-    eq = !memcmp(mac, piv, ivsz);
-    IF_TRACING(T_KEYSET, {
-      trace(T_KEYSET, "keyset: decrypting using keyset %u", ks->seq);
-      trace_block(T_CRYPTO, "crypto: computed MAC", mac, ivsz);
-    })
-    h->ops->destroy(h);
-    if (eq) {
-      BSTEP(bb, sz);
-      goto match;
-    }
-    IF_TRACING(T_KEYSET, {
-      trace(T_KEYSET, "keyset: decryption failed");
-      trace_block(T_CRYPTO, "crypto: expected MAC", piv, ivsz);
-      trace_block(T_CRYPTO, "crypto: invalid packet", q, sz);
-    })
   }
   T( trace(T_KEYSET, "keyset: no matching keys"); )
   return (-1);
-
-  /* --- We've found a match, so check the sequence number --- */
-
-match:
-  iseq = LOAD32(pseq);
-  IF_TRACING(T_KEYSET, {
-    trace(T_KEYSET, "keyset: decrypted OK (sequence = %lu)",
-         (unsigned long)iseq);
-    trace_block(T_CRYPTO, "crypto: decrypted packet", q, sz);
-  })
-  if (iseq < ks->iseq) {
-    a_warn("received packet has old sequence number (possible replay)");
-    return (-1);
-  }
-  if (iseq >= ks->iseq + KS_SEQWINSZ) {
-    uint32 n = iseq - (ks->iseq + KS_SEQWINSZ - 1);
-    if (n < KS_SEQWINSZ)
-      ks->iwin >>= n;
-    else
-      ks->iwin = 0;
-    ks->iseq += n;
-  }
-  seqbit = 1 << (iseq - ks->iseq);
-  if (ks->iwin & seqbit) {
-    a_warn("received packet repeats old sequence number");
-    return (-1);
-  }
-  ks->iwin |= seqbit;
-  return (0);
 }
 
 /*----- That's all, folks -------------------------------------------------*/