blob: 19e2ab28b14b03e6cd307ff5e47893b61d6a7b0c [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 */
Robert Craigc9bb91d2013-11-01 10:24:36 -0400439static void rule_map_free(rule_map *rm,
440 rule_map_switch s __attribute__((unused)) /* only glibc builds, ignored otherwise */) {
William Robertsf0e0a942012-08-27 15:41:15 -0700441
William Roberts610a4b12013-10-15 18:26:00 -0700442 size_t i;
443 size_t len = rm->length;
William Robertsf0e0a942012-08-27 15:41:15 -0700444 for (i = 0; i < len; i++) {
445 key_map *m = &(rm->m[i]);
446 free(m->data);
447 }
448
rpcraig5dbfdc02012-10-23 11:03:47 -0400449/* hdestroy() frees comparsion keys for non glibc */
450#ifdef __GLIBC__
William Robertsf0e0a942012-08-27 15:41:15 -0700451 if(s == rule_map_destroy_key && rm->key)
452 free(rm->key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400453#endif
William Robertsf0e0a942012-08-27 15:41:15 -0700454
455 free(rm);
456}
457
458static void free_kvp(kvp *k) {
459 free(k->key);
460 free(k->value);
461}
462
463/**
William Roberts61846292013-10-15 09:38:24 -0700464 * Checks a rule_map for any variation of KVP's that shouldn't be allowed.
465 * Note that this function logs all errors.
466 *
467 * Current Checks:
468 * 1. That a specified name entry should have a specified seinfo entry as well.
469 * @param rm
470 * The rule map to check for validity.
471 * @return
472 * true if the rule is valid, false otherwise.
473 */
474static bool rule_map_validate(const rule_map *rm) {
475
William Roberts610a4b12013-10-15 18:26:00 -0700476 size_t i;
William Roberts61846292013-10-15 09:38:24 -0700477 bool found_name = false;
478 bool found_seinfo = false;
479 char *name = NULL;
Stephen Smalley7b2bee92013-10-31 09:22:26 -0400480 const key_map *tmp;
William Roberts61846292013-10-15 09:38:24 -0700481
482 for(i=0; i < rm->length; i++) {
483 tmp = &(rm->m[i]);
484
485 if(!strcmp(tmp->name, "name") && tmp->data) {
486 name = tmp->data;
487 found_name = true;
488 }
489 if(!strcmp(tmp->name, "seinfo") && tmp->data) {
490 found_seinfo = true;
491 }
492 }
493
494 if(found_name && !found_seinfo) {
495 log_error("No seinfo specified with name=\"%s\", on line: %d\n",
496 name, rm->lineno);
497 return false;
498 }
499
500 return true;
501}
502
503/**
William Robertsf0e0a942012-08-27 15:41:15 -0700504 * Given a set of key value pairs, this will construct a new rule map.
505 * On error this function calls exit.
506 * @param keys
507 * Keys from a rule line to map
508 * @param num_of_keys
509 * The length of the keys array
510 * @param lineno
511 * The line number the keys were extracted from
512 * @return
513 * A rule map pointer.
514 */
William Roberts610a4b12013-10-15 18:26:00 -0700515static rule_map *rule_map_new(kvp keys[], size_t num_of_keys, int lineno) {
William Robertsf0e0a942012-08-27 15:41:15 -0700516
William Roberts610a4b12013-10-15 18:26:00 -0700517 size_t i = 0, j = 0;
William Roberts61846292013-10-15 09:38:24 -0700518 bool valid_rule;
William Robertsf0e0a942012-08-27 15:41:15 -0700519 rule_map *new_map = NULL;
520 kvp *k = NULL;
521 key_map *r = NULL, *x = NULL;
522
523 new_map = calloc(1, (num_of_keys * sizeof(key_map)) + sizeof(rule_map));
524 if (!new_map)
525 goto oom;
526
527 new_map->length = num_of_keys;
528 new_map->lineno = lineno;
529
530 /* For all the keys in a rule line*/
531 for (i = 0; i < num_of_keys; i++) {
532 k = &(keys[i]);
533 r = &(new_map->m[i]);
534
535 for (j = 0; j < KVP_NUM_OF_RULES; j++) {
536 x = &(rules[j]);
537
538 /* Only assign key name to map name */
539 if (strcasecmp(k->key, x->name)) {
540 if (i == KVP_NUM_OF_RULES) {
541 log_error("No match for key: %s\n", k->key);
542 goto err;
543 }
544 continue;
545 }
546
547 memcpy(r, x, sizeof(key_map));
548
549 /* Assign rule map value to one from file */
550 r->data = strdup(k->value);
551 if (!r->data)
552 goto oom;
553
554 /* Enforce type check*/
William Roberts0ae3a8a2012-09-04 11:51:04 -0700555 log_info("Validating keys!\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700556 if (!key_map_validate(r, lineno)) {
557 log_error("Could not validate\n");
558 goto err;
559 }
560
561 /* Only build key off of inputs*/
562 if (r->dir == dir_in) {
563 char *tmp;
William Robertsb3ab56c2012-09-17 14:35:02 -0700564 int key_len = strlen(k->key);
565 int val_len = strlen(k->value);
566 int l = (new_map->key) ? strlen(new_map->key) : 0;
567 l = l + key_len + val_len;
William Robertsf0e0a942012-08-27 15:41:15 -0700568 l += 1;
569
570 tmp = realloc(new_map->key, l);
571 if (!tmp)
572 goto oom;
573
William Robertsb3ab56c2012-09-17 14:35:02 -0700574 if (!new_map->key)
575 memset(tmp, 0, l);
576
William Robertsf0e0a942012-08-27 15:41:15 -0700577 new_map->key = tmp;
578
William Robertsb3ab56c2012-09-17 14:35:02 -0700579 strncat(new_map->key, k->key, key_len);
580 strncat(new_map->key, k->value, val_len);
William Robertsf0e0a942012-08-27 15:41:15 -0700581 }
582 break;
583 }
584 free_kvp(k);
585 }
586
587 if (new_map->key == NULL) {
588 log_error("Strange, no keys found, input file corrupt perhaps?\n");
589 goto err;
590 }
591
William Roberts61846292013-10-15 09:38:24 -0700592 valid_rule = rule_map_validate(new_map);
593 if(!valid_rule) {
594 /* Error message logged from rule_map_validate() */
595 goto err;
596 }
597
William Robertsf0e0a942012-08-27 15:41:15 -0700598 return new_map;
599
600oom:
601 log_error("Out of memory!\n");
602err:
603 if(new_map) {
604 rule_map_free(new_map, rule_map_destroy_key);
605 for (; i < num_of_keys; i++) {
606 k = &(keys[i]);
607 free_kvp(k);
608 }
609 }
610 exit(EXIT_FAILURE);
611}
612
613/**
614 * Print the usage of the program
615 */
616static void usage() {
617 printf(
618 "checkseapp [options] <input file>\n"
619 "Processes an seapp_contexts file specified by argument <input file> (default stdin) "
William Robertsae23a1f2012-09-05 12:53:52 -0700620 "and allows later declarations to override previous ones on a match.\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700621 "Options:\n"
622 "-h - print this help message\n"
William Roberts63297212013-04-19 19:06:23 -0700623 "-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 -0700624 "-v - enable verbose debugging informations\n"
William Roberts63297212013-04-19 19:06:23 -0700625 "-p policy file - specify policy file for strict checking of output selectors against the policy\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700626 "-o output file - specify output file, default is stdout\n");
627}
628
629static void init() {
630
631 /* If not set on stdin already */
632 if(!input_file) {
633 log_info("Opening input file: %s\n", in_file_name);
634 input_file = fopen(in_file_name, "r");
635 if (!input_file) {
636 log_error("Could not open file: %s error: %s\n", in_file_name, strerror(errno));
637 exit(EXIT_FAILURE);
638 }
639 }
640
641 /* If not set on std out already */
642 if(!output_file) {
643 output_file = fopen(out_file_name, "w+");
644 if (!output_file) {
645 log_error("Could not open file: %s error: %s\n", out_file_name, strerror(errno));
646 exit(EXIT_FAILURE);
647 }
648 }
649
650 if (pol.policy_file_name) {
651
652 log_info("Opening policy file: %s\n", pol.policy_file_name);
653 pol.policy_file = fopen(pol.policy_file_name, "rb");
654 if (!pol.policy_file) {
655 log_error("Could not open file: %s error: %s\n",
656 pol.policy_file_name, strerror(errno));
657 exit(EXIT_FAILURE);
658 }
659
660 pol.handle = sepol_handle_create();
661 if (!pol.handle) {
662 log_error("Could not create sepolicy handle: %s\n",
663 strerror(errno));
664 exit(EXIT_FAILURE);
665 }
666
667 if (sepol_policy_file_create(&pol.pf) < 0) {
668 log_error("Could not create sepolicy file: %s!\n",
669 strerror(errno));
670 exit(EXIT_FAILURE);
671 }
672
673 sepol_policy_file_set_fp(pol.pf, pol.policy_file);
674 sepol_policy_file_set_handle(pol.pf, pol.handle);
675
676 if (sepol_policydb_create(&pol.db) < 0) {
677 log_error("Could not create sepolicy db: %s!\n",
678 strerror(errno));
679 exit(EXIT_FAILURE);
680 }
681
682 if (sepol_policydb_read(pol.db, pol.pf) < 0) {
683 log_error("Could not lod policy file to db: %s!\n",
684 strerror(errno));
685 exit(EXIT_FAILURE);
686 }
687 }
688
689 log_info("Policy file set to: %s\n", (pol.policy_file_name == NULL) ? "None" : pol.policy_file_name);
690 log_info("Input file set to: %s\n", (in_file_name == NULL) ? "stdin" : in_file_name);
691 log_info("Output file set to: %s\n", (out_file_name == NULL) ? "stdout" : out_file_name);
692
William Roberts0ae3a8a2012-09-04 11:51:04 -0700693#if !defined(LINK_SEPOL_STATIC)
William Robertsa53ccf32012-09-17 12:53:44 -0700694 log_warn("LINK_SEPOL_STATIC is not defined\n""Not checking types!");
William Roberts0ae3a8a2012-09-04 11:51:04 -0700695#endif
696
William Robertsf0e0a942012-08-27 15:41:15 -0700697}
698
699/**
700 * Handle parsing and setting the global flags for the command line
701 * options. This function calls exit on failure.
702 * @param argc
703 * argument count
704 * @param argv
705 * argument list
706 */
707static void handle_options(int argc, char *argv[]) {
708
709 int c;
710 int num_of_args;
711
William Roberts63297212013-04-19 19:06:23 -0700712 while ((c = getopt(argc, argv, "ho:p:sv")) != -1) {
William Robertsf0e0a942012-08-27 15:41:15 -0700713 switch (c) {
714 case 'h':
715 usage();
716 exit(EXIT_SUCCESS);
717 case 'o':
718 out_file_name = optarg;
719 break;
720 case 'p':
721 pol.policy_file_name = optarg;
722 break;
William Roberts63297212013-04-19 19:06:23 -0700723 case 's':
724 is_strict = 1;
725 break;
William Robertsf0e0a942012-08-27 15:41:15 -0700726 case 'v':
727 log_set_verbose();
728 break;
729 case '?':
730 if (optopt == 'o' || optopt == 'p')
731 log_error("Option -%c requires an argument.\n", optopt);
732 else if (isprint (optopt))
733 log_error("Unknown option `-%c'.\n", optopt);
734 else {
735 log_error(
736 "Unknown option character `\\x%x'.\n",
737 optopt);
William Robertsf0e0a942012-08-27 15:41:15 -0700738 }
William Robertsf0e0a942012-08-27 15:41:15 -0700739 default:
740 exit(EXIT_FAILURE);
741 }
742 }
743
744 num_of_args = argc - optind;
745
746 if (num_of_args > 1) {
747 log_error("Too many arguments, expected 0 or 1, argument, got %d\n", num_of_args);
748 usage();
749 exit(EXIT_FAILURE);
750 } else if (num_of_args == 1) {
751 in_file_name = argv[argc - 1];
752 } else {
753 input_file = stdin;
754 in_file_name = "stdin";
755 }
756
757 if (!out_file_name) {
758 output_file = stdout;
759 out_file_name = "stdout";
760 }
761}
762
763/**
764 * Adds a rule_map double pointer, ie the hash table pointer to the list.
765 * By using a double pointer, the hash table can have a line be overridden
766 * and the value is updated in the list. This function calls exit on failure.
767 * @param rm
768 * the rule_map to add.
769 */
770static void list_add(hash_entry *e) {
771
772 line_order_list *node = malloc(sizeof(line_order_list));
773 if (node == NULL)
774 goto oom;
775
776 node->next = NULL;
777 node->e = e;
778
779 if (list_head == NULL)
780 list_head = list_tail = node;
781 else {
782 list_tail->next = node;
783 list_tail = list_tail->next;
784 }
785 return;
786
787oom:
788 log_error("Out of memory!\n");
789 exit(EXIT_FAILURE);
790}
791
792/**
793 * Free's the rule map list, which ultimatley contains
794 * all the malloc'd rule_maps.
795 */
796static void list_free() {
797 line_order_list *cursor, *tmp;
798 hash_entry *e;
799
800 cursor = list_head;
801 while (cursor) {
802 e = cursor->e;
803 rule_map_free(e->r, rule_map_destroy_key);
804 tmp = cursor;
805 cursor = cursor->next;
806 free(e);
807 free(tmp);
808 }
809}
810
811/**
812 * Adds a rule to the hash table and to the ordered list if needed.
813 * @param rm
814 * The rule map to add.
815 */
816static void rule_add(rule_map *rm) {
817
William Roberts0ae3a8a2012-09-04 11:51:04 -0700818 map_match cmp;
William Robertsf0e0a942012-08-27 15:41:15 -0700819 ENTRY e;
820 ENTRY *f;
821 hash_entry *entry;
822 hash_entry *tmp;
823 char *preserved_key;
824
825 e.key = rm->key;
826
William Roberts0ae3a8a2012-09-04 11:51:04 -0700827 log_info("Searching for key: %s\n", e.key);
William Robertsf0e0a942012-08-27 15:41:15 -0700828 /* Check to see if it has already been added*/
829 f = hsearch(e, FIND);
830
831 /*
832 * Since your only hashing on a partial key, the inputs we need to handle
833 * when you want to override the outputs for a given input set, as well as
834 * checking for duplicate entries.
835 */
836 if(f) {
William Roberts0ae3a8a2012-09-04 11:51:04 -0700837 log_info("Existing entry found!\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700838 tmp = (hash_entry *)f->data;
839 cmp = rule_map_cmp(rm, tmp->r);
William Roberts0ae3a8a2012-09-04 11:51:04 -0700840 log_info("Comparing on rule map ret: %d\n", cmp);
William Robertsf0e0a942012-08-27 15:41:15 -0700841 /* Override be freeing the old rule map and updating
842 the pointer */
William Roberts0ae3a8a2012-09-04 11:51:04 -0700843 if(cmp != map_matched) {
William Robertsf0e0a942012-08-27 15:41:15 -0700844
845 /*
846 * DO NOT free key pointers given to the hash map, instead
847 * free the new key. The ordering here is critical!
848 */
849 preserved_key = tmp->r->key;
850 rule_map_free(tmp->r, rule_map_preserve_key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400851/* hdestroy() frees comparsion keys for non glibc */
852#ifdef __GLIBC__
William Robertsf0e0a942012-08-27 15:41:15 -0700853 free(rm->key);
rpcraig5dbfdc02012-10-23 11:03:47 -0400854#endif
William Robertsf0e0a942012-08-27 15:41:15 -0700855 rm->key = preserved_key;
856 tmp->r = rm;
857 }
858 /* Duplicate */
859 else {
William Roberts63297212013-04-19 19:06:23 -0700860 /* if is_strict is set, then don't allow duplicates */
861 if(is_strict) {
862 log_error("Duplicate line detected in file: %s\n"
863 "Lines %d and %d match!\n",
864 out_file_name, tmp->r->lineno, rm->lineno);
865 rule_map_free(rm, rule_map_destroy_key);
866 goto err;
867 }
868
869 /* Allow duplicates, just drop the entry*/
870 log_info("Duplicate line detected in file: %s\n"
William Robertsf0e0a942012-08-27 15:41:15 -0700871 "Lines %d and %d match!\n",
872 out_file_name, tmp->r->lineno, rm->lineno);
873 rule_map_free(rm, rule_map_destroy_key);
William Robertsf0e0a942012-08-27 15:41:15 -0700874 }
875 }
876 /* It wasn't found, just add the rule map to the table */
877 else {
878
879 entry = malloc(sizeof(hash_entry));
880 if (!entry)
881 goto oom;
882
883 entry->r = rm;
884 e.data = entry;
885
886 f = hsearch(e, ENTER);
887 if(f == NULL) {
888 goto oom;
889 }
890
891 /* new entries must be added to the ordered list */
892 entry->r = rm;
893 list_add(entry);
894 }
895
896 return;
897oom:
898 if (e.key)
899 free(e.key);
900 if (entry)
901 free(entry);
902 if (rm)
903 free(rm);
904 log_error("Out of memory in function: %s\n", __FUNCTION__);
905err:
906 exit(EXIT_FAILURE);
907}
908
909/**
910 * Parses the seapp_contexts file and adds them to the
911 * hash table and ordered list entries when it encounters them.
912 * Calls exit on failure.
913 */
914static void parse() {
915
916 char line_buf[BUFSIZ];
917 char *token;
918 unsigned lineno = 0;
919 char *p, *name = NULL, *value = NULL, *saveptr;
920 size_t len;
921 kvp keys[KVP_NUM_OF_RULES];
William Roberts610a4b12013-10-15 18:26:00 -0700922 size_t token_cnt = 0;
William Robertsf0e0a942012-08-27 15:41:15 -0700923
924 while (fgets(line_buf, sizeof line_buf - 1, input_file)) {
925
926 lineno++;
927 log_info("Got line %d\n", lineno);
928 len = strlen(line_buf);
929 if (line_buf[len - 1] == '\n')
Alice Chuf6647eb2012-10-30 16:27:00 -0700930 line_buf[len - 1] = '\0';
William Robertsf0e0a942012-08-27 15:41:15 -0700931 p = line_buf;
932 while (isspace(*p))
933 p++;
Alice Chuf6647eb2012-10-30 16:27:00 -0700934 if (*p == '#' || *p == '\0')
William Robertsf0e0a942012-08-27 15:41:15 -0700935 continue;
936
937 token = strtok_r(p, " \t", &saveptr);
938 if (!token)
939 goto err;
940
941 token_cnt = 0;
942 memset(keys, 0, sizeof(kvp) * KVP_NUM_OF_RULES);
943 while (1) {
William Roberts0ae3a8a2012-09-04 11:51:04 -0700944
William Robertsf0e0a942012-08-27 15:41:15 -0700945 name = token;
946 value = strchr(name, '=');
947 if (!value)
948 goto err;
949 *value++ = 0;
950
951 keys[token_cnt].key = strdup(name);
952 if (!keys[token_cnt].key)
953 goto oom;
954
955 keys[token_cnt].value = strdup(value);
956 if (!keys[token_cnt].value)
957 goto oom;
958
959 token_cnt++;
960
961 token = strtok_r(NULL, " \t", &saveptr);
962 if (!token)
963 break;
964
965 } /*End token parsing */
966
967 rule_map *r = rule_map_new(keys, token_cnt, lineno);
968 rule_add(r);
969
970 } /* End file parsing */
971 return;
972
973err:
974 log_error("reading %s, line %u, name %s, value %s\n",
975 in_file_name, lineno, name, value);
976 exit(EXIT_FAILURE);
977oom:
978 log_error("In function %s: Out of memory\n", __FUNCTION__);
979 exit(EXIT_FAILURE);
980}
981
982/**
983 * Should be called after parsing to cause the printing of the rule_maps
984 * stored in the ordered list, head first, which preserves the "first encountered"
985 * ordering.
986 */
987static void output() {
988
989 rule_map *r;
990 line_order_list *cursor;
991 cursor = list_head;
992
993 while (cursor) {
994 r = cursor->e->r;
995 rule_map_print(output_file, r);
996 cursor = cursor->next;
William Robertsa8613182012-09-05 11:23:40 -0700997 fprintf(output_file, "\n");
William Robertsf0e0a942012-08-27 15:41:15 -0700998 }
999}
1000
1001/**
1002 * This function is registered to the at exit handler and should clean up
1003 * the programs dynamic resources, such as memory and fd's.
1004 */
1005static void cleanup() {
1006
1007 /* Only close this when it was opened by me and not the crt */
1008 if (out_file_name && output_file) {
1009 log_info("Closing file: %s\n", out_file_name);
1010 fclose(output_file);
1011 }
1012
1013 /* Only close this when it was opened by me and not the crt */
1014 if (in_file_name && input_file) {
1015 log_info("Closing file: %s\n", in_file_name);
1016 fclose(input_file);
1017 }
1018
1019 if (pol.policy_file) {
1020
1021 log_info("Closing file: %s\n", pol.policy_file_name);
1022 fclose(pol.policy_file);
1023
1024 if (pol.db)
1025 sepol_policydb_free(pol.db);
1026
1027 if (pol.pf)
1028 sepol_policy_file_free(pol.pf);
1029
1030 if (pol.handle)
1031 sepol_handle_destroy(pol.handle);
1032 }
1033
1034 log_info("Freeing list\n");
1035 list_free();
1036 hdestroy();
1037}
1038
1039int main(int argc, char *argv[]) {
1040 if (!hcreate(TABLE_SIZE)) {
1041 log_error("Could not create hash table: %s\n", strerror(errno));
1042 exit(EXIT_FAILURE);
1043 }
1044 atexit(cleanup);
1045 handle_options(argc, argv);
1046 init();
1047 log_info("Starting to parse\n");
1048 parse();
1049 log_info("Parsing completed, generating output\n");
1050 output();
1051 log_info("Success, generated output\n");
1052 exit(EXIT_SUCCESS);
1053}