Add orig_coi to the reponse, fix bugs with coi-to-apc conversion.
[trust_router.git] / tid / tids.c
1 /*
2  * Copyright (c) 2012, 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 <string.h>
38 #include <stdio.h>
39 #include <errno.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <jansson.h>
43
44 #include <trust_router/tid.h>
45 #include <gsscon.h>
46 #include <tr_msg.h>
47
48 static TID_RESP *tids_create_response (TIDS_INSTANCE *tids, TID_REQ *req) 
49 {
50   TID_RESP *resp;
51
52   if ((NULL == (resp = calloc(sizeof(TID_RESP), 1)))) {
53     fprintf(stderr, "tids_create_response: Error allocating response structure.\n");
54     return NULL;
55   }
56   
57   resp->result = TID_SUCCESS; /* presume success */
58   if ((NULL == (resp->rp_realm = tr_dup_name(req->rp_realm))) ||
59       (NULL == (resp->realm = tr_dup_name(req->realm))) ||
60       (NULL == (resp->comm = tr_dup_name(req->comm)))) {
61     fprintf(stderr, "tids_create_response: Error allocating fields in response.\n");
62     return NULL;
63   }
64   if (req->orig_coi) {
65     if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
66       fprintf(stderr, "tids_create_response: Error allocating fields in response.\n");
67       return NULL;
68     }
69   }
70   return resp;
71 }
72
73 static void tids_destroy_response(TIDS_INSTANCE *tids, TID_RESP *resp) 
74 {
75   if (resp) {
76     if (resp->err_msg)
77       tr_free_name(resp->err_msg);
78     if (resp->rp_realm)
79       tr_free_name(resp->rp_realm);
80     if (resp->realm)
81       tr_free_name(resp->realm);
82     if (resp->comm)
83       tr_free_name(resp->comm);
84     if (resp->orig_coi)
85       tr_free_name(resp->orig_coi);
86     free (resp);
87   }
88 }
89
90 static int tids_listen (TIDS_INSTANCE *tids, int port) 
91 {
92     int rc = 0;
93     int conn = -1;
94     union {
95       struct sockaddr_storage storage;
96       struct sockaddr_in in4;
97     } addr;
98     struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
99     
100     saddr->sin_port = htons (port);
101     saddr->sin_family = AF_INET;
102     saddr->sin_addr.s_addr = INADDR_ANY;
103
104     if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
105       return conn;
106         
107     if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
108       return rc;
109         
110     if (0 > (rc = listen(conn, 512)))
111       return rc;
112     
113     fprintf (stdout, "tids_listen: TID Server listening on port %d\n", port);
114     return conn; 
115 }
116
117 static int tids_auth_connection (int conn, gss_ctx_id_t *gssctx)
118 {
119   int rc = 0;
120   int auth, autherr = 0;
121
122   if (rc = gsscon_passive_authenticate(conn, gssctx)) {
123     fprintf(stderr, "tids_auth_connection: Error from gsscon_passive_authenticate(), rc = %d.\n", rc);
124     return -1;
125   }
126
127   if (rc = gsscon_authorize(*gssctx, &auth, &autherr)) {
128     fprintf(stderr, "tids_auth_connection: Error from gsscon_authorize, rc = %d, autherr = %d.\n", 
129             rc, autherr);
130     return -1;
131   }
132
133   if (auth)
134     fprintf(stdout, "tids_auth_connection: Connection authenticated, conn = %d.\n", conn);
135   else
136     fprintf(stderr, "tids_auth_connection: Authentication failed, conn %d.\n", 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   fprintf(stdout, "tids_read_request():Request Received, %u bytes.\n", (unsigned) buflen);
154
155   /* Parse request */
156   if (NULL == ((*mreq) = tr_msg_decode(buf, buflen))) {
157     fprintf(stderr, "tids_read_request():Error decoding request.\n");
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     fprintf(stderr, "tids_read_request(): Not a TID Request, dropped.\n");
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;
175
176   /* Check that this is a valid TID Request.  If not, send an error return. */
177   if ((!mreq->tid_req) ||
178       (!mreq->tid_req->rp_realm) ||
179       (!mreq->tid_req->realm) ||
180       (!mreq->tid_req->comm)) {
181     fprintf(stderr, "tids_handle_request():Not a valid TID Request.\n");
182     (*resp)->result = TID_ERROR;
183     (*resp)->err_msg = tr_new_name("Bad request format");
184     return -1;
185   }
186
187   /* Call the caller's request handler */
188   /* TBD -- Handle different error returns/msgs */
189   if (0 > (rc = (*tids->req_handler)(tids, mreq->tid_req, &(*resp), tids->cookie))) {
190     /* set-up an error response */
191     (*resp)->result = TID_ERROR;
192     if (!(*resp)->err_msg)      /* Use msg set by handler, if any */
193       (*resp)->err_msg = tr_new_name("Internal processing error");
194   }
195   else {
196     /* set-up a success response */
197     (*resp)->result = TID_SUCCESS;
198     (*resp)->err_msg = NULL;    /* No error msg on successful return */
199   }
200     
201   return rc;
202 }
203
204 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
205   TID_RESP *resp = NULL;
206   int rc = 0;
207
208   /* If we already sent a response, don't send another no matter what. */
209   if (req->resp_sent)
210     return 0;
211
212   if (NULL == (resp = tids_create_response(tids, req))) {
213     fprintf(stderr, "tids_send_err_response: Can't create response.\n");
214     return -1;
215   }
216
217   /* mark this as an error response, and include the error message */
218   resp->result = TID_ERROR;
219   resp->err_msg = tr_new_name((char *)err_msg);
220
221   rc = tids_send_response(tids, req, resp);
222   
223   tids_destroy_response(tids, resp);
224   return rc;
225 }
226
227 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
228 {
229   int err;
230   TR_MSG mresp;
231   char *resp_buf;
232
233   if ((!tids) || (!req) || (!resp))
234     fprintf (stderr, "tids_send_response: Invalid parameters.\n");
235
236   /* Never send a second response if we already sent one. */
237   if (req->resp_sent)
238     return 0;
239
240   mresp.msg_type = TID_RESPONSE;
241   mresp.tid_resp = resp;
242   
243   if (NULL == (resp_buf = tr_msg_encode(&mresp))) {
244     fprintf(stderr, "tids_send_response: Error encoding json response.\n");
245     return -1;
246   }
247
248   fprintf(stderr, "tids_send_response: Encoded response:\n%s\n", resp_buf);
249   
250   /* Send the response over the connection */
251   if (err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf, 
252                                           strlen(resp_buf) + 1)) {
253     fprintf(stderr, "tids_send_response: Error sending response over connection.\n");
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 static void tids_handle_connection (TIDS_INSTANCE *tids, int conn)
266 {
267   TR_MSG *mreq = NULL;
268   TID_RESP *resp = NULL;
269   int rc = 0;
270   gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
271
272   if (tids_auth_connection(conn, &gssctx)) {
273     fprintf(stderr, "tids_handle_connection: Error authorizing TID Server connection.\n");
274     close(conn);
275     return;
276   }
277
278   fprintf(stdout, "tids_handle_connection: Connection authorized!\n");
279
280   while (1) {   /* continue until an error breaks us out */
281
282     if (0 > (rc = tids_read_request(tids, conn, &gssctx, &mreq))) {
283       fprintf(stderr, "tids_handle_connection: Error from tids_read_request(), rc = %d.\n", rc);
284       return;
285     } else if (0 == rc) {
286       continue;
287     }
288
289     /* Put connection information into the request structure */
290     mreq->tid_req->conn = conn;
291     mreq->tid_req->gssctx = gssctx;
292
293     /* Allocate a response structure and populate common fields */
294     if (NULL == (resp = tids_create_response (tids, mreq->tid_req))) {
295       fprintf(stderr, "tids_handle_connection: Error creating response structure.\n");
296       /* try to send an error */
297       tids_send_err_response(tids, mreq->tid_req, "Error creating response.\n");
298       return;
299     }
300
301     if (0 > (rc = tids_handle_request(tids, mreq, &resp))) {
302       fprintf(stderr, "tids_handle_connection: Error from tids_handle_request(), rc = %d.\n", rc);
303       /* Fall through, to send the response, either way */
304     }
305
306     if (0 > (rc = tids_send_response(tids, mreq->tid_req, resp))) {
307       fprintf(stderr, "tids_handle_connection: Error from tids_send_response(), rc = %d.\n", rc);
308       /* if we didn't already send a response, try to send a generic error. */
309       if (!mreq->tid_req->resp_sent)
310         tids_send_err_response(tids, mreq->tid_req, "Error sending response.\n");
311       /* Fall through to free the response, either way. */
312     }
313     
314     tids_destroy_response(tids, resp);
315     return;
316   } 
317 }
318
319 TIDS_INSTANCE *tids_create (void)
320 {
321   TIDS_INSTANCE *tids = NULL;
322   if (tids = malloc(sizeof(TIDS_INSTANCE)))
323     memset(tids, 0, sizeof(TIDS_INSTANCE));
324   return tids;
325 }
326
327 int tids_start (TIDS_INSTANCE *tids, 
328                 TIDS_REQ_FUNC *req_handler,
329                 void *cookie)
330 {
331   int listen = -1;
332   int conn = -1;
333   pid_t pid;
334   int optval = 1;
335
336   if (0 > (listen = tids_listen(tids, TID_PORT)))
337     perror ("Error from tids_listen()");
338
339   setsockopt(listen, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
340
341   /* store the caller's request handler & cookie */
342   tids->req_handler = req_handler;
343   tids->cookie = cookie;
344
345   while(1) {    /* accept incoming conns until we are stopped */
346
347     if (0 > (conn = accept(listen, NULL, NULL))) {
348       perror("Error from TIDS Server accept()");
349       return 1;
350     }
351
352     if (0 > (pid = fork())) {
353       perror("Error on fork()");
354       return 1;
355     }
356
357     if (pid == 0) {
358       close(listen);
359       tids_handle_connection(tids, conn);
360       close(conn);
361       exit(0);
362     } else {
363       close(conn);
364     }
365   }
366
367   return 1;     /* should never get here */
368 }
369
370 void tids_destroy (TIDS_INSTANCE *tids)
371 {
372   if (tids)
373     free(tids);
374 }
375
376