• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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] [-s service] user [fromcon]\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 * usercon = NULL, *cur_context = NULL;
23 	char *user = NULL, *level = NULL, *role=NULL, *seuser=NULL, *dlevel=NULL;
24 	char *service = NULL;
25 	int ret, opt;
26 	int verbose = 0;
27 
28 	while ((opt = getopt(argc, argv, "l:r:s:v")) > 0) {
29 		switch (opt) {
30 		case 'l':
31 			free(level);
32 			level = strdup(optarg);
33 			break;
34 		case 'r':
35 			free(role);
36 			role = strdup(optarg);
37 			break;
38 		case 's':
39 			free(service);
40 			service = strdup(optarg);
41 			break;
42 		case 'v':
43 			verbose = 1;
44 			break;
45 		default:
46 			usage(argv[0], "invalid option", 1);
47 		}
48 	}
49 
50 	if (((argc - optind) < 1) || ((argc - optind) > 2))
51 		usage(argv[0], "invalid number of arguments", 2);
52 
53 	/* If selinux isn't available, bail out. */
54 	if (!is_selinux_enabled()) {
55 		fprintf(stderr,
56 			"%s may be used only on a SELinux kernel.\n", argv[0]);
57 		return 1;
58 	}
59 
60 	user = argv[optind];
61 
62 	/* If a context wasn't passed, use the current context. */
63 	if (((argc - optind) < 2)) {
64 		if (getcon(&cur_context) < 0) {
65 			fprintf(stderr, "Couldn't get current context.\n");
66 			return 2;
67 		}
68 	} else
69 		cur_context = argv[optind + 1];
70 
71 	if ((ret = getseuser(user, service, &seuser, &dlevel)) == 0) {
72 		if (! level) level=dlevel;
73 		if (role != NULL && role[0])
74 			ret=get_default_context_with_rolelevel(seuser, role, level,cur_context,&usercon);
75 		else
76 			ret=get_default_context_with_level(seuser, level, cur_context,&usercon);
77 	}
78 	if (ret < 0)
79 		perror(argv[0]);
80 	else {
81 		if (verbose) {
82 			printf("%s: %s from %s %s %s %s -> %s\n", argv[0], user, cur_context, seuser, role, level, usercon);
83 		} else {
84 			printf("%s\n", usercon);
85 		}
86 	}
87 
88 	free(role);
89 	free(seuser);
90 	if (level != dlevel) free(level);
91 	free(dlevel);
92 	free(usercon);
93 
94 	return ret >= 0;
95 }
96