Add TRP handling events, plus change to cfg layout.
[trust_router.git] / tid / example / tids_main.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 <stdio.h>
36 #include <string.h>
37 #include <stdlib.h>
38 #include <talloc.h>
39 #include <sqlite3.h>
40 #include <argp.h>
41 #include <poll.h>
42
43 #include <tr_debug.h>
44 #include <tid_internal.h>
45 #include <trust_router/tr_constraint.h>
46 #include <trust_router/tr_dh.h>
47 #include <openssl/rand.h>
48
49 static sqlite3 *db = NULL;
50 static sqlite3_stmt *insert_stmt = NULL;
51 static sqlite3_stmt *authorization_insert = NULL;
52
53 static int  create_key_id(char *out_id, size_t len)
54 {
55   unsigned char rand_buf[32];
56   size_t bin_len;
57   if (len <8)
58     return -1;
59   strncpy(out_id, "key-", len);
60   len -= 4;
61   out_id += 4;
62   if (sizeof(rand_buf)*2+1 < len)
63     len = sizeof(rand_buf)*2 + 1;
64   bin_len = (len-1)/2;
65   if (-1 == RAND_pseudo_bytes(rand_buf, bin_len))
66       return -1;
67   tr_bin_to_hex(rand_buf, bin_len, out_id, len);
68   out_id[bin_len*2] = '\0';
69   return 0;
70 }
71
72 static int sqlify_wc(
73                      TID_REQ *req,
74                      const char **wc,
75                      size_t len,
76                      char **error)
77 {
78   size_t lc;
79   *error = NULL;
80   for (lc = 0; lc < len; lc++) {
81     if (strchr(wc[lc], '%')) {
82       *error = talloc_asprintf( req, "Constraint match `%s' is not appropriate for SQL",
83                                   wc[lc]);
84       return -1;
85     }
86     if ('*' ==wc[lc][0]) {
87       char *s;
88       s = talloc_strdup(req, wc[lc]);
89       s[0] = '%';
90       wc[lc] = s;
91     }
92   }
93   return 0;
94 }
95
96         
97
98 static int handle_authorizations(TID_REQ *req, const unsigned char *dh_hash,
99                                  size_t hash_len)
100 {
101   TR_CONSTRAINT_SET *intersected = NULL;
102   const char **domain_wc, **realm_wc;
103   size_t domain_len, realm_len;
104   size_t domain_index, realm_index;
105   char *error;
106   int sqlite3_result;
107
108   if (!req->cons) {
109     tr_debug("Request has no constraints, so no authorizations.");
110     return 0;
111   }
112   intersected = tr_constraint_set_intersect(req, req->cons);
113   if (!intersected)
114     return -1;
115   if (0 != tr_constraint_set_get_match_strings(req,
116                                                intersected, "domain",
117                                                &domain_wc, &domain_len))
118     return -1;
119   if (0 != tr_constraint_set_get_match_strings(req,
120                                                intersected, "realm",
121                                                &realm_wc, &realm_len))
122     return -1;
123   tr_debug(" %u domain constraint matches and %u realm constraint matches",
124            (unsigned) domain_len, (unsigned) realm_len);
125   if (0 != sqlify_wc(req, domain_wc, domain_len, &error)) {
126     tr_debug("Processing domain constraints: %s", error);
127     return -1;
128   }else if (0 != sqlify_wc(req, realm_wc, realm_len, &error)) {
129     tr_debug("Processing realm constraints: %s", error);
130     return -1;
131   }
132   if (!authorization_insert) {
133     tr_debug( " No database, no authorizations inserted");
134     return 0;
135   }
136   for (domain_index = 0; domain_index < domain_len; domain_index++)
137     for (realm_index = 0; realm_index < realm_len; realm_index++) {
138       TR_NAME *community = req->orig_coi;
139       if (!community)
140         community = req->comm;
141       sqlite3_bind_blob(authorization_insert, 1, dh_hash, hash_len, SQLITE_TRANSIENT);
142       sqlite3_bind_text(authorization_insert, 2, community->buf, community->len, SQLITE_TRANSIENT);
143       sqlite3_bind_text(authorization_insert, 3, realm_wc[realm_index], -1, SQLITE_TRANSIENT);
144       sqlite3_bind_text(authorization_insert, 4, domain_wc[domain_index], -1, SQLITE_TRANSIENT);
145       sqlite3_bind_text(authorization_insert, 5, req->comm->buf, req->comm->len, SQLITE_TRANSIENT);
146       sqlite3_result = sqlite3_step(authorization_insert);
147       if (SQLITE_DONE != sqlite3_result)
148         tr_crit("sqlite3: failed to write to database");
149       sqlite3_reset(authorization_insert);
150     }
151   return 0;
152 }
153
154
155 static int tids_req_handler (TIDS_INSTANCE *tids,
156                       TID_REQ *req, 
157                       TID_RESP *resp,
158                       void *cookie)
159 {
160   unsigned char *s_keybuf = NULL;
161   int s_keylen = 0;
162   char key_id[12];
163   unsigned char *pub_digest;
164   size_t pub_digest_len;
165   
166
167   tr_debug("tids_req_handler: Request received! target_realm = %s, community = %s", req->realm->buf, req->comm->buf);
168   if (tids)
169     tids->req_count++;
170
171   if (!(resp) || !resp) {
172     tr_debug("tids_req_handler: No response structure.");
173     return -1;
174   }
175
176
177   /* Allocate a new server block */
178   if (NULL == (resp->servers = talloc_zero(resp, TID_SRVR_BLK))){
179     tr_crit("tids_req_handler(): malloc failed.");
180     return -1;
181   }
182
183   resp->num_servers = 1;
184
185   /* TBD -- Set up the server IP Address */
186
187   if (!(req) || !(req->tidc_dh)) {
188     tr_debug("tids_req_handler(): No client DH info.");
189     return -1;
190   }
191
192   if ((!req->tidc_dh->p) || (!req->tidc_dh->g)) {
193     tr_debug("tids_req_handler: NULL dh values.");
194     return -1;
195   }
196
197   /* Generate the server DH block based on the client DH block */
198   // fprintf(stderr, "Generating the server DH block.\n");
199   // fprintf(stderr, "...from client DH block, dh_g = %s, dh_p = %s.\n", BN_bn2hex(req->tidc_dh->g), BN_bn2hex(req->tidc_dh->p));
200
201   if (NULL == (resp->servers->aaa_server_dh = tr_create_matching_dh(NULL, 0, req->tidc_dh))) {
202     tr_debug("tids_req_handler: Can't create server DH params.");
203     return -1;
204   }
205
206   if (0 == inet_aton(tids->ipaddr, &(resp->servers->aaa_server_addr))) {
207     tr_debug("tids_req_handler: inet_aton() failed.");
208     return -1;
209   }
210
211   /* Set the key name */
212   if (-1 == create_key_id(key_id, sizeof(key_id)))
213     return -1;
214   resp->servers->key_name = tr_new_name(key_id);
215
216   /* Generate the server key */
217   // fprintf(stderr, "Generating the server key.\n");
218
219   if (0 > (s_keylen = tr_compute_dh_key(&s_keybuf, 
220                                         req->tidc_dh->pub_key, 
221                                         resp->servers->aaa_server_dh))) {
222     tr_debug("tids_req_handler: Key computation failed.");
223     return -1;
224   }
225   if (0 != tr_dh_pub_hash(req,
226                           &pub_digest, &pub_digest_len)) {
227     tr_debug("tids_req_handler: Unable to digest client public key");
228     return -1;
229   }
230   if (0 != handle_authorizations(req, pub_digest, pub_digest_len))
231     return -1;
232   resp->servers->path = req->path;
233   if (req->expiration_interval < 1)
234     req->expiration_interval = 1;
235   g_get_current_time(&resp->servers->key_expiration);
236   resp->servers->key_expiration.tv_sec += req->expiration_interval * 60 /*in minutes*/;
237
238   if (NULL != insert_stmt) {
239     int sqlite3_result;
240     gchar *expiration_str = g_time_val_to_iso8601(&resp->servers->key_expiration);
241         sqlite3_bind_text(insert_stmt, 1, key_id, -1, SQLITE_TRANSIENT);
242     sqlite3_bind_blob(insert_stmt, 2, s_keybuf, s_keylen, SQLITE_TRANSIENT);
243     sqlite3_bind_blob(insert_stmt, 3, pub_digest, pub_digest_len, SQLITE_TRANSIENT);
244         sqlite3_bind_text(insert_stmt, 4, expiration_str, -1, SQLITE_TRANSIENT);
245     sqlite3_result = sqlite3_step(insert_stmt);
246     if (SQLITE_DONE != sqlite3_result)
247       tr_crit("sqlite3: failed to write to database");
248     sqlite3_reset(insert_stmt);
249   }
250   
251   /* Print out the key. */
252   // fprintf(stderr, "tids_req_handler(): Server Key Generated (len = %d):\n", s_keylen);
253   // for (i = 0; i < s_keylen; i++) {
254   // fprintf(stderr, "%x", s_keybuf[i]); 
255   // }
256   // fprintf(stderr, "\n");
257
258   return s_keylen;
259 }
260
261 static int auth_handler(gss_name_t gss_name, TR_NAME *client,
262                         void *expected_client)
263 {
264   TR_NAME *expected_client_trname = (TR_NAME*) expected_client;
265   int result=tr_name_cmp(client, expected_client_trname);
266   if (result != 0) {
267     tr_notice("Auth denied for incorrect gss-name ('%.*s' requested, expected '%.*s').",
268               client->len, client->buf,
269               expected_client_trname->len, expected_client_trname->buf);
270   }
271   return result;
272 }
273
274 /* command-line option setup */
275
276 /* argp global parameters */
277 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
278
279 /* doc strings */
280 static const char doc[]=PACKAGE_NAME " - TID Server";
281 static const char arg_doc[]="<ip-address> <gss-name> <hostname> <database-name>"; /* string describing arguments, if any */
282
283 /* define the options here. Fields are:
284  * { long-name, short-name, variable name, options, help description } */
285 static const struct argp_option cmdline_options[] = {
286   { NULL }
287 };
288
289 /* structure for communicating with option parser */
290 struct cmdline_args {
291   char *ip_address;
292   char *gss_name;
293   char *hostname;
294   char *database_name;
295 };
296
297 /* parser for individual options - fills in a struct cmdline_args */
298 static error_t parse_option(int key, char *arg, struct argp_state *state)
299 {
300   /* get a shorthand to the command line argument structure, part of state */
301   struct cmdline_args *arguments=state->input;
302
303   switch (key) {
304   case ARGP_KEY_ARG: /* handle argument (not option) */
305     switch (state->arg_num) {
306     case 0:
307       arguments->ip_address=arg;
308       break;
309
310     case 1:
311       arguments->gss_name=arg;
312       break;
313
314     case 2:
315       arguments->hostname=arg;
316       break;
317
318     case 3:
319       arguments->database_name=arg;
320       break;
321
322     default:
323       /* too many arguments */
324       argp_usage(state);
325     }
326     break;
327
328   case ARGP_KEY_END: /* no more arguments */
329     if (state->arg_num < 4) {
330       /* not enough arguments encountered */
331       argp_usage(state);
332     }
333     break;
334
335   default:
336     return ARGP_ERR_UNKNOWN;
337   }
338
339   return 0; /* success */
340 }
341
342 /* assemble the argp parser */
343 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc};
344
345 int main (int argc, 
346           char *argv[]) 
347 {
348   TIDS_INSTANCE *tids;
349   TR_NAME *gssname = NULL;
350   struct cmdline_args opts={NULL};
351   int tids_socket=-1;
352   struct pollfd *poll_fds=NULL;
353
354   /* parse the command line*/
355   argp_parse(&argp, argc, argv, 0, 0, &opts);
356
357   talloc_set_log_stderr();
358
359   /* Use standalone logging */
360   tr_log_open();
361
362   /* set logging levels */
363   tr_log_threshold(LOG_CRIT);
364   tr_console_threshold(LOG_DEBUG);
365
366   gssname = tr_new_name(opts.gss_name);
367   if (SQLITE_OK != sqlite3_open(opts.database_name, &db)) {
368     tr_crit("Error opening database %s", opts.database_name);
369     exit(1);
370   }
371   sqlite3_busy_timeout( db, 1000);
372   sqlite3_prepare_v2(db, "insert into psk_keys_tab (keyid, key, client_dh_pub, key_expiration) values(?, ?, ?, ?)",
373                      -1, &insert_stmt, NULL);
374   sqlite3_prepare_v2(db, "insert into authorizations (client_dh_pub, coi, acceptor_realm, hostname, apc) values(?, ?, ?, ?, ?)",
375                      -1, &authorization_insert, NULL);
376
377   /* Create a TID server instance */
378   if (NULL == (tids = tids_create(NULL))) {
379     tr_crit("Unable to create TIDS instance, exiting.");
380     return 1;
381   }
382
383   tids->ipaddr = opts.ip_address;
384
385   /* get listener for tids port */
386   tids_socket = tids_get_listener(tids, &tids_req_handler , auth_handler, opts.hostname, TID_PORT, gssname);
387
388   poll_fds=malloc(sizeof(*poll_fds));
389   if (poll_fds == NULL) {
390     tr_crit("Could not allocate event polling list, exiting.");
391     return 1;
392   }
393
394   poll_fds[0].fd=tids_socket;
395   poll_fds[0].events=POLLIN; /* poll on ready for reading */
396   poll_fds[0].revents=0; 
397
398   /* main event loop */
399   while (1) {
400     /* wait up to 100 ms for an event, then handle any idle work */
401     if(poll(poll_fds, 1, 100) > 0) {
402       if (poll_fds[0].revents & POLLIN) {
403         if (0 != tids_accept(tids, tids_socket)) {
404           tr_err("Error handling tids request.");
405         }
406       }
407     }
408     /* idle loop stuff here */
409   }
410
411   /* Clean-up the TID server instance */
412   tids_destroy(tids);
413
414   return 1;
415 }
416