Merge pull request #86 from painless-security/jennifer/aaa_server_port
[trust_router.git] / mon / mons.c
1 /*
2  * Copyright (c) 2018, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <talloc.h>
36 #include <fcntl.h>
37 #include <unistd.h>
38 #include <netdb.h>
39
40 #include <tr.h>
41 #include <tr_debug.h>
42 #include <mon_internal.h>
43 #include <tr_socket.h>
44 #include <sys/wait.h>
45 #include <sys/resource.h>
46 #include <tr_gss.h>
47
48 #include "mons_handlers.h"
49
50 static void mons_sweep_procs(MONS_INSTANCE *mons);
51
52 static int mons_destructor(void *object)
53 {
54   MONS_INSTANCE *mons = talloc_get_type_abort(object, MONS_INSTANCE);
55   if (mons->handlers)
56     g_ptr_array_unref(mons->handlers);
57
58   if (mons->pids)
59     g_array_unref(mons->pids);
60
61   return 0;
62 }
63
64 /**
65  * Allocate a new MONS_INSTANCE
66  *
67  * @param mem_ctx talloc context for allocation
68  * @return new MONS_INSTANCE or null on failure
69  */
70 MONS_INSTANCE *mons_new(TALLOC_CTX *mem_ctx)
71 {
72   MONS_INSTANCE *mons = talloc(mem_ctx, MONS_INSTANCE);
73
74   if (mons) {
75     mons->hostname = NULL;
76     mons->mon_port = 0;
77     mons->tids = NULL;
78     mons->trps = NULL;
79     mons->req_handler = NULL;
80     mons->auth_handler = NULL;
81     mons->cookie = NULL;
82
83     /* Before any steps that may fail, install the destructor */
84     talloc_set_destructor((void *)mons, mons_destructor);
85
86     mons->authorized_gss_names = tr_gss_names_new(mons);
87     if (mons->authorized_gss_names == NULL) {
88       talloc_free(mons);
89       return NULL;
90     }
91
92     mons->handlers = g_ptr_array_new();
93     if (mons->handlers == NULL) {
94       talloc_free(mons);
95       return NULL;
96     }
97
98     mons->pids = g_array_new(FALSE, FALSE, sizeof(pid_t));
99     if (mons->pids == NULL) {
100       talloc_free(mons);
101       return NULL;
102     }
103   }
104   return mons;
105 }
106
107 /**
108  * Callback to process a request and produce a response
109  *
110  * @param req_str JSON-encoded request
111  * @param data pointer to a MONS_INSTANCE
112  * @return pointer to the response string or null to send no response
113  */
114 static TR_MSG *mons_req_cb(TALLOC_CTX *mem_ctx, TR_MSG *req_msg, void *data)
115 {
116   TALLOC_CTX *tmp_ctx = talloc_new(NULL);
117   MONS_INSTANCE *mons = talloc_get_type_abort(data, MONS_INSTANCE);
118   MON_REQ *req = NULL;
119   MON_RESP *resp = NULL;
120   TR_MSG *resp_msg = NULL; /* This is the response value */
121
122   /* Validate inputs */
123   if (req_msg == NULL)
124     goto cleanup;
125
126   req = tr_msg_get_mon_req(req_msg);
127   if (req == NULL) {
128     /* this is an internal error */
129     tr_err("mons_req_cb: Received incorrect message type (was %d, expected %d)",
130            tr_msg_get_msg_type(req_msg),
131            MON_REQUEST);
132     /* TODO send an error response */
133     goto cleanup;
134   }
135
136   /* Allocate a response message */
137   resp_msg = talloc(tmp_ctx, TR_MSG);
138   if (resp_msg == NULL) {
139     /* can't return a message, just emit an error */
140     tr_crit("mons_req_cb: Error allocating response message.");
141     goto cleanup;
142   }
143
144   /* Handle the request */
145   resp = mons_handle_request(resp_msg, mons, req);
146   if (resp == NULL) {
147     /* error processing the request */
148     /* TODO send back an error */
149     goto cleanup;
150   }
151
152   /* Set the response message payload */
153   tr_msg_set_mon_resp(resp_msg, resp);
154
155   /* Put the response message in the caller's context so it does not get freed when we exit */
156   talloc_steal(mem_ctx, resp_msg);
157
158 cleanup:
159   talloc_free(tmp_ctx);
160   return resp_msg;
161 }
162
163 /**
164  * Create a listener for monitoring requests
165  *
166  * Accept connections with mons_accept()
167  *
168  * @param mons monitoring server instance
169  * @param req_handler
170  * @param auth_handler
171  * @param hostname
172  * @param port
173  * @param cookie
174  * @param fd_out
175  * @param max_fd
176  * @return
177  */
178 int mons_get_listener(MONS_INSTANCE *mons,
179                       MONS_REQ_FUNC *req_handler,
180                       MONS_AUTH_FUNC *auth_handler,
181                       const char *hostname,
182                       int port,
183                       void *cookie,
184                       int *fd_out,
185                       size_t max_fd)
186 {
187   size_t n_fd=0;
188   size_t ii=0;
189
190   mons->mon_port = port;
191   n_fd = tr_sock_listen_all(port, fd_out, max_fd);
192   if (n_fd<=0)
193     tr_err("mons_get_listener: Error opening port %d", port);
194   else {
195     /* opening port succeeded */
196     tr_info("mons_get_listener: Opened port %d.", port);
197
198     /* make this socket non-blocking */
199     for (ii=0; ii<n_fd; ii++) {
200       if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
201         tr_err("mons_get_listener: Error setting O_NONBLOCK.");
202         for (ii=0; ii<n_fd; ii++) {
203           close(fd_out[ii]);
204           fd_out[ii]=-1;
205         }
206         n_fd=0;
207         break;
208       }
209     }
210   }
211
212   if (n_fd>0) {
213     /* store the caller's request handler & cookie */
214     mons->req_handler = req_handler;
215     mons->auth_handler = auth_handler;
216     mons->hostname = hostname;
217     mons->cookie = cookie;
218   }
219
220   return (int) n_fd;
221 }
222
223 /**
224  * Process to handle an incoming monitoring request
225  *
226  * This should be run in a child process after fork(). Handles the request
227  * and terminates. Never returns to the caller.
228  *
229  * @param mons the monitoring server instance
230  * @param conn_fd file descriptor for the incoming connection
231  */
232 static void mons_handle_proc(MONS_INSTANCE *mons, int conn_fd)
233 {
234   struct rlimit rlim; /* for disabling core dump */
235
236   switch(tr_gss_handle_connection(conn_fd,
237                                   "trustmonitor", mons->hostname, /* acceptor name */
238                                   mons->auth_handler, mons->cookie, /* auth callback and cookie */
239                                   mons_req_cb, mons /* req callback and cookie */
240   )) {
241     case TR_GSS_SUCCESS:
242       /* do nothing */
243       break;
244
245     case TR_GSS_ERROR:
246       tr_debug("mons_accept: Error returned by tr_gss_handle_connection()");
247       break;
248
249     default:
250       tr_err("mons_accept: Unexpected value returned by tr_gss_handle_connection()");
251       break;
252   }
253   close(conn_fd);
254
255   /* This ought to be an exit(0), but log4shib does not play well with fork() due to
256    * threading issues. To ensure we do not get stuck in the exit handler, we will
257    * abort. First disable core dump for this subprocess (the main process will still
258    * dump core if the environment allows). */
259   rlim.rlim_cur = 0; /* max core size of 0 */
260   rlim.rlim_max = 0; /* prevent the core size limit from being raised later */
261   setrlimit(RLIMIT_CORE, &rlim);
262   abort(); /* exit hard */
263 }
264
265 /**
266  * Accept and process a connection on a port opened with mons_get_listener()
267  *
268  * @param mons monitoring interface instance
269  * @param listen FD of the connection socket
270  * @return 0 on success
271  */
272 int mons_accept(MONS_INSTANCE *mons, int listen)
273 {
274   int conn=-1;
275   int pid=-1;
276
277   if (0 > (conn = tr_sock_accept(listen))) {
278     tr_err("mons_accept: Error accepting connection");
279     return 1;
280   }
281
282   if (0 > (pid = fork())) {
283     perror("Error on fork()");
284     return 1;
285   }
286
287   if (pid == 0) {
288     /* Only the child process gets here */
289     close(listen); /* this belongs to the parent */
290     mons_handle_proc(mons, conn); /* never returns */
291   }
292
293   /* Only the parent process gets here */
294   close(conn); /* this belongs to the child */
295   g_array_append_val(mons->pids, pid);
296
297   /* clean up any processes that have completed */
298   mons_sweep_procs(mons);
299
300   return 0;
301 }
302
303 void mons_sweep_procs(MONS_INSTANCE *mons)
304 {
305   guint ii;
306   pid_t pid;
307   int status;
308
309   /* loop backwards over the array so we can remove elements as we go */
310   for (ii=mons->pids->len; ii > 0; ii--) {
311     /* ii-1 is the current index */
312     pid = g_array_index(mons->pids, pid_t, ii-1);
313     if (waitpid(pid, &status, WNOHANG) > 0) {
314       /* the process exited */
315       tr_debug("mons_sweep_procs: monitoring process %d terminated.", pid);
316
317       g_array_remove_index_fast(mons->pids, ii-1); /* disturbs only indices >= ii-1 which we've already handled */
318       if (WIFEXITED(status)) {
319         if (WEXITSTATUS(status) == 0)
320           tr_debug("mons_sweep_procs: monitoring process %d succeeded.", pid);
321         else
322           tr_debug("mons_sweep_procs: monitoring process %d exited with status %d.", pid, WTERMSIG(status));
323       } else if (WIFSIGNALED(status)) {
324         tr_debug("mons_sweep_procs: monitoring process %d terminated by signal %d.", pid, WTERMSIG(status));
325       }
326     }
327   }
328 }