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