chiark / gitweb /
Merge branches 'mdw/knock' and 'mdw/ipv6' into bleeding
[tripe] / server / servutil.c
index 77cfd2c6c7fceba19c55c14ef60b380985be9409..703e448ec8dcea95cf9405ff5378e1aebe1e97d4 100644 (file)
@@ -1,29 +1,26 @@
 /* -*-c-*-
- *
- * $Id$
  *
  * Various handy server-only utilities
  *
  * (c) 2001 Straylight/Edgeware
  */
 
-/*----- Licensing notice --------------------------------------------------* 
+/*----- Licensing notice --------------------------------------------------*
  *
  * 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 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 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.
+ *
  * 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 ------------------------------------------------------*/
 
 /*----- Global variables --------------------------------------------------*/
 
-octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ];
-
-/*----- Main code ---------------------------------------------------------*/
+octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
 
-/* --- @mpstr@ --- *
- *
- * Arguments:  @mp *m@ = a multiprecision integer
- *
- * Returns:    A pointer to the integer's textual representation.
- *
- * Use:                Converts a multiprecision integer to a string.  Corrupts
- *             @buf_t@.
- */
-
-const char *mpstr(mp *m)
-{
-  if (mp_writestring(m, (char *)buf_t, sizeof(buf_t), 10))
-    return ("<failed>");
-  return ((const char *)buf_t);
-}
-
-/* --- @gestr@ --- *
- *
- * Arguments:  @group *g@ = a group
- *             @ge *x@ = a group element
- *
- * Returns:    A pointer to the element's textual representation.
- *
- * Use:                Converts a group element to a string.  Corrupts
- *             @buf_t@.
- */
-
-const char *gestr(group *g, ge *x)
-{
-  if (group_writestring(g, x, (char *)buf_t, sizeof(buf_t)))
-    return ("<failed>");
-  return ((const char *)buf_t);
-}
-
-/* --- @timestr@ --- *
- *
- * Arguments:  @time_t t@ = a time to convert
- *
- * Returns:    A pointer to a textual representation of the time.
- *
- * Use:                Converts a time to a textual representation.  Corrupts
- *             @buf_t@.
- */
-
-const char *timestr(time_t t)
-{
-  struct tm *tm;
-  if (!t)
-    return ("NEVER");
-  tm = localtime(&t);
-  strftime((char *)buf_t, sizeof(buf_t), "%Y-%m-%dT%H:%M:%S", tm);
-  return ((const char *)buf_t);
-}
+/*----- Sequence numbers --------------------------------------------------*/
 
 /* --- @seq_reset@ --- *
  *
@@ -140,157 +82,289 @@ int seq_check(seqwin *s, uint32 q, const char *service)
   return (0);
 }
 
-/* --- @versioncmp@ --- *
- *
- * Arguments:  @const char *va, *vb@ = two version strings
+/*----- Rate limiting -----------------------------------------------------*/
+
+/* --- @ratelim_init@ --- *
  *
- * Returns:    Less than, equal to, or greater than zero, according to
- *             whether @va@ is less than, equal to, or greater than @vb@.
+ * Arguments:  @ratelim *r@ = rate-limiting state to fill in
+ *             @unsigned persec@ = credit to accumulate per second
+ *             @unsigned max@ = maximum credit to retain
  *
- * Use:                Compares version number strings.
+ * Returns:    ---
  *
- *             The algorithm is an extension of the Debian version
- *             comparison algorithm.  A version number consists of three
- *             components:
+ * Use:                Initialize a rate-limiting state.
+ */
+
+void ratelim_init(ratelim *r, unsigned persec, unsigned max)
+{
+  r->n = r->max = max;
+  r->persec = persec;
+  gettimeofday(&r->when, 0);
+}
+
+/* --- @ratelim_withdraw@ --- *
  *
- *               [EPOCH :] MAIN [- SUB]
+ * Arguments:  @ratelim *r@ = rate-limiting state
+ *             @unsigned n@ = credit to withdraw
  *
- *             The MAIN part may contain colons or hyphens if there is an
- *             EPOCH or SUB, respectively.  Version strings are compared
- *             componentwise: first epochs, then main parts, and finally
- *             subparts.
+ * Returns:    Zero if successful; @-1@ if there is unsufficient credit
  *
- *             The component comparison is done as follows.  First, the
- *             initial subsequence of nondigit characters is extracted from
- *             each string, and these are compared lexicographically, using
- *             ASCII ordering, except that letters precede non-letters.  If
- *             both are the same, an initial sequence of digits is extracted
- *             from the remaining parts of the version strings, and these
- *             are compared numerically (an empty sequence being considered
- *             to have the value zero).  This process is repeated until we
- *             have a winner or until both strings are exhausted.
+ * Use:                Updates the state with any accumulated credit.  Then, if
+ *             there there are more than @n@ credits available, withdraw @n@
+ *             and return successfully; otherwise, report failure.
  */
 
-struct vinfo {
-  const char *e, *el;
-  const char *m, *ml;
-  const char *s, *sl;
-};
-
-static int vint(const char **vv, const char *vl)
+int ratelim_withdraw(ratelim *r, unsigned n)
 {
-  int n = 0;
-  const char *v = *vv;
-  int ch;
-
-  while (v < vl) {
-    ch = *v;
-    if (!isdigit((unsigned char)ch))
-      break;
-    v++;
-    n = n * 10 + (ch - '0');
-  }
-  *vv = v;
-  return (n);
+  struct timeval now, delta;
+  unsigned long d;
+
+  gettimeofday(&now, 0);
+  TV_SUB(&delta, &now, &r->when);
+  d = (unsigned long)r->persec*delta.tv_sec +
+    (unsigned long)r->persec*delta.tv_usec/MILLION;
+  if (d < r->max - r->n) r->n += d;
+  else r->n = r->max;
+  r->when = now;
+
+  if (n > r->n) return (-1);
+  else { r->n -= n; return (0); }
 }
 
-static const char *vchr(const char **vv, const char *vl)
+/*----- Crypto ------------------------------------------------------------*/
+
+/* --- @ies_encrypt@ --- *
+ *
+ * Arguments:  @kdata *kpub@ = recipient's public key
+ *             @unsigned ty@ = message type octet
+ *             @buf *b@ = input message buffer
+ *             @buf *bb@ = output buffer for the ciphertext
+ *
+ * Returns:    On error, returns a @KSERR_...@ code or breaks the buffer;
+ *             on success, returns zero and the buffer is good.
+ *
+ * Use:                Encrypts a message for a recipient, given their public key.
+ *             This does not (by itself) provide forward secrecy or sender
+ *             authenticity.  The ciphertext is self-delimiting (unlike
+ *             @ks_encrypt@).
+ */
+
+int ies_encrypt(kdata *kpub, unsigned ty, buf *b, buf *bb)
 {
-  const char *v = *vv;
-  const char *b = v;
-  int ch;
-
-  while (v < vl) {
-    ch = *v;
-    if (isdigit((unsigned char)ch))
-      break;
-    v++;
-  }
-  *vv = v;
-  return (b);
+  dhgrp *g = kpub->grp;
+  dhsc *u = g->ops->randsc(g);
+  dhge *U = g->ops->mul(g, u, 0), *Z = g->ops->mul(g, u, kpub->K);
+  bulkalgs *algs = kpub->algs.bulk;
+  octet *len;
+  bulkctx *bulk;
+  deriveargs a;
+  size_t n;
+  buf bk;
+  int rc = 0;
+
+  IF_TRACING(T_CRYPTO, {
+    trace(T_CRYPTO,
+         "crypto: encrypting IES message (type 0x%02x) for recipient `%s'",
+         ty, kpub->tag);
+    trace_block(T_CRYPTO, "crypto: plaintext message", BCUR(b), BLEFT(b));
+  })
+
+  a.hc = kpub->algs.h; a.what = "tripe:ecies-"; a.f = DF_OUT;
+  buf_init(&bk, buf_u, sizeof(buf_u)); a.k = BBASE(&bk);
+  g->ops->stge(g, &bk, U, DHFMT_HASH); a.x = a.y = BLEN(&bk);
+  g->ops->stge(g, &bk, Z, DHFMT_HASH); a.z = BLEN(&bk);
+  assert(BOK(&bk));
+  T( trace_block(T_CRYPTO, "crypto: KEM clue", a.k, a.x);
+     trace_block(T_CRYPTO, "crypto: shared secret", a.k + a.y, a.z - a.y); )
+
+  len = BCUR(bb); buf_get(bb, 2);
+  bulk = algs->ops->genkeys(algs, &a);
+  bulk->ops = algs->ops;
+  g->ops->stge(g, bb, U, DHFMT_VAR); if (BBAD(bb)) goto end;
+  rc = bulk->ops->encrypt(bulk, ty, b, bb, 0);
+  if (rc || BBAD(bb)) goto end;
+  n = BCUR(bb) - len - 2; assert(n <= MASK16); STORE16(len, n);
+
+end:
+  bulk->ops->freectx(bulk);
+  g->ops->freesc(g, u);
+  g->ops->freege(g, U);
+  g->ops->freege(g, Z);
+  return (rc);
 }
 
-#define CMP(x, y) ((x) < (y) ? -1 : +1)
+/* --- @ies_decrypt@ --- *
+ *
+ * Arguments:  @kdata *kpub@ = private key key
+ *             @unsigned ty@ = message type octet
+ *             @buf *b@ = input ciphertext buffer
+ *             @buf *bb@ = output buffer for the message
+ *
+ * Returns:    On error, returns a @KSERR_...@ code; on success, returns
+ *             zero and the buffer is good.
+ *
+ * Use:                Decrypts a message encrypted using @ies_encrypt@, given our
+ *             private key.
+ */
 
-static int vcmp(const char *va, const char *val,
-               const char *vb, const char *vbl)
+int ies_decrypt(kdata *kpriv, unsigned ty, buf *b, buf *bb)
 {
-  const char *pa, *pb;
-  int ia, ib;
+  dhgrp *g = kpriv->grp;
+  bulkalgs *algs = kpriv->algs.bulk;
+  bulkctx *bulk = 0;
+  T( const octet *m; )
+  dhge *U = 0, *Z = 0;
+  deriveargs a;
+  uint32 seq;
+  buf bk, bc;
+  int rc;
 
-  for (;;) {
+  IF_TRACING(T_CRYPTO, {
+    trace(T_CRYPTO,
+         "crypto: decrypting IES message (type 0x%02x) to recipient `%s'",
+         ty, kpriv->tag);
+    trace_block(T_CRYPTO, "crypto: ciphertext message", BCUR(b), BLEFT(b));
+  })
+
+  if (buf_getbuf16(b, &bc) ||
+      (U = g->ops->ldge(g, &bc, DHFMT_VAR)) == 0 ||
+      g->ops->checkge(g, U))
+    { rc = KSERR_MALFORMED; goto end; }
+  Z = g->ops->mul(g, kpriv->k, U);
+
+  a.hc = kpriv->algs.h; a.what = "tripe:ecies-"; a.f = DF_IN;
+  buf_init(&bk, buf_u, sizeof(buf_u)); a.k = BBASE(&bk); a.x = 0;
+  g->ops->stge(g, &bk, U, DHFMT_HASH); a.y = BLEN(&bk);
+  g->ops->stge(g, &bk, Z, DHFMT_HASH); a.z = BLEN(&bk);
+  T( trace_block(T_CRYPTO, "crypto: KEM clue", a.k + a.x, a.y - a.x);
+     trace_block(T_CRYPTO, "crypto: shared secret", a.k + a.y, a.z - a.y); )
+  assert(BOK(&bk));
+
+  bulk = algs->ops->genkeys(algs, &a);
+  bulk->ops = algs->ops;
+  T( m = BCUR(bb); )
+  rc = bulk->ops->decrypt(bulk, ty, &bc, bb, &seq);
+  if (rc) goto end;
+  if (seq) { rc = KSERR_SEQ; goto end; }
+  assert(BOK(bb));
+  T( trace_block(T_CRYPTO, "crypto: decrypted message", m, BCUR(bb) - m); )
+
+end:
+  if (bulk) bulk->ops->freectx(bulk);
+  g->ops->freege(g, U);
+  g->ops->freege(g, Z);
+  return (rc);
+}
 
-    /* --- See if we're done --- */
+/*----- Random odds and sods ----------------------------------------------*/
 
-    if (va == val && vb == vbl)
-      return (0);
+/* --- @timestr@ --- *
+ *
+ * Arguments:  @time_t t@ = a time to convert
+ *
+ * Returns:    A pointer to a textual representation of the time.
+ *
+ * Use:                Converts a time to a textual representation.  Corrupts
+ *             @buf_u@.
+ */
 
-    /* --- Compare nondigit portions --- */
-
-    pa = vchr(&va, val); pb = vchr(&vb, vbl);
-    for (;;) {
-      if (pa == va && pb == vb)
-       break;
-      else if (pa == va)
-       return (-1);
-      else if (pb == vb)
-       return (+1);
-      else if (*pa == *pb) {
-       pa++; pb++;
-       continue;
-      } else if (isalpha((unsigned char)*pa) == isalpha((unsigned char)*pb))
-       return (CMP(*pa, *pb));
-      else if (isalpha((unsigned char)*pa))
-       return (-1);
-      else
-       return (+1);
-    }
-
-    /* --- Compare digit portions --- */
-
-    ia = vint(&va, val); ib = vint(&vb, vbl);
-    if (ia != ib)
-      return (CMP(ia, ib));
+const char *timestr(time_t t)
+{
+  struct tm *tm;
+  if (!t)
+    return ("NEVER");
+  tm = localtime(&t);
+  strftime((char *)buf_u, sizeof(buf_u), "%Y-%m-%dT%H:%M:%S", tm);
+  return ((const char *)buf_u);
+}
+
+/* --- @mystrieq@ --- *
+ *
+ * Arguments:  @const char *x, *y@ = two strings
+ *
+ * Returns:    True if @x@ and @y are equal, up to case.
+ */
+
+int mystrieq(const char *x, const char *y)
+{
+  for (;;) {
+    if (!*x && !*y) return (1);
+    if (tolower((unsigned char)*x) != tolower((unsigned char)*y))
+      return (0);
+    x++; y++;
   }
 }
 
-static void vsplit(const char *v, struct vinfo *vi)
+/*----- Address handling --------------------------------------------------*/
+
+const struct addrfam aftab[] = {
+#ifdef HAVE_LIBADNS
+#  define DEF(af, qf) { AF_##af, #af, adns_qf_##qf },
+#else
+#  define DEF(af, qf) { AF_##af, #af },
+#endif
+  ADDRFAM(DEF)
+#undef DEF
+};
+
+/* --- @afix@ --- *
+ *
+ * Arguments:  @int af@ = an address family code
+ *
+ * Returns:    The index of the address family's record in @aftab@, or @-1@.
+ */
+
+int afix(int af)
 {
-  const char *p;
-  size_t n;
+  int i;
 
-  if ((p = strchr(v, ':')) == 0)
-    vi->e = vi->el = 0;
-  else {
-    vi->e = v;
-    vi->el = p;
-    v = p + 1;
-  }
+  for (i = 0; i < NADDRFAM; i++)
+    if (af == aftab[i].af) return (i);
+  return (-1);
+}
 
-  n = strlen(v);
-  if ((p = strrchr(v, '-')) == 0)
-    vi->s = vi->sl = 0;
-  else {    
-    vi->s = p + 1;
-    vi->sl = v + n;
-    n = p - v;
-  }
+/* --- @addrsz@ --- *
+ *
+ * Arguments:  @const addr *a@ = a network address
+ *
+ * Returns:    The size of the address, for passing into the sockets API.
+ */
 
-  vi->m = v;
-  vi->ml = v + n;
+socklen_t addrsz(const addr *a)
+{
+  switch (a->sa.sa_family) {
+    case AF_INET: return (sizeof(a->sin));
+    case AF_INET6: return (sizeof(a->sin6));
+    default: abort();
+  }
 }
 
-int versioncmp(const char *va, const char *vb)
+/* --- @getport@, @setport@ --- *
+ *
+ * Arguments:  @addr *a@ = a network address
+ *             @unsigned port@ = port number to set
+ *
+ * Returns:    ---
+ *
+ * Use:                Retrieves or sets the port number in an address structure.
+ */
+
+unsigned getport(addr *a)
 {
-  struct vinfo via, vib;
-  int rc;
+  switch (a->sa.sa_family) {
+    case AF_INET: return (ntohs(a->sin.sin_port)); break;
+    case AF_INET6: return (ntohs(a->sin6.sin6_port)); break;
+    default: abort();
+  }
+}
 
-  vsplit(va, &via); vsplit(vb, &vib);
-  if ((rc = vcmp(via.e, via.el, vib.e, vib.el)) != 0 ||
-      (rc = vcmp(via.m, via.ml, vib.m, vib.ml)) != 0 ||
-      (rc = vcmp(via.s, via.sl, vib.s, vib.sl)) != 0)
-    return (rc);
-  return (0);
+void setport(addr *a, unsigned port)
+{
+  switch (a->sa.sa_family) {
+    case AF_INET: a->sin.sin_port = htons(port); break;
+    case AF_INET6: a->sin6.sin6_port = htons(port); break;
+    default: abort();
+  }
 }
 
 /*----- That's all, folks -------------------------------------------------*/