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, *cur_context = NULL;
23 char *user = NULL, *level = NULL;
24 int ret, i, opt;
25
26 while ((opt = getopt(argc, argv, "l:")) > 0) {
27 switch (opt) {
28 case 'l':
29 free(level);
30 level = strdup(optarg);
31 if (!level) {
32 fprintf(stderr, "memory allocation failure: %d(%s)\n",
33 errno, strerror(errno));
34 return 3;
35 }
36 break;
37 default:
38 usage(argv[0], "invalid option", 1);
39 }
40 }
41
42 if (((argc - optind) < 1) || ((argc - optind) > 2))
43 usage(argv[0], "invalid number of arguments", 2);
44
45 /* If selinux isn't available, bail out. */
46 if (!is_selinux_enabled()) {
47 fprintf(stderr,
48 "getconlist may be used only on a SELinux kernel.\n");
49 free(level);
50 return 1;
51 }
52
53 user = argv[optind];
54
55 /* If a context wasn't passed, use the current context. */
56 if (((argc - optind) < 2)) {
57 if (getcon(&cur_context) < 0) {
58 fprintf(stderr, "Couldn't get current context.\n");
59 free(level);
60 return 2;
61 }
62 } else {
63 cur_context = argv[optind + 1];
64 if (security_check_context(cur_context) != 0) {
65 fprintf(stderr, "Given context '%s' is invalid.\n", cur_context);
66 free(level);
67 return 3;
68 }
69 }
70
71 /* Get the list and print it */
72 if (level)
73 ret =
74 get_ordered_context_list_with_level(user, level,
75 cur_context, &list);
76 else
77 ret = get_ordered_context_list(user, cur_context, &list);
78 if (ret != -1) {
79 for (i = 0; list[i]; i++)
80 puts(list[i]);
81 freeconary(list);
82 } else {
83 fprintf(stderr, "get_ordered_context_list%s failure: %d(%s)\n",
84 level ? "_with_level" : "", errno, strerror(errno));
85 free(level);
86 return 4;
87 }
88
89 free(level);
90
91 return 0;
92 }
93