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