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