blob: d3a5dda8b7527f2a390cbc53137f5c14b8ac9d96 [file] [log] [blame]
William Robertsf0e0a942012-08-27 15:41:15 -07001#include <stdio.h>
2#include <stdarg.h>
3#include <ctype.h>
4#include <stdio.h>
5#include <stdlib.h>
6#include <unistd.h>
7#include <string.h>
8#include <errno.h>
9#include <stdint.h>
10#include <search.h>
11#include <sepol/sepol.h>
12#include <sepol/policydb/policydb.h>
13
14#define TABLE_SIZE 1024
15#define KVP_NUM_OF_RULES (sizeof(rules) / sizeof(key_map))
16#define log_set_verbose() do { logging_verbose = 1; log_info("Enabling verbose\n"); } while(0)
17#define log_error(fmt, ...) log_msg(stderr, "Error: ", fmt, ##__VA_ARGS__)
18#define log_warn(fmt, ...) log_msg(stderr, "Warning: ", fmt, ##__VA_ARGS__)
19#define log_info(fmt, ...) if (logging_verbose ) { log_msg(stdout, "Info: ", fmt, ##__VA_ARGS__); }
20
21typedef struct line_order_list line_order_list;
22typedef struct hash_entry hash_entry;
23typedef enum key_dir key_dir;
24typedef enum data_type data_type;
25typedef enum rule_map_switch rule_map_switch;
William Roberts0ae3a8a2012-09-04 11:51:04 -070026typedef enum map_match map_match;
William Robertsf0e0a942012-08-27 15:41:15 -070027typedef struct key_map key_map;
28typedef struct kvp kvp;
29typedef struct rule_map rule_map;
30typedef struct policy_info policy_info;
31
William Roberts0ae3a8a2012-09-04 11:51:04 -070032enum map_match {
33 map_no_matches,
34 map_input_matched,
35 map_matched
36};
37
William Robertsf0e0a942012-08-27 15:41:15 -070038/**
39 * Whether or not the "key" from a key vaue pair is considered an
40 * input or an output.
41 */
42enum key_dir {
43 dir_in, dir_out
44};
45
46/**
47 * Used as options to rule_map_free()
48 *
49 * This is needed to get around the fact that GNU C's hash_map doesn't copy the key, so
50 * we cannot free a key when overrding rule_map's in the table.
51 */
52enum rule_map_switch {
53 rule_map_preserve_key, /** Used to preserve the key in the rule_map, ie don't free it*/
54 rule_map_destroy_key /** Used when you need a full free of the rule_map structure*/
55};
56
57/**
58 * The expected "type" of data the value in the key
59 * value pair should be.
60 */
61enum data_type {
62 dt_bool, dt_string
63};
64
65/**
66 * This list is used to store a double pointer to each
67 * hash table / line rule combination. This way a replacement
68 * in the hash table automatically updates the list. The list
69 * is also used to keep "first encountered" ordering amongst
70 * the encountered key value pairs in the rules file.
71 */
72struct line_order_list {
73 hash_entry *e;
74 line_order_list *next;
75};
76
77/**
78 * The workhorse of the logic. This struct maps key value pairs to
79 * an associated set of meta data maintained in rule_map_new()
80 */
81struct key_map {
82 char *name;
83 key_dir dir;
84 data_type type;
85 char *data;
86};
87
88/**
89 * Key value pair struct, this represents the raw kvp values coming
90 * from the rules files.
91 */
92struct kvp {
93 char *key;
94 char *value;
95};
96
97/**
98 * Rules are made up of meta data and an associated set of kvp stored in a
99 * key_map array.
100 */
101struct rule_map {
102 char *key; /** key value before hashing */
103 int length; /** length of the key map */
104 int lineno; /** Line number rule was encounter on */
105 rule_map *next; /** next pointer used in hash table for chaining on collision */
106 key_map m[]; /** key value mapping */
107};
108
109struct hash_entry {
110 rule_map *r; /** The rule map to store at that location */
111};
112
113/**
114 * Data associated for a policy file
115 */
116struct policy_info {
117
118 char *policy_file_name; /** policy file path name */
119 FILE *policy_file; /** file handle to the policy file */
120 sepol_policydb_t *db;
121 sepol_policy_file_t *pf;
122 sepol_handle_t *handle;
123 sepol_context_t *con;
124};
125
126/** Set to !0 to enable verbose logging */
127static int logging_verbose = 0;
128
129/** file handle to the output file */
130static FILE *output_file = NULL;
131
132/** file handle to the input file */
133static FILE *input_file = NULL;
134
135/** output file path name */
136static char *out_file_name = NULL;
137
138/** input file path name */
139static char *in_file_name = NULL;
140
141static policy_info pol = {
142 .policy_file_name = NULL,
143 .policy_file = NULL,
144 .db = NULL,
145 .pf = NULL,
146 .handle = NULL,
147 .con = NULL
148};
149
150/**
151 * The heart of the mapping process, this must be updated if a new key value pair is added
152 * to a rule.
153 */
154key_map rules[] = {
155 /*Inputs*/
156 { .name = "isSystemServer", .type = dt_bool, .dir = dir_in, .data = NULL },
157 { .name = "user", .type = dt_string, .dir = dir_in, .data = NULL },
158 { .name = "seinfo", .type = dt_string, .dir = dir_in, .data = NULL },
159 { .name = "name", .type = dt_string, .dir = dir_in, .data = NULL },
160 { .name = "sebool", .type = dt_string, .dir = dir_in, .data = NULL },
161 /*Outputs*/
162 { .name = "domain", .type = dt_string, .dir = dir_out, .data = NULL },
163 { .name = "type", .type = dt_string, .dir = dir_out, .data = NULL },
164 { .name = "levelFromUid", .type = dt_bool, .dir = dir_out, .data = NULL },
165 { .name = "level", .type = dt_string, .dir = dir_out, .data = NULL },
166 };
167
168/**
169 * Head pointer to a linked list of
170 * rule map table entries, used for
171 * preserving the order of entries
172 * based on "first encounter"
173 */
174static line_order_list *list_head = NULL;
175
176/**
177 * Pointer to the tail of the list for
178 * quick appends to the end of the list
179 */
180static line_order_list *list_tail = NULL;
181
182/**
183 * Send a logging message to a file
184 * @param out
185 * Output file to send message too
186 * @param prefix
187 * A special prefix to write to the file, such as "Error:"
188 * @param fmt
189 * The printf style formatter to use, such as "%d"
190 */
191static void log_msg(FILE *out, const char *prefix, const char *fmt, ...) {
192 fprintf(out, "%s", prefix);
193 va_list args;
194 va_start(args, fmt);
195 vfprintf(out, fmt, args);
196 va_end(args);
197}
198
199/**
200 * Checks for a type in the policy.
201 * @param db
202 * The policy db to search
203 * @param type
204 * The type to search for
205 * @return
206 * 1 if the type is found, 0 otherwise.
207 * @warning
208 * This function always returns 1 if libsepol is not linked
209 * statically to this executable and LINK_SEPOL_STATIC is not
210 * defined.
211 */
212int check_type(sepol_policydb_t *db, char *type) {
213
214 int rc = 1;
215#if defined(LINK_SEPOL_STATIC)
216 policydb_t *d = (policydb_t *)db;
217 hashtab_datum_t dat;
218 dat = hashtab_search(d->p_types.table, type);
219 rc = (dat == NULL) ? 0 : 1;
220#endif
221 return rc;
222}
223
224/**
225 * Validates a key_map against a set of enforcement rules, this
226 * function exits the application on a type that cannot be properly
227 * checked
228 *
229 * @param m
230 * The key map to check
231 * @param lineno
232 * The line number in the source file for the corresponding key map
233 */
234static int key_map_validate(key_map *m, int lineno) {
235
236 int rc = 1;
237 int ret = 1;
William Robertsf0e0a942012-08-27 15:41:15 -0700238 int resp;
239 char *key = m->name;
240 char *value = m->data;
241 data_type type = m->type;
242 sepol_bool_key_t *se_key;
243
William Roberts0ae3a8a2012-09-04 11:51:04 -0700244 log_info("Validating %s=%s\n", key, value);
245
William Robertsf0e0a942012-08-27 15:41:15 -0700246 /* Booleans can always be checked for sanity */
247 if (type == dt_bool && (!strcmp("true", value) || !strcmp("false", value))) {
248 goto out;
249 }
250 else if (type == dt_bool) {
William Robertsae23a1f2012-09-05 12:53:52 -0700251 log_error("Expected boolean value got: %s=%s on line: %d in file: %s\n",
252 key, value, lineno, out_file_name);
William Robertsf0e0a942012-08-27 15:41:15 -0700253 rc = 0;
254 goto out;
255 }
256
257 /*
258 * If their is no policy file present,
259 * then it is not in strict mode so just return.
260 * User and name cannot really be checked.
261 */
262 if (!pol.policy_file) {
263 goto out;
264 }
265 else if (!strcasecmp(key, "sebool")) {
266
267 ret = sepol_bool_key_create(pol.handle, value, &se_key);
268 if (ret < 0) {
269 log_error("Could not create selinux boolean key, error: %s\n",
270 strerror(errno));
271 rc = 0;
272 goto out;
273 }
274
275 ret = sepol_bool_exists(pol.handle, pol.db, se_key, &resp);
276 if (ret < 0) {
277 log_error("Could not check selinux boolean, error: %s\n",
278 strerror(errno));
279 rc = 0;
William Robertsa53ccf32012-09-17 12:53:44 -0700280 sepol_bool_key_free(se_key);
281 goto out;
William Robertsf0e0a942012-08-27 15:41:15 -0700282 }
283
284 if(!resp) {
285 log_error("Could not find selinux boolean \"%s\" on line: %d in file: %s\n",
286 value, lineno, out_file_name);
287 rc = 0;
William Robertsa53ccf32012-09-17 12:53:44 -0700288 sepol_bool_key_free(se_key);
289 goto out;
William Robertsf0e0a942012-08-27 15:41:15 -0700290 }
William Robertsa53ccf32012-09-17 12:53:44 -0700291 sepol_bool_key_free(se_key);
William Robertsf0e0a942012-08-27 15:41:15 -0700292 }
293 else if (!strcasecmp(key, "type") || !strcasecmp(key, "domain")) {
294
295 if(!check_type(pol.db, value)) {
296 log_error("Could not find selinux type \"%s\" on line: %d in file: %s\n", value,
297 lineno, out_file_name);
298 rc = 0;
299 }
300 goto out;
301 }
William Robertsf0e0a942012-08-27 15:41:15 -0700302 else if (!strcasecmp(key, "level")) {
303
William Roberts0ae3a8a2012-09-04 11:51:04 -0700304 ret = sepol_mls_check(pol.handle, pol.db, value);
305 if (ret < 0) {
William Robertsae23a1f2012-09-05 12:53:52 -0700306 log_error("Could not find selinux level \"%s\", on line: %d in file: %s\n", value,
307 lineno, out_file_name);
William Roberts0ae3a8a2012-09-04 11:51:04 -0700308 rc = 0;
309 goto out;
William Robertsf0e0a942012-08-27 15:41:15 -0700310 }
311 }
312
William Roberts0ae3a8a2012-09-04 11:51:04 -0700313out:
314 log_info("Key map validate returning: %d\n", rc);
315 return rc;
William Robertsf0e0a942012-08-27 15:41:15 -0700316}
317
318/**
319 * Prints a rule map back to a file
320 * @param fp
321 * The file handle to print too
322 * @param r
323 * The rule map to print
324 */
325static void rule_map_print(FILE *fp, rule_map *r) {
326
327 int i;
328 key_map *m;
329
330 for (i = 0; i < r->length; i++) {
331 m = &(r->m[i]);
332 if (i < r->length - 1)
333 fprintf(fp, "%s=%s ", m->name, m->data);
334 else
335 fprintf(fp, "%s=%s", m->name, m->data);
336 }
337}
338
339/**
340 * Compare two rule maps for equality
341 * @param rmA
342 * a rule map to check
343 * @param rmB
344 * a rule map to check
345 * @return
William Robertsae23a1f2012-09-05 12:53:52 -0700346 * a map_match enum indicating the result
William Robertsf0e0a942012-08-27 15:41:15 -0700347 */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700348static map_match rule_map_cmp(rule_map *rmA, rule_map *rmB) {
William Robertsf0e0a942012-08-27 15:41:15 -0700349
350 int i;
351 int j;
352 int inputs_found = 0;
353 int num_of_matched_inputs = 0;
354 int input_mode = 0;
355 int matches = 0;
356 key_map *mA;
357 key_map *mB;
358
359 if (rmA->length != rmB->length)
William Roberts0ae3a8a2012-09-04 11:51:04 -0700360 return map_no_matches;
William Robertsf0e0a942012-08-27 15:41:15 -0700361
362 for (i = 0; i < rmA->length; i++) {
363 mA = &(rmA->m[i]);
364
365 for (j = 0; j < rmB->length; j++) {
366 mB = &(rmB->m[j]);
367 input_mode = 0;
368
369 if (mA->type != mB->type)
370 continue;
371
372 if (strcmp(mA->name, mB->name))
373 continue;
374
375 if (strcmp(mA->data, mB->data))
376 continue;
377
378 if (mB->dir != mA->dir)
379 continue;
380 else if (mB->dir == dir_in) {
381 input_mode = 1;
382 inputs_found++;
383 }
384
William Roberts0ae3a8a2012-09-04 11:51:04 -0700385 if (input_mode) {
386 log_info("Matched input lines: type=%s name=%s data=%s dir=%d\n", mA->type, mA->name, mA->data, mA->dir);
William Robertsf0e0a942012-08-27 15:41:15 -0700387 num_of_matched_inputs++;
William Roberts0ae3a8a2012-09-04 11:51:04 -0700388 }
William Robertsf0e0a942012-08-27 15:41:15 -0700389
390 /* Match found, move on */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700391 log_info("Matched lines: type=%s name=%s data=%s dir=%d\n", mA->type, mA->name, mA->data, mA->dir);
William Robertsf0e0a942012-08-27 15:41:15 -0700392 matches++;
393 break;
394 }
395 }
396
397 /* If they all matched*/
William Roberts0ae3a8a2012-09-04 11:51:04 -0700398 if (matches == rmA->length) {
399 log_info("Rule map cmp MATCH\n");
400 return map_matched;
401 }
William Robertsf0e0a942012-08-27 15:41:15 -0700402
403 /* They didn't all match but the input's did */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700404 else if (num_of_matched_inputs == inputs_found) {
405 log_info("Rule map cmp INPUT MATCH\n");
406 return map_input_matched;
407 }
William Robertsf0e0a942012-08-27 15:41:15 -0700408
409 /* They didn't all match, and the inputs didn't match, ie it didn't
410 * match */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700411 else {
412 log_info("Rule map cmp NO MATCH\n");
413 return map_no_matches;
414 }
William Robertsf0e0a942012-08-27 15:41:15 -0700415}
416
417/**
418 * Frees a rule map
419 * @param rm
420 * rule map to be freed.
421 */
422static void rule_map_free(rule_map *rm, rule_map_switch s) {
423
424 int i;
425 int len = rm->length;
426 for (i = 0; i < len; i++) {
427 key_map *m = &(rm->m[i]);
428 free(m->data);
429 }
430
431 if(s == rule_map_destroy_key && rm->key)
432 free(rm->key);
433
434 free(rm);
435}
436
437static void free_kvp(kvp *k) {
438 free(k->key);
439 free(k->value);
440}
441
442/**
443 * Given a set of key value pairs, this will construct a new rule map.
444 * On error this function calls exit.
445 * @param keys
446 * Keys from a rule line to map
447 * @param num_of_keys
448 * The length of the keys array
449 * @param lineno
450 * The line number the keys were extracted from
451 * @return
452 * A rule map pointer.
453 */
454static rule_map *rule_map_new(kvp keys[], unsigned int num_of_keys, int lineno) {
455
456 unsigned int i = 0, j = 0;
457 rule_map *new_map = NULL;
458 kvp *k = NULL;
459 key_map *r = NULL, *x = NULL;
460
461 new_map = calloc(1, (num_of_keys * sizeof(key_map)) + sizeof(rule_map));
462 if (!new_map)
463 goto oom;
464
465 new_map->length = num_of_keys;
466 new_map->lineno = lineno;
467
468 /* For all the keys in a rule line*/
469 for (i = 0; i < num_of_keys; i++) {
470 k = &(keys[i]);
471 r = &(new_map->m[i]);
472
473 for (j = 0; j < KVP_NUM_OF_RULES; j++) {
474 x = &(rules[j]);
475
476 /* Only assign key name to map name */
477 if (strcasecmp(k->key, x->name)) {
478 if (i == KVP_NUM_OF_RULES) {
479 log_error("No match for key: %s\n", k->key);
480 goto err;
481 }
482 continue;
483 }
484
485 memcpy(r, x, sizeof(key_map));
486
487 /* Assign rule map value to one from file */
488 r->data = strdup(k->value);
489 if (!r->data)
490 goto oom;
491
492 /* Enforce type check*/
William Roberts0ae3a8a2012-09-04 11:51:04 -0700493 log_info("Validating keys!\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700494 if (!key_map_validate(r, lineno)) {
495 log_error("Could not validate\n");
496 goto err;
497 }
498
499 /* Only build key off of inputs*/
500 if (r->dir == dir_in) {
501 char *tmp;
502 int l = strlen(k->key);
503 l += strlen(k->value);
504 l += (new_map->key) ? strlen(new_map->key) : 0;
505 l += 1;
506
507 tmp = realloc(new_map->key, l);
508 if (!tmp)
509 goto oom;
510
511 new_map->key = tmp;
512
513 strcat(new_map->key, k->key);
514 strcat(new_map->key, k->value);
515 }
516 break;
517 }
518 free_kvp(k);
519 }
520
521 if (new_map->key == NULL) {
522 log_error("Strange, no keys found, input file corrupt perhaps?\n");
523 goto err;
524 }
525
526 return new_map;
527
528oom:
529 log_error("Out of memory!\n");
530err:
531 if(new_map) {
532 rule_map_free(new_map, rule_map_destroy_key);
533 for (; i < num_of_keys; i++) {
534 k = &(keys[i]);
535 free_kvp(k);
536 }
537 }
538 exit(EXIT_FAILURE);
539}
540
541/**
542 * Print the usage of the program
543 */
544static void usage() {
545 printf(
546 "checkseapp [options] <input file>\n"
547 "Processes an seapp_contexts file specified by argument <input file> (default stdin) "
William Robertsae23a1f2012-09-05 12:53:52 -0700548 "and allows later declarations to override previous ones on a match.\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700549 "Options:\n"
550 "-h - print this help message\n"
551 "-v - enable verbose debugging informations\n"
552 "-p policy file - specify policy file for strict checking of output selectors\n"
553 "-o output file - specify output file, default is stdout\n");
554}
555
556static void init() {
557
558 /* If not set on stdin already */
559 if(!input_file) {
560 log_info("Opening input file: %s\n", in_file_name);
561 input_file = fopen(in_file_name, "r");
562 if (!input_file) {
563 log_error("Could not open file: %s error: %s\n", in_file_name, strerror(errno));
564 exit(EXIT_FAILURE);
565 }
566 }
567
568 /* If not set on std out already */
569 if(!output_file) {
570 output_file = fopen(out_file_name, "w+");
571 if (!output_file) {
572 log_error("Could not open file: %s error: %s\n", out_file_name, strerror(errno));
573 exit(EXIT_FAILURE);
574 }
575 }
576
577 if (pol.policy_file_name) {
578
579 log_info("Opening policy file: %s\n", pol.policy_file_name);
580 pol.policy_file = fopen(pol.policy_file_name, "rb");
581 if (!pol.policy_file) {
582 log_error("Could not open file: %s error: %s\n",
583 pol.policy_file_name, strerror(errno));
584 exit(EXIT_FAILURE);
585 }
586
587 pol.handle = sepol_handle_create();
588 if (!pol.handle) {
589 log_error("Could not create sepolicy handle: %s\n",
590 strerror(errno));
591 exit(EXIT_FAILURE);
592 }
593
594 if (sepol_policy_file_create(&pol.pf) < 0) {
595 log_error("Could not create sepolicy file: %s!\n",
596 strerror(errno));
597 exit(EXIT_FAILURE);
598 }
599
600 sepol_policy_file_set_fp(pol.pf, pol.policy_file);
601 sepol_policy_file_set_handle(pol.pf, pol.handle);
602
603 if (sepol_policydb_create(&pol.db) < 0) {
604 log_error("Could not create sepolicy db: %s!\n",
605 strerror(errno));
606 exit(EXIT_FAILURE);
607 }
608
609 if (sepol_policydb_read(pol.db, pol.pf) < 0) {
610 log_error("Could not lod policy file to db: %s!\n",
611 strerror(errno));
612 exit(EXIT_FAILURE);
613 }
614 }
615
616 log_info("Policy file set to: %s\n", (pol.policy_file_name == NULL) ? "None" : pol.policy_file_name);
617 log_info("Input file set to: %s\n", (in_file_name == NULL) ? "stdin" : in_file_name);
618 log_info("Output file set to: %s\n", (out_file_name == NULL) ? "stdout" : out_file_name);
619
William Roberts0ae3a8a2012-09-04 11:51:04 -0700620#if !defined(LINK_SEPOL_STATIC)
William Robertsa53ccf32012-09-17 12:53:44 -0700621 log_warn("LINK_SEPOL_STATIC is not defined\n""Not checking types!");
William Roberts0ae3a8a2012-09-04 11:51:04 -0700622#endif
623
William Robertsf0e0a942012-08-27 15:41:15 -0700624}
625
626/**
627 * Handle parsing and setting the global flags for the command line
628 * options. This function calls exit on failure.
629 * @param argc
630 * argument count
631 * @param argv
632 * argument list
633 */
634static void handle_options(int argc, char *argv[]) {
635
636 int c;
637 int num_of_args;
638
639 while ((c = getopt(argc, argv, "ho:p:v")) != -1) {
640 switch (c) {
641 case 'h':
642 usage();
643 exit(EXIT_SUCCESS);
644 case 'o':
645 out_file_name = optarg;
646 break;
647 case 'p':
648 pol.policy_file_name = optarg;
649 break;
650 case 'v':
651 log_set_verbose();
652 break;
653 case '?':
654 if (optopt == 'o' || optopt == 'p')
655 log_error("Option -%c requires an argument.\n", optopt);
656 else if (isprint (optopt))
657 log_error("Unknown option `-%c'.\n", optopt);
658 else {
659 log_error(
660 "Unknown option character `\\x%x'.\n",
661 optopt);
662 exit(EXIT_FAILURE);
663 }
664 break;
665 default:
666 exit(EXIT_FAILURE);
667 }
668 }
669
670 num_of_args = argc - optind;
671
672 if (num_of_args > 1) {
673 log_error("Too many arguments, expected 0 or 1, argument, got %d\n", num_of_args);
674 usage();
675 exit(EXIT_FAILURE);
676 } else if (num_of_args == 1) {
677 in_file_name = argv[argc - 1];
678 } else {
679 input_file = stdin;
680 in_file_name = "stdin";
681 }
682
683 if (!out_file_name) {
684 output_file = stdout;
685 out_file_name = "stdout";
686 }
687}
688
689/**
690 * Adds a rule_map double pointer, ie the hash table pointer to the list.
691 * By using a double pointer, the hash table can have a line be overridden
692 * and the value is updated in the list. This function calls exit on failure.
693 * @param rm
694 * the rule_map to add.
695 */
696static void list_add(hash_entry *e) {
697
698 line_order_list *node = malloc(sizeof(line_order_list));
699 if (node == NULL)
700 goto oom;
701
702 node->next = NULL;
703 node->e = e;
704
705 if (list_head == NULL)
706 list_head = list_tail = node;
707 else {
708 list_tail->next = node;
709 list_tail = list_tail->next;
710 }
711 return;
712
713oom:
714 log_error("Out of memory!\n");
715 exit(EXIT_FAILURE);
716}
717
718/**
719 * Free's the rule map list, which ultimatley contains
720 * all the malloc'd rule_maps.
721 */
722static void list_free() {
723 line_order_list *cursor, *tmp;
724 hash_entry *e;
725
726 cursor = list_head;
727 while (cursor) {
728 e = cursor->e;
729 rule_map_free(e->r, rule_map_destroy_key);
730 tmp = cursor;
731 cursor = cursor->next;
732 free(e);
733 free(tmp);
734 }
735}
736
737/**
738 * Adds a rule to the hash table and to the ordered list if needed.
739 * @param rm
740 * The rule map to add.
741 */
742static void rule_add(rule_map *rm) {
743
William Roberts0ae3a8a2012-09-04 11:51:04 -0700744 map_match cmp;
William Robertsf0e0a942012-08-27 15:41:15 -0700745 ENTRY e;
746 ENTRY *f;
747 hash_entry *entry;
748 hash_entry *tmp;
749 char *preserved_key;
750
751 e.key = rm->key;
752
William Roberts0ae3a8a2012-09-04 11:51:04 -0700753 log_info("Searching for key: %s\n", e.key);
William Robertsf0e0a942012-08-27 15:41:15 -0700754 /* Check to see if it has already been added*/
755 f = hsearch(e, FIND);
756
757 /*
758 * Since your only hashing on a partial key, the inputs we need to handle
759 * when you want to override the outputs for a given input set, as well as
760 * checking for duplicate entries.
761 */
762 if(f) {
William Roberts0ae3a8a2012-09-04 11:51:04 -0700763 log_info("Existing entry found!\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700764 tmp = (hash_entry *)f->data;
765 cmp = rule_map_cmp(rm, tmp->r);
William Roberts0ae3a8a2012-09-04 11:51:04 -0700766 log_info("Comparing on rule map ret: %d\n", cmp);
William Robertsf0e0a942012-08-27 15:41:15 -0700767 /* Override be freeing the old rule map and updating
768 the pointer */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700769 if(cmp != map_matched) {
William Robertsf0e0a942012-08-27 15:41:15 -0700770
771 /*
772 * DO NOT free key pointers given to the hash map, instead
773 * free the new key. The ordering here is critical!
774 */
775 preserved_key = tmp->r->key;
776 rule_map_free(tmp->r, rule_map_preserve_key);
777 free(rm->key);
778 rm->key = preserved_key;
779 tmp->r = rm;
780 }
781 /* Duplicate */
782 else {
783 log_error("Duplicate line detected in file: %s\n"
784 "Lines %d and %d match!\n",
785 out_file_name, tmp->r->lineno, rm->lineno);
786 rule_map_free(rm, rule_map_destroy_key);
787 goto err;
788 }
789 }
790 /* It wasn't found, just add the rule map to the table */
791 else {
792
793 entry = malloc(sizeof(hash_entry));
794 if (!entry)
795 goto oom;
796
797 entry->r = rm;
798 e.data = entry;
799
800 f = hsearch(e, ENTER);
801 if(f == NULL) {
802 goto oom;
803 }
804
805 /* new entries must be added to the ordered list */
806 entry->r = rm;
807 list_add(entry);
808 }
809
810 return;
811oom:
812 if (e.key)
813 free(e.key);
814 if (entry)
815 free(entry);
816 if (rm)
817 free(rm);
818 log_error("Out of memory in function: %s\n", __FUNCTION__);
819err:
820 exit(EXIT_FAILURE);
821}
822
823/**
824 * Parses the seapp_contexts file and adds them to the
825 * hash table and ordered list entries when it encounters them.
826 * Calls exit on failure.
827 */
828static void parse() {
829
830 char line_buf[BUFSIZ];
831 char *token;
832 unsigned lineno = 0;
833 char *p, *name = NULL, *value = NULL, *saveptr;
834 size_t len;
835 kvp keys[KVP_NUM_OF_RULES];
836 int token_cnt = 0;
837
838 while (fgets(line_buf, sizeof line_buf - 1, input_file)) {
839
840 lineno++;
841 log_info("Got line %d\n", lineno);
842 len = strlen(line_buf);
843 if (line_buf[len - 1] == '\n')
844 line_buf[len - 1] = 0;
845 p = line_buf;
846 while (isspace(*p))
847 p++;
848 if (*p == '#' || *p == 0)
849 continue;
850
851 token = strtok_r(p, " \t", &saveptr);
852 if (!token)
853 goto err;
854
855 token_cnt = 0;
856 memset(keys, 0, sizeof(kvp) * KVP_NUM_OF_RULES);
857 while (1) {
William Roberts0ae3a8a2012-09-04 11:51:04 -0700858
William Robertsf0e0a942012-08-27 15:41:15 -0700859 name = token;
860 value = strchr(name, '=');
861 if (!value)
862 goto err;
863 *value++ = 0;
864
865 keys[token_cnt].key = strdup(name);
866 if (!keys[token_cnt].key)
867 goto oom;
868
869 keys[token_cnt].value = strdup(value);
870 if (!keys[token_cnt].value)
871 goto oom;
872
873 token_cnt++;
874
875 token = strtok_r(NULL, " \t", &saveptr);
876 if (!token)
877 break;
878
879 } /*End token parsing */
880
881 rule_map *r = rule_map_new(keys, token_cnt, lineno);
882 rule_add(r);
883
884 } /* End file parsing */
885 return;
886
887err:
888 log_error("reading %s, line %u, name %s, value %s\n",
889 in_file_name, lineno, name, value);
890 exit(EXIT_FAILURE);
891oom:
892 log_error("In function %s: Out of memory\n", __FUNCTION__);
893 exit(EXIT_FAILURE);
894}
895
896/**
897 * Should be called after parsing to cause the printing of the rule_maps
898 * stored in the ordered list, head first, which preserves the "first encountered"
899 * ordering.
900 */
901static void output() {
902
903 rule_map *r;
904 line_order_list *cursor;
905 cursor = list_head;
906
907 while (cursor) {
908 r = cursor->e->r;
909 rule_map_print(output_file, r);
910 cursor = cursor->next;
William Robertsa8613182012-09-05 11:23:40 -0700911 fprintf(output_file, "\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700912 }
913}
914
915/**
916 * This function is registered to the at exit handler and should clean up
917 * the programs dynamic resources, such as memory and fd's.
918 */
919static void cleanup() {
920
921 /* Only close this when it was opened by me and not the crt */
922 if (out_file_name && output_file) {
923 log_info("Closing file: %s\n", out_file_name);
924 fclose(output_file);
925 }
926
927 /* Only close this when it was opened by me and not the crt */
928 if (in_file_name && input_file) {
929 log_info("Closing file: %s\n", in_file_name);
930 fclose(input_file);
931 }
932
933 if (pol.policy_file) {
934
935 log_info("Closing file: %s\n", pol.policy_file_name);
936 fclose(pol.policy_file);
937
938 if (pol.db)
939 sepol_policydb_free(pol.db);
940
941 if (pol.pf)
942 sepol_policy_file_free(pol.pf);
943
944 if (pol.handle)
945 sepol_handle_destroy(pol.handle);
946 }
947
948 log_info("Freeing list\n");
949 list_free();
950 hdestroy();
951}
952
953int main(int argc, char *argv[]) {
954 if (!hcreate(TABLE_SIZE)) {
955 log_error("Could not create hash table: %s\n", strerror(errno));
956 exit(EXIT_FAILURE);
957 }
958 atexit(cleanup);
959 handle_options(argc, argv);
960 init();
961 log_info("Starting to parse\n");
962 parse();
963 log_info("Parsing completed, generating output\n");
964 output();
965 log_info("Success, generated output\n");
966 exit(EXIT_SUCCESS);
967}