2 * Copyright (c) 1997,2007-8 Andrew G. Morgan <morgan@kernel.org>
4 * This sets/verifies the capabilities of a given file.
11 #include <sys/capability.h>
14 static void usage(void)
17 "usage: setcap [-q] [-v] (-r|-|<caps>) <filename> "
18 "[ ... (-r|-|<capsN>) <filenameN> ]\n"
20 " Note <filename> must be a regular (non-symlink) file.\n"
27 static int read_caps(int quiet, const char *filename, char *buffer)
32 fprintf(stderr, "Please enter caps for file [empty line to end]:\n");
35 int j = read(STDIN_FILENO, buffer, i);
38 fprintf(stderr, "\n[Error - aborting]\n");
42 if (j==0 || buffer[0] == '\n') {
56 return (i < MAXCAP ? 0:-1);
59 int main(int argc, char **argv)
61 int tried_to_cap_setfcap = 0;
62 char buffer[MAXCAP+1];
63 int retval, quiet=0, verify=0;
71 mycaps = cap_get_proc();
73 fprintf(stderr, "warning - unable to get process capabilities"
81 if (!strcmp(*++argv, "-q")) {
85 if (!strcmp(*argv, "-v")) {
90 if (!strcmp(*argv, "-r")) {
93 if (!strcmp(*argv,"-")) {
94 retval = read_caps(quiet, *argv, buffer);
102 cap_d = cap_from_text(text);
104 perror("fatal error");
112 result = cap_to_text(cap_d, &length);
113 fprintf(stderr, "caps set to: [%s]\n", result);
121 * Set the filesystem capability for this file.
128 cap_d = cap_from_text("=");
131 cap_on_file = cap_get_file(*++argv);
133 if (cap_on_file == NULL) {
134 cap_on_file = cap_from_text("=");
137 cmp = cap_compare(cap_on_file, cap_d);
138 cap_free(cap_on_file);
142 printf("%s differs in [%s%s%s]\n", *argv,
143 CAP_DIFFERS(cmp, CAP_PERMITTED) ? "p" : "",
144 CAP_DIFFERS(cmp, CAP_INHERITABLE) ? "i" : "",
145 CAP_DIFFERS(cmp, CAP_EFFECTIVE) ? "e" : "");
150 printf("%s: OK\n", *argv);
153 if (!tried_to_cap_setfcap) {
154 capflag = CAP_SETFCAP;
157 * Raise the effective CAP_SETFCAP.
159 if (cap_set_flag(mycaps, CAP_EFFECTIVE, 1, &capflag, CAP_SET)
161 perror("unable to manipulate CAP_SETFCAP - "
162 "try a newer libcap?");
165 if (cap_set_proc(mycaps) != 0) {
166 perror("unable to set CAP_SETFCAP effective capability");
169 tried_to_cap_setfcap = 1;
171 retval = cap_set_file(*++argv, cap_d);
174 "Failed to set capabilities on file `%s' (%s)\n",
175 argv[0], strerror(errno));