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