blob: dea2e5fd6ee1776ededd9805cca5149b03c894b1 [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
rpcraig5dbfdc02012-10-23 11:03:47 -0400431/* hdestroy() frees comparsion keys for non glibc */
432#ifdef __GLIBC__
William Robertsf0e0a942012-08-27 15:41:15 -0700433 if(s == rule_map_destroy_key && rm->key)
434 free(rm->key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400435#endif
William Robertsf0e0a942012-08-27 15:41:15 -0700436
437 free(rm);
438}
439
440static void free_kvp(kvp *k) {
441 free(k->key);
442 free(k->value);
443}
444
445/**
446 * Given a set of key value pairs, this will construct a new rule map.
447 * On error this function calls exit.
448 * @param keys
449 * Keys from a rule line to map
450 * @param num_of_keys
451 * The length of the keys array
452 * @param lineno
453 * The line number the keys were extracted from
454 * @return
455 * A rule map pointer.
456 */
457static rule_map *rule_map_new(kvp keys[], unsigned int num_of_keys, int lineno) {
458
459 unsigned int i = 0, j = 0;
460 rule_map *new_map = NULL;
461 kvp *k = NULL;
462 key_map *r = NULL, *x = NULL;
463
464 new_map = calloc(1, (num_of_keys * sizeof(key_map)) + sizeof(rule_map));
465 if (!new_map)
466 goto oom;
467
468 new_map->length = num_of_keys;
469 new_map->lineno = lineno;
470
471 /* For all the keys in a rule line*/
472 for (i = 0; i < num_of_keys; i++) {
473 k = &(keys[i]);
474 r = &(new_map->m[i]);
475
476 for (j = 0; j < KVP_NUM_OF_RULES; j++) {
477 x = &(rules[j]);
478
479 /* Only assign key name to map name */
480 if (strcasecmp(k->key, x->name)) {
481 if (i == KVP_NUM_OF_RULES) {
482 log_error("No match for key: %s\n", k->key);
483 goto err;
484 }
485 continue;
486 }
487
488 memcpy(r, x, sizeof(key_map));
489
490 /* Assign rule map value to one from file */
491 r->data = strdup(k->value);
492 if (!r->data)
493 goto oom;
494
495 /* Enforce type check*/
William Roberts0ae3a8a2012-09-04 11:51:04 -0700496 log_info("Validating keys!\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700497 if (!key_map_validate(r, lineno)) {
498 log_error("Could not validate\n");
499 goto err;
500 }
501
502 /* Only build key off of inputs*/
503 if (r->dir == dir_in) {
504 char *tmp;
William Robertsb3ab56c2012-09-17 14:35:02 -0700505 int key_len = strlen(k->key);
506 int val_len = strlen(k->value);
507 int l = (new_map->key) ? strlen(new_map->key) : 0;
508 l = l + key_len + val_len;
William Robertsf0e0a942012-08-27 15:41:15 -0700509 l += 1;
510
511 tmp = realloc(new_map->key, l);
512 if (!tmp)
513 goto oom;
514
William Robertsb3ab56c2012-09-17 14:35:02 -0700515 if (!new_map->key)
516 memset(tmp, 0, l);
517
William Robertsf0e0a942012-08-27 15:41:15 -0700518 new_map->key = tmp;
519
William Robertsb3ab56c2012-09-17 14:35:02 -0700520 strncat(new_map->key, k->key, key_len);
521 strncat(new_map->key, k->value, val_len);
William Robertsf0e0a942012-08-27 15:41:15 -0700522 }
523 break;
524 }
525 free_kvp(k);
526 }
527
528 if (new_map->key == NULL) {
529 log_error("Strange, no keys found, input file corrupt perhaps?\n");
530 goto err;
531 }
532
533 return new_map;
534
535oom:
536 log_error("Out of memory!\n");
537err:
538 if(new_map) {
539 rule_map_free(new_map, rule_map_destroy_key);
540 for (; i < num_of_keys; i++) {
541 k = &(keys[i]);
542 free_kvp(k);
543 }
544 }
545 exit(EXIT_FAILURE);
546}
547
548/**
549 * Print the usage of the program
550 */
551static void usage() {
552 printf(
553 "checkseapp [options] <input file>\n"
554 "Processes an seapp_contexts file specified by argument <input file> (default stdin) "
William Robertsae23a1f2012-09-05 12:53:52 -0700555 "and allows later declarations to override previous ones on a match.\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700556 "Options:\n"
557 "-h - print this help message\n"
558 "-v - enable verbose debugging informations\n"
559 "-p policy file - specify policy file for strict checking of output selectors\n"
560 "-o output file - specify output file, default is stdout\n");
561}
562
563static void init() {
564
565 /* If not set on stdin already */
566 if(!input_file) {
567 log_info("Opening input file: %s\n", in_file_name);
568 input_file = fopen(in_file_name, "r");
569 if (!input_file) {
570 log_error("Could not open file: %s error: %s\n", in_file_name, strerror(errno));
571 exit(EXIT_FAILURE);
572 }
573 }
574
575 /* If not set on std out already */
576 if(!output_file) {
577 output_file = fopen(out_file_name, "w+");
578 if (!output_file) {
579 log_error("Could not open file: %s error: %s\n", out_file_name, strerror(errno));
580 exit(EXIT_FAILURE);
581 }
582 }
583
584 if (pol.policy_file_name) {
585
586 log_info("Opening policy file: %s\n", pol.policy_file_name);
587 pol.policy_file = fopen(pol.policy_file_name, "rb");
588 if (!pol.policy_file) {
589 log_error("Could not open file: %s error: %s\n",
590 pol.policy_file_name, strerror(errno));
591 exit(EXIT_FAILURE);
592 }
593
594 pol.handle = sepol_handle_create();
595 if (!pol.handle) {
596 log_error("Could not create sepolicy handle: %s\n",
597 strerror(errno));
598 exit(EXIT_FAILURE);
599 }
600
601 if (sepol_policy_file_create(&pol.pf) < 0) {
602 log_error("Could not create sepolicy file: %s!\n",
603 strerror(errno));
604 exit(EXIT_FAILURE);
605 }
606
607 sepol_policy_file_set_fp(pol.pf, pol.policy_file);
608 sepol_policy_file_set_handle(pol.pf, pol.handle);
609
610 if (sepol_policydb_create(&pol.db) < 0) {
611 log_error("Could not create sepolicy db: %s!\n",
612 strerror(errno));
613 exit(EXIT_FAILURE);
614 }
615
616 if (sepol_policydb_read(pol.db, pol.pf) < 0) {
617 log_error("Could not lod policy file to db: %s!\n",
618 strerror(errno));
619 exit(EXIT_FAILURE);
620 }
621 }
622
623 log_info("Policy file set to: %s\n", (pol.policy_file_name == NULL) ? "None" : pol.policy_file_name);
624 log_info("Input file set to: %s\n", (in_file_name == NULL) ? "stdin" : in_file_name);
625 log_info("Output file set to: %s\n", (out_file_name == NULL) ? "stdout" : out_file_name);
626
William Roberts0ae3a8a2012-09-04 11:51:04 -0700627#if !defined(LINK_SEPOL_STATIC)
William Robertsa53ccf32012-09-17 12:53:44 -0700628 log_warn("LINK_SEPOL_STATIC is not defined\n""Not checking types!");
William Roberts0ae3a8a2012-09-04 11:51:04 -0700629#endif
630
William Robertsf0e0a942012-08-27 15:41:15 -0700631}
632
633/**
634 * Handle parsing and setting the global flags for the command line
635 * options. This function calls exit on failure.
636 * @param argc
637 * argument count
638 * @param argv
639 * argument list
640 */
641static void handle_options(int argc, char *argv[]) {
642
643 int c;
644 int num_of_args;
645
646 while ((c = getopt(argc, argv, "ho:p:v")) != -1) {
647 switch (c) {
648 case 'h':
649 usage();
650 exit(EXIT_SUCCESS);
651 case 'o':
652 out_file_name = optarg;
653 break;
654 case 'p':
655 pol.policy_file_name = optarg;
656 break;
657 case 'v':
658 log_set_verbose();
659 break;
660 case '?':
661 if (optopt == 'o' || optopt == 'p')
662 log_error("Option -%c requires an argument.\n", optopt);
663 else if (isprint (optopt))
664 log_error("Unknown option `-%c'.\n", optopt);
665 else {
666 log_error(
667 "Unknown option character `\\x%x'.\n",
668 optopt);
669 exit(EXIT_FAILURE);
670 }
671 break;
672 default:
673 exit(EXIT_FAILURE);
674 }
675 }
676
677 num_of_args = argc - optind;
678
679 if (num_of_args > 1) {
680 log_error("Too many arguments, expected 0 or 1, argument, got %d\n", num_of_args);
681 usage();
682 exit(EXIT_FAILURE);
683 } else if (num_of_args == 1) {
684 in_file_name = argv[argc - 1];
685 } else {
686 input_file = stdin;
687 in_file_name = "stdin";
688 }
689
690 if (!out_file_name) {
691 output_file = stdout;
692 out_file_name = "stdout";
693 }
694}
695
696/**
697 * Adds a rule_map double pointer, ie the hash table pointer to the list.
698 * By using a double pointer, the hash table can have a line be overridden
699 * and the value is updated in the list. This function calls exit on failure.
700 * @param rm
701 * the rule_map to add.
702 */
703static void list_add(hash_entry *e) {
704
705 line_order_list *node = malloc(sizeof(line_order_list));
706 if (node == NULL)
707 goto oom;
708
709 node->next = NULL;
710 node->e = e;
711
712 if (list_head == NULL)
713 list_head = list_tail = node;
714 else {
715 list_tail->next = node;
716 list_tail = list_tail->next;
717 }
718 return;
719
720oom:
721 log_error("Out of memory!\n");
722 exit(EXIT_FAILURE);
723}
724
725/**
726 * Free's the rule map list, which ultimatley contains
727 * all the malloc'd rule_maps.
728 */
729static void list_free() {
730 line_order_list *cursor, *tmp;
731 hash_entry *e;
732
733 cursor = list_head;
734 while (cursor) {
735 e = cursor->e;
736 rule_map_free(e->r, rule_map_destroy_key);
737 tmp = cursor;
738 cursor = cursor->next;
739 free(e);
740 free(tmp);
741 }
742}
743
744/**
745 * Adds a rule to the hash table and to the ordered list if needed.
746 * @param rm
747 * The rule map to add.
748 */
749static void rule_add(rule_map *rm) {
750
William Roberts0ae3a8a2012-09-04 11:51:04 -0700751 map_match cmp;
William Robertsf0e0a942012-08-27 15:41:15 -0700752 ENTRY e;
753 ENTRY *f;
754 hash_entry *entry;
755 hash_entry *tmp;
756 char *preserved_key;
757
758 e.key = rm->key;
759
William Roberts0ae3a8a2012-09-04 11:51:04 -0700760 log_info("Searching for key: %s\n", e.key);
William Robertsf0e0a942012-08-27 15:41:15 -0700761 /* Check to see if it has already been added*/
762 f = hsearch(e, FIND);
763
764 /*
765 * Since your only hashing on a partial key, the inputs we need to handle
766 * when you want to override the outputs for a given input set, as well as
767 * checking for duplicate entries.
768 */
769 if(f) {
William Roberts0ae3a8a2012-09-04 11:51:04 -0700770 log_info("Existing entry found!\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700771 tmp = (hash_entry *)f->data;
772 cmp = rule_map_cmp(rm, tmp->r);
William Roberts0ae3a8a2012-09-04 11:51:04 -0700773 log_info("Comparing on rule map ret: %d\n", cmp);
William Robertsf0e0a942012-08-27 15:41:15 -0700774 /* Override be freeing the old rule map and updating
775 the pointer */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700776 if(cmp != map_matched) {
William Robertsf0e0a942012-08-27 15:41:15 -0700777
778 /*
779 * DO NOT free key pointers given to the hash map, instead
780 * free the new key. The ordering here is critical!
781 */
782 preserved_key = tmp->r->key;
783 rule_map_free(tmp->r, rule_map_preserve_key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400784/* hdestroy() frees comparsion keys for non glibc */
785#ifdef __GLIBC__
William Robertsf0e0a942012-08-27 15:41:15 -0700786 free(rm->key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400787#endif
William Robertsf0e0a942012-08-27 15:41:15 -0700788 rm->key = preserved_key;
789 tmp->r = rm;
790 }
791 /* Duplicate */
792 else {
793 log_error("Duplicate line detected in file: %s\n"
794 "Lines %d and %d match!\n",
795 out_file_name, tmp->r->lineno, rm->lineno);
796 rule_map_free(rm, rule_map_destroy_key);
797 goto err;
798 }
799 }
800 /* It wasn't found, just add the rule map to the table */
801 else {
802
803 entry = malloc(sizeof(hash_entry));
804 if (!entry)
805 goto oom;
806
807 entry->r = rm;
808 e.data = entry;
809
810 f = hsearch(e, ENTER);
811 if(f == NULL) {
812 goto oom;
813 }
814
815 /* new entries must be added to the ordered list */
816 entry->r = rm;
817 list_add(entry);
818 }
819
820 return;
821oom:
822 if (e.key)
823 free(e.key);
824 if (entry)
825 free(entry);
826 if (rm)
827 free(rm);
828 log_error("Out of memory in function: %s\n", __FUNCTION__);
829err:
830 exit(EXIT_FAILURE);
831}
832
833/**
834 * Parses the seapp_contexts file and adds them to the
835 * hash table and ordered list entries when it encounters them.
836 * Calls exit on failure.
837 */
838static void parse() {
839
840 char line_buf[BUFSIZ];
841 char *token;
842 unsigned lineno = 0;
843 char *p, *name = NULL, *value = NULL, *saveptr;
844 size_t len;
845 kvp keys[KVP_NUM_OF_RULES];
846 int token_cnt = 0;
847
848 while (fgets(line_buf, sizeof line_buf - 1, input_file)) {
849
850 lineno++;
851 log_info("Got line %d\n", lineno);
852 len = strlen(line_buf);
853 if (line_buf[len - 1] == '\n')
Alice Chuf6647eb2012-10-30 16:27:00 -0700854 line_buf[len - 1] = '\0';
William Robertsf0e0a942012-08-27 15:41:15 -0700855 p = line_buf;
856 while (isspace(*p))
857 p++;
Alice Chuf6647eb2012-10-30 16:27:00 -0700858 if (*p == '#' || *p == '\0')
William Robertsf0e0a942012-08-27 15:41:15 -0700859 continue;
860
861 token = strtok_r(p, " \t", &saveptr);
862 if (!token)
863 goto err;
864
865 token_cnt = 0;
866 memset(keys, 0, sizeof(kvp) * KVP_NUM_OF_RULES);
867 while (1) {
William Roberts0ae3a8a2012-09-04 11:51:04 -0700868
William Robertsf0e0a942012-08-27 15:41:15 -0700869 name = token;
870 value = strchr(name, '=');
871 if (!value)
872 goto err;
873 *value++ = 0;
874
875 keys[token_cnt].key = strdup(name);
876 if (!keys[token_cnt].key)
877 goto oom;
878
879 keys[token_cnt].value = strdup(value);
880 if (!keys[token_cnt].value)
881 goto oom;
882
883 token_cnt++;
884
885 token = strtok_r(NULL, " \t", &saveptr);
886 if (!token)
887 break;
888
889 } /*End token parsing */
890
891 rule_map *r = rule_map_new(keys, token_cnt, lineno);
892 rule_add(r);
893
894 } /* End file parsing */
895 return;
896
897err:
898 log_error("reading %s, line %u, name %s, value %s\n",
899 in_file_name, lineno, name, value);
900 exit(EXIT_FAILURE);
901oom:
902 log_error("In function %s: Out of memory\n", __FUNCTION__);
903 exit(EXIT_FAILURE);
904}
905
906/**
907 * Should be called after parsing to cause the printing of the rule_maps
908 * stored in the ordered list, head first, which preserves the "first encountered"
909 * ordering.
910 */
911static void output() {
912
913 rule_map *r;
914 line_order_list *cursor;
915 cursor = list_head;
916
917 while (cursor) {
918 r = cursor->e->r;
919 rule_map_print(output_file, r);
920 cursor = cursor->next;
William Robertsa8613182012-09-05 11:23:40 -0700921 fprintf(output_file, "\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700922 }
923}
924
925/**
926 * This function is registered to the at exit handler and should clean up
927 * the programs dynamic resources, such as memory and fd's.
928 */
929static void cleanup() {
930
931 /* Only close this when it was opened by me and not the crt */
932 if (out_file_name && output_file) {
933 log_info("Closing file: %s\n", out_file_name);
934 fclose(output_file);
935 }
936
937 /* Only close this when it was opened by me and not the crt */
938 if (in_file_name && input_file) {
939 log_info("Closing file: %s\n", in_file_name);
940 fclose(input_file);
941 }
942
943 if (pol.policy_file) {
944
945 log_info("Closing file: %s\n", pol.policy_file_name);
946 fclose(pol.policy_file);
947
948 if (pol.db)
949 sepol_policydb_free(pol.db);
950
951 if (pol.pf)
952 sepol_policy_file_free(pol.pf);
953
954 if (pol.handle)
955 sepol_handle_destroy(pol.handle);
956 }
957
958 log_info("Freeing list\n");
959 list_free();
960 hdestroy();
961}
962
963int main(int argc, char *argv[]) {
964 if (!hcreate(TABLE_SIZE)) {
965 log_error("Could not create hash table: %s\n", strerror(errno));
966 exit(EXIT_FAILURE);
967 }
968 atexit(cleanup);
969 handle_options(argc, argv);
970 init();
971 log_info("Starting to parse\n");
972 parse();
973 log_info("Parsing completed, generating output\n");
974 output();
975 log_info("Success, generated output\n");
976 exit(EXIT_SUCCESS);
977}