3d37739e7295adef960e3ddb42f3eac52b7cf1b7
[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 #include <tr_gss.h>
53 #include <tr_event.h>
54
55 static TID_RESP *tids_create_response(TALLOC_CTX *mem_ctx, TIDS_INSTANCE *tids, TID_REQ *req)
56 {
57   TID_RESP *resp=NULL;
58   int success=0;
59
60   if (NULL == (resp = tid_resp_new(mem_ctx))) {
61     tr_crit("tids_create_response: Error allocating response structure.");
62     return NULL;
63   }
64   
65   resp->result = TID_SUCCESS; /* presume success */
66   if ((NULL == (resp->rp_realm = tr_dup_name(req->rp_realm))) ||
67       (NULL == (resp->realm = tr_dup_name(req->realm))) ||
68       (NULL == (resp->comm = tr_dup_name(req->comm)))) {
69     tr_crit("tids_create_response: Error allocating fields in response.");
70     goto cleanup;
71   }
72   if (req->orig_coi) {
73     if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
74       tr_crit("tids_create_response: Error allocating fields in response.");
75       goto cleanup;
76     }
77   }
78
79   success=1;
80
81 cleanup:
82   if ((!success) && (resp!=NULL)) {
83     talloc_free(resp);
84     resp=NULL;
85   }
86   return resp;
87 }
88
89 /* returns EACCES if authorization is denied */
90 static int tids_auth_cb(gss_name_t clientName, gss_buffer_t displayName,
91                         void *data)
92 {
93   struct tids_instance *inst = (struct tids_instance *) data;
94   TR_NAME name ={(char *) displayName->value, (int) displayName->length};
95   int result=0;
96
97   if (0!=inst->auth_handler(clientName, &name, inst->cookie)) {
98     tr_debug("tids_auth_cb: client '%.*s' denied authorization.", name.len, name.buf);
99     result=EACCES; /* denied */
100   }
101
102   return result;
103 }
104
105 static int tids_handle_request(TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
106 {
107   int rc=-1;
108
109   /* Check that this is a valid TID Request.  If not, send an error return. */
110   if ((!req) ||
111       (!(req->rp_realm)) ||
112       (!(req->realm)) ||
113       (!(req->comm))) {
114     tr_notice("tids_handle_request(): Not a valid TID Request.");
115     resp->result = TID_ERROR;
116     resp->err_msg = tr_new_name("Bad request format");
117     return -1;
118   }
119
120   tr_debug("tids_handle_request: adding self to req path.");
121   tid_req_add_path(req, tids->hostname, tids->tids_port);
122   
123   /* Call the caller's request handler */
124   /* TBD -- Handle different error returns/msgs */
125   if (0 > (rc = (*tids->req_handler)(tids, req, resp, tids->cookie))) {
126     /* set-up an error response */
127     tr_debug("tids_handle_request: req_handler returned error.");
128     resp->result = TID_ERROR;
129     if (!resp->err_msg) /* Use msg set by handler, if any */
130       resp->err_msg = tr_new_name("Internal processing error");
131   }
132   else {
133     /* set-up a success response */
134     tr_debug("tids_handle_request: req_handler returned success.");
135     resp->result = TID_SUCCESS;
136     resp->err_msg = NULL;       /* No error msg on successful return */
137   }
138     
139   return rc;
140 }
141
142 /**
143  * Produces a JSON-encoded msg containing the TID response
144  *
145  * @param mem_ctx talloc context for the return value
146  * @param tids TIDS_INSTANCE handling the request
147  * @param req incoming request
148  * @param resp outgoing response
149  * @return JSON-encoded message containing the TID response
150  */
151 static char *tids_encode_response(TALLOC_CTX *mem_ctx, TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
152 {
153   TR_MSG mresp;
154   char *resp_buf = NULL;
155
156   /* Construct the response message */
157   mresp.msg_type = TID_RESPONSE;
158   tr_msg_set_resp(&mresp, resp);
159
160   /* Encode the message to JSON */
161   resp_buf = tr_msg_encode(mem_ctx, &mresp);
162   if (resp_buf == NULL) {
163     tr_err("tids_encode_response: Error encoding json response.");
164     return NULL;
165   }
166   tr_debug("tids_encode_response: Encoded response: %s", resp_buf);
167
168   /* Success */
169   return resp_buf;
170 }
171
172 /**
173  * Encode/send an error response
174  *
175  * Part of the public interface
176  *
177  * @param tids
178  * @param req
179  * @param err_msg
180  * @return
181  */
182 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
183   TID_RESP *resp = NULL;
184   int rc = 0;
185
186   if ((!tids) || (!req) || (!err_msg)) {
187     tr_debug("tids_send_err_response: Invalid parameters.");
188     return -1;
189   }
190
191   /* If we already sent a response, don't send another no matter what. */
192   if (req->resp_sent)
193     return 0;
194
195   if (NULL == (resp = tids_create_response(req, tids, req))) {
196     tr_crit("tids_send_err_response: Can't create response.");
197     return -1;
198   }
199
200   /* mark this as an error response, and include the error message */
201   resp->result = TID_ERROR;
202   resp->err_msg = tr_new_name((char *)err_msg);
203   resp->error_path = req->path;
204
205   rc = tids_send_response(tids, req, resp);
206
207   tid_resp_free(resp);
208   return rc;
209 }
210
211 /**
212  * Encode/send a response
213  *
214  * Part of the public interface
215  *
216  * @param tids
217  * @param req
218  * @param resp
219  * @return
220  */
221 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
222 {
223   int err;
224   char *resp_buf;
225
226   if ((!tids) || (!req) || (!resp)) {
227     tr_debug("tids_send_response: Invalid parameters.");
228     return -1;
229   }
230
231   /* Never send a second response if we already sent one. */
232   if (req->resp_sent)
233     return 0;
234
235   resp_buf = tids_encode_response(NULL, tids, req, resp);
236   if (resp_buf == NULL) {
237     tr_err("tids_send_response: Error encoding json response.");
238     tr_audit_req(req);
239     return -1;
240   }
241
242   tr_debug("tids_send_response: Encoded response: %s", resp_buf);
243
244   /* If external logging is enabled, fire off a message */
245   /* TODO Can be moved to end once segfault in gsscon_write_encrypted_token fixed */
246   tr_audit_resp(resp);
247
248   /* Send the response over the connection */
249   err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf,
250                                             strlen(resp_buf) + 1);
251   if (err) {
252     tr_notice("tids_send_response: Error sending response over connection.");
253     tr_audit_req(req);
254     return -1;
255   }
256
257   /* indicate that a response has been sent for this request */
258   req->resp_sent = 1;
259
260   free(resp_buf);
261
262   return 0;
263 }
264
265 /**
266  * Callback to process a request and produce a response
267  *
268  * @param req_str JSON-encoded request
269  * @param data pointer to a TIDS_INSTANCE
270  * @return pointer to the response string or null to send no response
271  */
272 static char *tids_req_cb(TALLOC_CTX *mem_ctx, const char *req_str, void *data)
273 {
274   TIDS_INSTANCE *tids = talloc_get_type_abort(data, TIDS_INSTANCE);
275   TR_MSG *mreq = NULL;
276   TID_REQ *req = NULL;
277   TID_RESP *resp = NULL;
278   char *resp_str = NULL;
279   int rc = 0;
280
281   mreq = tr_msg_decode(req_str, strlen(req_str)); // allocates memory on success!
282   if (mreq == NULL) {
283     tr_debug("tids_req_cb: Error decoding request.");
284     return NULL;
285   }
286
287   /* If this isn't a TID Request, just drop it. */
288   if (mreq->msg_type != TID_REQUEST) {
289     tr_msg_free_decoded(mreq);
290     tr_debug("tids_req_cb: Not a TID request, dropped.");
291     return NULL;
292   }
293
294   /* Get a handle on the request itself. Don't free req - it belongs to mreq */
295   req = tr_msg_get_req(mreq);
296
297   /* Allocate a response structure and populate common fields. The resp is in req's talloc context,
298    * which will be cleaned up when mreq is freed. */
299   resp = tids_create_response(req, tids, req);
300   if (resp == NULL) {
301     /* If we were unable to create a response, we cannot reply. Log an
302      * error if we can, then drop the request. */
303     tr_msg_free_decoded(mreq);
304     tr_crit("tids_req_cb: Error creating response structure.");
305     return NULL;
306   }
307
308   /* Handle the request and fill in resp */
309   rc = tids_handle_request(tids, req, resp);
310   if (rc < 0) {
311     tr_debug("tids_req_cb: Error from tids_handle_request(), rc = %d.", rc);
312     /* Fall through, to send the response, either way */
313   }
314
315   /* Convert the completed response into an encoded response */
316   resp_str = tids_encode_response(mem_ctx, tids, req, resp);
317
318   /* Finished; free the request and return */
319   tr_msg_free_decoded(mreq); // this frees req and resp, too
320   return resp_str;
321 }
322
323 TIDS_INSTANCE *tids_new(TALLOC_CTX *mem_ctx)
324 {
325   return talloc_zero(mem_ctx, TIDS_INSTANCE);
326 }
327
328 /**
329  * Create a new TIDS instance
330  *
331  * Deprecated: exists for ABI compatibility, but tids_new() should be used instead
332  *
333  */
334 TIDS_INSTANCE *tids_create(void)
335 {
336   return talloc_zero(NULL, TIDS_INSTANCE);
337 }
338 /* Get a listener for tids requests, returns its socket fd. Accept
339  * connections with tids_accept() */
340 int tids_get_listener(TIDS_INSTANCE *tids,
341                       TIDS_REQ_FUNC *req_handler,
342                       tids_auth_func *auth_handler,
343                       const char *hostname,
344                       unsigned int port,
345                       void *cookie,
346                       int *fd_out,
347                       size_t max_fd)
348 {
349   nfds_t n_fd = 0;
350   nfds_t ii = 0;
351
352   tids->tids_port = port;
353   n_fd = tr_sock_listen_all(port, fd_out, max_fd);
354
355   if (n_fd == 0)
356     tr_err("tids_get_listener: Error opening port %d");
357   else {
358     /* opening port succeeded */
359     tr_info("tids_get_listener: Opened port %d.", port);
360     
361     /* make this socket non-blocking */
362     for (ii=0; ii<n_fd; ii++) {
363       if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
364         tr_err("tids_get_listener: Error setting O_NONBLOCK.");
365         for (ii=0; ii<n_fd; ii++) {
366           close(fd_out[ii]);
367           fd_out[ii]=-1;
368         }
369         n_fd = 0;
370         break;
371       }
372     }
373   }
374
375   if (n_fd > 0) {
376     /* store the caller's request handler & cookie */
377     tids->req_handler = req_handler;
378     tids->auth_handler = auth_handler;
379     tids->hostname = hostname;
380     tids->cookie = cookie;
381   }
382
383   return (int)n_fd;
384 }
385
386 /* Accept and process a connection on a port opened with tids_get_listener() */
387 int tids_accept(TIDS_INSTANCE *tids, int listen)
388 {
389   int conn=-1;
390   int pid=-1;
391
392   if (0 > (conn = accept(listen, NULL, NULL))) {
393     perror("Error from TIDS Server accept()");
394     return 1;
395   }
396
397   if (0 > (pid = fork())) {
398     perror("Error on fork()");
399     return 1;
400   }
401
402   if (pid == 0) {
403     close(listen);
404     tr_gss_handle_connection(conn,
405                              "trustidentity", tids->hostname, /* acceptor name */
406                              tids_auth_cb, tids, /* auth callback and cookie */
407                              tids_req_cb, tids /* req callback and cookie */
408     );
409     close(conn);
410     exit(0); /* exit to kill forked child process */
411   } else {
412     close(conn);
413   }
414
415   /* clean up any processes that have completed  (TBD: move to main loop?) */
416   while (waitpid(-1, 0, WNOHANG) > 0);
417
418   return 0;
419 }
420
421 /* Process tids requests forever. Should not return except on error. */
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[TR_MAX_SOCKETS]={0};
430   nfds_t n_fd=0;
431   struct pollfd poll_fd[TR_MAX_SOCKETS]={{0}};
432   int ii=0;
433
434   n_fd=tids_get_listener(tids, req_handler, auth_handler, hostname, port, cookie, fd, TR_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
479 void tids_destroy (TIDS_INSTANCE *tids)
480 {
481   /* clean up logfiles */
482   tr_log_close();
483
484   if (tids)
485     free(tids);
486 }