chiark / gitweb /
server/: Introduce accessor functions for reading and writing port numbers.
[tripe] / server / peer.c
index e57c6ba4cfe3342b03734b15f6c0d5c647302985..ea6e09bb8a8b85897bfa47685e45e3ca590c893a 100644 (file)
@@ -9,30 +9,33 @@
  *
  * 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 ------------------------------------------------------*/
 
 #include "tripe.h"
 
+/*----- Global state ------------------------------------------------------*/
+
+sel_file udpsock[NADDRFAM];
+
 /*----- Static variables --------------------------------------------------*/
 
 static sym_table byname;
 static addrmap byaddr;
-static sel_file sock;
+static unsigned nmobile;
 
 /*----- Tunnel table ------------------------------------------------------*/
 
@@ -122,6 +125,198 @@ found:
   p_pingdone(pg, PING_OK);
 }
 
+/* --- @p_rxupdstats@ --- *
+ *
+ * Arguments:  @peer *p@ = peer to update
+ *             @size_t n@ = size of incoming packet
+ *
+ * Returns:    ---
+ *
+ * Use:                Updates the peer's incoming packet statistics.
+ */
+
+static void p_rxupdstats(peer *p, size_t n)
+{
+  p->st.t_last = time(0);
+  p->st.n_in++;
+  p->st.sz_in += n;
+}
+
+/* --- @p_encrypt@ --- *
+ *
+ * Arguments:  @peer *p@ = peer to encrypt message to
+ *             @int ty@ message type to send
+ *             @buf *bin, *bout@ = input and output buffers
+ *
+ * Returns:    ---
+ *
+ * Use:                Convenience function for packet encryption.  Forces
+ *             renegotiation when necessary.  Check for the output buffer
+ *             being broken to find out whether the encryption was
+ *             successful.
+ */
+
+static int p_encrypt(peer *p, int ty, buf *bin, buf *bout)
+{
+  int err = ksl_encrypt(&p->ks, ty, bin, bout);
+
+  if (err == KSERR_REGEN) {
+    kx_start(&p->kx, 1);
+    err = 0;
+  }
+  if (!BOK(bout))
+    err = -1;
+  return (err);
+}
+
+/* --- @p_updateaddr@ --- *
+ *
+ * Arguments:  @peer *p@ = pointer to peer block
+ *             @const addr *a@ = address to associate with this peer
+ *
+ * Returns:    Zero if the address was changed; @+1@ if it was already
+ *             right.
+ *
+ * Use:                Updates our idea of @p@'s address.
+ */
+
+int p_updateaddr(peer *p, const addr *a)
+{
+  peer *q;
+  peer_byaddr *pa, *qa;
+  int ix;
+  unsigned f;
+
+  /* --- Figure out how to proceed --- *
+   *
+   * If this address already belongs to a different peer, then swap the
+   * addresses over.  This doesn't leave the displaced peer in an especially
+   * good state, but it ought to get sorted out soon enough.
+   */
+
+  pa = am_find(&byaddr, a, sizeof(peer_byaddr), &f);
+  if (f && pa->p == p)
+    return (+1);
+  else if (!f) {
+    T( trace(T_PEER, "peer: updating address for `%s'", p_name(p)); )
+    am_remove(&byaddr, p->byaddr);
+    p->byaddr = pa; p->spec.sa = *a; pa->p = p;
+    p->afix = afix(p->spec.sa.sa.sa_family); assert(p->afix >= 0);
+    a_notify("NEWADDR", "?PEER", p, "?ADDR", a, A_END);
+    return (0);
+  } else {
+    q = pa->p; qa = p->byaddr;
+    T( trace(T_PEER, "peer: swapping addresses for `%s' and `%s'",
+            p_name(p), p_name(q)); )
+    q->byaddr = qa; qa->p = q; q->spec.sa = p->spec.sa;
+    p->byaddr = pa; pa->p = p; p->spec.sa = *a;
+    ix = p->afix; p->afix = q->afix; q->afix = ix;
+    a_notify("NEWADDR", "?PEER", p, "?ADDR", a, A_END);
+    a_notify("NEWADDR", "?PEER", q, "?ADDR", &q->spec.sa, A_END);
+    return (0);
+  }
+}
+
+/* --- @p_decrypt@ --- *
+ *
+ * Arguments:  @peer **pp@ = pointer to peer to decrypt message from
+ *             @addr *a@ = address the packet arrived on
+ *             @size_t n@ = size of original incoming packet
+ *             @int ty@ = message type to expect
+ *             @buf *bin, *bout@ = input and output buffers
+ *
+ * Returns:    Zero on success; nonzero on error.
+ *
+ * Use:                Convenience function for packet decryption.  Reports errors
+ *             and updates statistics appropriately.
+ *
+ *             If @*pp@ is null on entry and there are mobile peers then we
+ *             see if any of them can decrypt the packet.  If so, we record
+ *             @*a@ as the peer's new address and send a notification.
+ */
+
+static int p_decrypt(peer **pp, addr *a, size_t n,
+                    int ty, buf *bin, buf *bout)
+{
+  peer *p, *q;
+  int err = KSERR_DECRYPT;
+
+  /* --- If we have a match on the source address then try that first --- */
+
+  q = *pp;
+  if (q) {
+    T( trace(T_PEER, "peer: decrypting packet from known peer `%s'",
+            p_name(q)); )
+    if ((err = ksl_decrypt(&q->ks, ty, bin, bout)) != KSERR_DECRYPT ||
+       !(q->spec.f & PSF_MOBILE) || nmobile == 1) {
+      p = q;
+      goto match;
+    }
+    T( trace(T_PEER, "peer: failed to decrypt: try other mobile peers..."); )
+  } else if (nmobile)
+    T( trace(T_PEER, "peer: unknown source: trying mobile peers...") );
+  else {
+    p = 0;
+    goto searched;
+  }
+
+  /* --- See whether any mobile peer is interested --- */
+
+  p = 0;
+  FOREACH_PEER(qq, {
+    if (qq == q || !(qq->spec.f & PSF_MOBILE)) continue;
+    if ((err = ksl_decrypt(&qq->ks, ty, bin, bout)) == KSERR_DECRYPT) {
+      T( trace(T_PEER, "peer: peer `%s' failed to decrypt",
+              p_name(qq)); )
+       continue;
+    } else {
+      p = qq;
+      IF_TRACING(T_PEER, {
+       if (!err)
+         trace(T_PEER, "peer: peer `%s' reports success", p_name(qq));
+       else {
+         trace(T_PEER, "peer: peer `%s' reports decryption error %d",
+               p_name(qq), err);
+       }
+      })
+      break;
+    }
+  });
+
+  /* --- We've searched the mobile peers --- */
+
+searched:
+  if (!p) {
+    if (!q)
+      a_warn("PEER", "-", "unexpected-source", "?ADDR", a, A_END);
+    else {
+      a_warn("PEER", "?PEER", p, "decrypt-failed",
+            "error-code", "%d", err, A_END);
+      p_rxupdstats(q, n);
+    }
+    return (-1);
+  }
+
+  /* --- We found one that accepted, so update the peer's address --- */
+
+  if (!err) {
+    *pp = p;
+    p_updateaddr(p, a);
+  }
+
+match:
+  p_rxupdstats(p, n);
+  if (err) {
+    if (p) p->st.n_reject++;
+    a_warn("PEER", "?PEER", p, "decrypt-failed",
+          "error-code", "%d", err, A_END);
+    return (-1);
+  }
+  if (!BOK(bout))
+    return (-1);
+  return (0);
+}
+
 /* --- @p_read@ --- *
  *
  * Arguments:  @int fd@ = file descriptor to read from
@@ -137,14 +332,14 @@ static void p_read(int fd, unsigned mode, void *v)
 {
   peer *p = 0;
   addr a;
-  size_t sz;
+  socklen_t sz;
   ssize_t n;
   int ch;
   buf b, bb;
 
   /* --- Read the data --- */
 
-  TIMER;
+  QUICKRAND;
   sz = sizeof(addr);
   n = recvfrom(fd, buf_i, sizeof(buf_i), 0, &a.sa, &sz);
   if (n < 0) {
@@ -174,23 +369,27 @@ static void p_read(int fd, unsigned mode, void *v)
     return;
   }
 
-  /* --- Find the appropriate peer --- */
+  /* --- Find the appropriate peer --- *
+   *
+   * At this stage, don't worry too much about whether we actually found it.
+   */
 
-  if ((p = p_findbyaddr(&a)) == 0) {
-    a_warn("PEER", "-", "unexpected-source", "?ADDR", &a, A_END);
-    return;
-  }
+  p = p_findbyaddr(&a);
 
   IF_TRACING(T_PEER, {
-    trace(T_PEER, "peer: packet received from `%s'", p->spec.name);
+    if (p) {
+      trace(T_PEER,
+           "peer: packet received from `%s' from address INET %s %d",
+           p_name(p), inet_ntoa(a.sin.sin_addr), ntohs(a.sin.sin_port));
+    } else {
+      trace(T_PEER, "peer: packet received from unknown address INET %s %d",
+           inet_ntoa(a.sin.sin_addr), ntohs(a.sin.sin_port));
+    }
     trace_block(T_PACKET, "peer: packet contents", buf_i, n);
   })
 
   /* --- Pick the packet apart --- */
 
-  p->st.t_last = time(0);
-  p->st.n_in++;
-  p->st.sz_in += n;
   buf_init(&b, buf_i, n);
   if ((ch = buf_getbyte(&b)) < 0) {
     a_warn("PEER", "?PEER", p, "bad-packet", "no-type", A_END);
@@ -204,15 +403,12 @@ static void p_read(int fd, unsigned mode, void *v)
               "bad-packet",
               "unknown-type", "0x%02x", ch,
               A_END);
-       p->st.n_reject++;
+       if (p) p->st.n_reject++;
        return;
       }
       buf_init(&bb, buf_o, sizeof(buf_o));
-      if (ksl_decrypt(&p->ks, MSG_PACKET, &b, &bb)) {
-       p->st.n_reject++;
-       a_warn("PEER", "?PEER", p, "decrypt-failed", A_END);
+      if (p_decrypt(&p, &a, n, MSG_PACKET, &b, &bb))
        return;
-      }
       if (BOK(&bb)) {
        p->st.n_ipin++;
        p->st.sz_ipin += BSZ(&b);
@@ -223,42 +419,43 @@ static void p_read(int fd, unsigned mode, void *v)
       }
       break;
     case MSG_KEYEXCH:
+      if (!p) goto unexp;
+      p_rxupdstats(p, n);
       kx_message(&p->kx, ch & MSG_TYPEMASK, &b);
       break;
     case MSG_MISC:
       switch (ch & MSG_TYPEMASK) {
        case MISC_NOP:
+         if (!p) goto unexp;
+         p_rxupdstats(p, n);
          T( trace(T_PEER, "peer: received NOP packet"); )
          break;
        case MISC_PING:
+         if (!p) goto unexp;
+         p_rxupdstats(p, n);
          buf_put(p_txstart(p, MSG_MISC | MISC_PONG), BCUR(&b), BLEFT(&b));
          p_txend(p);
          break;
        case MISC_PONG:
+         if (!p) goto unexp;
+         p_rxupdstats(p, n);
          p_ponged(p, MISC_PONG, &b);
          break;
        case MISC_EPING:
          buf_init(&bb, buf_t, sizeof(buf_t));
-         if (ksl_decrypt(&p->ks, ch, &b, &bb)) {
-           p->st.n_reject++;
-           a_warn("PEER", "?PEER", p, "decrypt-failed", A_END);
+         if (p_decrypt(&p, &a, n, ch, &b, &bb))
            return;
-         }
          if (BOK(&bb)) {
            buf_flip(&bb);
-           if (ksl_encrypt(&p->ks, MSG_MISC | MISC_EPONG, &bb,
-                           p_txstart(p, MSG_MISC | MISC_EPONG)))
-             kx_start(&p->kx, 0);
+           p_encrypt(p, MSG_MISC | MISC_EPONG, &bb,
+                     p_txstart(p, MSG_MISC | MISC_EPONG));
            p_txend(p);
          }
          break;
        case MISC_EPONG:
          buf_init(&bb, buf_t, sizeof(buf_t));
-         if (ksl_decrypt(&p->ks, ch, &b, &bb)) {
-           p->st.n_reject++;
-           a_warn("PEER", "?PEER", p, "decrypt-failed", A_END);
+         if (p_decrypt(&p, &a, n, ch, &b, &bb))
            return;
-         }
          if (BOK(&bb)) {
            buf_flip(&bb);
            p_ponged(p, MISC_EPONG, &bb);
@@ -267,13 +464,16 @@ static void p_read(int fd, unsigned mode, void *v)
       }
       break;
     default:
-      p->st.n_reject++;
+      if (p) p->st.n_reject++;
       a_warn("PEER",
             "?PEER", p,
             "bad-packet",
-            "unknown-category" "0x%02x", ch,
+            "unknown-category", "0x%02x", ch,
             A_END);
       break;
+    unexp:
+      a_warn("PEER", "-", "unexpected-source", "?ADDR", &a, A_END);
+      break;
   }
 }
 
@@ -308,14 +508,16 @@ static void p_setkatimer(peer *);
 
 static int p_dotxend(peer *p)
 {
+  socklen_t sasz = addrsz(&p->spec.sa);
+
   if (!BOK(&p->b)) {
     a_warn("PEER", "?PEER", p, "packet-build-failed", A_END);
     return (0);
   }
   IF_TRACING(T_PEER, trace_block(T_PACKET, "peer: sending packet",
                                 BBASE(&p->b), BLEN(&p->b)); )
-  if (sendto(sock.fd, BBASE(&p->b), BLEN(&p->b),
-            0, &p->spec.sa.sa, p->spec.sasz) < 0) {
+  if (sendto(udpsock[p->afix].fd, BBASE(&p->b), BLEN(&p->b),
+            0, &p->spec.sa.sa, sasz) < 0) {
     a_warn("PEER", "?PEER", p, "socket-write-error", "?ERRNO", A_END);
     return (0);
   } else {
@@ -427,8 +629,7 @@ int p_pingsend(peer *p, ping *pg, unsigned type,
       buf_init(&bb, buf_t, sizeof(buf_t));
       p_pingwrite(pg, &bb);
       buf_flip(&bb);
-      if (ksl_encrypt(&p->ks, MSG_MISC | MISC_EPING, &bb, b))
-       kx_start(&p->kx, 0);
+      p_encrypt(p, MSG_MISC | MISC_EPING, &bb, b);
       if (!BOK(b))
        return (-1);
       p_txend(p);
@@ -485,9 +686,8 @@ void p_tun(peer *p, buf *b)
 {
   buf *bb = p_txstart(p, MSG_PACKET);
 
-  TIMER;
-  if (ksl_encrypt(&p->ks, MSG_PACKET, b, bb))
-    kx_start(&p->kx, 0);
+  QUICKRAND;
+  p_encrypt(p, MSG_PACKET, b, bb);
   if (BOK(bb) && BLEN(bb)) {
     p->st.n_ipout++;
     p->st.sz_ipout += BLEN(bb);
@@ -608,8 +808,8 @@ void p_init(struct in_addr addr, unsigned port)
        strerror(errno));
   }
   fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
-  sel_initfile(&sel, &sock, fd, SEL_READ, p_read, 0);
-  sel_addfile(&sock);
+  sel_initfile(&sel, &udpsock[AFIX_INET], fd, SEL_READ, p_read, 0);
+  sel_addfile(&udpsock[AFIX_INET]);
   T( trace(T_PEER, "peer: created socket"); )
 
   sym_create(&byname);
@@ -618,20 +818,19 @@ void p_init(struct in_addr addr, unsigned port)
 
 /* --- @p_port@ --- *
  *
- * Arguments:  ---
+ * Arguments:  @int i@ = address family index to retrieve
  *
  * Returns:    Port number used for socket.
  */
 
-unsigned p_port(void)
+unsigned p_port(int i)
 {
   addr a;
-  size_t sz = sizeof(addr);
+  socklen_t sz = sizeof(addr);
 
-  if (getsockname(sock.fd, &a.sa, &sz))
+  if (getsockname(udpsock[i].fd, &a.sa, &sz))
     die(EXIT_FAILURE, "couldn't read port number: %s", strerror(errno));
-  assert(a.sa.sa_family == AF_INET);
-  return (ntohs(a.sin.sin_port));
+  return (getport(&a));
 }
 
 /* --- @p_keepalive@ --- *
@@ -647,6 +846,7 @@ unsigned p_port(void)
 static void p_keepalive(struct timeval *now, void *pv)
 {
   peer *p = pv;
+
   p_txstart(p, MSG_MISC | MISC_NOP); p_dotxend(p);
   T( trace(T_PEER, "peer: sent keepalive to %s", p->spec.name); )
   p_setkatimer(p);
@@ -685,6 +885,8 @@ static void p_setkatimer(peer *p)
 peer *p_create(peerspec *spec)
 {
   peer *p = CREATE(peer);
+  const tunnel_ops *tops = spec->tops;
+  int fd;
   unsigned f;
 
   p->byname = sym_find(&byname, spec->name, -1, sizeof(peer_byname), &f);
@@ -696,34 +898,47 @@ peer *p_create(peerspec *spec)
   T( trace(T_PEER, "peer: creating new peer `%s'", spec->name); )
   p->spec = *spec;
   p->spec.name = (/*unconst*/ char *)SYM_NAME(p->byname);
+  if (spec->tag) p->spec.tag = xstrdup(spec->tag);
+  if (spec->privtag) p->spec.privtag = xstrdup(spec->privtag);
   p->ks = 0;
   p->pings = 0;
   p->ifname = 0;
+  p->afix = afix(p->spec.sa.sa.sa_family); assert(p->afix >= 0);
   memset(&p->st, 0, sizeof(stats));
   p->st.t_start = time(0);
-  if ((p->t = spec->tops->create(p, &p->ifname)) == 0)
+  if (!(tops->flags & TUNF_PRIVOPEN))
+    fd = -1;
+  else if ((fd = ps_tunfd(tops, &p->ifname)) < 0)
     goto tidy_2;
-  p_setkatimer(p);
-  if (kx_init(&p->kx, p, &p->ks, p->spec.kxf))
+  if ((p->t = tops->create(p, fd, &p->ifname)) == 0)
     goto tidy_3;
+  T( trace(T_TUNNEL, "peer: attached interface %s to peer `%s'",
+          p->ifname, p_name(p)); )
+  p_setkatimer(p);
+  if (kx_init(&p->kx, p, &p->ks, p->spec.f & PSF_KXMASK))
+    goto tidy_4;
   a_notify("ADD",
-           "?PEER", p,
-           "%s", p->ifname,
-           "?ADDR", &p->spec.sa,
-           A_END);
-  if (!(p->spec.kxf & KXF_CORK)) {
+          "?PEER", p,
+          "%s", p->ifname,
+          "?ADDR", &p->spec.sa,
+          A_END);
+  if (!(p->spec.f & KXF_CORK)) {
     a_notify("KXSTART", "?PEER", p, A_END);
     /* Couldn't tell anyone before */
   }
+  if (p->spec.f & PSF_MOBILE) nmobile++;
   return (p);
 
-tidy_3:
-  if (spec->t_ka)
-    sel_rmtimer(&p->tka);
+tidy_4:
+  if (spec->t_ka) sel_rmtimer(&p->tka);
   xfree(p->ifname);
   p->t->ops->destroy(p->t);
+tidy_3:
+  if (fd >= 0) close(fd);
 tidy_2:
   am_remove(&byaddr, p->byaddr);
+  if (p->spec.tag) xfree(p->spec.tag);
+  if (p->spec.privtag) xfree(p->spec.privtag);
 tidy_1:
   sym_remove(&byname, p->byname);
 tidy_0:
@@ -738,7 +953,28 @@ tidy_0:
  * Returns:    A pointer to the peer's name.
  */
 
-const char *p_name(peer *p) { return (p->spec.name); }
+const char *p_name(peer *p)
+  { if (p) return (p->spec.name); else return ("-"); }
+
+/* --- @p_tag@ --- *
+ *
+ * Arguments:  @peer *p@ = pointer to a peer block
+ *
+ * Returns:    A pointer to the peer's public key tag.
+ */
+
+const char *p_tag(peer *p)
+  { return (p->spec.tag ? p->spec.tag : p->spec.name); }
+
+/* --- @p_privtag@ --- *
+ *
+ * Arguments:  @peer *p@ = pointer to a peer block
+ *
+ * Returns:    A pointer to the peer's private key tag.
+ */
+
+const char *p_privtag(peer *p)
+  { return (p->spec.privtag ? p->spec.privtag : tag_priv); }
 
 /* --- @p_spec@ --- *
  *
@@ -762,8 +998,10 @@ peer *p_findbyaddr(const addr *a)
 {
   peer_byaddr *pa;
 
-  if ((pa = am_find(&byaddr, a, 0, 0)) != 0)
+  if ((pa = am_find(&byaddr, a, 0, 0)) != 0) {
+    assert(pa->p);
     return (pa->p);
+  }
   return (0);
 }
 
@@ -802,11 +1040,12 @@ void p_destroy(peer *p)
   a_notify("KILL", "%s", p->spec.name, A_END);
   ksl_free(&p->ks);
   kx_free(&p->kx);
-  if (p->ifname)
-    xfree(p->ifname);
+  if (p->spec.f & PSF_MOBILE) nmobile--;
+  if (p->ifname) xfree(p->ifname);
+  if (p->spec.tag) xfree(p->spec.tag);
+  if (p->spec.privtag) xfree(p->spec.privtag);
   p->t->ops->destroy(p->t);
-  if (p->spec.t_ka)
-    sel_rmtimer(&p->tka);
+  if (p->spec.t_ka) sel_rmtimer(&p->tka);
   for (pg = p->pings; pg; pg = ppg) {
     ppg = pg->next;
     p_pingdone(pg, PING_PEERDIED);