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