blob: ed781bfcaf745aab61a7dc214874b004f368ee82 [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>
William Roberts61846292013-10-15 09:38:24 -070011#include <stdbool.h>
William Robertsf0e0a942012-08-27 15:41:15 -070012#include <sepol/sepol.h>
13#include <sepol/policydb/policydb.h>
14
15#define TABLE_SIZE 1024
16#define KVP_NUM_OF_RULES (sizeof(rules) / sizeof(key_map))
17#define log_set_verbose() do { logging_verbose = 1; log_info("Enabling verbose\n"); } while(0)
18#define log_error(fmt, ...) log_msg(stderr, "Error: ", fmt, ##__VA_ARGS__)
19#define log_warn(fmt, ...) log_msg(stderr, "Warning: ", fmt, ##__VA_ARGS__)
20#define log_info(fmt, ...) if (logging_verbose ) { log_msg(stdout, "Info: ", fmt, ##__VA_ARGS__); }
21
22typedef struct line_order_list line_order_list;
23typedef struct hash_entry hash_entry;
24typedef enum key_dir key_dir;
25typedef enum data_type data_type;
26typedef enum rule_map_switch rule_map_switch;
William Roberts0ae3a8a2012-09-04 11:51:04 -070027typedef enum map_match map_match;
William Robertsf0e0a942012-08-27 15:41:15 -070028typedef struct key_map key_map;
29typedef struct kvp kvp;
30typedef struct rule_map rule_map;
31typedef struct policy_info policy_info;
32
William Roberts0ae3a8a2012-09-04 11:51:04 -070033enum map_match {
34 map_no_matches,
35 map_input_matched,
36 map_matched
37};
38
William Robertsf0e0a942012-08-27 15:41:15 -070039/**
40 * Whether or not the "key" from a key vaue pair is considered an
41 * input or an output.
42 */
43enum key_dir {
44 dir_in, dir_out
45};
46
47/**
48 * Used as options to rule_map_free()
49 *
50 * This is needed to get around the fact that GNU C's hash_map doesn't copy the key, so
51 * we cannot free a key when overrding rule_map's in the table.
52 */
53enum rule_map_switch {
54 rule_map_preserve_key, /** Used to preserve the key in the rule_map, ie don't free it*/
55 rule_map_destroy_key /** Used when you need a full free of the rule_map structure*/
56};
57
58/**
59 * The expected "type" of data the value in the key
60 * value pair should be.
61 */
62enum data_type {
63 dt_bool, dt_string
64};
65
66/**
67 * This list is used to store a double pointer to each
68 * hash table / line rule combination. This way a replacement
69 * in the hash table automatically updates the list. The list
70 * is also used to keep "first encountered" ordering amongst
71 * the encountered key value pairs in the rules file.
72 */
73struct line_order_list {
74 hash_entry *e;
75 line_order_list *next;
76};
77
78/**
79 * The workhorse of the logic. This struct maps key value pairs to
80 * an associated set of meta data maintained in rule_map_new()
81 */
82struct key_map {
83 char *name;
84 key_dir dir;
85 data_type type;
86 char *data;
87};
88
89/**
90 * Key value pair struct, this represents the raw kvp values coming
91 * from the rules files.
92 */
93struct kvp {
94 char *key;
95 char *value;
96};
97
98/**
99 * Rules are made up of meta data and an associated set of kvp stored in a
100 * key_map array.
101 */
102struct rule_map {
103 char *key; /** key value before hashing */
William Roberts610a4b12013-10-15 18:26:00 -0700104 size_t length; /** length of the key map */
William Robertsf0e0a942012-08-27 15:41:15 -0700105 int lineno; /** Line number rule was encounter on */
William Robertsf0e0a942012-08-27 15:41:15 -0700106 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
William Roberts63297212013-04-19 19:06:23 -0700129/** set to !0 to enable strict checking of duplicate entries */
130static int is_strict = 0;
131
William Robertsf0e0a942012-08-27 15:41:15 -0700132/** file handle to the output file */
133static FILE *output_file = NULL;
134
135/** file handle to the input file */
136static FILE *input_file = NULL;
137
138/** output file path name */
139static char *out_file_name = NULL;
140
141/** input file path name */
142static char *in_file_name = NULL;
143
144static policy_info pol = {
145 .policy_file_name = NULL,
146 .policy_file = NULL,
147 .db = NULL,
148 .pf = NULL,
149 .handle = NULL,
150 .con = NULL
151};
152
153/**
154 * The heart of the mapping process, this must be updated if a new key value pair is added
155 * to a rule.
156 */
157key_map rules[] = {
158 /*Inputs*/
159 { .name = "isSystemServer", .type = dt_bool, .dir = dir_in, .data = NULL },
160 { .name = "user", .type = dt_string, .dir = dir_in, .data = NULL },
161 { .name = "seinfo", .type = dt_string, .dir = dir_in, .data = NULL },
162 { .name = "name", .type = dt_string, .dir = dir_in, .data = NULL },
163 { .name = "sebool", .type = dt_string, .dir = dir_in, .data = NULL },
164 /*Outputs*/
165 { .name = "domain", .type = dt_string, .dir = dir_out, .data = NULL },
166 { .name = "type", .type = dt_string, .dir = dir_out, .data = NULL },
167 { .name = "levelFromUid", .type = dt_bool, .dir = dir_out, .data = NULL },
Stephen Smalley38084142012-11-28 10:46:18 -0500168 { .name = "levelFrom", .type = dt_string, .dir = dir_out, .data = NULL },
William Robertsf0e0a942012-08-27 15:41:15 -0700169 { .name = "level", .type = dt_string, .dir = dir_out, .data = NULL },
William Robertsfff29802012-11-27 14:20:34 -0800170};
William Robertsf0e0a942012-08-27 15:41:15 -0700171
172/**
173 * Head pointer to a linked list of
174 * rule map table entries, used for
175 * preserving the order of entries
176 * based on "first encounter"
177 */
178static line_order_list *list_head = NULL;
179
180/**
181 * Pointer to the tail of the list for
182 * quick appends to the end of the list
183 */
184static line_order_list *list_tail = NULL;
185
186/**
187 * Send a logging message to a file
188 * @param out
189 * Output file to send message too
190 * @param prefix
191 * A special prefix to write to the file, such as "Error:"
192 * @param fmt
193 * The printf style formatter to use, such as "%d"
194 */
William Roberts1e8c0612013-04-19 19:06:02 -0700195static void __attribute__ ((format(printf, 3, 4)))
196log_msg(FILE *out, const char *prefix, const char *fmt, ...) {
197
William Robertsf0e0a942012-08-27 15:41:15 -0700198 fprintf(out, "%s", prefix);
199 va_list args;
200 va_start(args, fmt);
201 vfprintf(out, fmt, args);
202 va_end(args);
203}
204
205/**
206 * Checks for a type in the policy.
207 * @param db
208 * The policy db to search
209 * @param type
210 * The type to search for
211 * @return
212 * 1 if the type is found, 0 otherwise.
213 * @warning
214 * This function always returns 1 if libsepol is not linked
215 * statically to this executable and LINK_SEPOL_STATIC is not
216 * defined.
217 */
218int check_type(sepol_policydb_t *db, char *type) {
219
220 int rc = 1;
221#if defined(LINK_SEPOL_STATIC)
222 policydb_t *d = (policydb_t *)db;
223 hashtab_datum_t dat;
224 dat = hashtab_search(d->p_types.table, type);
225 rc = (dat == NULL) ? 0 : 1;
226#endif
227 return rc;
228}
229
230/**
231 * Validates a key_map against a set of enforcement rules, this
232 * function exits the application on a type that cannot be properly
233 * checked
234 *
235 * @param m
236 * The key map to check
237 * @param lineno
238 * The line number in the source file for the corresponding key map
William Robertsfff29802012-11-27 14:20:34 -0800239 * @return
240 * 1 if valid, 0 if invalid
William Robertsf0e0a942012-08-27 15:41:15 -0700241 */
242static int key_map_validate(key_map *m, int lineno) {
243
244 int rc = 1;
245 int ret = 1;
William Robertsf0e0a942012-08-27 15:41:15 -0700246 int resp;
247 char *key = m->name;
248 char *value = m->data;
249 data_type type = m->type;
250 sepol_bool_key_t *se_key;
251
William Roberts0ae3a8a2012-09-04 11:51:04 -0700252 log_info("Validating %s=%s\n", key, value);
253
William Robertsf0e0a942012-08-27 15:41:15 -0700254 /* Booleans can always be checked for sanity */
255 if (type == dt_bool && (!strcmp("true", value) || !strcmp("false", value))) {
256 goto out;
257 }
258 else if (type == dt_bool) {
William Robertsae23a1f2012-09-05 12:53:52 -0700259 log_error("Expected boolean value got: %s=%s on line: %d in file: %s\n",
260 key, value, lineno, out_file_name);
William Robertsf0e0a942012-08-27 15:41:15 -0700261 rc = 0;
262 goto out;
263 }
264
Stephen Smalley38084142012-11-28 10:46:18 -0500265 if (!strcasecmp(key, "levelFrom") &&
266 (strcasecmp(value, "none") && strcasecmp(value, "all") &&
267 strcasecmp(value, "app") && strcasecmp(value, "user"))) {
268 log_error("Unknown levelFrom=%s on line: %d in file: %s\n",
269 value, lineno, out_file_name);
270 rc = 0;
271 goto out;
272 }
273
William Robertsf0e0a942012-08-27 15:41:15 -0700274 /*
William Roberts63297212013-04-19 19:06:23 -0700275 * If there is no policy file present,
276 * then it is not going to enforce the types against the policy so just return.
William Robertsf0e0a942012-08-27 15:41:15 -0700277 * User and name cannot really be checked.
278 */
279 if (!pol.policy_file) {
280 goto out;
281 }
282 else if (!strcasecmp(key, "sebool")) {
283
284 ret = sepol_bool_key_create(pol.handle, value, &se_key);
285 if (ret < 0) {
286 log_error("Could not create selinux boolean key, error: %s\n",
287 strerror(errno));
288 rc = 0;
289 goto out;
290 }
291
292 ret = sepol_bool_exists(pol.handle, pol.db, se_key, &resp);
293 if (ret < 0) {
294 log_error("Could not check selinux boolean, error: %s\n",
295 strerror(errno));
296 rc = 0;
William Robertsa53ccf32012-09-17 12:53:44 -0700297 sepol_bool_key_free(se_key);
298 goto out;
William Robertsf0e0a942012-08-27 15:41:15 -0700299 }
300
301 if(!resp) {
302 log_error("Could not find selinux boolean \"%s\" on line: %d in file: %s\n",
303 value, lineno, out_file_name);
304 rc = 0;
William Robertsa53ccf32012-09-17 12:53:44 -0700305 sepol_bool_key_free(se_key);
306 goto out;
William Robertsf0e0a942012-08-27 15:41:15 -0700307 }
William Robertsa53ccf32012-09-17 12:53:44 -0700308 sepol_bool_key_free(se_key);
William Robertsf0e0a942012-08-27 15:41:15 -0700309 }
310 else if (!strcasecmp(key, "type") || !strcasecmp(key, "domain")) {
311
312 if(!check_type(pol.db, value)) {
313 log_error("Could not find selinux type \"%s\" on line: %d in file: %s\n", value,
314 lineno, out_file_name);
315 rc = 0;
316 }
317 goto out;
318 }
William Robertsf0e0a942012-08-27 15:41:15 -0700319 else if (!strcasecmp(key, "level")) {
320
William Roberts0ae3a8a2012-09-04 11:51:04 -0700321 ret = sepol_mls_check(pol.handle, pol.db, value);
322 if (ret < 0) {
William Robertsae23a1f2012-09-05 12:53:52 -0700323 log_error("Could not find selinux level \"%s\", on line: %d in file: %s\n", value,
324 lineno, out_file_name);
William Roberts0ae3a8a2012-09-04 11:51:04 -0700325 rc = 0;
326 goto out;
William Robertsf0e0a942012-08-27 15:41:15 -0700327 }
328 }
329
William Roberts0ae3a8a2012-09-04 11:51:04 -0700330out:
331 log_info("Key map validate returning: %d\n", rc);
332 return rc;
William Robertsf0e0a942012-08-27 15:41:15 -0700333}
334
335/**
336 * Prints a rule map back to a file
337 * @param fp
338 * The file handle to print too
339 * @param r
340 * The rule map to print
341 */
342static void rule_map_print(FILE *fp, rule_map *r) {
343
William Roberts610a4b12013-10-15 18:26:00 -0700344 size_t i;
William Robertsf0e0a942012-08-27 15:41:15 -0700345 key_map *m;
346
347 for (i = 0; i < r->length; i++) {
348 m = &(r->m[i]);
349 if (i < r->length - 1)
350 fprintf(fp, "%s=%s ", m->name, m->data);
351 else
352 fprintf(fp, "%s=%s", m->name, m->data);
353 }
354}
355
356/**
357 * Compare two rule maps for equality
358 * @param rmA
359 * a rule map to check
360 * @param rmB
361 * a rule map to check
362 * @return
William Robertsae23a1f2012-09-05 12:53:52 -0700363 * a map_match enum indicating the result
William Robertsf0e0a942012-08-27 15:41:15 -0700364 */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700365static map_match rule_map_cmp(rule_map *rmA, rule_map *rmB) {
William Robertsf0e0a942012-08-27 15:41:15 -0700366
William Roberts610a4b12013-10-15 18:26:00 -0700367 size_t i;
368 size_t j;
William Robertsf0e0a942012-08-27 15:41:15 -0700369 int inputs_found = 0;
370 int num_of_matched_inputs = 0;
371 int input_mode = 0;
William Roberts610a4b12013-10-15 18:26:00 -0700372 size_t matches = 0;
William Robertsf0e0a942012-08-27 15:41:15 -0700373 key_map *mA;
374 key_map *mB;
375
376 if (rmA->length != rmB->length)
William Roberts0ae3a8a2012-09-04 11:51:04 -0700377 return map_no_matches;
William Robertsf0e0a942012-08-27 15:41:15 -0700378
379 for (i = 0; i < rmA->length; i++) {
380 mA = &(rmA->m[i]);
381
382 for (j = 0; j < rmB->length; j++) {
383 mB = &(rmB->m[j]);
384 input_mode = 0;
385
386 if (mA->type != mB->type)
387 continue;
388
389 if (strcmp(mA->name, mB->name))
390 continue;
391
392 if (strcmp(mA->data, mB->data))
393 continue;
394
395 if (mB->dir != mA->dir)
396 continue;
397 else if (mB->dir == dir_in) {
398 input_mode = 1;
399 inputs_found++;
400 }
401
William Roberts0ae3a8a2012-09-04 11:51:04 -0700402 if (input_mode) {
William Roberts1e8c0612013-04-19 19:06:02 -0700403 log_info("Matched input lines: name=%s data=%s\n", mA->name, mA->data);
William Robertsf0e0a942012-08-27 15:41:15 -0700404 num_of_matched_inputs++;
William Roberts0ae3a8a2012-09-04 11:51:04 -0700405 }
William Robertsf0e0a942012-08-27 15:41:15 -0700406
407 /* Match found, move on */
William Roberts1e8c0612013-04-19 19:06:02 -0700408 log_info("Matched lines: name=%s data=%s", mA->name, mA->data);
William Robertsf0e0a942012-08-27 15:41:15 -0700409 matches++;
410 break;
411 }
412 }
413
414 /* If they all matched*/
William Roberts0ae3a8a2012-09-04 11:51:04 -0700415 if (matches == rmA->length) {
416 log_info("Rule map cmp MATCH\n");
417 return map_matched;
418 }
William Robertsf0e0a942012-08-27 15:41:15 -0700419
420 /* They didn't all match but the input's did */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700421 else if (num_of_matched_inputs == inputs_found) {
422 log_info("Rule map cmp INPUT MATCH\n");
423 return map_input_matched;
424 }
William Robertsf0e0a942012-08-27 15:41:15 -0700425
426 /* They didn't all match, and the inputs didn't match, ie it didn't
427 * match */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700428 else {
429 log_info("Rule map cmp NO MATCH\n");
430 return map_no_matches;
431 }
William Robertsf0e0a942012-08-27 15:41:15 -0700432}
433
434/**
435 * Frees a rule map
436 * @param rm
437 * rule map to be freed.
438 */
439static void rule_map_free(rule_map *rm, rule_map_switch s) {
440
William Roberts610a4b12013-10-15 18:26:00 -0700441 size_t i;
442 size_t len = rm->length;
William Robertsf0e0a942012-08-27 15:41:15 -0700443 for (i = 0; i < len; i++) {
444 key_map *m = &(rm->m[i]);
445 free(m->data);
446 }
447
rpcraig5dbfdc02012-10-23 11:03:47 -0400448/* hdestroy() frees comparsion keys for non glibc */
449#ifdef __GLIBC__
William Robertsf0e0a942012-08-27 15:41:15 -0700450 if(s == rule_map_destroy_key && rm->key)
451 free(rm->key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400452#endif
William Robertsf0e0a942012-08-27 15:41:15 -0700453
454 free(rm);
455}
456
457static void free_kvp(kvp *k) {
458 free(k->key);
459 free(k->value);
460}
461
462/**
William Roberts61846292013-10-15 09:38:24 -0700463 * Checks a rule_map for any variation of KVP's that shouldn't be allowed.
464 * Note that this function logs all errors.
465 *
466 * Current Checks:
467 * 1. That a specified name entry should have a specified seinfo entry as well.
468 * @param rm
469 * The rule map to check for validity.
470 * @return
471 * true if the rule is valid, false otherwise.
472 */
473static bool rule_map_validate(const rule_map *rm) {
474
William Roberts610a4b12013-10-15 18:26:00 -0700475 size_t i;
William Roberts61846292013-10-15 09:38:24 -0700476 bool found_name = false;
477 bool found_seinfo = false;
478 char *name = NULL;
Stephen Smalley7b2bee92013-10-31 09:22:26 -0400479 const key_map *tmp;
William Roberts61846292013-10-15 09:38:24 -0700480
481 for(i=0; i < rm->length; i++) {
482 tmp = &(rm->m[i]);
483
484 if(!strcmp(tmp->name, "name") && tmp->data) {
485 name = tmp->data;
486 found_name = true;
487 }
488 if(!strcmp(tmp->name, "seinfo") && tmp->data) {
489 found_seinfo = true;
490 }
491 }
492
493 if(found_name && !found_seinfo) {
494 log_error("No seinfo specified with name=\"%s\", on line: %d\n",
495 name, rm->lineno);
496 return false;
497 }
498
499 return true;
500}
501
502/**
William Robertsf0e0a942012-08-27 15:41:15 -0700503 * Given a set of key value pairs, this will construct a new rule map.
504 * On error this function calls exit.
505 * @param keys
506 * Keys from a rule line to map
507 * @param num_of_keys
508 * The length of the keys array
509 * @param lineno
510 * The line number the keys were extracted from
511 * @return
512 * A rule map pointer.
513 */
William Roberts610a4b12013-10-15 18:26:00 -0700514static rule_map *rule_map_new(kvp keys[], size_t num_of_keys, int lineno) {
William Robertsf0e0a942012-08-27 15:41:15 -0700515
William Roberts610a4b12013-10-15 18:26:00 -0700516 size_t i = 0, j = 0;
William Roberts61846292013-10-15 09:38:24 -0700517 bool valid_rule;
William Robertsf0e0a942012-08-27 15:41:15 -0700518 rule_map *new_map = NULL;
519 kvp *k = NULL;
520 key_map *r = NULL, *x = NULL;
521
522 new_map = calloc(1, (num_of_keys * sizeof(key_map)) + sizeof(rule_map));
523 if (!new_map)
524 goto oom;
525
526 new_map->length = num_of_keys;
527 new_map->lineno = lineno;
528
529 /* For all the keys in a rule line*/
530 for (i = 0; i < num_of_keys; i++) {
531 k = &(keys[i]);
532 r = &(new_map->m[i]);
533
534 for (j = 0; j < KVP_NUM_OF_RULES; j++) {
535 x = &(rules[j]);
536
537 /* Only assign key name to map name */
538 if (strcasecmp(k->key, x->name)) {
539 if (i == KVP_NUM_OF_RULES) {
540 log_error("No match for key: %s\n", k->key);
541 goto err;
542 }
543 continue;
544 }
545
546 memcpy(r, x, sizeof(key_map));
547
548 /* Assign rule map value to one from file */
549 r->data = strdup(k->value);
550 if (!r->data)
551 goto oom;
552
553 /* Enforce type check*/
William Roberts0ae3a8a2012-09-04 11:51:04 -0700554 log_info("Validating keys!\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700555 if (!key_map_validate(r, lineno)) {
556 log_error("Could not validate\n");
557 goto err;
558 }
559
560 /* Only build key off of inputs*/
561 if (r->dir == dir_in) {
562 char *tmp;
William Robertsb3ab56c2012-09-17 14:35:02 -0700563 int key_len = strlen(k->key);
564 int val_len = strlen(k->value);
565 int l = (new_map->key) ? strlen(new_map->key) : 0;
566 l = l + key_len + val_len;
William Robertsf0e0a942012-08-27 15:41:15 -0700567 l += 1;
568
569 tmp = realloc(new_map->key, l);
570 if (!tmp)
571 goto oom;
572
William Robertsb3ab56c2012-09-17 14:35:02 -0700573 if (!new_map->key)
574 memset(tmp, 0, l);
575
William Robertsf0e0a942012-08-27 15:41:15 -0700576 new_map->key = tmp;
577
William Robertsb3ab56c2012-09-17 14:35:02 -0700578 strncat(new_map->key, k->key, key_len);
579 strncat(new_map->key, k->value, val_len);
William Robertsf0e0a942012-08-27 15:41:15 -0700580 }
581 break;
582 }
583 free_kvp(k);
584 }
585
586 if (new_map->key == NULL) {
587 log_error("Strange, no keys found, input file corrupt perhaps?\n");
588 goto err;
589 }
590
William Roberts61846292013-10-15 09:38:24 -0700591 valid_rule = rule_map_validate(new_map);
592 if(!valid_rule) {
593 /* Error message logged from rule_map_validate() */
594 goto err;
595 }
596
William Robertsf0e0a942012-08-27 15:41:15 -0700597 return new_map;
598
599oom:
600 log_error("Out of memory!\n");
601err:
602 if(new_map) {
603 rule_map_free(new_map, rule_map_destroy_key);
604 for (; i < num_of_keys; i++) {
605 k = &(keys[i]);
606 free_kvp(k);
607 }
608 }
609 exit(EXIT_FAILURE);
610}
611
612/**
613 * Print the usage of the program
614 */
615static void usage() {
616 printf(
617 "checkseapp [options] <input file>\n"
618 "Processes an seapp_contexts file specified by argument <input file> (default stdin) "
William Robertsae23a1f2012-09-05 12:53:52 -0700619 "and allows later declarations to override previous ones on a match.\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700620 "Options:\n"
621 "-h - print this help message\n"
William Roberts63297212013-04-19 19:06:23 -0700622 "-s - enable strict checking of duplicates. This causes the program to exit on a duplicate entry with a non-zero exit status\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700623 "-v - enable verbose debugging informations\n"
William Roberts63297212013-04-19 19:06:23 -0700624 "-p policy file - specify policy file for strict checking of output selectors against the policy\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700625 "-o output file - specify output file, default is stdout\n");
626}
627
628static void init() {
629
630 /* If not set on stdin already */
631 if(!input_file) {
632 log_info("Opening input file: %s\n", in_file_name);
633 input_file = fopen(in_file_name, "r");
634 if (!input_file) {
635 log_error("Could not open file: %s error: %s\n", in_file_name, strerror(errno));
636 exit(EXIT_FAILURE);
637 }
638 }
639
640 /* If not set on std out already */
641 if(!output_file) {
642 output_file = fopen(out_file_name, "w+");
643 if (!output_file) {
644 log_error("Could not open file: %s error: %s\n", out_file_name, strerror(errno));
645 exit(EXIT_FAILURE);
646 }
647 }
648
649 if (pol.policy_file_name) {
650
651 log_info("Opening policy file: %s\n", pol.policy_file_name);
652 pol.policy_file = fopen(pol.policy_file_name, "rb");
653 if (!pol.policy_file) {
654 log_error("Could not open file: %s error: %s\n",
655 pol.policy_file_name, strerror(errno));
656 exit(EXIT_FAILURE);
657 }
658
659 pol.handle = sepol_handle_create();
660 if (!pol.handle) {
661 log_error("Could not create sepolicy handle: %s\n",
662 strerror(errno));
663 exit(EXIT_FAILURE);
664 }
665
666 if (sepol_policy_file_create(&pol.pf) < 0) {
667 log_error("Could not create sepolicy file: %s!\n",
668 strerror(errno));
669 exit(EXIT_FAILURE);
670 }
671
672 sepol_policy_file_set_fp(pol.pf, pol.policy_file);
673 sepol_policy_file_set_handle(pol.pf, pol.handle);
674
675 if (sepol_policydb_create(&pol.db) < 0) {
676 log_error("Could not create sepolicy db: %s!\n",
677 strerror(errno));
678 exit(EXIT_FAILURE);
679 }
680
681 if (sepol_policydb_read(pol.db, pol.pf) < 0) {
682 log_error("Could not lod policy file to db: %s!\n",
683 strerror(errno));
684 exit(EXIT_FAILURE);
685 }
686 }
687
688 log_info("Policy file set to: %s\n", (pol.policy_file_name == NULL) ? "None" : pol.policy_file_name);
689 log_info("Input file set to: %s\n", (in_file_name == NULL) ? "stdin" : in_file_name);
690 log_info("Output file set to: %s\n", (out_file_name == NULL) ? "stdout" : out_file_name);
691
William Roberts0ae3a8a2012-09-04 11:51:04 -0700692#if !defined(LINK_SEPOL_STATIC)
William Robertsa53ccf32012-09-17 12:53:44 -0700693 log_warn("LINK_SEPOL_STATIC is not defined\n""Not checking types!");
William Roberts0ae3a8a2012-09-04 11:51:04 -0700694#endif
695
William Robertsf0e0a942012-08-27 15:41:15 -0700696}
697
698/**
699 * Handle parsing and setting the global flags for the command line
700 * options. This function calls exit on failure.
701 * @param argc
702 * argument count
703 * @param argv
704 * argument list
705 */
706static void handle_options(int argc, char *argv[]) {
707
708 int c;
709 int num_of_args;
710
William Roberts63297212013-04-19 19:06:23 -0700711 while ((c = getopt(argc, argv, "ho:p:sv")) != -1) {
William Robertsf0e0a942012-08-27 15:41:15 -0700712 switch (c) {
713 case 'h':
714 usage();
715 exit(EXIT_SUCCESS);
716 case 'o':
717 out_file_name = optarg;
718 break;
719 case 'p':
720 pol.policy_file_name = optarg;
721 break;
William Roberts63297212013-04-19 19:06:23 -0700722 case 's':
723 is_strict = 1;
724 break;
William Robertsf0e0a942012-08-27 15:41:15 -0700725 case 'v':
726 log_set_verbose();
727 break;
728 case '?':
729 if (optopt == 'o' || optopt == 'p')
730 log_error("Option -%c requires an argument.\n", optopt);
731 else if (isprint (optopt))
732 log_error("Unknown option `-%c'.\n", optopt);
733 else {
734 log_error(
735 "Unknown option character `\\x%x'.\n",
736 optopt);
William Robertsf0e0a942012-08-27 15:41:15 -0700737 }
William Robertsf0e0a942012-08-27 15:41:15 -0700738 default:
739 exit(EXIT_FAILURE);
740 }
741 }
742
743 num_of_args = argc - optind;
744
745 if (num_of_args > 1) {
746 log_error("Too many arguments, expected 0 or 1, argument, got %d\n", num_of_args);
747 usage();
748 exit(EXIT_FAILURE);
749 } else if (num_of_args == 1) {
750 in_file_name = argv[argc - 1];
751 } else {
752 input_file = stdin;
753 in_file_name = "stdin";
754 }
755
756 if (!out_file_name) {
757 output_file = stdout;
758 out_file_name = "stdout";
759 }
760}
761
762/**
763 * Adds a rule_map double pointer, ie the hash table pointer to the list.
764 * By using a double pointer, the hash table can have a line be overridden
765 * and the value is updated in the list. This function calls exit on failure.
766 * @param rm
767 * the rule_map to add.
768 */
769static void list_add(hash_entry *e) {
770
771 line_order_list *node = malloc(sizeof(line_order_list));
772 if (node == NULL)
773 goto oom;
774
775 node->next = NULL;
776 node->e = e;
777
778 if (list_head == NULL)
779 list_head = list_tail = node;
780 else {
781 list_tail->next = node;
782 list_tail = list_tail->next;
783 }
784 return;
785
786oom:
787 log_error("Out of memory!\n");
788 exit(EXIT_FAILURE);
789}
790
791/**
792 * Free's the rule map list, which ultimatley contains
793 * all the malloc'd rule_maps.
794 */
795static void list_free() {
796 line_order_list *cursor, *tmp;
797 hash_entry *e;
798
799 cursor = list_head;
800 while (cursor) {
801 e = cursor->e;
802 rule_map_free(e->r, rule_map_destroy_key);
803 tmp = cursor;
804 cursor = cursor->next;
805 free(e);
806 free(tmp);
807 }
808}
809
810/**
811 * Adds a rule to the hash table and to the ordered list if needed.
812 * @param rm
813 * The rule map to add.
814 */
815static void rule_add(rule_map *rm) {
816
William Roberts0ae3a8a2012-09-04 11:51:04 -0700817 map_match cmp;
William Robertsf0e0a942012-08-27 15:41:15 -0700818 ENTRY e;
819 ENTRY *f;
820 hash_entry *entry;
821 hash_entry *tmp;
822 char *preserved_key;
823
824 e.key = rm->key;
825
William Roberts0ae3a8a2012-09-04 11:51:04 -0700826 log_info("Searching for key: %s\n", e.key);
William Robertsf0e0a942012-08-27 15:41:15 -0700827 /* Check to see if it has already been added*/
828 f = hsearch(e, FIND);
829
830 /*
831 * Since your only hashing on a partial key, the inputs we need to handle
832 * when you want to override the outputs for a given input set, as well as
833 * checking for duplicate entries.
834 */
835 if(f) {
William Roberts0ae3a8a2012-09-04 11:51:04 -0700836 log_info("Existing entry found!\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700837 tmp = (hash_entry *)f->data;
838 cmp = rule_map_cmp(rm, tmp->r);
William Roberts0ae3a8a2012-09-04 11:51:04 -0700839 log_info("Comparing on rule map ret: %d\n", cmp);
William Robertsf0e0a942012-08-27 15:41:15 -0700840 /* Override be freeing the old rule map and updating
841 the pointer */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700842 if(cmp != map_matched) {
William Robertsf0e0a942012-08-27 15:41:15 -0700843
844 /*
845 * DO NOT free key pointers given to the hash map, instead
846 * free the new key. The ordering here is critical!
847 */
848 preserved_key = tmp->r->key;
849 rule_map_free(tmp->r, rule_map_preserve_key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400850/* hdestroy() frees comparsion keys for non glibc */
851#ifdef __GLIBC__
William Robertsf0e0a942012-08-27 15:41:15 -0700852 free(rm->key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400853#endif
William Robertsf0e0a942012-08-27 15:41:15 -0700854 rm->key = preserved_key;
855 tmp->r = rm;
856 }
857 /* Duplicate */
858 else {
William Roberts63297212013-04-19 19:06:23 -0700859 /* if is_strict is set, then don't allow duplicates */
860 if(is_strict) {
861 log_error("Duplicate line detected in file: %s\n"
862 "Lines %d and %d match!\n",
863 out_file_name, tmp->r->lineno, rm->lineno);
864 rule_map_free(rm, rule_map_destroy_key);
865 goto err;
866 }
867
868 /* Allow duplicates, just drop the entry*/
869 log_info("Duplicate line detected in file: %s\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700870 "Lines %d and %d match!\n",
871 out_file_name, tmp->r->lineno, rm->lineno);
872 rule_map_free(rm, rule_map_destroy_key);
William Robertsf0e0a942012-08-27 15:41:15 -0700873 }
874 }
875 /* It wasn't found, just add the rule map to the table */
876 else {
877
878 entry = malloc(sizeof(hash_entry));
879 if (!entry)
880 goto oom;
881
882 entry->r = rm;
883 e.data = entry;
884
885 f = hsearch(e, ENTER);
886 if(f == NULL) {
887 goto oom;
888 }
889
890 /* new entries must be added to the ordered list */
891 entry->r = rm;
892 list_add(entry);
893 }
894
895 return;
896oom:
897 if (e.key)
898 free(e.key);
899 if (entry)
900 free(entry);
901 if (rm)
902 free(rm);
903 log_error("Out of memory in function: %s\n", __FUNCTION__);
904err:
905 exit(EXIT_FAILURE);
906}
907
908/**
909 * Parses the seapp_contexts file and adds them to the
910 * hash table and ordered list entries when it encounters them.
911 * Calls exit on failure.
912 */
913static void parse() {
914
915 char line_buf[BUFSIZ];
916 char *token;
917 unsigned lineno = 0;
918 char *p, *name = NULL, *value = NULL, *saveptr;
919 size_t len;
920 kvp keys[KVP_NUM_OF_RULES];
William Roberts610a4b12013-10-15 18:26:00 -0700921 size_t token_cnt = 0;
William Robertsf0e0a942012-08-27 15:41:15 -0700922
923 while (fgets(line_buf, sizeof line_buf - 1, input_file)) {
924
925 lineno++;
926 log_info("Got line %d\n", lineno);
927 len = strlen(line_buf);
928 if (line_buf[len - 1] == '\n')
Alice Chuf6647eb2012-10-30 16:27:00 -0700929 line_buf[len - 1] = '\0';
William Robertsf0e0a942012-08-27 15:41:15 -0700930 p = line_buf;
931 while (isspace(*p))
932 p++;
Alice Chuf6647eb2012-10-30 16:27:00 -0700933 if (*p == '#' || *p == '\0')
William Robertsf0e0a942012-08-27 15:41:15 -0700934 continue;
935
936 token = strtok_r(p, " \t", &saveptr);
937 if (!token)
938 goto err;
939
940 token_cnt = 0;
941 memset(keys, 0, sizeof(kvp) * KVP_NUM_OF_RULES);
942 while (1) {
William Roberts0ae3a8a2012-09-04 11:51:04 -0700943
William Robertsf0e0a942012-08-27 15:41:15 -0700944 name = token;
945 value = strchr(name, '=');
946 if (!value)
947 goto err;
948 *value++ = 0;
949
950 keys[token_cnt].key = strdup(name);
951 if (!keys[token_cnt].key)
952 goto oom;
953
954 keys[token_cnt].value = strdup(value);
955 if (!keys[token_cnt].value)
956 goto oom;
957
958 token_cnt++;
959
960 token = strtok_r(NULL, " \t", &saveptr);
961 if (!token)
962 break;
963
964 } /*End token parsing */
965
966 rule_map *r = rule_map_new(keys, token_cnt, lineno);
967 rule_add(r);
968
969 } /* End file parsing */
970 return;
971
972err:
973 log_error("reading %s, line %u, name %s, value %s\n",
974 in_file_name, lineno, name, value);
975 exit(EXIT_FAILURE);
976oom:
977 log_error("In function %s: Out of memory\n", __FUNCTION__);
978 exit(EXIT_FAILURE);
979}
980
981/**
982 * Should be called after parsing to cause the printing of the rule_maps
983 * stored in the ordered list, head first, which preserves the "first encountered"
984 * ordering.
985 */
986static void output() {
987
988 rule_map *r;
989 line_order_list *cursor;
990 cursor = list_head;
991
992 while (cursor) {
993 r = cursor->e->r;
994 rule_map_print(output_file, r);
995 cursor = cursor->next;
William Robertsa8613182012-09-05 11:23:40 -0700996 fprintf(output_file, "\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700997 }
998}
999
1000/**
1001 * This function is registered to the at exit handler and should clean up
1002 * the programs dynamic resources, such as memory and fd's.
1003 */
1004static void cleanup() {
1005
1006 /* Only close this when it was opened by me and not the crt */
1007 if (out_file_name && output_file) {
1008 log_info("Closing file: %s\n", out_file_name);
1009 fclose(output_file);
1010 }
1011
1012 /* Only close this when it was opened by me and not the crt */
1013 if (in_file_name && input_file) {
1014 log_info("Closing file: %s\n", in_file_name);
1015 fclose(input_file);
1016 }
1017
1018 if (pol.policy_file) {
1019
1020 log_info("Closing file: %s\n", pol.policy_file_name);
1021 fclose(pol.policy_file);
1022
1023 if (pol.db)
1024 sepol_policydb_free(pol.db);
1025
1026 if (pol.pf)
1027 sepol_policy_file_free(pol.pf);
1028
1029 if (pol.handle)
1030 sepol_handle_destroy(pol.handle);
1031 }
1032
1033 log_info("Freeing list\n");
1034 list_free();
1035 hdestroy();
1036}
1037
1038int main(int argc, char *argv[]) {
1039 if (!hcreate(TABLE_SIZE)) {
1040 log_error("Could not create hash table: %s\n", strerror(errno));
1041 exit(EXIT_FAILURE);
1042 }
1043 atexit(cleanup);
1044 handle_options(argc, argv);
1045 init();
1046 log_info("Starting to parse\n");
1047 parse();
1048 log_info("Parsing completed, generating output\n");
1049 output();
1050 log_info("Success, generated output\n");
1051 exit(EXIT_SUCCESS);
1052}