1 #include <unistd.h>
2 #include <sys/types.h>
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <errno.h>
7 #include <string.h>
8 #include <ctype.h>
9 #include <selinux/selinux.h>
10 #include <selinux/get_context_list.h>
11
usage(const char * name,const char * detail,int rc)12 static __attribute__ ((__noreturn__)) void usage(const char *name, const char *detail, int rc)
13 {
14 fprintf(stderr, "usage: %s [-l level] user [context]\n", name);
15 if (detail)
16 fprintf(stderr, "%s: %s\n", name, detail);
17 exit(rc);
18 }
19
main(int argc,char ** argv)20 int main(int argc, char **argv)
21 {
22 char **list;
23 const char *cur_context, *user;
24 char *cur_con = NULL, *level = NULL;
25 int ret, i, opt;
26
27 while ((opt = getopt(argc, argv, "l:")) > 0) {
28 switch (opt) {
29 case 'l':
30 free(level);
31 level = strdup(optarg);
32 if (!level) {
33 fprintf(stderr, "memory allocation failure: %d(%s)\n",
34 errno, strerror(errno));
35 return 3;
36 }
37 break;
38 default:
39 usage(argv[0], "invalid option", 1);
40 }
41 }
42
43 if (((argc - optind) < 1) || ((argc - optind) > 2))
44 usage(argv[0], "invalid number of arguments", 2);
45
46 /* If selinux isn't available, bail out. */
47 if (!is_selinux_enabled()) {
48 fprintf(stderr,
49 "getconlist may be used only on a SELinux kernel.\n");
50 free(level);
51 return 1;
52 }
53
54 user = argv[optind];
55
56 /* If a context wasn't passed, use the current context. */
57 if (((argc - optind) < 2)) {
58 if (getcon(&cur_con) < 0) {
59 fprintf(stderr, "Couldn't get current context: %s\n", strerror(errno));
60 free(level);
61 return 2;
62 }
63 cur_context = cur_con;
64 } else {
65 cur_context = argv[optind + 1];
66 if (security_check_context(cur_context) != 0) {
67 fprintf(stderr, "Given context '%s' is invalid.\n", cur_context);
68 free(level);
69 return 3;
70 }
71 }
72
73 /* Get the list and print it */
74 if (level)
75 ret =
76 get_ordered_context_list_with_level(user, level,
77 cur_context, &list);
78 else
79 ret = get_ordered_context_list(user, cur_context, &list);
80 if (ret != -1) {
81 for (i = 0; list[i]; i++)
82 puts(list[i]);
83 freeconary(list);
84 } else {
85 fprintf(stderr, "get_ordered_context_list%s failure: %d(%s)\n",
86 level ? "_with_level" : "", errno, strerror(errno));
87 free(cur_con);
88 free(level);
89 return 4;
90 }
91
92 free(cur_con);
93 free(level);
94
95 return 0;
96 }
97