chiark / gitweb /
mon/tripemon.in: Add per-peer key selection and mobile options.
[tripe] / server / keyset.c
index fe491280cbcfd4f3792ce0dd9450cfa392d9f3c5..94fcae022175a7d242e6b4ee694fcb42d5021bb2 100644 (file)
 
 #include "tripe.h"
 
-/*----- Tunable parameters ------------------------------------------------*/
-
-/* --- Note on size limits --- *
- *
- * For a 64-bit block cipher (e.g., Blowfish), the probability of a collision
- * occurring after 32 MB is less than %$2^{-21}$%, and the probability of a
- * collision occurring after 64 MB is less than %$2^{-19}$%.  These could be
- * adjusted dependent on the encryption scheme, but it's too much pain.
- */
-
-#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)
 
-#define SEQSZ 4                                /* Size of sequence number packet */
-
 /*----- Low-level packet encryption and decryption ------------------------*/
 
 /* --- Encrypted data format --- *
@@ -82,7 +65,9 @@
  *             @buf *b@ = pointer to an input buffer
  *             @buf *bb@ = pointer to an output buffer
  *
- * Returns:    Zero if OK, nonzero if a new key is required.
+ * Returns:    Zero if OK; @KSERR_REGEN@ if it's time to generate new keys.
+ *             Also returns zero if there was insufficient buffer space, but
+ *             the buffer is broken in this case.
  *
  * Use:                Encrypts a message with the given key.  We assume that the
  *             keyset is OK to use.
 
 static int doencrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
 {
-  ghash *h;
-  gcipher *c = ks->cout;
-  const octet *p = BCUR(b);
+  int rc;
   size_t sz = BLEFT(b);
-  octet *qmac, *qseq, *qiv, *qpk;
-  uint32 oseq;
-  size_t ivsz = GC_CLASS(c)->blksz;
-  size_t tagsz = ks->tagsz;
   size_t osz, nsz;
-  octet t[4];
-  int rc = 0;
 
-  /* --- Allocate the required buffer space --- */
+  /* --- Initial tracing --- */
 
-  if (buf_ensure(bb, tagsz + SEQSZ + ivsz + sz))
-    return (0); /* Caution! */
-  qmac = BCUR(bb); qseq = qmac + tagsz; qiv = qseq + SEQSZ; qpk = qiv + ivsz;
-  BSTEP(bb, tagsz + SEQSZ + ivsz + sz);
-  STORE32(t, ty);
-
-  oseq = ks->oseq++; STORE32(qseq, oseq);
   IF_TRACING(T_KEYSET, {
-    trace(T_KEYSET, "keyset: encrypting packet %lu using keyset %u",
-         (unsigned long)oseq, ks->seq);
-    trace_block(T_CRYPTO, "crypto: plaintext packet", p, sz);
+    trace(T_KEYSET,
+         "keyset: encrypting packet %lu (type %u) using keyset %u",
+         (unsigned long)ks->oseq, ty, ks->seq);
+    trace_block(T_CRYPTO, "crypto: plaintext packet", BCUR(b), sz);
   })
 
-  /* --- Encrypt the packet --- */
-
-  if (ivsz) {
-    rand_get(RAND_GLOBAL, qiv, ivsz);
-    GC_SETIV(c, qiv);
-    IF_TRACING(T_KEYSET, {
-      trace_block(T_CRYPTO, "crypto: initialization vector", qiv, ivsz);
-    })
-  }
-  GC_ENCRYPT(c, p, qpk, sz);
-  IF_TRACING(T_KEYSET, {
-    trace_block(T_CRYPTO, "crypto: encrypted packet", qpk, sz);
-  })
+  /* --- Apply the bulk-crypto transformation --- */
 
-  /* --- Now compute the MAC --- */
-
-  if (tagsz) {
-    h = GM_INIT(ks->mout);
-    GH_HASH(h, t, sizeof(t));
-    GH_HASH(h, qseq, SEQSZ + ivsz + sz);
-    memcpy(qmac, GH_DONE(h, 0), tagsz);
-    GH_DESTROY(h);
-    IF_TRACING(T_KEYSET, {
-      trace_block(T_CRYPTO, "crypto: computed MAC", qmac, tagsz);
-    })
-  }
+  rc = ks->bulk->encrypt(ks, ty, b, bb);
+  if (rc || !BOK(bb)) return (rc);
 
-  /* --- Deduct the packet size from the key's data life --- */
+  /* --- Do the necessary accounting for data volume --- */
 
   osz = ks->sz_exp;
-  if (osz > sz)
-    nsz = osz - sz;
-  else
-    nsz = 0;
-  if (osz >= SZ_REGEN && nsz < SZ_REGEN) {
+  nsz = osz > sz ? osz - sz : 0;
+  if (osz >= ks->sz_regen && ks->sz_regen > nsz) {
     T( trace(T_KEYSET, "keyset: keyset %u data regen limit exceeded -- "
             "forcing exchange", ks->seq); )
-    rc = -1;
+    rc = KSERR_REGEN;
   }
   ks->sz_exp = nsz;
+
+  /* --- We're done --- */
+
   return (rc);
 }
 
@@ -168,7 +117,7 @@ static int doencrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
  *             @buf *bb@ = pointer to an output buffer
  *             @uint32 *seq@ = where to store the sequence number
  *
- * Returns:    Zero if OK, nonzero if it failed.
+ * Returns:    Zero on success; @KSERR_DECRYPT@ on failure.
  *
  * Use:                Attempts to decrypt a message with the given key.  No other
  *             checking (e.g., sequence number checks) is performed.  We
@@ -180,71 +129,24 @@ static int doencrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
 
 static int dodecrypt(keyset *ks, unsigned ty, buf *b, buf *bb, uint32 *seq)
 {
-  const octet *pmac, *piv, *pseq, *ppk;
-  size_t psz = BLEFT(b);
-  size_t sz;
-  octet *q = BCUR(bb);
-  ghash *h;
-  gcipher *c = ks->cin;
-  size_t ivsz = GC_CLASS(c)->blksz;
-  size_t tagsz = ks->tagsz;
-  octet *mac;
-  int eq;
-  octet t[4];
-
-  /* --- Break up the packet into its components --- */
-
-  if (psz < ivsz + SEQSZ + tagsz) {
-    T( trace(T_KEYSET, "keyset: block too small for keyset %u", ks->seq); )
-    return (-1);
-  }
-  sz = psz - ivsz - SEQSZ - tagsz;
-  pmac = BCUR(b); pseq = pmac + tagsz; piv = pseq + SEQSZ; ppk = piv + ivsz;
-  STORE32(t, ty);
+  const octet *q = BCUR(bb);
+  int rc;
 
   IF_TRACING(T_KEYSET, {
-    trace(T_KEYSET, "keyset: decrypting using keyset %u", ks->seq);
-    trace_block(T_CRYPTO, "crypto: ciphertext packet", ppk, sz);
+    trace(T_KEYSET,
+         "keyset: try decrypting packet (type %u) using keyset %u",
+         ty, ks->seq);
+    trace_block(T_CRYPTO, "crypto: ciphertext packet", BCUR(b), BLEFT(b));
   })
 
-  /* --- Verify the MAC on the packet --- */
-
-  if (tagsz) {
-    h = GM_INIT(ks->min);
-    GH_HASH(h, t, sizeof(t));
-    GH_HASH(h, pseq, SEQSZ + ivsz + sz);
-    mac = GH_DONE(h, 0);
-    eq = !memcmp(mac, pmac, tagsz);
-    IF_TRACING(T_KEYSET, {
-      trace_block(T_CRYPTO, "crypto: computed MAC", mac, tagsz);
-    })
-    GH_DESTROY(h);
-    if (!eq) {
-      IF_TRACING(T_KEYSET, {
-       trace(T_KEYSET, "keyset: incorrect MAC: decryption failed");
-       trace_block(T_CRYPTO, "crypto: expected MAC", pmac, tagsz);
-      })
-      return (-1);
-    }
-  }
+  rc = ks->bulk->decrypt(ks, ty, b, bb, seq);
+  if (rc) return (rc);
 
-  /* --- Decrypt the packet --- */
-
-  if (ivsz) {
-    GC_SETIV(c, piv);
-    IF_TRACING(T_KEYSET, {
-      trace_block(T_CRYPTO, "crypto: initialization vector", piv, ivsz);
-    })
-  }
-  GC_DECRYPT(c, ppk, q, sz);
-  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);
+         (unsigned long)*seq);
+    trace_block(T_CRYPTO, "crypto: decrypted packet", q, BCUR(bb) - q);
   })
-  BSTEP(bb, sz);
   return (0);
 }
 
@@ -264,10 +166,19 @@ void ks_drop(keyset *ks)
 {
   if (--ks->ref)
     return;
-  GC_DESTROY(ks->cin);
-  GC_DESTROY(ks->cout);
-  GM_DESTROY(ks->min);
-  GM_DESTROY(ks->mout);
+
+#define DROP(dir, a, drop) do { if (ks->dir.a) drop(ks->dir.a); } while (0)
+#define DROP_DIR(dir) do {                                             \
+  DROP(dir, c, GC_DESTROY);                                            \
+  DROP(dir, m, GM_DESTROY);                                            \
+} while (0)
+
+  DROP_DIR(in);
+  DROP_DIR(out);
+
+#undef DROP
+#undef DROP_DIR
+
   DESTROY(ks);
 }
 
@@ -294,86 +205,70 @@ void ks_drop(keyset *ks)
  *             calling @ks_encrypt@ directly.
  */
 
+static void gen_dir(const algswitch *algs, struct ksdir *ksd,
+                   const char *whichdir,
+                   const octet *from, size_t fromsz,
+                   const octet *to, size_t tosz,
+                   const octet *both, size_t bothsz)
+{
+#define SETKEY(what, a, init) do {                                     \
+  ghash *_h;                                                           \
+  octet *_hh;                                                          \
+                                                                       \
+  if (!algs->a)                                                                \
+    ksd->a = 0;                                                                \
+  else {                                                               \
+    _h = GH_INIT(algs->h);                                             \
+    HASH_STRING(_h, "tripe-" what);                                    \
+    GH_HASH(_h, from, fromsz);                                         \
+    GH_HASH(_h, to, tosz);                                             \
+    GH_HASH(_h, both, bothsz);                                         \
+    _hh = GH_DONE(_h, 0);                                              \
+    IF_TRACING(T_KEYSET, { IF_TRACING(T_CRYPTO, {                      \
+      char _buf[32];                                                   \
+      sprintf(_buf, "crypto: %s key " what, whichdir);                 \
+      trace_block(T_CRYPTO, _buf, _hh, algs->a##ksz);                  \
+    }) })                                                              \
+    ksd->a = init(algs->a, _hh, algs->a##ksz);                         \
+    GH_DESTROY(_h);                                                    \
+  }                                                                    \
+} while (0)
+
+  SETKEY("encryption", c, GC_INIT);
+  SETKEY("integrity", m, GM_KEY);
+  SETKEY("blkc", b, GC_INIT);
+
+#undef SETKEY
+}
+
 keyset *ks_gen(const void *k, size_t x, size_t y, size_t z, peer *p)
 {
-  ghash *h;
-  const octet *hh;
   keyset *ks = CREATE(keyset);
   time_t now = time(0);
   const octet *pp = k;
+  const algswitch *algs = &p->kx.kpriv->algs;
   T( static unsigned seq = 0; )
 
   T( trace(T_KEYSET, "keyset: adding new keyset %u", seq); )
 
-  /* --- Construct the various keys --- *
-   *
-   * This is done with macros, because it's quite tedious.
-   */
-
-#define MINE GH_HASH(h, pp, x)
-#define YOURS GH_HASH(h, pp + x, y - x)
-#define OURS GH_HASH(h, pp + y, z - y)
-
-#define HASH_in MINE; YOURS; OURS
-#define HASH_out YOURS; MINE; OURS
-#define INIT_c(k) GC_INIT(algs.c, (k), algs.cksz)
-#define INIT_m(k) GM_KEY(algs.m, (k), algs.mksz)
-#define STR_c "encryption"
-#define STR_m "integrity"
-#define STR_in "incoming"
-#define STR_out "outgoing"
-
-#define SETKEY(a, dir) do {                                            \
-  h = GH_INIT(algs.h);                                                 \
-  HASH_STRING(h, "tripe-" STR_##a);                                    \
-  HASH_##dir;                                                          \
-  hh = GH_DONE(h, 0);                                                  \
-  IF_TRACING(T_KEYSET, {                                               \
-    trace_block(T_CRYPTO, "crypto: " STR_##dir " key " STR_##a,                \
-               hh, algs.a##ksz);                                       \
-  })                                                                   \
-  ks->a##dir = INIT_##a(hh);                                           \
-  GH_DESTROY(h);                                                       \
-} while (0)
-
-  SETKEY(c, in); SETKEY(c, out);
-  SETKEY(m, in); SETKEY(m, out);
-
-#undef MINE
-#undef YOURS
-#undef OURS
-#undef STR_c
-#undef STR_m
-#undef STR_in
-#undef STR_out
-#undef INIT_c
-#undef INIT_m
-#undef HASH_in
-#undef HASH_out
-#undef SETKEY
+  gen_dir(algs, &ks->in, "incoming", pp, x, pp + x, y - x, pp + y, z - y);
+  gen_dir(algs, &ks->out, "outgoing", pp + x, y - x, pp, x, pp + y, z - y);
 
   T( ks->seq = seq++; )
+  ks->bulk = algs->bulk;
   ks->ref = 1;
   ks->t_exp = now + T_EXP;
-  ks->sz_exp = SZ_EXP;
+  ks->sz_exp = algs->expsz;
+  ks->sz_regen = algs->expsz/2;
   ks->oseq = 0;
   seq_reset(&ks->iseq);
   ks->next = 0;
   ks->p = p;
   ks->f = KSF_LISTEN;
-  ks->tagsz = algs.tagsz;
+  ks->tagsz = algs->tagsz;
   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
@@ -399,14 +294,20 @@ void ks_activate(keyset *ks)
  *             @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.
+ * Returns:    Zero if successful; @KSERR_REGEN@ if we should negotiate a
+ *             new key; @KSERR_NOKEYS@ if the key is not usable.  Also
+ *             returns zero if there was insufficient buffer (but the output
+ *             buffer is broken in this case).
  *
  * 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.
+ *
+ *             The encryption transform is permitted to corrupt @buf_u@ for
+ *             its own purposes.  Neither the source nor destination should
+ *             be within @buf_u@; and callers mustn't expect anything stored
+ *             in @buf_u@ to still
  */
 
 int ks_encrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
@@ -415,7 +316,7 @@ int ks_encrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
 
   if (!KEYOK(ks, now)) {
     buf_break(bb);
-    return (0);
+    return (KSERR_NOKEYS);
   }
   return (doencrypt(ks, ty, b, bb));
 }
@@ -427,23 +328,30 @@ int ks_encrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
  *             @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.
+ * Returns:    Zero on success; @KSERR_...@ on failure.  Also returns
+ *             zero if there was insufficient buffer (but the output buffer
+ *             is broken in this case).
  *
  * 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.
+ *
+ *             The decryption transform is permitted to corrupt @buf_u@ for
+ *             its own purposes.  Neither the source nor destination should
+ *             be within @buf_u@; and callers mustn't expect anything stored
+ *             in @buf_u@ to still
  */
 
 int ks_decrypt(keyset *ks, unsigned ty, buf *b, buf *bb)
 {
   time_t now = time(0);
   uint32 seq;
+  int err;
 
-  if (!KEYOK(ks, now) ||
-      buf_ensure(bb, BLEN(b)) ||
-      dodecrypt(ks, ty, b, bb, &seq) ||
-      seq_check(&ks->iseq, seq, "SYMM"))
-    return (-1);
+  if (!KEYOK(ks, now)) return (KSERR_DECRYPT);
+  if (buf_ensure(bb, BLEN(b))) return (0);
+  if ((err = dodecrypt(ks, ty, b, bb, &seq)) != 0) return (err);
+  if (seq_check(&ks->iseq, seq, "SYMM")) return (KSERR_SEQ);
   return (0);
 }
 
@@ -532,7 +440,10 @@ void ksl_prune(keyset **ksroot)
  *             @buf *b@ = pointer to input buffer
  *             @buf *bb@ = pointer to output buffer
  *
- * Returns:    Nonzero if a new key is needed.
+ * Returns:    Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
+ *             new key; @KSERR_NOKEYS@ if there are no suitable keys
+ *             available.  Also returns zero if there was insufficient
+ *             buffer space (but the output buffer is broken in this case).
  *
  * Use:                Encrypts a packet.
  */
@@ -546,7 +457,7 @@ int ksl_encrypt(keyset **ksroot, unsigned ty, buf *b, buf *bb)
     if (!ks) {
       T( trace(T_KEYSET, "keyset: no suitable keysets found"); )
       buf_break(bb);
-      return (-1);
+      return (KSERR_NOKEYS);
     }
     if (KEYOK(ks, now) && !(ks->f & KSF_LISTEN))
       break;
@@ -563,7 +474,9 @@ int ksl_encrypt(keyset **ksroot, unsigned ty, buf *b, buf *bb)
  *             @buf *b@ = pointer to input buffer
  *             @buf *bb@ = pointer to output buffer
  *
- * Returns:    Nonzero if the packet couldn't be decrypted.
+ * Returns:    Zero on success; @KSERR_DECRYPT@ on failure.  Also returns
+ *             zero if there was insufficient buffer (but the output buffer
+ *             is broken in this case).
  *
  * Use:                Decrypts a packet.
  */
@@ -573,24 +486,29 @@ int ksl_decrypt(keyset **ksroot, unsigned ty, buf *b, buf *bb)
   time_t now = time(0);
   keyset *ks;
   uint32 seq;
+  int err;
 
   if (buf_ensure(bb, BLEN(b)))
-    return (-1);
+    return (0);
 
   for (ks = *ksroot; ks; ks = ks->next) {
     if (!KEYOK(ks, now))
       continue;
-    if (!dodecrypt(ks, ty, b, bb, &seq)) {
+    if ((err = dodecrypt(ks, ty, b, bb, &seq)) == 0) {
       if (ks->f & KSF_LISTEN) {
        T( trace(T_KEYSET, "keyset: implicitly activating keyset %u",
                 ks->seq); )
        ks->f &= ~KSF_LISTEN;
       }
-      return (seq_check(&ks->iseq, seq, "SYMM"));
+      if (seq_check(&ks->iseq, seq, "SYMM"))
+       return (KSERR_SEQ);
+      else
+       return (0);
     }
+    if (err != KSERR_DECRYPT) return (err);
   }
   T( trace(T_KEYSET, "keyset: no matching keys, or incorrect MAC"); )
-  return (-1);
+  return (KSERR_DECRYPT);
 }
 
 /*----- That's all, folks -------------------------------------------------*/