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