2 * Copyright (c) 2012, 2015, JANET(UK)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
42 #include <sys/socket.h>
44 #include <netinet/in.h>
47 #include <tid_internal.h>
52 static TID_RESP *tids_create_response (TIDS_INSTANCE *tids, TID_REQ *req)
57 if (NULL == (resp = tid_resp_new(req))) {
58 tr_crit("tids_create_response: Error allocating response structure.");
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.");
70 if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
71 tr_crit("tids_create_response: Error allocating fields in response.");
79 if ((!success) && (resp!=NULL)) {
86 static int tids_listen(TIDS_INSTANCE *tids, int port, int *fd_out, size_t max_fd)
91 struct addrinfo *ai=NULL;
92 struct addrinfo *ai_head=NULL;
93 struct addrinfo hints={.ai_flags=AI_PASSIVE,
95 .ai_socktype=SOCK_STREAM,
96 .ai_protocol=IPPROTO_TCP};
100 port_str=talloc_asprintf(NULL, "%d", port);
101 if (port_str==NULL) {
102 tr_debug("tids_listen: unable to allocate port.");
106 getaddrinfo(NULL, port_str, &hints, &ai_head);
107 talloc_free(port_str);
109 /* TODO: listen on all ports */
110 for (ai=ai_head,n_opened=0; (ai!=NULL)&&(n_opened<max_fd); ai=ai->ai_next) {
111 if (0 > (conn = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))) {
112 tr_debug("tids_listen: unable to open socket.");
117 if (0!=setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)))
118 tr_debug("tids_listen: unable to set SO_REUSEADDR."); /* not fatal? */
120 if (ai->ai_family==AF_INET6) {
121 /* don't allow IPv4-mapped IPv6 addresses (per RFC4942, not sure
122 * if still relevant) */
123 if (0!=setsockopt(conn, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval))) {
124 tr_debug("tids_listen: unable to set IPV6_V6ONLY. Skipping interface.");
130 rc=bind(conn, ai->ai_addr, ai->ai_addrlen);
132 tr_debug("tids_listen: unable to bind to socket.");
137 if (0>listen(conn, 512)) {
138 tr_debug("tids_listen: unable to listen on bound socket.");
143 /* ok, this one worked. Save it */
144 fd_out[n_opened++]=conn;
146 freeaddrinfo(ai_head);
149 tr_debug("tids_listen: no addresses available for listening.");
153 tr_debug("tids_listen: TRP Server listening on port %d on %d socket%s",
156 (n_opened==1)?"":"s");
161 /* returns EACCES if authorization is denied */
162 static int tids_auth_cb(gss_name_t clientName, gss_buffer_t displayName,
165 struct tids_instance *inst = (struct tids_instance *) data;
166 TR_NAME name ={(char *) displayName->value,
167 displayName->length};
170 if (0!=inst->auth_handler(clientName, &name, inst->cookie)) {
171 tr_debug("tids_auth_cb: client '%.*s' denied authorization.", name.len, name.buf);
172 result=EACCES; /* denied */
178 /* returns 0 on authorization success, 1 on failure, or -1 in case of error */
179 static int tids_auth_connection (TIDS_INSTANCE *inst,
181 gss_ctx_id_t *gssctx)
184 int auth, autherr = 0;
185 gss_buffer_desc nameBuffer = {0, NULL};
189 nameLen = asprintf(&name, "trustidentity@%s", inst->hostname);
190 nameBuffer.length = nameLen;
191 nameBuffer.value = name;
193 if (rc = gsscon_passive_authenticate(conn, nameBuffer, gssctx, tids_auth_cb, inst)) {
194 tr_debug("tids_auth_connection: Error from gsscon_passive_authenticate(), rc = %d.", rc);
199 nameBuffer.value=NULL; nameBuffer.length=0;
201 if (rc = gsscon_authorize(*gssctx, &auth, &autherr)) {
202 tr_debug("tids_auth_connection: Error from gsscon_authorize, rc = %d, autherr = %d.",
208 tr_debug("tids_auth_connection: Connection authenticated, conn = %d.", conn);
210 tr_debug("tids_auth_connection: Authentication failed, conn %d.", conn);
215 static int tids_read_request (TIDS_INSTANCE *tids, int conn, gss_ctx_id_t *gssctx, TR_MSG **mreq)
221 if (err = gsscon_read_encrypted_token(conn, *gssctx, &buf, &buflen)) {
227 tr_debug("tids_read_request():Request Received, %u bytes.", (unsigned) buflen);
230 if (NULL == ((*mreq) = tr_msg_decode(buf, buflen))) {
231 tr_debug("tids_read_request():Error decoding request.");
236 /* If this isn't a TID Request, just drop it. */
237 if (TID_REQUEST != (*mreq)->msg_type) {
238 tr_debug("tids_read_request(): Not a TID Request, dropped.");
246 static int tids_handle_request (TIDS_INSTANCE *tids, TR_MSG *mreq, TID_RESP *resp)
250 /* Check that this is a valid TID Request. If not, send an error return. */
251 if ((!tr_msg_get_req(mreq)) ||
252 (!tr_msg_get_req(mreq)->rp_realm) ||
253 (!tr_msg_get_req(mreq)->realm) ||
254 (!tr_msg_get_req(mreq)->comm)) {
255 tr_notice("tids_handle_request(): Not a valid TID Request.");
256 resp->result = TID_ERROR;
257 resp->err_msg = tr_new_name("Bad request format");
261 tr_debug("tids_handle_request: adding self to req path.");
262 tid_req_add_path(tr_msg_get_req(mreq), tids->hostname, tids->tids_port);
264 /* Call the caller's request handler */
265 /* TBD -- Handle different error returns/msgs */
266 if (0 > (rc = (*tids->req_handler)(tids, tr_msg_get_req(mreq), resp, tids->cookie))) {
267 /* set-up an error response */
268 tr_debug("tids_handle_request: req_handler returned error.");
269 resp->result = TID_ERROR;
270 if (!resp->err_msg) /* Use msg set by handler, if any */
271 resp->err_msg = tr_new_name("Internal processing error");
274 /* set-up a success response */
275 tr_debug("tids_handle_request: req_handler returned success.");
276 resp->result = TID_SUCCESS;
277 resp->err_msg = NULL; /* No error msg on successful return */
283 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
284 TID_RESP *resp = NULL;
287 /* If we already sent a response, don't send another no matter what. */
291 if (NULL == (resp = tids_create_response(tids, req))) {
292 tr_crit("tids_send_err_response: Can't create response.");
297 /* mark this as an error response, and include the error message */
298 resp->result = TID_ERROR;
299 resp->err_msg = tr_new_name((char *)err_msg);
300 resp->error_path = req->path;
302 rc = tids_send_response(tids, req, resp);
308 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
314 if ((!tids) || (!req) || (!resp))
315 tr_debug("tids_send_response: Invalid parameters.");
317 /* Never send a second response if we already sent one. */
321 mresp.msg_type = TID_RESPONSE;
322 tr_msg_set_resp(&mresp, resp);
324 if (NULL == (resp_buf = tr_msg_encode(&mresp))) {
326 fprintf(stderr, "tids_send_response: Error encoding json response.\n");
332 tr_debug("tids_send_response: Encoded response: %s", resp_buf);
334 /* If external logging is enabled, fire off a message */
335 /* TODO Can be moved to end once segfault in gsscon_write_encrypted_token fixed */
338 /* Send the response over the connection */
339 if (err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf,
340 strlen(resp_buf) + 1)) {
341 tr_notice("tids_send_response: Error sending response over connection.");
348 /* indicate that a response has been sent for this request */
356 static void tids_handle_connection (TIDS_INSTANCE *tids, int conn)
359 TID_RESP *resp = NULL;
361 gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
363 if (tids_auth_connection(tids, conn, &gssctx)) {
364 tr_notice("tids_handle_connection: Error authorizing TID Server connection.");
369 tr_debug("tids_handle_connection: Connection authorized!");
371 while (1) { /* continue until an error breaks us out */
373 if (0 > (rc = tids_read_request(tids, conn, &gssctx, &mreq))) {
374 tr_debug("tids_handle_connection: Error from tids_read_request(), rc = %d.", rc);
376 } else if (0 == rc) {
380 /* Put connection information into the request structure */
381 tr_msg_get_req(mreq)->conn = conn;
382 tr_msg_get_req(mreq)->gssctx = gssctx;
384 /* Allocate a response structure and populate common fields */
385 if (NULL == (resp = tids_create_response (tids, tr_msg_get_req(mreq)))) {
386 tr_crit("tids_handle_connection: Error creating response structure.");
387 /* try to send an error */
388 tids_send_err_response(tids, tr_msg_get_req(mreq), "Error creating response.");
389 tr_msg_free_decoded(mreq);
393 if (0 > (rc = tids_handle_request(tids, mreq, resp))) {
394 tr_debug("tids_handle_connection: Error from tids_handle_request(), rc = %d.", rc);
395 /* Fall through, to send the response, either way */
398 if (0 > (rc = tids_send_response(tids, tr_msg_get_req(mreq), resp))) {
399 tr_debug("tids_handle_connection: Error from tids_send_response(), rc = %d.", rc);
400 /* if we didn't already send a response, try to send a generic error. */
401 if (!tr_msg_get_req(mreq)->resp_sent)
402 tids_send_err_response(tids, tr_msg_get_req(mreq), "Error sending response.");
403 /* Fall through to free the response, either way. */
406 tr_msg_free_decoded(mreq); /* takes resp with it */
411 TIDS_INSTANCE *tids_create (TALLOC_CTX *mem_ctx)
413 return talloc_zero(mem_ctx, TIDS_INSTANCE);
416 /* Get a listener for tids requests, returns its socket fd. Accept
417 * connections with tids_accept() */
418 int tids_get_listener(TIDS_INSTANCE *tids,
419 TIDS_REQ_FUNC *req_handler,
420 TIDS_AUTH_FUNC *auth_handler,
421 const char *hostname,
430 tids->tids_port = port;
431 n_fd=tids_listen(tids, port, fd_out, max_fd);
433 tr_debug("tids_get_listener: Error opening port %d");
435 /* opening port succeeded */
436 tr_debug("tids_get_listener: Opened port %d.", port);
438 /* make this socket non-blocking */
439 for (ii=0; ii<n_fd; ii++) {
440 if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
441 tr_debug("tids_get_listener: Error setting O_NONBLOCK.");
442 for (ii=0; ii<n_fd; ii++) {
453 /* store the caller's request handler & cookie */
454 tids->req_handler = req_handler;
455 tids->auth_handler = auth_handler;
456 tids->hostname = hostname;
457 tids->cookie = cookie;
463 /* Accept and process a connection on a port opened with tids_get_listener() */
464 int tids_accept(TIDS_INSTANCE *tids, int listen)
469 if (0 > (conn = accept(listen, NULL, NULL))) {
470 perror("Error from TIDS Server accept()");
474 if (0 > (pid = fork())) {
475 perror("Error on fork()");
481 tids_handle_connection(tids, conn);
483 exit(0); /* exit to kill forked child process */
488 /* clean up any processes that have completed (TBD: move to main loop?) */
489 while (waitpid(-1, 0, WNOHANG) > 0);
494 void tids_destroy (TIDS_INSTANCE *tids)
496 /* clean up logfiles */