Validate internal configuration more thoroughly
[trust_router.git] / common / tr_config.c
1 /*
2  * Copyright (c) 2012-2018, 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 <string.h>
37 #include <jansson.h>
38 #include <dirent.h>
39 #include <talloc.h>
40
41 #include <tr_cfgwatch.h>
42 #include <tr_comm.h>
43 #include <tr_config.h>
44 #include <tr_gss_names.h>
45 #include <tr_debug.h>
46 #include <tr_filter.h>
47 #include <trust_router/tr_constraint.h>
48 #include <tr_idp.h>
49 #include <tr.h>
50 #include <trust_router/trp.h>
51
52 #if JANSSON_VERSION_HEX < 0x020500
53 #include "jansson_iterators.h"
54 #endif
55
56 void tr_print_config (TR_CFG *cfg) {
57   tr_notice("tr_print_config: Logging running trust router configuration.");
58   tr_print_comms(cfg->ctable);
59 }
60
61 void tr_print_comms (TR_COMM_TABLE *ctab)
62 {
63   TR_COMM *comm = NULL;
64
65   for (comm = ctab->comms; NULL != comm; comm = comm->next) {
66     tr_notice("tr_print_config: Community %s:", comm->id->buf);
67
68     tr_notice("tr_print_config:  - Member IdPs:");
69     tr_print_comm_idps(ctab, comm);
70
71     tr_notice("tr_print_config:  - Member RPs:");
72     tr_print_comm_rps(ctab, comm);
73   }
74 }
75
76 void tr_print_comm_idps(TR_COMM_TABLE *ctab, TR_COMM *comm)
77 {
78   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
79   TR_COMM_ITER *iter=NULL;
80   TR_IDP_REALM *idp = NULL;
81   char *s=NULL;
82
83   iter=tr_comm_iter_new(tmp_ctx);
84   if (iter==NULL) {
85     tr_notice("tr_print_config: unable to allocate IdP iterator.");
86     talloc_free(tmp_ctx);
87     return;
88   }
89   
90   for (idp=tr_idp_realm_iter_first(iter, ctab, tr_comm_get_id(comm));
91        NULL!=idp;
92        idp=tr_idp_realm_iter_next(iter)) {
93     s=tr_idp_realm_to_str(tmp_ctx, idp);
94     if (s!=NULL)
95       tr_notice("tr_print_config:    - @%s", s);
96     else
97       tr_notice("tr_print_config: unable to allocate IdP output string.");
98   }
99   talloc_free(tmp_ctx);
100 }
101
102 void tr_print_comm_rps(TR_COMM_TABLE *ctab, TR_COMM *comm)
103 {
104   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
105   TR_COMM_ITER *iter=NULL;
106   TR_RP_REALM *rp = NULL;
107   char *s=NULL;
108
109   iter=tr_comm_iter_new(tmp_ctx);
110   if (iter==NULL) {
111     tr_notice("tr_print_config: unable to allocate RP iterator.");
112     talloc_free(tmp_ctx);
113     return;
114   }
115   
116   for (rp=tr_rp_realm_iter_first(iter, ctab, tr_comm_get_id(comm));
117        NULL!=rp;
118        rp=tr_rp_realm_iter_next(iter)) {
119     s=tr_rp_realm_to_str(tmp_ctx, rp);
120     if (s!=NULL)
121       tr_notice("tr_print_config:    - @%s", s);
122     else
123       tr_notice("tr_print_config: unable to allocate RP output string.");
124   }
125   talloc_free(tmp_ctx);
126 }
127
128 static int tr_cfg_destructor(void *object)
129 {
130   TR_CFG *cfg = talloc_get_type_abort(object, TR_CFG);
131   if (cfg->files)
132     g_array_unref(cfg->files);
133   return 0;
134 }
135 TR_CFG *tr_cfg_new(TALLOC_CTX *mem_ctx)
136 {
137   TR_CFG *cfg=talloc(mem_ctx, TR_CFG);
138   if (cfg!=NULL) {
139     cfg->internal=NULL;
140     cfg->rp_clients=NULL;
141     cfg->peers=NULL;
142     cfg->default_servers=NULL;
143     cfg->ctable=tr_comm_table_new(cfg);
144     if (cfg->ctable==NULL) {
145       talloc_free(cfg);
146       return NULL;
147     }
148     cfg->files = g_array_new(FALSE, FALSE, sizeof(TR_CFG_FILE));
149     if (cfg->files == NULL) {
150       talloc_free(cfg);
151       return NULL;
152     }
153     talloc_set_destructor((void *)cfg, tr_cfg_destructor);
154   }
155   return cfg;
156 }
157
158 void tr_cfg_free (TR_CFG *cfg)
159 {
160   talloc_free(cfg);
161 }
162
163 TR_CFG_MGR *tr_cfg_mgr_new(TALLOC_CTX *mem_ctx)
164 {
165   return talloc_zero(mem_ctx, TR_CFG_MGR);
166 }
167
168 void tr_cfg_mgr_free (TR_CFG_MGR *cfg_mgr) {
169   talloc_free(cfg_mgr);
170 }
171
172 TR_CFG_RC tr_apply_new_config (TR_CFG_MGR *cfg_mgr)
173 {
174   /* cfg_mgr->active is allowed to be null, but new cannot be */
175   if ((cfg_mgr==NULL) || (cfg_mgr->new==NULL))
176     return TR_CFG_BAD_PARAMS;
177
178   if (cfg_mgr->active != NULL)
179     tr_cfg_free(cfg_mgr->active);
180
181   cfg_mgr->active = cfg_mgr->new;
182   cfg_mgr->new=NULL; /* only keep a single handle on the new configuration */
183
184   tr_log_threshold(cfg_mgr->active->internal->log_threshold);
185   tr_console_threshold(cfg_mgr->active->internal->console_threshold);
186
187   return TR_CFG_SUCCESS;
188 }
189
190
191 TR_CFG_RC tr_cfg_validate(TR_CFG *trc)
192 {
193   TR_CFG_RC rc = TR_CFG_SUCCESS;
194
195   if (!trc)
196     return TR_CFG_BAD_PARAMS;
197
198   /* validate the internal config - error messages will be generated there, so don't genreate
199    * our own */
200   if (tr_cfg_validate_internal(trc->internal) != TR_CFG_SUCCESS)
201     rc = TR_CFG_ERROR;
202
203   if (NULL == trc->rp_clients) {
204     tr_debug("tr_cfg_validate: Error: No RP Clients configured");
205     rc = TR_CFG_ERROR;
206   }
207
208   if (0==tr_comm_table_size(trc->ctable)) {
209     tr_debug("tr_cfg_validate: Error: No Communities configured");
210     rc = TR_CFG_ERROR;
211   }
212
213   if ((NULL == trc->default_servers) && (NULL == trc->ctable->idp_realms)) {
214     tr_debug("tr_cfg_validate: Error: No default servers or IDPs configured.");
215     rc = TR_CFG_ERROR;
216   }
217   
218   return rc;
219 }
220
221 static void tr_cfg_log_json_error(const char *label, json_error_t *rc)
222 {
223   tr_debug("%s: JSON parse error on line %d: %s",
224            label,
225            rc->line,
226            rc->text);
227 }
228
229 /**
230  * Parse a config file and return its JSON structure. Also emits a serial number to the log
231  * if one is present.
232  *
233  * @param file_with_path The file (with path!) to parse
234  * @return Pointer to the result of parsing, or null on error
235  */
236 static json_t *tr_cfg_parse_one_config_file(const char *file_with_path)
237 {
238   json_t *jcfg=NULL;
239   json_error_t rc;
240
241   if (NULL==(jcfg=json_load_file(file_with_path, 
242                                  JSON_DISABLE_EOF_CHECK|JSON_REJECT_DUPLICATES, &rc))) {
243     tr_debug("tr_cfg_parse_one_config_file: Error parsing config file %s.", 
244              file_with_path);
245     tr_cfg_log_json_error("tr_cfg_parse_one_config_file", &rc);
246     return NULL;
247   }
248
249   return jcfg;
250 }
251
252 /* extract serial number */
253 static json_int_t get_cfg_serial(json_t *jcfg)
254 {
255   json_t *jser=NULL;
256
257   if (NULL != (jser = json_object_get(jcfg, "serial_number"))) {
258     if (json_is_integer(jser)) {
259       return json_integer_value(jser);
260     }
261   }
262   return TR_CFG_INVALID_SERIAL;
263 }
264
265 /**
266  * Helper to free an array returned by tr_cfg_parse_config_files
267  * @param n_jcfgs
268  * @param jcfgs
269  */
270 static void tr_cfg_parse_free_jcfgs(unsigned int n_jcfgs, json_t **jcfgs)
271 {
272   int ii=0;
273   for (ii=0; ii<n_jcfgs; ii++)
274     json_decref(jcfgs[ii]);
275   talloc_free(jcfgs);
276 }
277
278 /**
279  * Parse a list of configuration files. Returns an array of JSON objects, free this with
280  * tr_cfg_parse_free_jcfgs(), a helper function
281  *
282  * @param config_dir
283  * @param n_files
284  * @param cfg_files
285  * @return
286  */
287 static json_t **tr_cfg_parse_config_files(TALLOC_CTX *mem_ctx, unsigned int n_files, GArray *files)
288 {
289   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
290   unsigned int ii=0;
291   json_t **jcfgs=NULL;
292   TR_CFG_FILE *this_file = NULL;
293
294   /* first allocate the jcfgs */
295   jcfgs=talloc_array(NULL, json_t *, n_files);
296   if (jcfgs==NULL) {
297     tr_crit("tr_parse_config_files: cannot allocate JSON structure array");
298     goto cleanup;
299   }
300   for (ii=0; ii<n_files; ii++) {
301     this_file = &g_array_index(files, TR_CFG_FILE, ii);
302     jcfgs[ii]=tr_cfg_parse_one_config_file(this_file->name);
303     if (jcfgs[ii]==NULL) {
304       tr_err("tr_parse_config: Error parsing JSON in %s", this_file->name);
305       tr_cfg_parse_free_jcfgs(ii, jcfgs); /* frees the JSON objects and the jcfgs array */
306       jcfgs=NULL;
307       goto cleanup;
308     }
309
310     this_file->serial = get_cfg_serial(jcfgs[ii]);
311     if (this_file->serial != TR_CFG_INVALID_SERIAL) {
312       tr_notice("tr_parse_config_files: Attempting to load revision %"
313                     JSON_INTEGER_FORMAT
314                     " of '%s'.",
315                 this_file->serial,
316                 this_file->name);
317     } else {
318       tr_notice("tr_parse_config_files: Attempting to load '%s'.",
319                 this_file->name);
320     }
321   }
322
323 cleanup:
324   if (jcfgs)
325     talloc_steal(mem_ctx, jcfgs); /* give this to the caller's context if we succeeded */
326   talloc_free(tmp_ctx);
327   return jcfgs;
328 }
329
330 /* define a type for config parse functions */
331 typedef TR_CFG_RC (TR_CFG_PARSE_FN)(TR_CFG *, json_t *);
332 /**
333  * Helper function to parse a collection of JSON structures using a generic parse function.
334  *
335  * @param cfg Config structure to receive results
336  * @param parse_fn Function to apply
337  * @param n_jcfg Number of JSON structures in the array
338  * @param jcfgs Pointer to an array of decoded JSON structures
339  * @param key Key to extract from each jcfg before parsing, or NULL to use the object itself
340  * @return TR_CFG_SUCCESS on success, _FAIL or an error code on failure
341  */
342 static TR_CFG_RC tr_cfg_parse_helper(TR_CFG *cfg,
343                                      TR_CFG_PARSE_FN parse_fn,
344                                      unsigned int n_jcfg,
345                                      json_t **jcfgs,
346                                      const char *key)
347 {
348   size_t ii=0;
349   json_t *this_jcfg=NULL;
350   TR_CFG_RC ret=TR_CFG_ERROR;
351
352   if ((cfg==NULL) || (jcfgs==NULL) || (parse_fn==NULL))
353     return TR_CFG_ERROR;
354
355   for (ii=0; ii<n_jcfg; ii++) {
356     if (key)
357       this_jcfg = json_object_get(jcfgs[ii], key);
358     else
359       this_jcfg = jcfgs[ii];
360
361     /* do not try to parse a missing jcfg */
362     if (this_jcfg == NULL)
363       continue;
364
365     ret=parse_fn(cfg, this_jcfg);
366     if (ret!=TR_CFG_SUCCESS)
367       break;
368   }
369   return ret;
370 }
371
372 static void add_files(TR_CFG *cfg, unsigned int n, char **filenames)
373 {
374   TR_CFG_FILE frec = {0};
375
376   while ((n--) > 0) {
377     frec.name = talloc_strdup(cfg, filenames[n]);
378     frec.serial = TR_CFG_INVALID_SERIAL;
379
380     g_array_append_val(cfg->files, frec);
381   }
382 }
383
384 /**
385  *  Read a list of configuration files
386  *
387  * @param cfg_mgr Configuration manager
388  * @param n_files Number of entries in cfg_files
389  * @param files_with_paths Array of filenames with path to load
390  * @return TR_CFG_SUCCESS on success, TR_CFG_ERROR or a more specific error on failure
391  */
392 TR_CFG_RC tr_parse_config(TR_CFG_MGR *cfg_mgr, unsigned int n_files, char **files_with_paths)
393 {
394   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
395   json_t **jcfgs=NULL;
396   TR_CFG_RC cfg_rc=TR_CFG_ERROR;
397
398   if ((!cfg_mgr) || (!files_with_paths)) {
399     cfg_rc=TR_CFG_BAD_PARAMS;
400     goto cleanup;
401   }
402
403   /* get a fresh config to fill in, freeing old one if needed */
404   if (cfg_mgr->new != NULL)
405     tr_cfg_free(cfg_mgr->new);
406   cfg_mgr->new=tr_cfg_new(tmp_ctx); /* belongs to the temporary context for now */
407   if (cfg_mgr->new == NULL) {
408     cfg_rc=TR_CFG_NOMEM;
409     goto cleanup;
410   }
411
412   /* add the list of files to the config */
413   add_files(cfg_mgr->new, n_files, files_with_paths);
414
415   /* first parse the json */
416   jcfgs=tr_cfg_parse_config_files(tmp_ctx, n_files, cfg_mgr->new->files);
417   if (jcfgs==NULL) {
418     cfg_rc=TR_CFG_NOPARSE;
419     goto cleanup;
420   }
421
422   cfg_mgr->new->peers=trp_ptable_new(cfg_mgr); /* not sure why this isn't in cfg_mgr->new's context */
423
424   /* now run through the parsers on the JSON */
425   if ((TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_internal, n_files, jcfgs, "tr_internal"))) ||
426       (TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_local_orgs, n_files, jcfgs, NULL))) ||
427       (TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_peer_orgs, n_files, jcfgs, NULL))) ||
428       (TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_default_servers, n_files, jcfgs,
429                                                       NULL))) ||
430       (TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_comms, n_files, jcfgs, NULL))))
431     goto cleanup; /* cfg_rc was set above */
432
433   /* make sure we got a complete, consistent configuration */
434   if (TR_CFG_SUCCESS != tr_cfg_validate(cfg_mgr->new)) {
435     tr_err("tr_parse_config: Error: INVALID CONFIGURATION");
436     cfg_rc=TR_CFG_ERROR;
437     goto cleanup;
438   }
439
440   /* success! */
441   talloc_steal(cfg_mgr, cfg_mgr->new); /* hand this over to the cfg_mgr context */
442   cfg_rc=TR_CFG_SUCCESS;
443
444 cleanup:
445   if (jcfgs!=NULL)
446     tr_cfg_parse_free_jcfgs(n_files, jcfgs);
447   talloc_free(tmp_ctx);
448   return cfg_rc;
449 }
450
451 static int is_cfg_file(const struct dirent *dent) {
452   size_t n;
453
454   /* Only accept filenames ending in ".cfg" and starting with a character
455    * other than an ASCII '.' */
456
457   /* filename must be at least 4 characters long to be acceptable */
458   n=strlen(dent->d_name);
459   if (n < 4) {
460     return 0;
461   }
462
463   /* filename must not start with '.' */
464   if ('.' == dent->d_name[0]) {
465     return 0;
466   }
467
468   /* If the above passed and the last four characters of the filename are .cfg, accept.
469    * (n.b., assumes an earlier test checked that the name is >= 4 chars long.) */
470   if (0 == strcmp(&(dent->d_name[n-4]), ".cfg")) {
471     return 1;
472   }
473
474   /* otherwise, return false. */
475   return 0;
476 }
477
478 /* Find configuration files in a particular directory. Returns the
479  * number of entries found, 0 if none are found, or <0 for some
480  * errors. If n>=0, the cfg_files parameter will contain a newly
481  * allocated array of pointers to struct dirent entries, as returned
482  * by scandir(). These can be freed with tr_free_config_file_list().
483  */
484 int tr_find_config_files(const char *config_dir, struct dirent ***cfg_files) {
485   int n = 0;
486   
487   n = scandir(config_dir, cfg_files, is_cfg_file, alphasort);
488
489   if (n < 0) {
490     perror("scandir");
491     tr_debug("tr_find_config: scandir error trying to scan %s.", config_dir);
492   } 
493
494   return n;
495 }
496
497 /* Free memory allocated for configuration file list returned from tr_find_config_files().
498  * This can be called regardless of the return value of tr_find_config_values(). */
499 void tr_free_config_file_list(int n, struct dirent ***cfg_files) {
500   int ii;
501
502   /* if n < 0, then scandir did not allocate anything because it failed */
503   if((n>=0) && (*cfg_files != NULL)) {
504     for(ii=0; ii<n; ii++) {
505       free((*cfg_files)[ii]);
506     }
507     free(*cfg_files); /* safe even if n==0 */
508     *cfg_files=NULL; /* this will help prevent accidentally freeing twice */
509   }
510 }