Add a 'request_id' to TID requests and responses
[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 <assert.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <string.h>
40 #include <stdio.h>
41 #include <errno.h>
42 #include <sys/socket.h>
43 #include <sys/wait.h>
44 #include <netinet/in.h>
45 #include <jansson.h>
46 #include <talloc.h>
47 #include <poll.h>
48 #include <tid_internal.h>
49 #include <gsscon.h>
50 #include <tr_debug.h>
51 #include <tr_msg.h>
52
53 static TID_RESP *tids_create_response (TIDS_INSTANCE *tids, TID_REQ *req) 
54 {
55   TID_RESP *resp=NULL;
56   int success=0;
57
58   if (NULL == (resp = tid_resp_new(req))) {
59     tr_crit("tids_create_response: Error allocating response structure.");
60     return NULL;
61   }
62   
63   resp->result = TID_SUCCESS; /* presume success */
64   if ((NULL == (resp->rp_realm = tr_dup_name(req->rp_realm))) ||
65       (NULL == (resp->realm = tr_dup_name(req->realm))) ||
66       (NULL == (resp->comm = tr_dup_name(req->comm)))) {
67     tr_crit("tids_create_response: Error allocating fields in response.");
68     goto cleanup;
69   }
70   if (req->orig_coi) {
71     if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
72       tr_crit("tids_create_response: Error allocating fields in response.");
73       goto cleanup;
74     }
75   }
76   if (req->request_id) {
77     if (NULL == (resp->request_id = tr_dup_name(req->request_id))) {
78       tr_crit("tids_create_response: Error allocating fields in response.");
79       goto cleanup;
80     }
81   }
82
83   success=1;
84
85 cleanup:
86   if ((!success) && (resp!=NULL)) {
87     talloc_free(resp);
88     resp=NULL;
89   }
90   return resp;
91 }
92
93 static int tids_listen(TIDS_INSTANCE *tids, int port, int *fd_out, size_t max_fd) 
94 {
95   int rc = 0;
96   int conn = -1;
97   int optval = 1;
98   struct addrinfo *ai=NULL;
99   struct addrinfo *ai_head=NULL;
100   struct addrinfo hints={.ai_flags=AI_PASSIVE,
101                          .ai_family=AF_UNSPEC,
102                          .ai_socktype=SOCK_STREAM,
103                          .ai_protocol=IPPROTO_TCP};
104   char *port_str=NULL;
105   size_t n_opened=0;
106
107   tr_debug("tids_listen: started!");
108   port_str=talloc_asprintf(NULL, "%d", port);
109   if (port_str==NULL) {
110     tr_debug("tids_listen: unable to allocate port.");
111     return -1;
112   }
113
114   tr_debug("getaddrinfo()=%d", getaddrinfo(NULL, port_str, &hints, &ai_head));
115   talloc_free(port_str);
116   tr_debug("tids_listen: got address info");
117
118   /* TODO: listen on all ports */
119   for (ai=ai_head,n_opened=0; (ai!=NULL)&&(n_opened<max_fd); ai=ai->ai_next) {
120     if (0 > (conn = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))) {
121       tr_debug("tids_listen: unable to open socket.");
122       continue;
123     }
124
125     optval=1;
126     if (0!=setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)))
127       tr_debug("tids_listen: unable to set SO_REUSEADDR."); /* not fatal? */
128
129     if (ai->ai_family==AF_INET6) {
130       /* don't allow IPv4-mapped IPv6 addresses (per RFC4942, not sure
131        * if still relevant) */
132       if (0!=setsockopt(conn, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval))) {
133         tr_debug("tids_listen: unable to set IPV6_V6ONLY. Skipping interface.");
134         close(conn);
135         continue;
136       }
137     }
138
139     rc=bind(conn, ai->ai_addr, ai->ai_addrlen);
140     if (rc<0) {
141       tr_debug("tids_listen: unable to bind to socket.");
142       close(conn);
143       continue;
144     }
145
146     if (0>listen(conn, 512)) {
147       tr_debug("tids_listen: unable to listen on bound socket.");
148       close(conn);
149       continue;
150     }
151
152     /* ok, this one worked. Save it */
153     fd_out[n_opened++]=conn;
154   }
155   freeaddrinfo(ai_head);
156
157   if (n_opened==0) {
158     tr_debug("tids_listen: no addresses available for listening.");
159     return -1;
160   }
161
162   tr_debug("tids_listen: TRP Server listening on port %d on %d socket%s",
163            port,
164            n_opened,
165            (n_opened==1)?"":"s");
166
167   return n_opened;
168 }
169
170 /* returns EACCES if authorization is denied */
171 static int tids_auth_cb(gss_name_t clientName, gss_buffer_t displayName,
172                         void *data)
173 {
174   struct tids_instance *inst = (struct tids_instance *) data;
175   TR_NAME name ={(char *) displayName->value,
176                  displayName->length};
177   int result=0;
178
179   if (0!=inst->auth_handler(clientName, &name, inst->cookie)) {
180     tr_debug("tids_auth_cb: client '%.*s' denied authorization.", name.len, name.buf);
181     result=EACCES; /* denied */
182   }
183
184   return result;
185 }
186
187 /* returns 0 on authorization success, 1 on failure, or -1 in case of error */
188 static int tids_auth_connection (TIDS_INSTANCE *inst,
189                                  int conn,
190                                  gss_ctx_id_t *gssctx)
191 {
192   int rc = 0;
193   int auth, autherr = 0;
194   gss_buffer_desc nameBuffer = {0, NULL};
195   char *name = 0;
196   int nameLen = 0;
197
198   nameLen = asprintf(&name, "trustidentity@%s", inst->hostname);
199   nameBuffer.length = nameLen;
200   nameBuffer.value = name;
201
202   if (rc = gsscon_passive_authenticate(conn, nameBuffer, gssctx, tids_auth_cb, inst)) {
203     tr_debug("tids_auth_connection: Error from gsscon_passive_authenticate(), rc = %d.", rc);
204     free(name);
205     return -1;
206   }
207   free(name);
208   nameBuffer.value=NULL; nameBuffer.length=0;
209
210   if (rc = gsscon_authorize(*gssctx, &auth, &autherr)) {
211     tr_debug("tids_auth_connection: Error from gsscon_authorize, rc = %d, autherr = %d.", 
212             rc, autherr);
213     return -1;
214   }
215
216   if (auth)
217     tr_debug("tids_auth_connection: Connection authenticated, conn = %d.", conn);
218   else
219     tr_debug("tids_auth_connection: Authentication failed, conn %d.", conn);
220
221   return !auth;
222 }
223
224 static int tids_read_request (TIDS_INSTANCE *tids, int conn, gss_ctx_id_t *gssctx, TR_MSG **mreq)
225 {
226   int err;
227   char *buf;
228   size_t buflen = 0;
229
230   if (err = gsscon_read_encrypted_token(conn, *gssctx, &buf, &buflen)) {
231     if (buf)
232       free(buf);
233     return -1;
234   }
235
236   tr_debug("tids_read_request():Request Received, %u bytes.", (unsigned) buflen);
237
238   /* Parse request */
239   if (NULL == ((*mreq) = tr_msg_decode(buf, buflen))) {
240     tr_debug("tids_read_request():Error decoding request.");
241     free (buf);
242     return -1;
243   }
244
245   /* If this isn't a TID Request, just drop it. */
246   if (TID_REQUEST != (*mreq)->msg_type) {
247     tr_debug("tids_read_request(): Not a TID Request, dropped.");
248     return -1;
249   }
250
251   free (buf);
252   return buflen;
253 }
254
255 static int tids_handle_request (TIDS_INSTANCE *tids, TR_MSG *mreq, TID_RESP *resp) 
256 {
257   int rc=-1;
258
259   /* Check that this is a valid TID Request.  If not, send an error return. */
260   if ((!tr_msg_get_req(mreq)) ||
261       (!tr_msg_get_req(mreq)->rp_realm) ||
262       (!tr_msg_get_req(mreq)->realm) ||
263       (!tr_msg_get_req(mreq)->comm)) {
264     tr_notice("tids_handle_request(): Not a valid TID Request.");
265     resp->result = TID_ERROR;
266     resp->err_msg = tr_new_name("Bad request format");
267     return -1;
268   }
269
270   tr_debug("tids_handle_request: adding self to req path.");
271   tid_req_add_path(tr_msg_get_req(mreq), tids->hostname, tids->tids_port);
272   
273   /* Call the caller's request handler */
274   /* TBD -- Handle different error returns/msgs */
275   if (0 > (rc = (*tids->req_handler)(tids, tr_msg_get_req(mreq), resp, tids->cookie))) {
276     /* set-up an error response */
277     tr_debug("tids_handle_request: req_handler returned error.");
278     resp->result = TID_ERROR;
279     if (!resp->err_msg) /* Use msg set by handler, if any */
280       resp->err_msg = tr_new_name("Internal processing error");
281   }
282   else {
283     /* set-up a success response */
284     tr_debug("tids_handle_request: req_handler returned success.");
285     resp->result = TID_SUCCESS;
286     resp->err_msg = NULL;       /* No error msg on successful return */
287   }
288     
289   return rc;
290 }
291
292 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
293   TID_RESP *resp = NULL;
294   int rc = 0;
295
296   /* If we already sent a response, don't send another no matter what. */
297   if (req->resp_sent)
298     return 0;
299
300   if (NULL == (resp = tids_create_response(tids, req))) {
301     tr_crit("tids_send_err_response: Can't create response.");
302     return -1;
303   }
304   
305   /* mark this as an error response, and include the error message */
306   resp->result = TID_ERROR;
307   resp->err_msg = tr_new_name((char *)err_msg);
308   resp->error_path = req->path;
309
310   rc = tids_send_response(tids, req, resp);
311   
312   tid_resp_free(resp);
313   return rc;
314 }
315
316 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
317 {
318   int err;
319   TR_MSG mresp;
320   char *resp_buf;
321
322   if ((!tids) || (!req) || (!resp))
323     tr_debug("tids_send_response: Invalid parameters.");
324
325   /* Never send a second response if we already sent one. */
326   if (req->resp_sent)
327     return 0;
328
329   mresp.msg_type = TID_RESPONSE;
330   tr_msg_set_resp(&mresp, resp);
331
332   if (NULL == (resp_buf = tr_msg_encode(&mresp))) {
333
334     tr_err("tids_send_response: Error encoding json response.");
335     tr_audit_req(req);
336
337     return -1;
338   }
339
340   tr_debug("tids_send_response: Encoded response: %s", resp_buf);
341
342   /* If external logging is enabled, fire off a message */
343   /* TODO Can be moved to end once segfault in gsscon_write_encrypted_token fixed */
344   tr_audit_resp(resp);
345
346   /* Send the response over the connection */
347   if (err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf, 
348                                           strlen(resp_buf) + 1)) {
349     tr_notice("tids_send_response: Error sending response over connection.");
350
351     tr_audit_req(req);
352
353     return -1;
354   }
355
356   /* indicate that a response has been sent for this request */
357   req->resp_sent = 1;
358
359   free(resp_buf);
360
361   return 0;
362 }
363
364 static void tids_handle_connection (TIDS_INSTANCE *tids, int conn)
365 {
366   TR_MSG *mreq = NULL;
367   TID_RESP *resp = NULL;
368   int rc = 0;
369   gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
370
371   if (tids_auth_connection(tids, conn, &gssctx)) {
372     tr_notice("tids_handle_connection: Error authorizing TID Server connection.");
373     close(conn);
374     return;
375   }
376
377   tr_debug("tids_handle_connection: Connection authorized!");
378
379   while (1) {   /* continue until an error breaks us out */
380
381     if (0 > (rc = tids_read_request(tids, conn, &gssctx, &mreq))) {
382       tr_debug("tids_handle_connection: Error from tids_read_request(), rc = %d.", rc);
383       return;
384     } else if (0 == rc) {
385       continue;
386     }
387
388     /* Put connection information into the request structure */
389     tr_msg_get_req(mreq)->conn = conn;
390     tr_msg_get_req(mreq)->gssctx = gssctx;
391
392     /* Allocate a response structure and populate common fields */
393     if (NULL == (resp = tids_create_response (tids, tr_msg_get_req(mreq)))) {
394       tr_crit("tids_handle_connection: Error creating response structure.");
395       /* try to send an error */
396       tids_send_err_response(tids, tr_msg_get_req(mreq), "Error creating response.");
397       tr_msg_free_decoded(mreq);
398       return;
399     }
400
401     if (0 > (rc = tids_handle_request(tids, mreq, resp))) {
402       tr_debug("tids_handle_connection: Error from tids_handle_request(), rc = %d.", rc);
403       /* Fall through, to send the response, either way */
404     }
405
406     if (0 > (rc = tids_send_response(tids, tr_msg_get_req(mreq), resp))) {
407       tr_debug("tids_handle_connection: Error from tids_send_response(), rc = %d.", rc);
408       /* if we didn't already send a response, try to send a generic error. */
409       if (!tr_msg_get_req(mreq)->resp_sent)
410         tids_send_err_response(tids, tr_msg_get_req(mreq), "Error sending response.");
411       /* Fall through to free the response, either way. */
412     }
413     
414     tr_msg_free_decoded(mreq); /* takes resp with it */
415     return;
416   } 
417 }
418
419 TIDS_INSTANCE *tids_create (void)
420 {
421   return talloc_zero(NULL, TIDS_INSTANCE);
422 }
423
424 /* Get a listener for tids requests, returns its socket fd. Accept
425  * connections with tids_accept() */
426 int tids_get_listener(TIDS_INSTANCE *tids, 
427                       TIDS_REQ_FUNC *req_handler,
428                       tids_auth_func *auth_handler,
429                       const char *hostname,
430                       unsigned int port,
431                       void *cookie,
432                       int *fd_out,
433                       size_t max_fd)
434 {
435   size_t n_fd=0;
436   size_t ii=0;
437
438   tids->tids_port = port;
439   n_fd=tids_listen(tids, port, fd_out, max_fd);
440   if (n_fd<=0)
441     tr_err("tids_get_listener: Error opening port %d");
442   else {
443     /* opening port succeeded */
444     tr_info("tids_get_listener: Opened port %d.", port);
445     
446     /* make this socket non-blocking */
447     for (ii=0; ii<n_fd; ii++) {
448       if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
449         tr_err("tids_get_listener: Error setting O_NONBLOCK.");
450         for (ii=0; ii<n_fd; ii++) {
451           close(fd_out[ii]);
452           fd_out[ii]=-1;
453         }
454         n_fd=0;
455         break;
456       }
457     }
458   }
459
460   if (n_fd>0) {
461     /* store the caller's request handler & cookie */
462     tids->req_handler = req_handler;
463     tids->auth_handler = auth_handler;
464     tids->hostname = hostname;
465     tids->cookie = cookie;
466   }
467
468   return n_fd;
469 }
470
471 /* Accept and process a connection on a port opened with tids_get_listener() */
472 int tids_accept(TIDS_INSTANCE *tids, int listen)
473 {
474   int conn=-1;
475   int pid=-1;
476
477   if (0 > (conn = accept(listen, NULL, NULL))) {
478     perror("Error from TIDS Server accept()");
479     return 1;
480   }
481
482   if (0 > (pid = fork())) {
483     perror("Error on fork()");
484     return 1;
485   }
486
487   if (pid == 0) {
488     close(listen);
489     tids_handle_connection(tids, conn);
490     close(conn);
491     exit(0); /* exit to kill forked child process */
492   } else {
493     close(conn);
494   }
495
496   /* clean up any processes that have completed  (TBD: move to main loop?) */
497   while (waitpid(-1, 0, WNOHANG) > 0);
498
499   return 0;
500 }
501
502 /* Process tids requests forever. Should not return except on error. */
503 #define MAX_SOCKETS 10
504 int tids_start (TIDS_INSTANCE *tids, 
505                 TIDS_REQ_FUNC *req_handler,
506                 tids_auth_func *auth_handler,
507                 const char *hostname,
508                 unsigned int port,
509                 void *cookie)
510 {
511   int fd[MAX_SOCKETS]={0};
512   size_t n_fd=0;
513   struct pollfd poll_fd[MAX_SOCKETS]={{0}};
514   int ii=0;
515
516   n_fd=tids_get_listener(tids, req_handler, auth_handler, hostname, port, cookie, fd, MAX_SOCKETS);
517   if (n_fd <= 0) {
518     perror ("Error from tids_listen()");
519     return 1;
520   }
521
522   tr_info("Trust Path Query Server starting on host %s:%d.", hostname, port);
523
524   /* set up the poll structs */
525   for (ii=0; ii<n_fd; ii++) {
526     poll_fd[ii].fd=fd[ii];
527     poll_fd[ii].events=POLLIN;
528   }
529
530   while(1) {    /* accept incoming conns until we are stopped */
531     /* clear out events from previous iteration */
532     for (ii=0; ii<n_fd; ii++)
533       poll_fd[ii].revents=0;
534
535     /* wait indefinitely for a connection */
536     if (poll(poll_fd, n_fd, -1) < 0) {
537       perror("Error from poll()");
538       return 1;
539     }
540
541     /* fork handlers for any sockets that have data */
542     for (ii=0; ii<n_fd; ii++) {
543       if (poll_fd[ii].revents == 0)
544         continue;
545
546       if ((poll_fd[ii].revents & POLLERR) || (poll_fd[ii].revents & POLLNVAL)) {
547         perror("Error polling fd");
548         continue;
549       }
550
551       if (poll_fd[ii].revents & POLLIN) {
552         if (tids_accept(tids, poll_fd[ii].fd))
553           tr_err("tids_start: error in tids_accept().");
554       }
555     }
556   }
557
558   return 1;     /* should never get here, loops "forever" */
559 }
560 #undef MAX_SOCKETS
561
562 void tids_destroy (TIDS_INSTANCE *tids)
563 {
564   /* clean up logfiles */
565   tr_log_close();
566
567   if (tids)
568     free(tids);
569 }