0a507c272db08e140c4db3728a071360072b72ec
[trust_router.git] / common / tr_constraint.c
1 /*
2  * Copyright (c) 2012-2014, 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 #include <jansson.h>
35 #include "jansson_iterators.h"
36 #include <assert.h>
37 #include <talloc.h>
38
39 #include <trust_router/tr_constraint.h>
40 #include <tr_filter.h>
41 #include <tid_internal.h>
42 #include <tr_debug.h>
43
44
45 static int tr_constraint_destructor(void *obj)
46 {
47   TR_CONSTRAINT *cons = talloc_get_type_abort(obj, TR_CONSTRAINT);
48   int ii = 0;
49
50   if (cons->type != NULL)
51     tr_free_name(cons->type);
52   for (ii = 0; ii < TR_MAX_CONST_MATCHES; ii++) {
53     if (cons->matches[ii] != NULL)
54       tr_free_name(cons->matches[ii]);
55   }
56   return 0;
57 }
58
59 TR_CONSTRAINT *tr_constraint_new(TALLOC_CTX *mem_ctx)
60 {
61   TR_CONSTRAINT *cons = talloc(mem_ctx, TR_CONSTRAINT);
62   int ii = 0;
63
64   if (cons != NULL) {
65     cons->type = NULL;
66     for (ii = 0; ii < TR_MAX_CONST_MATCHES; ii++)
67       cons->matches[ii] = NULL;
68     talloc_set_destructor((void *) cons, tr_constraint_destructor);
69   }
70   return cons;
71 }
72
73 void tr_constraint_free(TR_CONSTRAINT *cons)
74 {
75   talloc_free(cons);
76 }
77
78 TR_CONSTRAINT *tr_constraint_dup(TALLOC_CTX *mem_ctx, TR_CONSTRAINT *cons)
79 {
80   TALLOC_CTX *tmp_ctx = NULL;
81   TR_CONSTRAINT *new = NULL;
82   int ii = 0;
83
84   if (cons == NULL)
85     return NULL;
86
87   tmp_ctx = talloc_new(NULL);
88   new = tr_constraint_new(tmp_ctx);
89
90   if (new != NULL) {
91     new->type = tr_dup_name(cons->type);
92     for (ii = 0; ii < TR_MAX_CONST_MATCHES; ii++)
93       new->matches[ii] = tr_dup_name(cons->matches[ii]);
94     talloc_steal(mem_ctx, new);
95   }
96
97   talloc_free(tmp_ctx);
98   return new;
99 }
100
101 /* Returns TRUE (1) if the the string (str) matches the wildcard string (wc_str), FALSE (0) if not.
102  * Allows for a single '*' as the wildcard character if it is the first character. Leading white
103  * space is significant.
104  */
105 int tr_prefix_wildcard_match(const char *str, const char *wc_str)
106 {
107   const char *wc_post = wc_str;
108   size_t len = 0;
109   size_t wc_len = 0;
110
111   if ((!str) || (!wc_str))
112     return 0;
113
114   len = strlen(str);
115   if (0 == (wc_len = strlen(wc_str)))
116     return 0;
117
118   /* TBD -- skip leading white space? */
119   if ('*' == wc_str[0]) {
120     wc_post = &(wc_str[1]);
121     wc_len--;
122   } else if (len != wc_len)
123     return 0;
124
125
126   if (wc_len > len)
127     return 0;
128
129   if (0 == strcmp(&(str[len - wc_len]), wc_post)) {
130     return 1;
131   } else
132     return 0;
133 }
134
135 /* This combines the two constraints in a filter line (TR_FLINE) into a single
136  * set with two constraints. */
137 TR_CONSTRAINT_SET *tr_constraint_set_from_fline(TR_FLINE *fline)
138 {
139   json_t *cset = NULL;
140
141   if (!fline)
142     return NULL;
143
144   if (fline->realm_cons)
145     tr_constraint_add_to_set((TR_CONSTRAINT_SET **) &cset, fline->realm_cons);
146   if (fline->domain_cons)
147     tr_constraint_add_to_set((TR_CONSTRAINT_SET **) &cset, fline->domain_cons);
148
149   return (TR_CONSTRAINT_SET *) cset;
150 }
151
152 /* A constraint set is represented in json as an array of constraint
153  * objects.  So, a constraint set (cset) that consists of one realm
154  * constraint and one domain constraint might look like:
155  *
156  *      {cset: [{domain: [a.com, b.co.uk]},
157  *              {realm: [c.net, d.org]}]}
158  *
159  * This routine takes a TR_CONSTRAINT, converts it to its JSON representation,
160  * and adds that to the TR_CONSTRAINT_SET.
161  */
162 void tr_constraint_add_to_set(TR_CONSTRAINT_SET **cset, TR_CONSTRAINT *cons)
163 {
164   json_t *jcons = NULL;
165   json_t *jmatches = NULL;
166   int i = 0;
167
168   if ((!cset) || (!cons))
169     return;
170
171   /* If we don't already have a json object, create one */
172   if (!(*cset))
173     *cset = (TR_CONSTRAINT_SET *) json_array();
174
175   /* Create a json object representing cons */
176   jmatches = json_array();
177   jcons = json_object();
178
179   for (i = 0; ((i < TR_MAX_CONST_MATCHES) && (NULL != cons->matches[i])); i++) {
180     json_array_append_new(jmatches, json_string(cons->matches[i]->buf));
181   }
182
183   json_object_set_new(jcons, cons->type->buf, jmatches);
184
185   /* Add the created object to the cset object */
186   json_array_append_new((json_t *) *cset, jcons);
187 }
188
189 /* Test whether a JSON object has a valid structure
190  * to represent a constraint set.
191  */
192 int tr_constraint_set_validate(TR_CONSTRAINT_SET *cset) {
193   json_t *json = (json_t *) cset;
194   size_t i;
195   json_t *set_member;
196   if (!json_is_array(json)) {
197     tr_debug("Constraint_set is not an array");
198     return 0;
199   }
200   json_array_foreach(json, i, set_member) {
201     json_t *value;
202     const char *key;
203     if (!json_is_object(set_member)) {
204       tr_debug("Constraint member at %zu is not an object\n", i);
205       return 0;
206     }
207     json_object_foreach(set_member, key, value) {
208       size_t inner_index;
209       json_t *inner_value;
210       if (!json_is_array(value)) {
211         tr_debug("Constraint type %s at index %zu in constraint set is not an array\n", key,
212                  i);
213         return 0;
214       }
215       json_array_foreach(value, inner_index, inner_value) {
216         if (!json_is_string(inner_value)) {
217           tr_debug("Constraint type %s at index %zu in constraint set has non-string element %zu\n",
218                    key, i, inner_index);
219           return 0;
220         }
221       }
222     }
223   }
224   return 1;
225 }
226
227
228 /**
229  * Create a new constraint set containing all constraints from #orig
230  * with constraint_type #constraint_type and no others.  This constraint set is
231  * live until #request is freed.
232  */
233 TR_CONSTRAINT_SET *tr_constraint_set_filter(TID_REQ *request,
234                                             TR_CONSTRAINT_SET *orig,
235                                             const char *constraint_type)
236 {
237   json_t *orig_cset = (json_t *) orig;
238   json_t *new_cs = NULL;
239   size_t index;
240   json_t *set_member;
241   if (!tr_constraint_set_validate((TR_CONSTRAINT_SET *) orig_cset)) {
242     tr_debug ("tr_constraint_set_filter: not a valid constraint set\n");
243     return NULL;
244   }
245   assert (new_cs = json_array());
246   json_array_foreach(orig_cset, index, set_member) {
247     if (json_object_get(set_member, constraint_type))
248       json_array_append(new_cs, set_member);
249   }
250   tid_req_cleanup_json(request, new_cs);
251   return (TR_CONSTRAINT_SET *) new_cs;
252 }
253
254 /**
255  * Within a given constraint object merge any overlapping domain or
256  * realm constraints.  For example ['*','*.net'] can be simplified to
257  * ['*']
258  */
259 static void merge_constraints(json_t *constraint, const char *key)
260 {
261   json_t *value_1, *value_2, *constraint_array;
262   size_t index_1, index_2;
263   /*
264    * Go through the loop pairwise linear, removing elements where one
265    * element is a subset of the other.  Always shrik the array from
266    * the end so that index_1 never becomes invalid (swapping if
267    * needed).
268    */
269   constraint_array = json_object_get(constraint, key);
270   if (NULL == constraint_array)
271     return;
272   json_array_foreach(constraint_array, index_1, value_1)json_array_foreach(constraint_array, index_2, value_2) {
273       if (index_2 <= index_1)
274         continue;
275       if (tr_prefix_wildcard_match(json_string_value(value_2),
276                                    json_string_value(value_1))) {
277         json_array_remove(constraint_array, index_2);
278         index_2--;
279       } else if (tr_prefix_wildcard_match(json_string_value(value_1),
280                                           json_string_value(value_2))) {
281         json_array_set(constraint_array, index_1, value_2);
282         json_array_remove(constraint_array, index_2);
283         index_2--;
284       }
285     }
286 }
287
288 /**
289  * Returns an array of constraint strings that is the intersection of
290  * all constraints in the constraint_set of type #type
291  */
292 static json_t *constraint_intersect_internal(TR_CONSTRAINT_SET *constraints,
293                                              const char *constraint_type)
294 {
295   json_t *constraint, *result = NULL;
296   size_t i;
297   json_array_foreach((json_t *) constraints, i, constraint) {
298     merge_constraints(constraint, constraint_type);
299     if (NULL == result) {
300       result = json_object_get(constraint, constraint_type);
301       if (NULL != result)
302         result = json_copy(result);
303     } else {
304       json_t *intersect, *value_1, *value_2;
305       size_t index_1, index_2;
306       intersect = json_object_get(constraint, constraint_type);
307       /*If an element of the constraint set doesn't have a particular
308        * constraint type, we ignore that element of the constraint set.
309        * However, if no element of the constraint set has a particular
310        *     constraint type we return empty (no access) rather than universal
311        * access.*/
312       if (!intersect)
313         continue;
314       result_loop:
315       json_array_foreach(result, index_1, value_1) {
316         json_array_foreach(intersect, index_2, value_2) {
317           if (tr_prefix_wildcard_match(json_string_value(value_1),
318                                        json_string_value(value_2)))
319             goto result_acceptable;
320           else if (tr_prefix_wildcard_match(json_string_value(value_2),
321                                             json_string_value(value_1))) {
322             json_array_set(result, index_1, value_2);
323             goto result_acceptable;
324           }
325         }
326         json_array_remove(result, index_1);
327         if (index_1 == 0)
328           goto result_loop;
329         index_1--;
330         result_acceptable:
331         continue;
332       }
333     }
334   }
335   return result;
336 }
337
338 /**
339  * Return the intersection of domain and realm constraints.
340  * Return is live until #request is freed.
341  */
342 TR_CONSTRAINT_SET *tr_constraint_set_intersect(TID_REQ *request,
343                                                TR_CONSTRAINT_SET *input)
344 {
345   json_t *domain = NULL, *realm = NULL;
346   json_t *result = NULL, *result_array = NULL;
347   if (tr_constraint_set_validate(input)) {
348     domain = constraint_intersect_internal(input, "domain");
349     realm = constraint_intersect_internal(input, "realm");
350   }
351   assert(result = json_object());
352   if (domain)
353     json_object_set_new(result, "domain", domain);
354   if (realm)
355     json_object_set_new(result, "realm", realm);
356   assert(result_array = json_array());
357   json_array_append_new(result_array, result);
358   tid_req_cleanup_json(request, result_array);
359   return (TR_CONSTRAINT_SET *) result_array;
360 }
361
362 /** Get the set of wildcard strings that matches a fully intersected
363  * constraint set.  Requires that the constraint set only have one
364  * constraint in it, but the constraint may have multiple matches for
365  * a given type.  Returns true on success false on failure.  The
366  * output is live as long as the request is live.
367  */
368 int tr_constraint_set_get_match_strings(TID_REQ *request,
369                                         TR_CONSTRAINT_SET *constraints,
370                                         const char *constraint_type,
371                                         tr_const_string **output,
372                                         size_t *output_len)
373 {
374   json_t *cset = (json_t *) constraints;
375   json_t *member, *matches, *value;;
376   size_t index, array_size;
377   assert (output && output_len);
378   *output = NULL;
379   *output_len = 0;
380   if (json_array_size(cset) != 1) {
381     tr_debug("Constraint set for get_match_strings has more than one member\n");
382     return -1;
383   }
384   member = json_array_get(cset, 0);
385   matches = json_object_get(member, constraint_type);
386   if (!matches)
387     return -1;
388   array_size = json_array_size(matches);
389   if (array_size == 0)
390     return -1;
391   *output = talloc_array_ptrtype(request, *output, array_size);
392   json_array_foreach(matches, index, value)(*output)[index] = json_string_value(value);
393   *output_len = array_size;
394   return 0;
395 }