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