Merge branch 'jennifer/march2016-patches'
[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 <string.h>
39 #include <stdio.h>
40 #include <errno.h>
41 #include <sys/socket.h>
42 #include <sys/wait.h>
43 #include <netinet/in.h>
44 #include <jansson.h>
45 #include <talloc.h>
46 #include <tid_internal.h>
47 #include <gsscon.h>
48 #include <tr_debug.h>
49 #include <tr_msg.h>
50
51 static TID_RESP *tids_create_response (TIDS_INSTANCE *tids, TID_REQ *req) 
52 {
53   TID_RESP *resp;
54
55   if ((NULL == (resp = talloc_zero(req, TID_RESP)))) {
56     tr_crit("tids_create_response: Error allocating response structure.");
57     return NULL;
58   }
59   
60   resp->result = TID_SUCCESS; /* presume success */
61   if ((NULL == (resp->rp_realm = tr_dup_name(req->rp_realm))) ||
62       (NULL == (resp->realm = tr_dup_name(req->realm))) ||
63       (NULL == (resp->comm = tr_dup_name(req->comm)))) {
64     tr_crit("tids_create_response: Error allocating fields in response.");
65     return NULL;
66   }
67   if (req->orig_coi) {
68     if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
69       tr_crit("tids_create_response: Error allocating fields in response.");
70       return NULL;
71     }
72   }
73   return resp;
74 }
75
76 static void tids_destroy_response(TIDS_INSTANCE *tids, TID_RESP *resp) 
77 {
78   if (resp) {
79     if (resp->err_msg)
80       tr_free_name(resp->err_msg);
81     if (resp->rp_realm)
82       tr_free_name(resp->rp_realm);
83     if (resp->realm)
84       tr_free_name(resp->realm);
85     if (resp->comm)
86       tr_free_name(resp->comm);
87     if (resp->orig_coi)
88       tr_free_name(resp->orig_coi);
89     talloc_free(resp);
90   }
91 }
92
93 static int tids_listen (TIDS_INSTANCE *tids, int port) 
94 {
95     int rc = 0;
96     int conn = -1;
97     int optval = 1;
98
99     union {
100       struct sockaddr_storage storage;
101       struct sockaddr_in in4;
102     } addr;
103
104     struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
105
106     saddr->sin_port = htons (port);
107     saddr->sin_family = AF_INET;
108     saddr->sin_addr.s_addr = INADDR_ANY;
109
110     if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
111       return conn;
112
113     setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
114
115     if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
116       return rc;
117
118     if (0 > (rc = listen(conn, 512)))
119       return rc;
120
121     tr_debug("tids_listen: TID Server listening on port %d", port);
122     return conn;
123 }
124
125 /* returns EACCES if authorization is denied */
126 static int tids_auth_cb(gss_name_t clientName, gss_buffer_t displayName,
127                         void *data)
128 {
129   struct tids_instance *inst = (struct tids_instance *) data;
130   TR_NAME name ={(char *) displayName->value,
131                  displayName->length};
132   int result=0;
133
134   if (0!=inst->auth_handler(clientName, &name, inst->cookie)) {
135     tr_debug("tids_auth_cb: client '%.*s' denied authorization.", name.len, name.buf);
136     result=EACCES; /* denied */
137   }
138
139   return result;
140 }
141
142 /* returns 0 on authorization success, 1 on failure, or -1 in case of error */
143 static int tids_auth_connection (struct tids_instance *inst,
144                                  int conn, gss_ctx_id_t *gssctx)
145 {
146   int rc = 0;
147   int auth, autherr = 0;
148   gss_buffer_desc nameBuffer = {0, NULL};
149   char *name = 0;
150   int nameLen = 0;
151
152   nameLen = asprintf(&name, "trustidentity@%s", inst->hostname);
153   nameBuffer.length = nameLen;
154   nameBuffer.value = name;
155   
156   if (rc = gsscon_passive_authenticate(conn, nameBuffer, gssctx, tids_auth_cb, inst)) {
157     tr_debug("tids_auth_connection: Error from gsscon_passive_authenticate(), rc = %d.", rc);
158     return -1;
159   }
160
161   if (rc = gsscon_authorize(*gssctx, &auth, &autherr)) {
162     tr_debug("tids_auth_connection: Error from gsscon_authorize, rc = %d, autherr = %d.", 
163             rc, autherr);
164     return -1;
165   }
166
167   if (auth)
168     tr_debug("tids_auth_connection: Connection authenticated, conn = %d.", conn);
169   else
170     tr_debug("tids_auth_connection: Authentication failed, conn %d.", conn);
171
172   return !auth;
173 }
174
175 static int tids_read_request (TIDS_INSTANCE *tids, int conn, gss_ctx_id_t *gssctx, TR_MSG **mreq)
176 {
177   int err;
178   char *buf;
179   size_t buflen = 0;
180
181   if (err = gsscon_read_encrypted_token(conn, *gssctx, &buf, &buflen)) {
182     if (buf)
183       free(buf);
184     return -1;
185   }
186
187   tr_debug("tids_read_request():Request Received, %u bytes.", (unsigned) buflen);
188
189   /* Parse request */
190   if (NULL == ((*mreq) = tr_msg_decode(buf, buflen))) {
191     tr_debug("tids_read_request():Error decoding request.");
192     free (buf);
193     return -1;
194   }
195
196   /* If this isn't a TID Request, just drop it. */
197   if (TID_REQUEST != (*mreq)->msg_type) {
198     tr_debug("tids_read_request(): Not a TID Request, dropped.");
199     return -1;
200   }
201
202   free (buf);
203   return buflen;
204 }
205
206 static int tids_handle_request (TIDS_INSTANCE *tids, TR_MSG *mreq, TID_RESP *resp) 
207 {
208   int rc;
209
210   /* Check that this is a valid TID Request.  If not, send an error return. */
211   if ((!tr_msg_get_req(mreq)) ||
212       (!tr_msg_get_req(mreq)->rp_realm) ||
213       (!tr_msg_get_req(mreq)->realm) ||
214       (!tr_msg_get_req(mreq)->comm)) {
215     tr_notice("tids_handle_request(): Not a valid TID Request.");
216     resp->result = TID_ERROR;
217     resp->err_msg = tr_new_name("Bad request format");
218     return -1;
219   }
220
221   tid_req_add_path(tr_msg_get_req(mreq), tids->hostname, tids->tids_port);
222   
223   /* Call the caller's request handler */
224   /* TBD -- Handle different error returns/msgs */
225   if (0 > (rc = (*tids->req_handler)(tids, tr_msg_get_req(mreq), resp, tids->cookie))) {
226     /* set-up an error response */
227     resp->result = TID_ERROR;
228     if (!resp->err_msg) /* Use msg set by handler, if any */
229       resp->err_msg = tr_new_name("Internal processing error");
230   }
231   else {
232     /* set-up a success response */
233     resp->result = TID_SUCCESS;
234     resp->err_msg = NULL;       /* No error msg on successful return */
235   }
236     
237   return rc;
238 }
239
240 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
241   TID_RESP *resp = NULL;
242   int rc = 0;
243
244   /* If we already sent a response, don't send another no matter what. */
245   if (req->resp_sent)
246     return 0;
247
248   if (NULL == (resp = tids_create_response(tids, req))) {
249     tr_crit("tids_send_err_response: Can't create response.");
250     return -1;
251   }
252
253   
254   /* mark this as an error response, and include the error message */
255   resp->result = TID_ERROR;
256   resp->err_msg = tr_new_name((char *)err_msg);
257   resp->error_path = req->path;
258
259   rc = tids_send_response(tids, req, resp);
260   
261   tids_destroy_response(tids, resp);
262   return rc;
263 }
264
265 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
266 {
267   int err;
268   TR_MSG mresp;
269   char *resp_buf;
270
271   if ((!tids) || (!req) || (!resp))
272     tr_debug("tids_send_response: Invalid parameters.");
273
274   /* Never send a second response if we already sent one. */
275   if (req->resp_sent)
276     return 0;
277
278   mresp.msg_type = TID_RESPONSE;
279   tr_msg_set_resp(&mresp, resp);
280
281   if (NULL == (resp_buf = tr_msg_encode(&mresp))) {
282
283     fprintf(stderr, "tids_send_response: Error encoding json response.\n");
284     tr_audit_req(req);
285
286     return -1;
287   }
288
289   tr_debug("tids_send_response: Encoded response: %s", resp_buf);
290
291   /* If external logging is enabled, fire off a message */
292   /* TODO Can be moved to end once segfault in gsscon_write_encrypted_token fixed */
293   tr_audit_resp(resp);
294
295   /* Send the response over the connection */
296   if (err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf, 
297                                           strlen(resp_buf) + 1)) {
298     tr_notice("tids_send_response: Error sending response over connection.");
299
300     tr_audit_req(req);
301
302     return -1;
303   }
304
305   /* indicate that a response has been sent for this request */
306   req->resp_sent = 1;
307
308   free(resp_buf);
309
310   return 0;
311 }
312
313 static void tids_handle_connection (TIDS_INSTANCE *tids, int conn)
314 {
315   TR_MSG *mreq = NULL;
316   TID_RESP *resp = NULL;
317   int rc = 0;
318   gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
319
320   if (tids_auth_connection(tids, conn, &gssctx)) {
321     tr_notice("tids_handle_connection: Error authorizing TID Server connection.");
322     close(conn);
323     return;
324   }
325
326   tr_debug("tids_handle_connection: Connection authorized!");
327
328   while (1) {   /* continue until an error breaks us out */
329
330     if (0 > (rc = tids_read_request(tids, conn, &gssctx, &mreq))) {
331       tr_debug("tids_handle_connection: Error from tids_read_request(), rc = %d.", rc);
332       return;
333     } else if (0 == rc) {
334       continue;
335     }
336
337     /* Put connection information into the request structure */
338     tr_msg_get_req(mreq)->conn = conn;
339     tr_msg_get_req(mreq)->gssctx = gssctx;
340
341     /* Allocate a response structure and populate common fields */
342     if (NULL == (resp = tids_create_response (tids, tr_msg_get_req(mreq)))) {
343       tr_crit("tids_handle_connection: Error creating response structure.");
344       /* try to send an error */
345       tids_send_err_response(tids, tr_msg_get_req(mreq), "Error creating response.");
346       return;
347     }
348
349     if (0 > (rc = tids_handle_request(tids, mreq, resp))) {
350       tr_debug("tids_handle_connection: Error from tids_handle_request(), rc = %d.", rc);
351       /* Fall through, to send the response, either way */
352     }
353
354     if (0 > (rc = tids_send_response(tids, tr_msg_get_req(mreq), resp))) {
355       tr_debug("tids_handle_connection: Error from tids_send_response(), rc = %d.", rc);
356       /* if we didn't already send a response, try to send a generic error. */
357       if (!tr_msg_get_req(mreq)->resp_sent)
358         tids_send_err_response(tids, tr_msg_get_req(mreq), "Error sending response.");
359       /* Fall through to free the response, either way. */
360     }
361     
362     tids_destroy_response(tids, resp);
363     return;
364   } 
365 }
366
367 TIDS_INSTANCE *tids_create (void)
368 {
369   TIDS_INSTANCE *tids = NULL;
370   if (tids = malloc(sizeof(TIDS_INSTANCE)))
371     memset(tids, 0, sizeof(TIDS_INSTANCE));
372   return tids;
373 }
374
375 /* Process tids requests forever. Should not return except on error. */
376 int tids_start (TIDS_INSTANCE *tids, 
377                 TIDS_REQ_FUNC *req_handler,
378                 tids_auth_func *auth_handler,
379                 const char *hostname,
380                 unsigned int port,
381                 void *cookie)
382 {
383   int listen = -1;
384   int conn = -1;
385   pid_t pid;
386
387   tids->tids_port = port;
388   if (0 > (listen = tids_listen(tids, port)))
389     perror ("Error from tids_listen()");
390
391   /* store the caller's request handler & cookie */
392   tids->req_handler = req_handler;
393   tids->auth_handler = auth_handler;
394   tids->hostname = hostname;
395   tids->cookie = cookie;
396
397   tr_info("Trust Path Query Server starting on host %s:%d.", hostname, port);
398
399   while(1) {    /* accept incoming conns until we are stopped */
400
401     if (0 > (conn = accept(listen, NULL, NULL))) {
402       perror("Error from TIDS Server accept()");
403       return 1;
404     }
405
406     if (0 > (pid = fork())) {
407       perror("Error on fork()");
408       return 1;
409     }
410
411     if (pid == 0) {
412       close(listen);
413       tids_handle_connection(tids, conn);
414       close(conn);
415       exit(0); /* exit to kill forked child process */
416     } else {
417       close(conn);
418     }
419
420     /* clean up any processes that have completed */
421     while (waitpid(-1, 0, WNOHANG) > 0);
422   }
423
424   return 1;     /* should never get here, loops "forever" */
425 }
426
427 void tids_destroy (TIDS_INSTANCE *tids)
428 {
429   /* clean up logfiles */
430   tr_log_close();
431
432   if (tids)
433     free(tids);
434 }