• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <sepol/module.h>
2 #include <getopt.h>
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <sys/mman.h>
11 #include <fcntl.h>
12 #include <errno.h>
13 
14 char *progname = NULL;
15 extern char *optarg;
16 
usage(void)17 static __attribute__((__noreturn__)) void usage(void)
18 {
19 	printf("usage: %s ppfile modfile [fcfile]\n", progname);
20 	exit(1);
21 }
22 
file_to_policy_file(const char * filename,struct sepol_policy_file ** pf,const char * mode)23 static int file_to_policy_file(const char *filename, struct sepol_policy_file **pf, const char *mode)
24 {
25 	FILE *f;
26 
27 	if (sepol_policy_file_create(pf)) {
28 		fprintf(stderr, "%s:  Out of memory\n", progname);
29 		return -1;
30 	}
31 
32 	f = fopen(filename, mode);
33 	if (!f) {
34 		fprintf(stderr, "%s:  Could not open file %s:  %s\n", progname, strerror(errno), filename);
35 		return -1;
36 	}
37 	sepol_policy_file_set_fp(*pf, f);
38 	return 0;
39 }
40 
main(int argc,char ** argv)41 int main(int argc, char **argv)
42 {
43 	struct sepol_module_package *pkg;
44 	struct sepol_policy_file *in, *out;
45 	FILE *fp;
46 	size_t len;
47 	char *ppfile, *modfile, *fcfile = NULL, *fcdata;
48 
49 	progname = argv[0];
50 
51 	if (argc < 3) {
52 		usage();
53 		exit(1);
54 	}
55 
56 	ppfile = argv[1];
57 	modfile = argv[2];
58 	if (argc >= 3)
59 		fcfile = argv[3];
60 
61 	if (file_to_policy_file(ppfile, &in, "r"))
62 		exit(1);
63 
64 	if (sepol_module_package_create(&pkg)) {
65                 fprintf(stderr, "%s:  Out of memory\n", progname);
66                 exit(1);
67 	}
68 
69 	if (sepol_module_package_read(pkg, in, 0) == -1) {
70                 fprintf(stderr, "%s:  Error while reading policy module from %s\n",
71 			progname, ppfile);
72                 exit(1);
73 	}
74 
75 	if (file_to_policy_file(modfile, &out, "w"))
76 		exit(1);
77 
78         if (sepol_policydb_write(sepol_module_package_get_policy(pkg), out)) {
79                 fprintf(stderr, "%s:  Error while writing module to %s\n", progname, modfile);
80                 exit(1);
81         }
82 
83 	sepol_policy_file_free(in);
84 	sepol_policy_file_free(out);
85 
86 	len = sepol_module_package_get_file_contexts_len(pkg);
87 	if (fcfile && len) {
88 		fp = fopen(fcfile, "w");
89 		if (!fp) {
90 			fprintf(stderr, "%s:  Could not open file %s:  %s\n", progname, strerror(errno), fcfile);
91 			exit(1);
92 		}
93 		fcdata = sepol_module_package_get_file_contexts(pkg);
94 		if (fwrite(fcdata, 1, len, fp) != len) {
95 			fprintf(stderr, "%s:  Could not write file %s:  %s\n", progname, strerror(errno), fcfile);
96 			exit(1);
97 		}
98 		fclose(fp);
99 	}
100 
101 	sepol_module_package_free(pkg);
102 	exit(0);
103 }
104