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