1a29620a024f6bd5962c5ce4874af63d824b1d7c
[trust_router.git] / tid / tids.c
1 /*
2  * Copyright (c) 2012, 2015, 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 <stdlib.h>
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <string.h>
39 #include <stdio.h>
40 #include <sys/socket.h>
41 #include <sys/wait.h>
42 #include <jansson.h>
43 #include <talloc.h>
44 #include <poll.h>
45 #include <tid_internal.h>
46 #include <gsscon.h>
47 #include <tr_debug.h>
48 #include <tr_msg.h>
49 #include <tr_socket.h>
50 #include <tr_gss.h>
51 #include <tr_event.h>
52
53 /**
54  * Create a response with minimal fields filled in
55  *
56  * @param mem_ctx talloc context for the return value
57  * @param req request to respond to
58  * @return new response structure allocated in the mem_ctx context
59  */
60 static TID_RESP *tids_create_response(TALLOC_CTX *mem_ctx, TID_REQ *req)
61 {
62   TID_RESP *resp=NULL;
63   int success=0;
64
65   if (NULL == (resp = tid_resp_new(mem_ctx))) {
66     tr_crit("tids_create_response: Error allocating response structure.");
67     return NULL;
68   }
69   
70   resp->result = TID_SUCCESS; /* presume success */
71   if ((NULL == (resp->rp_realm = tr_dup_name(req->rp_realm))) ||
72       (NULL == (resp->realm = tr_dup_name(req->realm))) ||
73       (NULL == (resp->comm = tr_dup_name(req->comm)))) {
74     tr_crit("tids_create_response: Error allocating fields in response.");
75     goto cleanup;
76   }
77   if (req->orig_coi) {
78     if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
79       tr_crit("tids_create_response: Error allocating fields in response.");
80       goto cleanup;
81     }
82   }
83   if (req->request_id) {
84     if (NULL == (resp->request_id = tr_dup_name(req->request_id))) {
85       tr_crit("tids_create_response: Error allocating fields in response.");
86       goto cleanup;
87     }
88   }
89
90   success=1;
91
92 cleanup:
93   if ((!success) && (resp!=NULL)) {
94     talloc_free(resp);
95     resp=NULL;
96   }
97   return resp;
98 }
99
100 static int tids_handle_request(TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
101 {
102   int rc=-1;
103
104   /* Check that this is a valid TID Request.  If not, send an error return. */
105   if ((!req) ||
106       (!(req->rp_realm)) ||
107       (!(req->realm)) ||
108       (!(req->comm))) {
109     tr_notice("tids_handle_request(): Not a valid TID Request.");
110     tid_resp_set_result(resp, TID_ERROR);
111     tid_resp_set_err_msg(resp, tr_new_name("Bad request format"));
112     return -1;
113   }
114
115   tr_debug("tids_handle_request: adding self to req path.");
116   tid_req_add_path(req, tids->hostname, tids->tids_port);
117   
118   /* Call the caller's request handler */
119   /* TBD -- Handle different error returns/msgs */
120   if (0 > (rc = (*tids->req_handler)(tids, req, resp, tids->cookie))) {
121     /* set-up an error response */
122     tr_debug("tids_handle_request: req_handler returned error.");
123     tid_resp_set_result(resp, TID_ERROR);
124     if (!tid_resp_get_err_msg(resp))    /* Use msg set by handler, if any */
125       tid_resp_set_err_msg(resp, tr_new_name("Internal processing error"));
126   } else {
127     /* set-up a success response */
128     tr_debug("tids_handle_request: req_handler returned success.");
129     tid_resp_set_result(resp, TID_SUCCESS);
130     resp->err_msg = NULL;       /* No error msg on successful return */
131   }
132     
133   return rc;
134 }
135
136 /**
137  * Produces a JSON-encoded msg containing the TID response
138  *
139  * @param mem_ctx talloc context for the return value
140  * @param resp outgoing response
141  * @return JSON-encoded message containing the TID response
142  */
143 static char *tids_encode_response(TALLOC_CTX *mem_ctx, TID_RESP *resp)
144 {
145   TR_MSG mresp;
146   char *resp_buf = NULL;
147
148   /* Construct the response message */
149   mresp.msg_type = TID_RESPONSE;
150   tr_msg_set_resp(&mresp, resp);
151
152   /* Encode the message to JSON */
153   resp_buf = tr_msg_encode(mem_ctx, &mresp);
154   if (resp_buf == NULL) {
155     tr_err("tids_encode_response: Error encoding json response.");
156     return NULL;
157   }
158   tr_debug("tids_encode_response: Encoded response: %s", resp_buf);
159
160   /* Success */
161   return resp_buf;
162 }
163
164 /**
165  * Encode/send an error response
166  *
167  * Part of the public interface
168  *
169  * @param tids
170  * @param req
171  * @param err_msg
172  * @return
173  */
174 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
175   TID_RESP *resp = NULL;
176   int rc = 0;
177
178   if ((!tids) || (!req) || (!err_msg)) {
179     tr_debug("tids_send_err_response: Invalid parameters.");
180     return -1;
181   }
182
183   /* If we already sent a response, don't send another no matter what. */
184   if (req->resp_sent)
185     return 0;
186
187   if (NULL == (resp = tids_create_response(req, req))) {
188     tr_crit("tids_send_err_response: Can't create response.");
189     return -1;
190   }
191
192   /* mark this as an error response, and include the error message */
193   resp->result = TID_ERROR;
194   resp->err_msg = tr_new_name((char *)err_msg);
195   resp->error_path = req->path;
196
197   rc = tids_send_response(tids, req, resp);
198
199   tid_resp_free(resp);
200   return rc;
201 }
202
203 /**
204  * Encode/send a response
205  *
206  * Part of the public interface
207  *
208  * @param tids not actually used, but kept for ABI compatibility
209  * @param req
210  * @param resp
211  * @return
212  */
213 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
214 {
215   int err;
216   char *resp_buf;
217
218   if ((!tids) || (!req) || (!resp)) {
219     tr_debug("tids_send_response: Invalid parameters.");
220     return -1;
221   }
222
223   /* Never send a second response if we already sent one. */
224   if (req->resp_sent)
225     return 0;
226
227   resp_buf = tids_encode_response(NULL, NULL);
228   if (resp_buf == NULL) {
229     tr_err("tids_send_response: Error encoding json response.");
230     tr_audit_req(req);
231     return -1;
232   }
233
234   tr_debug("tids_send_response: Encoded response: %s", resp_buf);
235
236   /* If external logging is enabled, fire off a message */
237   /* TODO Can be moved to end once segfault in gsscon_write_encrypted_token fixed */
238   tr_audit_resp(resp);
239
240   /* Send the response over the connection */
241   err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf,
242                                             strlen(resp_buf) + 1);
243   if (err) {
244     tr_notice("tids_send_response: Error sending response over connection.");
245     tr_audit_req(req);
246     return -1;
247   }
248
249   /* indicate that a response has been sent for this request */
250   req->resp_sent = 1;
251
252   free(resp_buf);
253
254   return 0;
255 }
256
257 /**
258  * Callback to process a request and produce a response
259  *
260  * @param req_str JSON-encoded request
261  * @param data pointer to a TIDS_INSTANCE
262  * @return pointer to the response string or null to send no response
263  */
264 static TR_MSG *tids_req_cb(TALLOC_CTX *mem_ctx, TR_MSG *mreq, void *data)
265 {
266   TALLOC_CTX *tmp_ctx = talloc_new(NULL);
267   TIDS_INSTANCE *tids = talloc_get_type_abort(data, TIDS_INSTANCE);
268   TID_REQ *req = NULL;
269   TID_RESP *resp = NULL;
270   TR_MSG *resp_msg = NULL; /* this is the return value */
271   int rc = 0;
272
273   /* If this isn't a TID Request, just drop it. */
274   if (mreq->msg_type != TID_REQUEST) {
275     tr_debug("tids_req_cb: Not a TID request, dropped.");
276     goto cleanup;
277   }
278
279   /* Get a handle on the request itself. Don't free req - it belongs to mreq */
280   req = tr_msg_get_req(mreq);
281
282   /* Allocate a response message */
283   resp_msg = talloc(tmp_ctx, TR_MSG);
284   if (resp_msg == NULL) {
285     /* We cannot create a response message, so all we can really do is emit
286      * an error message and return. */
287     tr_crit("tids_req_cb: Error allocating response message.");
288     goto cleanup;
289   }
290
291   /* Allocate a response structure and populate common fields. Put it in the
292    * response message's talloc context. */
293   resp = tids_create_response(resp_msg, req);
294   if (resp == NULL) {
295     /* If we were unable to create a response, we cannot reply. Log an
296      * error if we can, then drop the request. */
297     tr_crit("tids_req_cb: Error creating response structure.");
298     resp_msg = NULL; /* the contents are in tmp_ctx, so they will still be cleaned up */
299     goto cleanup;
300   }
301   /* Now officially assign the response to the message. */
302   tr_msg_set_resp(resp_msg, resp);
303
304   /* Handle the request and fill in resp */
305   rc = tids_handle_request(tids, req, resp);
306   if (rc < 0) {
307     tr_debug("tids_req_cb: Error from tids_handle_request(), rc = %d.", rc);
308     /* Fall through, to send the response, either way */
309   }
310
311   /* put the response message in the caller's context */
312   talloc_steal(mem_ctx, resp_msg);
313
314 cleanup:
315   talloc_free(tmp_ctx);
316   return resp_msg;
317 }
318
319 static int tids_destructor(void *object)
320 {
321   TIDS_INSTANCE *tids = talloc_get_type_abort(object, TIDS_INSTANCE);
322   if (tids->pids)
323     g_array_unref(tids->pids);
324   return 0;
325 }
326
327 TIDS_INSTANCE *tids_new(TALLOC_CTX *mem_ctx)
328 {
329   TIDS_INSTANCE *tids = talloc_zero(mem_ctx, TIDS_INSTANCE);
330   if (tids) {
331     tids->pids = g_array_new(FALSE, FALSE, sizeof(struct tid_process));
332     if (tids->pids == NULL) {
333       talloc_free(tids);
334       return NULL;
335     }
336     talloc_set_destructor((void *)tids, tids_destructor);
337   }
338   return tids;
339 }
340
341 /**
342  * Create a new TIDS instance
343  *
344  * Deprecated: exists for ABI compatibility, but tids_new() should be used instead
345  *
346  */
347 TIDS_INSTANCE *tids_create(void)
348 {
349   return tids_new(NULL);
350 }
351
352 /* Get a listener for tids requests, returns its socket fd. Accept
353  * connections with tids_accept() */
354 nfds_t tids_get_listener(TIDS_INSTANCE *tids,
355                          TIDS_REQ_FUNC *req_handler,
356                          tids_auth_func *auth_handler,
357                          const char *hostname,
358                          unsigned int port,
359                          void *cookie,
360                          int *fd_out,
361                          size_t max_fd)
362 {
363   nfds_t n_fd = 0;
364   nfds_t ii = 0;
365
366   tids->tids_port = port;
367   n_fd = tr_sock_listen_all(port, fd_out, max_fd);
368
369   if (n_fd == 0)
370     tr_err("tids_get_listener: Error opening port %d");
371   else {
372     /* opening port succeeded */
373     tr_info("tids_get_listener: Opened port %d.", port);
374     
375     /* make this socket non-blocking */
376     for (ii=0; ii<n_fd; ii++) {
377       if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
378         tr_err("tids_get_listener: Error setting O_NONBLOCK.");
379         for (ii=0; ii<n_fd; ii++) {
380           close(fd_out[ii]);
381           fd_out[ii]=-1;
382         }
383         n_fd = 0;
384         break;
385       }
386     }
387   }
388
389   if (n_fd > 0) {
390     /* store the caller's request handler & cookie */
391     tids->req_handler = req_handler;
392     tids->auth_handler = auth_handler;
393     tids->hostname = hostname;
394     tids->cookie = cookie;
395   }
396
397   return (int)n_fd;
398 }
399
400 /* Strings used to report results from the handler process. The
401  * TIDS_MAX_MESSAGE_LEN must be longer than the longest message, including
402  * null termination (i.e., strlen() + 1) */
403 #define TIDS_MAX_MESSAGE_LEN (10)
404 #define TIDS_SUCCESS_MESSAGE "OK"
405 #define TIDS_ERROR_MESSAGE   "ERR"
406
407 /**
408  * Process to handle an incoming TIDS request
409  *
410  * This should be run in the child process after a fork(). Handles
411  * the request, writes the result to result_fd, and terminates via exit().
412  * Never returns to the caller.
413  *
414  * @param tids TID server instance
415  * @param conn_fd file descriptor for the incoming connection
416  * @param result_fd writable file descriptor for the result, or 0 to disable reporting
417  */
418 static void tids_handle_proc(TIDS_INSTANCE *tids, int conn_fd, int result_fd)
419 {
420   const char *response_message = NULL;
421
422   switch(tr_gss_handle_connection(conn_fd,
423                                   "trustidentity", tids->hostname, /* acceptor name */
424                                   tids->auth_handler, tids->cookie, /* auth callback and cookie */
425                                   tids_req_cb, tids /* req callback and cookie */
426   )) {
427     case TR_GSS_SUCCESS:
428       response_message = TIDS_SUCCESS_MESSAGE;
429       break;
430
431     case TR_GSS_ERROR:
432     default:
433       response_message = TIDS_ERROR_MESSAGE;
434       break;
435   }
436
437   if (0 != result_fd) {
438     /* write strlen + 1 to include the null termination */
439     if (write(result_fd, response_message, strlen(response_message) + 1) < 0)
440       tr_err("tids_accept: child process unable to write to pipe");
441   }
442
443   close(result_fd);
444   close(conn_fd);
445
446   /* This ought to be an exit(0), but log4shib does not play well with our (mis)use of threads and
447  * fork() in the main process. Until we sort that out, we abort() to force termination of this
448  * process. */
449   abort(); /* exit hard */
450 }
451
452 /* Accept and process a connection on a port opened with tids_get_listener() */
453 int tids_accept(TIDS_INSTANCE *tids, int listen)
454 {
455   int conn=-1;
456   int pid=-1;
457   int pipe_fd[2];
458   struct tid_process tp = {0};
459
460   if (0 > (conn = tr_sock_accept(listen))) {
461     tr_err("tids_accept: Error accepting connection");
462     return 1;
463   }
464
465   if (0 > pipe(pipe_fd)) {
466     perror("Error on pipe()");
467     return 1;
468   }
469   /* pipe_fd[0] is for reading, pipe_fd[1] is for writing */
470
471   if (0 > (pid = fork())) {
472     perror("Error on fork()");
473     return 1;
474   }
475
476   if (pid == 0) {
477     /* Only the child process gets here */
478     close(pipe_fd[0]); /* close the read end of the pipe, the child only writes */
479     close(listen); /* close the child process's handle on the listen port */
480
481     tids_handle_proc(tids, conn, pipe_fd[1]); /* never returns */
482   }
483
484   /* Only the parent process gets here */
485   close(pipe_fd[1]); /* close the write end of the pipe, the parent only listens */
486   close(conn); /* connection belongs to the child, so close parent's handle */
487
488   /* remember the PID of our child process */
489   tr_info("tids_accept: Spawned TID process %d to handle incoming connection.", pid);
490   tp.pid = pid;
491   tp.read_fd = pipe_fd[0];
492   g_array_append_val(tids->pids, tp);
493
494   /* clean up any processes that have completed */
495   tids_sweep_procs(tids);
496   return 0;
497 }
498
499 /**
500  * Clean up any finished TID request processes
501  *
502  * This is called by the main process after forking each TID request. If you want to be
503  * sure finished processes are cleaned up promptly even during a lull in TID requests,
504  * this can be called from the main thread of the main process. It is not thread-safe,
505  * so should not be used from sub-threads. It should not be called by child processes -
506  * this would probably be harmless but ineffective.
507  *
508  * @param tids
509  */
510 void tids_sweep_procs(TIDS_INSTANCE *tids)
511 {
512   guint ii;
513   struct tid_process tp = {0};
514   char result[TIDS_MAX_MESSAGE_LEN] = {0};
515   ssize_t result_len;
516   int status;
517   int wait_rc;
518
519   /* loop backwards over the array so we can remove elements as we go */
520   for (ii=tids->pids->len; ii > 0; ii--) {
521     /* ii-1 is the current index - get our own copy, we may destroy the list's copy */
522     tp = g_array_index(tids->pids, struct tid_process, ii-1);
523
524     wait_rc = waitpid(tp.pid, &status, WNOHANG);
525     if (wait_rc == 0)
526       continue; /* process still running */
527
528     if (wait_rc < 0) {
529       /* invalid options will probably keep being invalid, report that condition */
530       if(errno == EINVAL)
531         tr_crit("tids_sweep_procs: waitpid called with invalid options");
532
533       /* If we got ECHILD, that means the PID was invalid; we'll assume the process was
534        * terminated and we missed it. For all other errors, move on
535        * to the next PID to check. */
536       if (errno != ECHILD)
537         continue;
538
539       tr_warning("tid_sweep_procs: TID process %d disappeared", tp.pid);
540     }
541
542     /* remove the item (we still have a copy of the data) */
543     g_array_remove_index_fast(tids->pids, ii-1); /* disturbs only indices >= ii-1 which we've already handled */
544
545     /* Report exit status unless we got ECHILD above or somehow waitpid returned the wrong pid */
546     if (wait_rc == tp.pid) {
547       if (WIFEXITED(status)) {
548         tr_debug("tids_sweep_procs: TID process %d exited with status %d.", tp.pid, WTERMSIG(status));
549       } else if (WIFSIGNALED(status)) {
550         tr_debug("tids_sweep_procs: TID process %d terminated by signal %d.", tp.pid, WTERMSIG(status));
551       }
552     } else if (wait_rc > 0) {
553       tr_err("tids_sweep_procs: waitpid returned pid %d, expected %d", wait_rc, tp.pid);
554     }
555
556     /* read the pipe - if the TID request worked, it will have written status before terminating */
557     result_len = read(tp.read_fd, result, TIDS_MAX_MESSAGE_LEN);
558     close(tp.read_fd);
559
560     if ((result_len > 0) && (strcmp(result, TIDS_SUCCESS_MESSAGE) == 0)) {
561       tids->req_count++;
562       tr_info("tids_sweep_procs: TID process %d exited successfully.", tp.pid);
563     } else {
564       tids->error_count++;
565       tr_info("tids_sweep_procs: TID process %d exited with an error.", tp.pid);
566     }
567   }
568 }
569
570 /* Process tids requests forever. Should not return except on error. */
571 int tids_start (TIDS_INSTANCE *tids,
572                 TIDS_REQ_FUNC *req_handler,
573                 tids_auth_func *auth_handler,
574                 const char *hostname,
575                 unsigned int port,
576                 void *cookie)
577 {
578   int fd[TR_MAX_SOCKETS]={0};
579   nfds_t n_fd=0;
580   struct pollfd poll_fd[TR_MAX_SOCKETS]={{0}};
581   int ii=0;
582
583   n_fd = tids_get_listener(tids, req_handler, auth_handler, hostname, port, cookie, fd, TR_MAX_SOCKETS);
584   if (n_fd <= 0) {
585     perror ("Error from tids_listen()");
586     return 1;
587   }
588
589   tr_info("Trust Path Query Server starting on host %s:%d.", hostname, port);
590
591   /* set up the poll structs */
592   for (ii=0; ii<n_fd; ii++) {
593     poll_fd[ii].fd=fd[ii];
594     poll_fd[ii].events=POLLIN;
595   }
596
597   while(1) {    /* accept incoming conns until we are stopped */
598     /* clear out events from previous iteration */
599     for (ii=0; ii<n_fd; ii++)
600       poll_fd[ii].revents=0;
601
602     /* wait indefinitely for a connection */
603     if (poll(poll_fd, n_fd, -1) < 0) {
604       perror("Error from poll()");
605       return 1;
606     }
607
608     /* fork handlers for any sockets that have data */
609     for (ii=0; ii<n_fd; ii++) {
610       if (poll_fd[ii].revents == 0)
611         continue;
612
613       if ((poll_fd[ii].revents & POLLERR) || (poll_fd[ii].revents & POLLNVAL)) {
614         perror("Error polling fd");
615         continue;
616       }
617
618       if (poll_fd[ii].revents & POLLIN) {
619         if (tids_accept(tids, poll_fd[ii].fd))
620           tr_err("tids_start: error in tids_accept().");
621       }
622     }
623   }
624
625   return 1;     /* should never get here, loops "forever" */
626 }
627
628 void tids_destroy (TIDS_INSTANCE *tids)
629 {
630   /* clean up logfiles */
631   tr_log_close();
632
633   if (tids)
634     free(tids);
635 }