Checkpoint commit: refactoring the request code in TIDS for better reuse
authorJennifer Richards <jennifer@painless-security.com>
Thu, 12 Apr 2018 20:24:32 +0000 (16:24 -0400)
committerJennifer Richards <jennifer@painless-security.com>
Thu, 12 Apr 2018 20:24:32 +0000 (16:24 -0400)
  * Move tr_gss.[ch] to tr_gss_names.[ch], that is what the files contain
  * Add new tr_gss.[ch] containing generalized GSS request/response code
  * Refactor tids request handlers to use generalized code

  * First steps towards a monitoring interface handler, not functional
  * Rename listen_on_all_addrs() to tr_sock_listen_all()
  * Make better use of talloc in a few places
  * Clean up a few missing or unused #includes
  * Fix a few data types for the sake of pedantry

28 files changed:
CMakeLists.txt
Makefile.am
common/tr_config.c
common/tr_gss.c [new file with mode: 0644]
common/tr_msg.c
common/tr_rp.c
common/tr_socket.c
include/mon_internal.h
include/tid_internal.h
include/tr_config.h
include/tr_event.h
include/tr_gss.h [new file with mode: 0644]
include/tr_msg.h
include/tr_rp.h
include/tr_socket.h
include/tr_trp.h
include/trp_ptable.h
include/trust_router/tid.h
mon/mons.c [new file with mode: 0644]
tid/tidc.c
tid/tids.c
tr/tr_main.c
tr/tr_mon.c [new file with mode: 0644]
tr/tr_tid.c
trp/msgtst.c
trp/test/ptbl_test.c
trp/trp_ptable.c
trp/trps.c

index b81f3d3..0c7d8c0 100644 (file)
@@ -91,7 +91,7 @@ set(SOURCE_FILES
     trp/trp_upd.c
     trp/trpc.c
     trp/trps.c include/tr_name_internal.h mon/mon_req.c mon/mon_req_encode.c mon/mon_req_decode.c
-        mon/mon_resp.c mon/mon_common.c mon/mon_resp_encode.c tr/tr_mon.c mon/mons.c include/tr_socket.h)
+        mon/mon_resp.c mon/mon_common.c mon/mon_resp_encode.c tr/tr_mon.c mon/mons.c include/tr_socket.h common/tr_gss.c include/tr_gss.h)
 
 # Does not actually build!
 add_executable(trust_router ${SOURCE_FILES})
index 133da05..e13e55a 100644 (file)
@@ -78,6 +78,7 @@ tr/tr_event.c \
 tr/tr_cfgwatch.c \
 tr/tr_tid.c \
 tr/tr_trp.c \
+common/tr_gss.c \
 $(tid_srcs) \
 $(trp_srcs) \
 $(common_srcs)
@@ -86,6 +87,7 @@ tr_trust_router_LDFLAGS = $(AM_LDFLAGS) -levent_pthreads -pthread
 tr_trust_router_LDADD = gsscon/libgsscon.la $(GLIB_LIBS)
 tr_trpc_SOURCES =tr/trpc_main.c \
 tr/tr_trp.c \
+common/tr_gss.c \
 $(trp_srcs) \
 $(tid_srcs) \
 $(common_srcs)
@@ -109,6 +111,7 @@ trp/trp_rtable.c
 trp_test_rtbl_test_LDADD =  $(GLIB_LIBS)
 
 trp_test_ptbl_test_SOURCES = trp/test/ptbl_test.c \
+common/tr_gss.c \
 $(tid_srcs) \
 $(trp_srcs) \
 $(common_srcs)
@@ -116,6 +119,7 @@ trp_test_ptbl_test_LDADD = gsscon/libgsscon.la $(GLIB_LIBS)
 trp_test_ptbl_test_LDFLAGS = $(AM_LDFLAGS) -pthread
 
 tid_example_tidc_SOURCES = tid/example/tidc_main.c \
+common/tr_gss.c \
 $(tid_srcs) \
 $(trp_srcs) \
 $(common_srcs)
@@ -123,6 +127,7 @@ tid_example_tidc_LDADD = gsscon/libgsscon.la  $(GLIB_LIBS)
 tid_example_tidc_LDFLAGS = $(AM_LDFLAGS) -pthread
 
 tid_example_tids_SOURCES = tid/example/tids_main.c \
+common/tr_gss.c \
 $(tid_srcs) \
 $(trp_srcs) \
 $(common_srcs)
@@ -141,6 +146,7 @@ common_tests_mq_test_LDFLAGS = $(AM_LDFLAGS) -ltalloc -pthread
 
 common_tests_cfg_test_SOURCES = common/tests/cfg_test.c \
 $(common_srcs) \
+common/tr_gss.c \
 $(tid_srcs) \
 $(trp_srcs)
 common_tests_cfg_test_LDADD = gsscon/libgsscon.la  $(GLIB_LIBS)
@@ -152,6 +158,7 @@ common/tests/thread_test.c
 
 common_tests_commtest_SOURCES = common/tests/commtest.c \
 $(common_srcs) \
+common/tr_gss.c \
 $(tid_srcs) \
 $(trp_srcs)
 common_tests_commtest_LDADD = gsscon/libgsscon.la $(GLIB_LIBS)
@@ -161,6 +168,7 @@ common_tests_thread_test_LDFLAGS = $(AM_LDFLAGS) -ltalloc -pthread
 
 common_tests_name_test_SOURCES = common/tests/name_test.c \
               $(common_srcs) \
+              common/tr_gss.c \
               $(tid_srcs) \
               $(trp_srcs)
 common_tests_name_test_LDADD = gsscon/libgsscon.la $(GLIB_LIBS)
@@ -169,6 +177,7 @@ common_tests_name_test_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
 
 common_tests_filt_test_SOURCES = common/tests/filt_test.c \
               $(common_srcs) \
+              common/tr_gss.c \
               $(tid_srcs) \
               $(trp_srcs)
 common_tests_filt_test_LDADD = gsscon/libgsscon.la $(GLIB_LIBS)
@@ -209,7 +218,7 @@ noinst_HEADERS = include/gsscon.h include/tr_config.h \
        include/tr_cfgwatch.h include/tr_event.h \
        include/tr_mq.h include/trp_ptable.h \
        include/trp_rtable.h include/tr_util.h \
-       include/tr_name_internal.h
+       include/tr_name_internal.h include/tr_gss.h
 
 pkgdata_DATA=schema.sql
 nobase_dist_pkgdata_DATA=redhat/init redhat/sysconfig redhat/organizations.cfg redhat/tidc-wrapper redhat/trust_router-wrapper redhat/tr-test-internal.cfg redhat/default-internal.cfg redhat/tids-wrapper redhat/sysconfig.tids
index c1fc6d9..06d15a6 100644 (file)
@@ -41,7 +41,7 @@
 #include <tr_cfgwatch.h>
 #include <tr_comm.h>
 #include <tr_config.h>
-#include <tr_gss.h>
+#include <tr_gss_names.h>
 #include <tr_debug.h>
 #include <tr_filter.h>
 #include <trust_router/tr_constraint.h>
diff --git a/common/tr_gss.c b/common/tr_gss.c
new file mode 100644 (file)
index 0000000..495f8f8
--- /dev/null
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 2018, JANET(UK)
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of JANET(UK) nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <talloc.h>
+#include <gssapi.h>
+#include <string.h>
+
+#include <tr_msg.h>
+#include <tr_debug.h>
+#include <gsscon.h>
+#include <tr_gss.h>
+
+
+/**
+ * Callback to handle GSS authentication and authorization
+ *
+ * @param conn connection file descriptor
+ * @param acceptor_name name of acceptor to present to initiator
+ * @param acceptor_realm realm of acceptor to present to initiator
+ * @param gssctx GSS context
+ * @param auth_cb authorization callback
+ * @param auth_cookie generic data to pass to the authorization callback
+ * @return 0 on successful auth, 1 on disallowed auth, -1 on error
+ */
+static int tr_gss_auth_connection(int conn,
+                                  const char *acceptor_name,
+                                  const char *acceptor_realm,
+                                  gss_ctx_id_t *gssctx,
+                                  TR_GSS_AUTH_FN auth_cb,
+                                  void *auth_cookie)
+{
+  int rc = 0;
+  int auth, autherr = 0;
+  gss_buffer_desc nameBuffer = {0, NULL};
+
+  nameBuffer.value = talloc_asprintf(NULL, "%s@%s", acceptor_name, acceptor_realm);
+  if (nameBuffer.value == NULL) {
+    tr_err("tr_gss_auth_connection: Error allocating acceptor name.");
+    return -1;
+  }
+  nameBuffer.length = strlen(nameBuffer.value);
+
+  rc = gsscon_passive_authenticate(conn, nameBuffer, gssctx, auth_cb, auth_cookie);
+  talloc_free(nameBuffer.value);
+  if (rc) {
+    tr_debug("tr_gss_auth_connection: Error from gsscon_passive_authenticate(), rc = %d.", rc);
+    return -1;
+  }
+
+  rc = gsscon_authorize(*gssctx, &auth, &autherr);
+  if (rc) {
+    tr_debug("tr_gss_auth_connection: Error from gsscon_authorize, rc = %d, autherr = %d.",
+             rc, autherr);
+    return -1;
+  }
+
+  if (auth)
+    tr_debug("tr_gss_auth_connection: Connection authenticated, conn = %d.", conn);
+  else
+    tr_debug("tr_gss_auth_connection: Authentication failed, conn %d.", conn);
+
+  return !auth;
+}
+
+/**
+ * Read a request from the GSS connection
+ *
+ * @param mem_ctx talloc context for the result
+ * @param conn file descriptor for the connection
+ * @param gssctx GSS context
+ * @return talloc'ed string containing the request, or null on error
+ */
+static char *tr_gss_read_req(TALLOC_CTX *mem_ctx, int conn, gss_ctx_id_t gssctx)
+{
+  int err;
+  char *retval = NULL;
+  char *buf = NULL;
+  size_t buflen = 0;
+
+  err = gsscon_read_encrypted_token(conn, gssctx, &buf, &buflen);
+  if (err || (buf == NULL)) {
+    if (buf)
+      free(buf);
+    tr_debug("tr_gss_read_req: Error reading from connection, rc=%d", err);
+    return NULL;
+  }
+
+  tr_debug("tr_gss_read_req: Read %u bytes.", (unsigned) buflen);
+
+  // get a talloc'ed version, guaranteed to have a null termination
+  retval = talloc_asprintf(mem_ctx, "%.*s", (int) buflen, buf);
+  free(buf);
+
+  return retval;
+}
+
+/**
+ * Write a response to the GSS connection
+ *
+ * @param conn file descriptor for the connection
+ * @param gssctx GSS context
+ * @param resp encoded response string to send
+ * @return 0 on success, -1 on error
+ */
+static int tr_gss_write_resp(int conn, gss_ctx_id_t gssctx, const char *resp)
+{
+  int err = 0;
+
+  /* Send the response over the connection */
+  err = gsscon_write_encrypted_token (conn, gssctx, resp, strlen(resp) + 1);
+  if (err) {
+    tr_debug("tr_gss_send_response: Error sending response over connection, rc=%d.", err);
+    return -1;
+  }
+  return 0;
+}
+
+/**
+ * Handle a request/response connection
+ *
+ * Authorizes/authenticates the connection, then reads a response, passes that to a
+ * callback to get a response, sends that, then returns.
+ *
+ * @param conn connection file descriptor
+ * @param acceptor_name acceptor name to present
+ * @param acceptor_realm acceptor realm to present
+ * @param auth_cb callback for authorization
+ * @param auth_cookie cookie for the auth_cb
+ * @param req_cb callback to handle the request and produce the response
+ * @param req_cookie cookie for the req_cb
+ */
+void tr_gss_handle_connection(int conn,
+                              const char *acceptor_name,
+                              const char *acceptor_realm,
+                              TR_GSS_AUTH_FN auth_cb,
+                              void *auth_cookie,
+                              TR_GSS_HANDLE_REQ_FN req_cb,
+                              void *req_cookie)
+{
+  TALLOC_CTX *tmp_ctx = talloc_new(NULL);
+  gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
+  char *req_str = NULL;
+  char *resp_str = NULL;
+
+  if (tr_gss_auth_connection(conn,
+                             acceptor_name,
+                             acceptor_realm,
+                             &gssctx,
+                             auth_cb,
+                             auth_cookie)) {
+    tr_notice("tr_gss_handle_connection: Error authorizing connection.");
+    goto cleanup;
+  }
+
+  tr_debug("tr_gss_handle_connection: Connection authorized");
+
+  // TODO: should there be a timeout on this?
+  while (1) {  /* continue until an error breaks us out */
+    // try to read a request
+    req_str = tr_gss_read_req(tmp_ctx, conn, gssctx);
+
+    if ( req_str == NULL) {
+      // an error occurred, give up
+      tr_notice("tr_gss_handle_connection: Error reading request");
+      goto cleanup;
+    } else if (strlen(req_str) > 0) {
+      // we got a request message, exit the loop and process it
+      break;
+    }
+
+    // no error, but no message, keep waiting for one
+    talloc_free(req_str); // this would be cleaned up anyway, but may as well free it
+  }
+
+  /* Hand off the request for processing and get the response */
+  resp_str = req_cb(tmp_ctx, req_str, req_cookie);
+
+  if (resp_str == NULL) {
+    // no response, clean up
+    goto cleanup;
+  }
+
+  // send the response
+  if (tr_gss_write_resp(conn, gssctx, resp_str)) {
+    tr_notice("tr_gss_handle_connection: Error writing response");
+  }
+
+cleanup:
+  talloc_free(tmp_ctx);
+}
index 59a2efd..e0e406a 100644 (file)
@@ -1144,10 +1144,11 @@ cleanup:
   return req;
 }
 
-char *tr_msg_encode(TR_MSG *msg) 
+char *tr_msg_encode(TALLOC_CTX *mem_ctx, TR_MSG *msg)
 {
   json_t *jmsg=NULL;
   json_t *jmsg_type=NULL;
+  char *encoded_tmp=NULL;
   char *encoded=NULL;
   TID_RESP *tidresp=NULL;
   TID_REQ *tidreq=NULL;
@@ -1192,9 +1193,14 @@ char *tr_msg_encode(TR_MSG *msg)
       return NULL;
     }
 
-  encoded=json_dumps(jmsg, 0);
+  /* We should perhaps use json_set_alloc_funcs to automatically use talloc, but for
+   * now, we'll encode to a malloc'ed buffer, then copy that to a talloc'ed buffer. */
+  encoded_tmp=json_dumps(jmsg, 0);                // malloc'ed version
+  json_decref(jmsg);                              // free the JSON structure
+  encoded = talloc_strdup(mem_ctx, encoded_tmp);  // get the talloc'ed version
+  free(encoded_tmp);                              // free the malloc'ed version
+
   tr_debug("tr_msg_encode: outgoing msg=%s", encoded);
-  json_decref(jmsg);
   return encoded;
 }
 
index 4acdc4b..6d0880a 100644 (file)
@@ -36,7 +36,7 @@
 
 #include <tr.h>
 #include <tr_name_internal.h>
-#include <tr_gss.h>
+#include <tr_gss_names.h>
 #include <tr_config.h>
 #include <tr_rp.h>
 #include <tr_debug.h>
index f05003a..313d931 100644 (file)
@@ -36,6 +36,7 @@
 #include <stdlib.h>
 #include <unistd.h>
 #include <netdb.h>
+#include <poll.h> // for nfds_t
 
 #include <tr_debug.h>
 #include <tr_socket.h>
@@ -53,7 +54,7 @@
  * @param max_fd maximum number of file descriptors to write
  * @return number of file descriptors written into the output array
  */
-ssize_t listen_on_all_addrs(unsigned int port, int *fd_out, size_t max_fd)
+nfds_t tr_sock_listen_all(unsigned int port, int *fd_out, nfds_t max_fd)
 {
   int rc = 0;
   int conn = -1;
@@ -68,26 +69,26 @@ ssize_t listen_on_all_addrs(unsigned int port, int *fd_out, size_t max_fd)
       .ai_protocol=IPPROTO_TCP
   };
   char *port_str=NULL;
-  size_t n_opened=0;
+  nfds_t n_opened=0;
 
   port_str=talloc_asprintf(NULL, "%d", port);
   if (port_str==NULL) {
-    tr_err("listen_on_all_addrs: unable to allocate port");
-    return -1;
+    tr_err("tr_sock_listen_all: unable to allocate port");
+    return 0;
   }
 
   gai_retval = getaddrinfo(NULL, port_str, &hints, &ai_head);
   talloc_free(port_str);
   if (gai_retval != 0) {
-    tr_err("listen_on_all_addrs: getaddrinfo() failed (%s)", gai_strerror(gai_retval));
-    return -1;
+    tr_err("tr_sock_listen_all: getaddrinfo() failed (%s)", gai_strerror(gai_retval));
+    return 0;
   }
-  tr_debug("listen_on_all_addrs: got address info");
+  tr_debug("tr_sock_listen_all: got address info");
 
   /* TODO: listen on all ports - I don't recall what this means (jlr, 4/11/2018) */
   for (ai=ai_head,n_opened=0; (ai!=NULL)&&(n_opened<max_fd); ai=ai->ai_next) {
     if (0 > (conn = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))) {
-      tr_debug("listen_on_all_addrs: unable to open socket");
+      tr_debug("tr_sock_listen_all: unable to open socket");
       continue;
     }
 
@@ -99,7 +100,7 @@ ssize_t listen_on_all_addrs(unsigned int port, int *fd_out, size_t max_fd)
       /* don't allow IPv4-mapped IPv6 addresses (per RFC4942, not sure
        * if still relevant) */
       if (0!=setsockopt(conn, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval))) {
-        tr_debug("listen_on_all_addrs: unable to set IPV6_V6ONLY, skipping interface");
+        tr_debug("tr_sock_listen_all: unable to set IPV6_V6ONLY, skipping interface");
         close(conn);
         continue;
       }
@@ -107,13 +108,13 @@ ssize_t listen_on_all_addrs(unsigned int port, int *fd_out, size_t max_fd)
 
     rc=bind(conn, ai->ai_addr, ai->ai_addrlen);
     if (rc<0) {
-      tr_debug("listen_on_all_addrs: unable to bind to socket");
+      tr_debug("tr_sock_listen_all: unable to bind to socket");
       close(conn);
       continue;
     }
 
     if (0>listen(conn, 512)) {
-      tr_debug("listen_on_all_addrs: unable to listen on bound socket");
+      tr_debug("tr_sock_listen_all: unable to listen on bound socket");
       close(conn);
       continue;
     }
@@ -124,14 +125,15 @@ ssize_t listen_on_all_addrs(unsigned int port, int *fd_out, size_t max_fd)
   freeaddrinfo(ai_head);
 
   if (n_opened==0) {
-    tr_debug("listen_on_all_addrs: no addresses available for listening.");
-    return -1;
+    tr_debug("tr_sock_listen_all: no addresses available for listening.");
+    return 0;
   }
 
-  tr_debug("listen_on_all_addrs: monitoring interface listening on port %d on %d socket%s",
+  tr_debug("tr_sock_listen_all: monitoring interface listening on port %d on %d socket%s",
            port,
            n_opened,
            (n_opened==1)?"":"s");
 
   return n_opened;
 }
+
index 58cfdee..f49889a 100644 (file)
 #define TRUST_ROUTER_MON_REQ_H
 
 #include <talloc.h>
+#include <stdint.h>
 #include <jansson.h>
 #include <gmodule.h>
+
+#include <tr.h>
+#include <tr_gss_names.h>
 #include <tr_name_internal.h>
+#include <gssapi.h>
 
 /* Typedefs */
 typedef struct mon_req MON_REQ;
@@ -53,6 +58,10 @@ typedef enum mon_opt_type MON_OPT_TYPE;
 
 typedef enum mon_rc MON_RC;
 
+typedef struct mons_instance MONS_INSTANCE;
+
+typedef int (MONS_REQ_FUNC)(MONS_INSTANCE *, MON_REQ *, MON_RESP *, void *);
+typedef int (MONS_AUTH_FUNC)(gss_name_t client_name, TR_NAME *display_name, void *cookie);
 
 /* Struct and enum definitions */
 enum mon_rc {
@@ -108,6 +117,15 @@ struct mon_resp {
   json_t *payload;
 };
 
+/* Monitoring server instance */
+struct mons_instance {
+  unsigned int port;
+  TR_GSS_NAMES *authorized_gss_names;
+  MONS_REQ_FUNC *req_handler;
+  MONS_AUTH_FUNC *auth_handler;
+  void *cookie;
+};
+
 /* Prototypes */
 /* tr_mon.c */
 const char *mon_cmd_to_string(MON_CMD cmd);
@@ -139,4 +157,9 @@ void mon_resp_free(MON_RESP *resp);
 /* mon_resp_encode.c */
 json_t *mon_resp_encode(MON_RESP *resp);
 
+/* mons.c */
+MONS_INSTANCE *mons_new(TALLOC_CTX *mem_ctx);
+int mons_get_listener(MONS_INSTANCE *mons, MONS_REQ_FUNC *req_handler, MONS_AUTH_FUNC *auth_handler, unsigned int port,
+                      void *cookie, int *fd_out, size_t max_fd);
+
 #endif //TRUST_ROUTER_MON_REQ_H
index f02c4d1..b6bd8fc 100644 (file)
@@ -97,7 +97,7 @@ struct tids_instance {
   TIDS_REQ_FUNC *req_handler;
   tids_auth_func *auth_handler;
   void *cookie;
-  uint16_t tids_port;
+  unsigned int tids_port;
   TR_NAME *gss_name;           /* GSS name client used for authentication */
 };
 
index 89fd328..dae9d4a 100644 (file)
@@ -73,6 +73,7 @@ typedef struct tr_cfg_internal {
   unsigned int max_tree_depth;
   unsigned int tids_port;
   unsigned int trps_port;
+  unsigned int monitoring_port;
   const char *hostname;
   int log_threshold;
   int console_threshold;
index dc93860..55cc272 100644 (file)
@@ -41,7 +41,7 @@
 
 /* struct for hanging on to a socket listener event */
 struct tr_socket_event {
-  size_t n_sock_fd; /* how many of those are filled in? */
+  int n_sock_fd; /* how many of those are filled in? */
   int sock_fd[TR_MAX_SOCKETS]; /* the fd for the socket */
   struct event *ev[TR_MAX_SOCKETS]; /* its events */
 };
diff --git a/include/tr_gss.h b/include/tr_gss.h
new file mode 100644 (file)
index 0000000..9cd378e
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2018, JANET(UK)
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of JANET(UK) nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef TRUST_ROUTER_TR_GSS_H
+#define TRUST_ROUTER_TR_GSS_H
+
+#include <tr_msg.h>
+
+typedef int (TR_GSS_AUTH_FN)(gss_name_t, gss_buffer_t, void *);
+typedef char *(TR_GSS_HANDLE_REQ_FN)(TALLOC_CTX *, const char *, void *);
+
+void tr_gss_handle_connection(int conn, const char *acceptor_name, const char *acceptor_realm, TR_GSS_AUTH_FN auth_cb,
+                              void *auth_cookie, TR_GSS_HANDLE_REQ_FN req_cb, void *req_cookie);
+
+#endif //TRUST_ROUTER_TR_GSS_H
index e10fd1a..59b7cf7 100644 (file)
@@ -68,7 +68,7 @@ void tr_msg_set_trp_req(TR_MSG *msg, TRP_REQ *req);
 
 
 /* Encoders/Decoders */
-char *tr_msg_encode(TR_MSG *msg);
+char *tr_msg_encode(TALLOC_CTX *mem_ctx, TR_MSG *msg);
 TR_MSG *tr_msg_decode(const char *jmsg, size_t len);
 void tr_msg_free_encoded(char *jmsg);
 void tr_msg_free_decoded(TR_MSG *msg);
index fa6b84e..a9e56df 100644 (file)
@@ -37,7 +37,7 @@
 
 #include <talloc.h>
 
-#include <tr_gss.h>
+#include <tr_gss_names.h>
 #include <tr_filter.h>
 
 typedef struct tr_rp_client {
index 33648c1..064c6fc 100644 (file)
@@ -36,7 +36,8 @@
 #define TRUST_ROUTER_TR_SOCKET_H
 
 #include <stdlib.h>
+#include <poll.h> // for nfds_t
 
-ssize_t listen_on_all_addrs(unsigned int port, int *fd_out, size_t max_fd);
+nfds_t tr_sock_listen_all(unsigned int port, int *fd_out, nfds_t max_fd);
 
 #endif //TRUST_ROUTER_TR_SOCKET_H
index 297295f..80c9a61 100644 (file)
@@ -44,6 +44,7 @@
 #include <tr_config.h>
 #include <tr_cfgwatch.h>
 #include <tr_event.h>
+#include <mon_internal.h>
 
 typedef struct tr_trps_events {
   struct event *trps_ev;
@@ -59,6 +60,7 @@ struct tr_instance {
   TR_CFG_MGR *cfg_mgr;
   TIDS_INSTANCE *tids;
   TRPS_INSTANCE *trps;
+  MONS_INSTANCE *mons;
   TR_CFGWATCH *cfgwatch;
   TR_TRPS_EVENTS *events;
 };
index 186f77a..0bf7c30 100644 (file)
@@ -39,7 +39,7 @@
 #include <talloc.h>
 
 #include <tr_name_internal.h>
-#include <tr_gss.h>
+#include <tr_gss_names.h>
 #include <trust_router/trp.h>
 #include <tr_filter.h>
 
index 8fc4267..cca0834 100644 (file)
@@ -151,14 +151,15 @@ TR_EXPORT DH *tidc_set_dh(TIDC_INSTANCE *, DH *);
 TR_EXPORT void tidc_destroy(TIDC_INSTANCE *tidc);
 
 /* TID Server functions, in tid/tids.c */
+TIDS_INSTANCE *tids_new(TALLOC_CTX *mem_ctx);
 TR_EXPORT TIDS_INSTANCE *tids_create (void);
 TR_EXPORT int tids_start (TIDS_INSTANCE *tids, TIDS_REQ_FUNC *req_handler,
                           tids_auth_func *auth_handler, const char *hostname,
                           unsigned int port, void *cookie);
 TR_EXPORT int tids_get_listener (TIDS_INSTANCE *tids, TIDS_REQ_FUNC *req_handler,
-                                 tids_auth_func *auth_handler, const char *hostname, 
+                                 tids_auth_func *auth_handler, const char *hostname,
                                  unsigned int port, void *cookie, int *fd_out, size_t max_fd);
-TR_EXPORT int tids_accept(TIDS_INSTANCE *tids, int listen);
+TR_EXPORT int tids_accept(TIDS_INSTANCE *mons, int listen);
 TR_EXPORT int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp);
 TR_EXPORT int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg);
 TR_EXPORT void tids_destroy (TIDS_INSTANCE *tids);
diff --git a/mon/mons.c b/mon/mons.c
new file mode 100644 (file)
index 0000000..29f405b
--- /dev/null
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2018, JANET(UK)
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of JANET(UK) nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <talloc.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <netdb.h>
+
+#include <tr.h>
+#include <tr_debug.h>
+#include <mon_internal.h>
+#include <tr_socket.h>
+#include <sys/wait.h>
+
+/**
+ * Allocate a new MONS_INSTANCE
+ *
+ * @param mem_ctx talloc context for allocation
+ * @return new MONS_INSTANCE or null on failure
+ */
+MONS_INSTANCE *mons_new(TALLOC_CTX *mem_ctx)
+{
+  MONS_INSTANCE *mons = talloc(mem_ctx, MONS_INSTANCE);
+
+  if (mons) {
+    mons->port = 0;
+    mons->req_handler = NULL;
+    mons->auth_handler = NULL;
+    mons->cookie = NULL;
+    mons->authorized_gss_names = tr_gss_names_new(mons);
+    if (mons->authorized_gss_names == NULL) {
+      talloc_free(mons);
+      mons = NULL;
+    }
+  }
+  return mons;
+}
+
+/**
+ * Create a listener for monitoring requests
+ *
+ * Accept connections with mons_accept()
+ *
+ * @param mons monitoring server instance
+ * @param req_handler
+ * @param auth_handler
+ * @param hostname
+ * @param port
+ * @param cookie
+ * @param fd_out
+ * @param max_fd
+ * @return
+ */
+int mons_get_listener(MONS_INSTANCE *mons,
+                      MONS_REQ_FUNC *req_handler,
+                      MONS_AUTH_FUNC *auth_handler,
+                      unsigned int port,
+                      void *cookie,
+                      int *fd_out,
+                      size_t max_fd)
+{
+  size_t n_fd=0;
+  size_t ii=0;
+
+  mons->port = port;
+  n_fd = tr_sock_listen_all(port, fd_out, max_fd);
+  if (n_fd<=0)
+    tr_err("mons_get_listener: Error opening port %d");
+  else {
+    /* opening port succeeded */
+    tr_info("mons_get_listener: Opened port %d.", port);
+
+    /* make this socket non-blocking */
+    for (ii=0; ii<n_fd; ii++) {
+      if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
+        tr_err("mons_get_listener: Error setting O_NONBLOCK.");
+        for (ii=0; ii<n_fd; ii++) {
+          close(fd_out[ii]);
+          fd_out[ii]=-1;
+        }
+        n_fd=0;
+        break;
+      }
+    }
+  }
+
+  if (n_fd>0) {
+    /* store the caller's request handler & cookie */
+    mons->req_handler = req_handler;
+    mons->auth_handler = auth_handler;
+    mons->cookie = cookie;
+  }
+
+  return (int) n_fd;
+}
+
+/**
+ * Accept and process a connection on a port opened with mons_get_listener()
+ *
+ * @param mons monitoring interface instance
+ * @param listen FD of the connection socket
+ * @return 0 on success
+ */
+int mons_accept(MONS_INSTANCE *mons, int listen)
+{
+  int conn=-1;
+  int pid=-1;
+
+  if (0 > (conn = accept(listen, NULL, NULL))) {
+    perror("Error from monitoring interface accept()");
+    return 1;
+  }
+
+  if (0 > (pid = fork())) {
+    perror("Error on fork()");
+    return 1;
+  }
+
+  if (pid == 0) {
+    close(listen);
+    mons_handle_connection(mons, conn);
+    close(conn);
+    exit(0); /* exit to kill forked child process */
+  } else {
+    close(conn);
+  }
+
+  /* clean up any processes that have completed */
+  while (waitpid(-1, 0, WNOHANG) > 0);
+
+  return 0;
+}
index d724322..648107a 100644 (file)
@@ -157,7 +157,7 @@ int tidc_fwd_request(TIDC_INSTANCE *tidc,
 
 
   /* Encode the request into a json string */
-  if (!(req_buf = tr_msg_encode(msg))) {
+  if (!(req_buf = tr_msg_encode(NULL, msg))) {
     tr_err("tidc_fwd_request: Error encoding TID request.\n");
     goto error;
   }
index 0cd5cf9..3d37739 100644 (file)
 #include <tr_debug.h>
 #include <tr_msg.h>
 #include <tr_socket.h>
+#include <tr_gss.h>
+#include <tr_event.h>
 
-static TID_RESP *tids_create_response (TIDS_INSTANCE *tids, TID_REQ *req) 
+static TID_RESP *tids_create_response(TALLOC_CTX *mem_ctx, TIDS_INSTANCE *tids, TID_REQ *req)
 {
   TID_RESP *resp=NULL;
   int success=0;
 
-  if (NULL == (resp = tid_resp_new(req))) {
+  if (NULL == (resp = tid_resp_new(mem_ctx))) {
     tr_crit("tids_create_response: Error allocating response structure.");
     return NULL;
   }
@@ -89,8 +91,7 @@ static int tids_auth_cb(gss_name_t clientName, gss_buffer_t displayName,
                        void *data)
 {
   struct tids_instance *inst = (struct tids_instance *) data;
-  TR_NAME name ={(char *) displayName->value,
-                displayName->length};
+  TR_NAME name ={(char *) displayName->value, (int) displayName->length};
   int result=0;
 
   if (0!=inst->auth_handler(clientName, &name, inst->cookie)) {
@@ -101,83 +102,15 @@ static int tids_auth_cb(gss_name_t clientName, gss_buffer_t displayName,
   return result;
 }
 
-/* returns 0 on authorization success, 1 on failure, or -1 in case of error */
-static int tids_auth_connection (TIDS_INSTANCE *inst,
-                                int conn,
-                                 gss_ctx_id_t *gssctx)
-{
-  int rc = 0;
-  int auth, autherr = 0;
-  gss_buffer_desc nameBuffer = {0, NULL};
-  char *name = 0;
-  int nameLen = 0;
-
-  nameLen = asprintf(&name, "trustidentity@%s", inst->hostname);
-  nameBuffer.length = nameLen;
-  nameBuffer.value = name;
-
-  if (rc = gsscon_passive_authenticate(conn, nameBuffer, gssctx, tids_auth_cb, inst)) {
-    tr_debug("tids_auth_connection: Error from gsscon_passive_authenticate(), rc = %d.", rc);
-    free(name);
-    return -1;
-  }
-  free(name);
-  nameBuffer.value=NULL; nameBuffer.length=0;
-
-  if (rc = gsscon_authorize(*gssctx, &auth, &autherr)) {
-    tr_debug("tids_auth_connection: Error from gsscon_authorize, rc = %d, autherr = %d.", 
-           rc, autherr);
-    return -1;
-  }
-
-  if (auth)
-    tr_debug("tids_auth_connection: Connection authenticated, conn = %d.", conn);
-  else
-    tr_debug("tids_auth_connection: Authentication failed, conn %d.", conn);
-
-  return !auth;
-}
-
-static int tids_read_request (TIDS_INSTANCE *tids, int conn, gss_ctx_id_t *gssctx, TR_MSG **mreq)
-{
-  int err;
-  char *buf;
-  size_t buflen = 0;
-
-  if (err = gsscon_read_encrypted_token(conn, *gssctx, &buf, &buflen)) {
-    if (buf)
-      free(buf);
-    return -1;
-  }
-
-  tr_debug("tids_read_request():Request Received, %u bytes.", (unsigned) buflen);
-
-  /* Parse request */
-  if (NULL == ((*mreq) = tr_msg_decode(buf, buflen))) {
-    tr_debug("tids_read_request():Error decoding request.");
-    free (buf);
-    return -1;
-  }
-
-  /* If this isn't a TID Request, just drop it. */
-  if (TID_REQUEST != (*mreq)->msg_type) {
-    tr_debug("tids_read_request(): Not a TID Request, dropped.");
-    return -1;
-  }
-
-  free (buf);
-  return buflen;
-}
-
-static int tids_handle_request (TIDS_INSTANCE *tids, TR_MSG *mreq, TID_RESP *resp) 
+static int tids_handle_request(TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
 {
   int rc=-1;
 
   /* Check that this is a valid TID Request.  If not, send an error return. */
-  if ((!tr_msg_get_req(mreq)) ||
-      (!tr_msg_get_req(mreq)->rp_realm) ||
-      (!tr_msg_get_req(mreq)->realm) ||
-      (!tr_msg_get_req(mreq)->comm)) {
+  if ((!req) ||
+      (!(req->rp_realm)) ||
+      (!(req->realm)) ||
+      (!(req->comm))) {
     tr_notice("tids_handle_request(): Not a valid TID Request.");
     resp->result = TID_ERROR;
     resp->err_msg = tr_new_name("Bad request format");
@@ -185,11 +118,11 @@ static int tids_handle_request (TIDS_INSTANCE *tids, TR_MSG *mreq, TID_RESP *res
   }
 
   tr_debug("tids_handle_request: adding self to req path.");
-  tid_req_add_path(tr_msg_get_req(mreq), tids->hostname, tids->tids_port);
+  tid_req_add_path(req, tids->hostname, tids->tids_port);
   
   /* Call the caller's request handler */
   /* TBD -- Handle different error returns/msgs */
-  if (0 > (rc = (*tids->req_handler)(tids, tr_msg_get_req(mreq), resp, tids->cookie))) {
+  if (0 > (rc = (*tids->req_handler)(tids, req, resp, tids->cookie))) {
     /* set-up an error response */
     tr_debug("tids_handle_request: req_handler returned error.");
     resp->result = TID_ERROR;
@@ -206,51 +139,103 @@ static int tids_handle_request (TIDS_INSTANCE *tids, TR_MSG *mreq, TID_RESP *res
   return rc;
 }
 
+/**
+ * Produces a JSON-encoded msg containing the TID response
+ *
+ * @param mem_ctx talloc context for the return value
+ * @param tids TIDS_INSTANCE handling the request
+ * @param req incoming request
+ * @param resp outgoing response
+ * @return JSON-encoded message containing the TID response
+ */
+static char *tids_encode_response(TALLOC_CTX *mem_ctx, TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
+{
+  TR_MSG mresp;
+  char *resp_buf = NULL;
+
+  /* Construct the response message */
+  mresp.msg_type = TID_RESPONSE;
+  tr_msg_set_resp(&mresp, resp);
+
+  /* Encode the message to JSON */
+  resp_buf = tr_msg_encode(mem_ctx, &mresp);
+  if (resp_buf == NULL) {
+    tr_err("tids_encode_response: Error encoding json response.");
+    return NULL;
+  }
+  tr_debug("tids_encode_response: Encoded response: %s", resp_buf);
+
+  /* Success */
+  return resp_buf;
+}
+
+/**
+ * Encode/send an error response
+ *
+ * Part of the public interface
+ *
+ * @param tids
+ * @param req
+ * @param err_msg
+ * @return
+ */
 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
   TID_RESP *resp = NULL;
   int rc = 0;
 
+  if ((!tids) || (!req) || (!err_msg)) {
+    tr_debug("tids_send_err_response: Invalid parameters.");
+    return -1;
+  }
+
   /* If we already sent a response, don't send another no matter what. */
   if (req->resp_sent)
     return 0;
 
-  if (NULL == (resp = tids_create_response(tids, req))) {
+  if (NULL == (resp = tids_create_response(req, tids, req))) {
     tr_crit("tids_send_err_response: Can't create response.");
     return -1;
   }
-  
+
   /* mark this as an error response, and include the error message */
   resp->result = TID_ERROR;
   resp->err_msg = tr_new_name((char *)err_msg);
   resp->error_path = req->path;
 
   rc = tids_send_response(tids, req, resp);
-  
+
   tid_resp_free(resp);
   return rc;
 }
 
+/**
+ * Encode/send a response
+ *
+ * Part of the public interface
+ *
+ * @param tids
+ * @param req
+ * @param resp
+ * @return
+ */
 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
 {
   int err;
-  TR_MSG mresp;
   char *resp_buf;
 
-  if ((!tids) || (!req) || (!resp))
+  if ((!tids) || (!req) || (!resp)) {
     tr_debug("tids_send_response: Invalid parameters.");
+    return -1;
+  }
 
   /* Never send a second response if we already sent one. */
   if (req->resp_sent)
     return 0;
 
-  mresp.msg_type = TID_RESPONSE;
-  tr_msg_set_resp(&mresp, resp);
-
-  if (NULL == (resp_buf = tr_msg_encode(&mresp))) {
-
+  resp_buf = tids_encode_response(NULL, tids, req, resp);
+  if (resp_buf == NULL) {
     tr_err("tids_send_response: Error encoding json response.");
     tr_audit_req(req);
-
     return -1;
   }
 
@@ -261,12 +246,11 @@ int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
   tr_audit_resp(resp);
 
   /* Send the response over the connection */
-  if (err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf, 
-                                         strlen(resp_buf) + 1)) {
+  err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf,
+                                            strlen(resp_buf) + 1);
+  if (err) {
     tr_notice("tids_send_response: Error sending response over connection.");
-
     tr_audit_req(req);
-
     return -1;
   }
 
@@ -278,69 +262,82 @@ int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
   return 0;
 }
 
-static void tids_handle_connection (TIDS_INSTANCE *tids, int conn)
+/**
+ * Callback to process a request and produce a response
+ *
+ * @param req_str JSON-encoded request
+ * @param data pointer to a TIDS_INSTANCE
+ * @return pointer to the response string or null to send no response
+ */
+static char *tids_req_cb(TALLOC_CTX *mem_ctx, const char *req_str, void *data)
 {
+  TIDS_INSTANCE *tids = talloc_get_type_abort(data, TIDS_INSTANCE);
   TR_MSG *mreq = NULL;
+  TID_REQ *req = NULL;
   TID_RESP *resp = NULL;
+  char *resp_str = NULL;
   int rc = 0;
-  gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
 
-  if (tids_auth_connection(tids, conn, &gssctx)) {
-    tr_notice("tids_handle_connection: Error authorizing TID Server connection.");
-    close(conn);
-    return;
+  mreq = tr_msg_decode(req_str, strlen(req_str)); // allocates memory on success!
+  if (mreq == NULL) {
+    tr_debug("tids_req_cb: Error decoding request.");
+    return NULL;
   }
 
-  tr_debug("tids_handle_connection: Connection authorized!");
+  /* If this isn't a TID Request, just drop it. */
+  if (mreq->msg_type != TID_REQUEST) {
+    tr_msg_free_decoded(mreq);
+    tr_debug("tids_req_cb: Not a TID request, dropped.");
+    return NULL;
+  }
 
-  while (1) {  /* continue until an error breaks us out */
+  /* Get a handle on the request itself. Don't free req - it belongs to mreq */
+  req = tr_msg_get_req(mreq);
+
+  /* Allocate a response structure and populate common fields. The resp is in req's talloc context,
+   * which will be cleaned up when mreq is freed. */
+  resp = tids_create_response(req, tids, req);
+  if (resp == NULL) {
+    /* If we were unable to create a response, we cannot reply. Log an
+     * error if we can, then drop the request. */
+    tr_msg_free_decoded(mreq);
+    tr_crit("tids_req_cb: Error creating response structure.");
+    return NULL;
+  }
 
-    if (0 > (rc = tids_read_request(tids, conn, &gssctx, &mreq))) {
-      tr_debug("tids_handle_connection: Error from tids_read_request(), rc = %d.", rc);
-      return;
-    } else if (0 == rc) {
-      continue;
-    }
+  /* Handle the request and fill in resp */
+  rc = tids_handle_request(tids, req, resp);
+  if (rc < 0) {
+    tr_debug("tids_req_cb: Error from tids_handle_request(), rc = %d.", rc);
+    /* Fall through, to send the response, either way */
+  }
 
-    /* Put connection information into the request structure */
-    tr_msg_get_req(mreq)->conn = conn;
-    tr_msg_get_req(mreq)->gssctx = gssctx;
-
-    /* Allocate a response structure and populate common fields */
-    if (NULL == (resp = tids_create_response (tids, tr_msg_get_req(mreq)))) {
-      tr_crit("tids_handle_connection: Error creating response structure.");
-      /* try to send an error */
-      tids_send_err_response(tids, tr_msg_get_req(mreq), "Error creating response.");
-      tr_msg_free_decoded(mreq);
-      return;
-    }
+  /* Convert the completed response into an encoded response */
+  resp_str = tids_encode_response(mem_ctx, tids, req, resp);
 
-    if (0 > (rc = tids_handle_request(tids, mreq, resp))) {
-      tr_debug("tids_handle_connection: Error from tids_handle_request(), rc = %d.", rc);
-      /* Fall through, to send the response, either way */
-    }
+  /* Finished; free the request and return */
+  tr_msg_free_decoded(mreq); // this frees req and resp, too
+  return resp_str;
+}
 
-    if (0 > (rc = tids_send_response(tids, tr_msg_get_req(mreq), resp))) {
-      tr_debug("tids_handle_connection: Error from tids_send_response(), rc = %d.", rc);
-      /* if we didn't already send a response, try to send a generic error. */
-      if (!tr_msg_get_req(mreq)->resp_sent)
-        tids_send_err_response(tids, tr_msg_get_req(mreq), "Error sending response.");
-      /* Fall through to free the response, either way. */
-    }
-    
-    tr_msg_free_decoded(mreq); /* takes resp with it */
-    return;
-  } 
+TIDS_INSTANCE *tids_new(TALLOC_CTX *mem_ctx)
+{
+  return talloc_zero(mem_ctx, TIDS_INSTANCE);
 }
 
-TIDS_INSTANCE *tids_create (void)
+/**
+ * Create a new TIDS instance
+ *
+ * Deprecated: exists for ABI compatibility, but tids_new() should be used instead
+ *
+ */
+TIDS_INSTANCE *tids_create(void)
 {
   return talloc_zero(NULL, TIDS_INSTANCE);
 }
-
 /* Get a listener for tids requests, returns its socket fd. Accept
  * connections with tids_accept() */
-int tids_get_listener(TIDS_INSTANCE *tids, 
+int tids_get_listener(TIDS_INSTANCE *tids,
                       TIDS_REQ_FUNC *req_handler,
                       tids_auth_func *auth_handler,
                       const char *hostname,
@@ -349,13 +346,13 @@ int tids_get_listener(TIDS_INSTANCE *tids,
                       int *fd_out,
                       size_t max_fd)
 {
-  size_t n_fd=0;
-  size_t ii=0;
+  nfds_t n_fd = 0;
+  nfds_t ii = 0;
 
   tids->tids_port = port;
-  n_fd=listen_on_all_addrs(port, fd_out, max_fd);
+  n_fd = tr_sock_listen_all(port, fd_out, max_fd);
 
-  if (n_fd<=0)
+  if (n_fd == 0)
     tr_err("tids_get_listener: Error opening port %d");
   else {
     /* opening port succeeded */
@@ -369,13 +366,13 @@ int tids_get_listener(TIDS_INSTANCE *tids,
           close(fd_out[ii]);
           fd_out[ii]=-1;
         }
-        n_fd=0;
+        n_fd = 0;
         break;
       }
     }
   }
 
-  if (n_fd>0) {
+  if (n_fd > 0) {
     /* store the caller's request handler & cookie */
     tids->req_handler = req_handler;
     tids->auth_handler = auth_handler;
@@ -383,7 +380,7 @@ int tids_get_listener(TIDS_INSTANCE *tids,
     tids->cookie = cookie;
   }
 
-  return n_fd;
+  return (int)n_fd;
 }
 
 /* Accept and process a connection on a port opened with tids_get_listener() */
@@ -404,7 +401,11 @@ int tids_accept(TIDS_INSTANCE *tids, int listen)
 
   if (pid == 0) {
     close(listen);
-    tids_handle_connection(tids, conn);
+    tr_gss_handle_connection(conn,
+                             "trustidentity", tids->hostname, /* acceptor name */
+                             tids_auth_cb, tids, /* auth callback and cookie */
+                             tids_req_cb, tids /* req callback and cookie */
+    );
     close(conn);
     exit(0); /* exit to kill forked child process */
   } else {
@@ -418,20 +419,19 @@ int tids_accept(TIDS_INSTANCE *tids, int listen)
 }
 
 /* Process tids requests forever. Should not return except on error. */
-#define MAX_SOCKETS 10
-int tids_start (TIDS_INSTANCE *tids, 
+int tids_start (TIDS_INSTANCE *tids,
                 TIDS_REQ_FUNC *req_handler,
                 tids_auth_func *auth_handler,
                 const char *hostname,
                 unsigned int port,
                 void *cookie)
 {
-  int fd[MAX_SOCKETS]={0};
-  size_t n_fd=0;
-  struct pollfd poll_fd[MAX_SOCKETS]={{0}};
+  int fd[TR_MAX_SOCKETS]={0};
+  nfds_t n_fd=0;
+  struct pollfd poll_fd[TR_MAX_SOCKETS]={{0}};
   int ii=0;
 
-  n_fd=tids_get_listener(tids, req_handler, auth_handler, hostname, port, cookie, fd, MAX_SOCKETS);
+  n_fd=tids_get_listener(tids, req_handler, auth_handler, hostname, port, cookie, fd, TR_MAX_SOCKETS);
   if (n_fd <= 0) {
     perror ("Error from tids_listen()");
     return 1;
@@ -475,7 +475,6 @@ int tids_start (TIDS_INSTANCE *tids,
 
   return 1;    /* should never get here, loops "forever" */
 }
-#undef MAX_SOCKETS
 
 void tids_destroy (TIDS_INSTANCE *tids)
 {
index a03ef4b..86fb8a9 100644 (file)
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <jansson.h>
 #include <argp.h>
 #include <event2/event.h>
 #include <talloc.h>
-#include <sys/time.h>
 #include <signal.h>
-#include <pthread.h>
 
 #include <tid_internal.h>
 #include <tr_tid.h>
@@ -153,6 +150,7 @@ int main(int argc, char *argv[])
   struct cmdline_args opts;
   struct event_base *ev_base;
   struct tr_socket_event tids_ev = {0};
+//  struct tr_socket_event mon_ev = {0};
   struct event *cfgwatch_ev;
 
   configure_signals();
@@ -192,11 +190,10 @@ int main(int argc, char *argv[])
   }
 
   /***** initialize the trust path query server instance *****/
-  if (NULL == (tr->tids = tids_create())) {
+  if (NULL == (tr->tids = tids_new(tr))) {
     tr_crit("Error initializing Trust Path Query Server instance.");
     return 1;
   }
-  talloc_steal(tr, tr->tids);
 
   /***** initialize the trust router protocol server instance *****/
   if (NULL == (tr->trps = trps_new(tr))) {
@@ -204,6 +201,12 @@ int main(int argc, char *argv[])
     return 1;
   }
 
+//  /***** initialize the monitoring interface instance *****/
+//  if (NULL == (tr->mons = mons_new(tr))) {
+//    tr_crit("Error initializing monitoring interface instance.");
+//    return 1;
+//  }
+
   /***** process configuration *****/
   tr->cfgwatch=tr_cfgwatch_create(tr);
   if (tr->cfgwatch == NULL) {
@@ -232,7 +235,12 @@ int main(int argc, char *argv[])
     return 1;
   }
 
-  /*tr_status_event_init();*/ /* install status reporting events */
+//  /* install monitoring interface events */
+//  tr_debug("Initializing monitoring interface events.");
+//  if (0 != tr_mon_event_init(tr->mons, ev_base, &mon_ev)) {
+//    tr_crit("Error initializing monitoring interface.");
+//    return 1;
+//  }
 
   /* install TID server events */
   tr_debug("Initializing TID server events.");
diff --git a/tr/tr_mon.c b/tr/tr_mon.c
new file mode 100644 (file)
index 0000000..f96d0ed
--- /dev/null
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) 2018, JANET(UK)
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of JANET(UK) nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <talloc.h>
+
+#include <tr_config.h>
+#include <tr_debug.h>
+#include <mon_internal.h>
+
+/*
+ * Cookie for the event handling callback
+ */
+struct tr_mons_event_cookie {
+  MONS_INSTANCE *mons;
+  TR_CFG_MGR *cfg_mgr;
+};
+
+
+/**
+ * Callback to handle a triggered event
+ *
+ * @param listener file descriptor of the socket that triggered the event
+ * @param event libevent2 event
+ * @param arg pointer to our MONS_INSTANCE
+ */
+static void tr_mons_event_cb(int listener, short event, void *arg)
+{
+  MONS_INSTANCE *mons = talloc_get_type_abort(arg, MONS_INSTANCE);
+
+  // check that we were not accidentally triggered
+  if (0==(event & EV_READ))
+    tr_debug("tr_mons_event_cb: unexpected event on monitoring interface socket (event=0x%X)", event);
+  else
+    mons_accept(mons, listener);
+}
+
+
+/**
+ * Callback to handle an incoming monitoring request
+ *
+ * @param mons monitoring interface instance
+ * @param orig_req incoming request
+ * @param resp destination for outgoing response
+ * @param cookie_in cookie from the event handling system
+ * @return 0 on success
+ */
+static int tr_mons_req_handler(MONS_INSTANCE *mons,
+                               MON_REQ *orig_req,
+                               MON_RESP *resp,
+                               void *cookie_in)
+{
+  return -1;
+}
+
+/**
+ * Callback to authorize a GSS client
+ *
+ * @param client_name ?
+ * @param gss_name GSS name of credential attempting to authorize
+ * @param cookie_in event cookie
+ * @return 0 if authorization is successful, -1 if not
+ */
+static int tr_mons_auth_handler(gss_name_t client_name, TR_NAME *gss_name, void *cookie_in)
+{
+  struct tr_mons_event_cookie *cookie=talloc_get_type_abort(cookie_in, struct tr_mons_event_cookie);
+  MONS_INSTANCE *mons = cookie->mons;
+  TR_CFG_MGR *cfg_mgr = cookie->cfg_mgr;
+
+  if ((!client_name) || (!gss_name) || (!mons) || (!cfg_mgr)) {
+    tr_debug("tr_mons_gss_handler: Bad parameters.");
+    return -1;
+  }
+
+  /* Ensure at least one client exists using this GSS name */
+  if (! tr_gss_names_matches(mons->authorized_gss_names, gss_name)) {
+    tr_info("tr_mons_gss_handler: Unauthorized request from %.*s", gss_name->len, gss_name->buf);
+    return -1;
+  }
+
+  /* Credential was valid, authorize it */
+  tr_info("tr_mons_gss_handler: Authorized request from %.*s", gss_name->len, gss_name->buf);
+  return 0;
+}
+
+
+/*
+ *
+ * Get a listener for monitoring requests, returns its socket fd. Accept
+ * connections with tids_accept() */
+
+/**
+ * Configure the monitoring service instance and set up its event handler
+ *
+ * @param base libevent2 event base
+ * @param mons MONS_INSTANCE for this monitoring interface
+ * @param cfg_mgr configuration manager instance
+ * @param mons_ev monitoring interface event instance
+ * @return 0 on success, nonzero on failure.
+ * */
+int tr_mon_event_init(struct event_base *base, MONS_INSTANCE *mons, TR_CFG_MGR *cfg_mgr, struct tr_socket_event *mons_ev)
+{
+  TALLOC_CTX *tmp_ctx=talloc_new(NULL);
+  struct tr_mons_event_cookie *cookie=NULL;
+  int retval=0;
+  int ii=0;
+
+  if (mons_ev == NULL) {
+    tr_debug("tr_mon_event_init: Null mons_ev.");
+    retval=1;
+    goto cleanup;
+  }
+
+  /* Create the cookie for callbacks. We'll put it in the mons context, so it will
+   * be cleaned up when mons is freed by talloc_free. */
+  cookie=talloc(tmp_ctx, struct tr_mons_event_cookie);
+  if (cookie == NULL) {
+    tr_debug("tr_mons_event_init: Unable to allocate cookie.");
+    retval=1;
+    goto cleanup;
+  }
+  cookie->mons=mons;
+  cookie->cfg_mgr=cfg_mgr;
+  talloc_steal(mons, cookie);
+
+  /* get a monitoring interface listener */
+  mons_ev->n_sock_fd = mons_get_listener(mons,
+                                         tr_mons_req_handler,
+                                         tr_mons_auth_handler,
+                                         cfg_mgr->active->internal->monitoring_port,
+                                         (void *)cookie,
+                                         mons_ev->sock_fd,
+                                         TR_MAX_SOCKETS);
+  if (mons_ev->n_sock_fd==0) {
+    tr_crit("Error opening monitoring interface socket.");
+    retval=1;
+    goto cleanup;
+  }
+
+  /* Set up events */
+  for (ii=0; ii<mons_ev->n_sock_fd; ii++) {
+    mons_ev->ev[ii]=event_new(base,
+                              mons_ev->sock_fd[ii],
+                              EV_READ|EV_PERSIST,
+                              tr_mons_event_cb,
+                              (void *)mons);
+    event_add(mons_ev->ev[ii], NULL);
+  }
+
+cleanup:
+  talloc_free(tmp_ctx);
+  return retval;
+}
index 0c69d55..464ebd4 100644 (file)
@@ -676,7 +676,7 @@ int tr_tids_event_init(struct event_base *base,
   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
   struct tr_tids_event_cookie *cookie=NULL;
   int retval=0;
-  size_t ii=0;
+  int ii=0;
 
   if (tids_ev == NULL) {
     tr_debug("tr_tids_event_init: Null tids_ev.");
@@ -698,14 +698,14 @@ int tr_tids_event_init(struct event_base *base,
   talloc_steal(tids, cookie);
 
   /* get a tids listener */
-  tids_ev->n_sock_fd=tids_get_listener(tids,
-                                       tr_tids_req_handler,
-                                       tr_tids_gss_handler,
-                                       cfg_mgr->active->internal->hostname,
-                                       cfg_mgr->active->internal->tids_port,
-                                       (void *)cookie,
-                                       tids_ev->sock_fd,
-                                       TR_MAX_SOCKETS);
+  tids_ev->n_sock_fd = tids_get_listener(tids,
+                                         tr_tids_req_handler,
+                                         tr_tids_gss_handler,
+                                         cfg_mgr->active->internal->hostname,
+                                         cfg_mgr->active->internal->tids_port,
+                                         (void *)cookie,
+                                         tids_ev->sock_fd,
+                                         TR_MAX_SOCKETS);
   if (tids_ev->n_sock_fd==0) {
     tr_crit("Error opening TID server socket.");
     retval=1;
index da39570..512e92e 100644 (file)
@@ -88,7 +88,7 @@ int main(int argc, const char *argv[])
 
   printf("\nEncoding...\n");
 
-  printf("Result: \n%s\n\n", tr_msg_encode(msg));
+  printf("Result: \n%s\n\n", tr_msg_encode(NULL, msg));
 
   talloc_report_full(main_ctx, stdout);
 
index e4824ea..568a445 100644 (file)
@@ -36,7 +36,7 @@
 #include <talloc.h>
 #include <assert.h>
 
-#include <tr_gss.h>
+#include <tr_gss_names.h>
 #include <trp_internal.h>
 #include <trp_ptable.h>
 
index e47846e..7552cff 100644 (file)
@@ -37,7 +37,7 @@
 
 #include <tr_name_internal.h>
 #include <trp_internal.h>
-#include <tr_gss.h>
+#include <tr_gss_names.h>
 #include <trp_ptable.h>
 #include <tr_debug.h>
 
index a4ebe81..11c6ddf 100644 (file)
@@ -39,6 +39,7 @@
 #include <sys/time.h>
 #include <glib.h>
 #include <string.h>
+#include <poll.h> // for nfds_t
 
 #include <gsscon.h>
 #include <tr_comm.h>
@@ -46,7 +47,7 @@
 #include <tr_rp.h>
 #include <tr_name_internal.h>
 #include <trp_internal.h>
-#include <tr_gss.h>
+#include <tr_gss_names.h>
 #include <trp_ptable.h>
 #include <trp_rtable.h>
 #include <tr_debug.h>
@@ -384,12 +385,12 @@ int trps_get_listener(TRPS_INSTANCE *trps,
                       int *fd_out,
                       size_t max_fd)
 {
-  size_t n_fd=0;
-  size_t ii=0;
+  nfds_t n_fd=0;
+  nfds_t ii=0;
 
-  n_fd=listen_on_all_addrs(port, fd_out, max_fd);
+  n_fd = tr_sock_listen_all(port, fd_out, max_fd);
 
-  if (n_fd==0)
+  if (n_fd == 0)
     tr_err("trps_get_listener: Error opening port %d.");
   else {
     /* opening port succeeded */
@@ -403,13 +404,13 @@ int trps_get_listener(TRPS_INSTANCE *trps,
           close(fd_out[ii]);
           fd_out[ii]=-1;
         }
-        n_fd=0;
+        n_fd = 0;
         break;
       }
     }
   }
 
-  if (n_fd>0) {
+  if (n_fd > 0) {
     /* store the caller's request handler & cookie */
     trps->msg_handler = msg_handler;
     trps->auth_handler = auth_handler;
@@ -418,7 +419,7 @@ int trps_get_listener(TRPS_INSTANCE *trps,
     trps->cookie = cookie;
   }
 
-  return n_fd;
+  return (int) n_fd;
 }
 
 TRP_RC trps_authorize_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
@@ -1747,7 +1748,7 @@ static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
         upd = (TRP_UPD *) g_ptr_array_index(updates, ii);
         /* now encode the update message */
         tr_msg_set_trp_upd(&msg, upd);
-        encoded = tr_msg_encode(&msg);
+        encoded = tr_msg_encode(NULL, &msg);
         if (encoded == NULL) {
           tr_err("trps_update_one_peer: error encoding update.");
           rc = TRP_ERROR;
@@ -1932,7 +1933,7 @@ TRP_RC trps_wildcard_route_req(TRPS_INSTANCE *trps, TR_NAME *peer_servicename)
   }
 
   tr_msg_set_trp_req(&msg, req);
-  encoded=tr_msg_encode(&msg);
+  encoded= tr_msg_encode(NULL, &msg);
   if (encoded==NULL) {
     tr_err("trps_wildcard_route_req: error encoding wildcard TRP request.");
     rc=TRP_ERROR;