libbb: move capability names code to libbb
[oweals/busybox.git] / util-linux / setpriv.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * setpriv implementation for busybox based on linux-utils-ng 2.29
4  *
5  * Copyright (C) 2017 by  <assafgordon@gmail.com>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  */
9 //config:config SETPRIV
10 //config:       bool "setpriv (3.4 kb)"
11 //config:       default y
12 //config:       select PLATFORM_LINUX
13 //config:       select LONG_OPTS
14 //config:       help
15 //config:       Run a program with different Linux privilege settings.
16 //config:       Requires kernel >= 3.5
17 //config:
18 //config:config FEATURE_SETPRIV_DUMP
19 //config:       bool "Support dumping current privilege state"
20 //config:       default y
21 //config:       depends on SETPRIV
22 //config:       help
23 //config:       Enables the "--dump" switch to print out the current privilege
24 //config:       state. This is helpful for diagnosing problems.
25 //config:
26 //config:config FEATURE_SETPRIV_CAPABILITIES
27 //config:       bool "Support capabilities"
28 //config:       default y
29 //config:       depends on SETPRIV
30 //config:       help
31 //config:       Capabilities can be used to grant processes additional rights
32 //config:       without the necessity to always execute as the root user.
33 //config:       Enabling this option enables "--dump" to show information on
34 //config:       capabilities.
35 //config:
36 //config:config FEATURE_SETPRIV_CAPABILITY_NAMES
37 //config:       bool "Support capability names"
38 //config:       default y
39 //config:       depends on SETPRIV && FEATURE_SETPRIV_CAPABILITIES
40 //config:       help
41 //config:       Capabilities can be either referenced via a human-readble name,
42 //config:       e.g. "net_admin", or using their index, e.g. "cap_12". Enabling
43 //config:       this option allows using the human-readable names in addition to
44 //config:       the index-based names.
45
46 //applet:IF_SETPRIV(APPLET(setpriv, BB_DIR_BIN, BB_SUID_DROP))
47
48 //kbuild:lib-$(CONFIG_SETPRIV) += setpriv.o
49
50 //usage:#define setpriv_trivial_usage
51 //usage:        "[OPTIONS] PROG [ARGS]"
52 //usage:#define setpriv_full_usage "\n\n"
53 //usage:       "Run PROG with different privilege settings\n"
54 //usage:        IF_FEATURE_SETPRIV_DUMP(
55 //usage:     "\n-d,--dump               Show current capabilities"
56 //usage:        )
57 //usage:     "\n--nnp,--no-new-privs    Ignore setuid/setgid bits and file capabilities"
58 //usage:        IF_FEATURE_SETPRIV_CAPABILITIES(
59 //usage:     "\n--inh-caps CAP,CAP      Set inheritable capabilities"
60 //usage:     "\n--ambient-caps CAP,CAP  Set ambient capabilities"
61 //usage:        )
62
63 //setpriv from util-linux 2.28:
64 // -d, --dump               show current state (and do not exec anything)
65 // --nnp, --no-new-privs    disallow granting new privileges
66 // --inh-caps <caps,...>    set inheritable capabilities
67 // --bounding-set <caps>    set capability bounding set
68 // --ruid <uid>             set real uid
69 // --euid <uid>             set effective uid
70 // --rgid <gid>             set real gid
71 // --egid <gid>             set effective gid
72 // --reuid <uid>            set real and effective uid
73 // --regid <gid>            set real and effective gid
74 // --clear-groups           clear supplementary groups
75 // --keep-groups            keep supplementary groups
76 // --groups <group,...>     set supplementary groups
77 // --securebits <bits>      set securebits
78 // --selinux-label <label>  set SELinux label
79 // --apparmor-profile <pr>  set AppArmor profile
80
81 #if ENABLE_FEATURE_SETPRIV_CAPABILITIES
82 #include <linux/capability.h>
83 // #include <sys/capability.h>
84 // This header is in libcap, but the functions are in libc.
85 // Comment in the header says this above capset/capget:
86 /* system calls - look to libc for function to system call mapping */
87 extern int capset(cap_user_header_t header, cap_user_data_t data);
88 extern int capget(cap_user_header_t header, const cap_user_data_t data);
89 // so for bbox, let's just repeat the declarations.
90 // This way, libcap needs not be installed in build environment.
91 #endif
92 #include <sys/prctl.h>
93 #include "libbb.h"
94
95 #ifndef PR_CAPBSET_READ
96 #define PR_CAPBSET_READ 23
97 #endif
98
99 #ifndef PR_SET_NO_NEW_PRIVS
100 #define PR_SET_NO_NEW_PRIVS 38
101 #endif
102
103 #ifndef PR_GET_NO_NEW_PRIVS
104 #define PR_GET_NO_NEW_PRIVS 39
105 #endif
106
107 #ifndef PR_CAP_AMBIENT
108 #define PR_CAP_AMBIENT 47
109 #define PR_CAP_AMBIENT_IS_SET 1
110 #define PR_CAP_AMBIENT_RAISE 2
111 #define PR_CAP_AMBIENT_LOWER 3
112 #endif
113
114 enum {
115         IF_FEATURE_SETPRIV_DUMP(OPTBIT_DUMP,)
116         IF_FEATURE_SETPRIV_CAPABILITIES(OPTBIT_INH,)
117         IF_FEATURE_SETPRIV_CAPABILITIES(OPTBIT_AMB,)
118         OPTBIT_NNP,
119
120         IF_FEATURE_SETPRIV_DUMP(OPT_DUMP = (1 << OPTBIT_DUMP),)
121         IF_FEATURE_SETPRIV_CAPABILITIES(OPT_INH  = (1 << OPTBIT_INH),)
122         IF_FEATURE_SETPRIV_CAPABILITIES(OPT_AMB  = (1 << OPTBIT_AMB),)
123         OPT_NNP  = (1 << OPTBIT_NNP),
124 };
125
126 #if ENABLE_FEATURE_SETPRIV_CAPABILITIES
127 struct caps {
128         struct __user_cap_header_struct header;
129         cap_user_data_t data;
130         int u32s;
131 };
132
133 static void getcaps(struct caps *caps)
134 {
135         static const uint8_t versions[] = {
136                 _LINUX_CAPABILITY_U32S_3, /* = 2 (fits into byte) */
137                 _LINUX_CAPABILITY_U32S_2, /* = 2 */
138                 _LINUX_CAPABILITY_U32S_1, /* = 1 */
139         };
140         int i;
141
142         caps->header.pid = 0;
143         for (i = 0; i < ARRAY_SIZE(versions); i++) {
144                 caps->header.version = versions[i];
145                 if (capget(&caps->header, NULL) == 0)
146                         goto got_it;
147         }
148         bb_simple_perror_msg_and_die("capget");
149  got_it:
150
151         switch (caps->header.version) {
152                 case _LINUX_CAPABILITY_VERSION_1:
153                         caps->u32s = _LINUX_CAPABILITY_U32S_1;
154                         break;
155                 case _LINUX_CAPABILITY_VERSION_2:
156                         caps->u32s = _LINUX_CAPABILITY_U32S_2;
157                         break;
158                 case _LINUX_CAPABILITY_VERSION_3:
159                         caps->u32s = _LINUX_CAPABILITY_U32S_3;
160                         break;
161                 default:
162                         bb_error_msg_and_die("unsupported capability version");
163         }
164
165         caps->data = xmalloc(sizeof(caps->data[0]) * caps->u32s);
166         if (capget(&caps->header, caps->data) < 0)
167                 bb_simple_perror_msg_and_die("capget");
168 }
169
170 static unsigned parse_cap(const char *cap)
171 {
172         switch (cap[0]) {
173         case '-':
174                 break;
175         case '+':
176                 break;
177         default:
178                 bb_error_msg_and_die("invalid capability '%s'", cap);
179                 break;
180         }
181
182         cap++;
183         return cap_name_to_number(cap);
184 }
185
186 static void set_inh_caps(char *capstring)
187 {
188         struct caps caps;
189
190         getcaps(&caps);
191
192         capstring = strtok(capstring, ",");
193         while (capstring) {
194                 unsigned cap;
195
196                 cap = parse_cap(capstring);
197                 if (CAP_TO_INDEX(cap) >= caps.u32s)
198                         bb_error_msg_and_die("invalid capability cap");
199
200                 if (capstring[0] == '+')
201                         caps.data[CAP_TO_INDEX(cap)].inheritable |= CAP_TO_MASK(cap);
202                 else
203                         caps.data[CAP_TO_INDEX(cap)].inheritable &= ~CAP_TO_MASK(cap);
204                 capstring = strtok(NULL, ",");
205         }
206
207         if ((capset(&caps.header, caps.data)) < 0)
208                 bb_perror_msg_and_die("capset");
209
210         if (ENABLE_FEATURE_CLEAN_UP)
211                 free(caps.data);
212 }
213
214 static void set_ambient_caps(char *string)
215 {
216         char *cap;
217
218         cap = strtok(string, ",");
219         while (cap) {
220                 unsigned index;
221
222                 index = parse_cap(cap);
223                 if (cap[0] == '+') {
224                         if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, index, 0, 0) < 0)
225                                 bb_perror_msg("cap_ambient_raise");
226                 } else {
227                         if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_LOWER, index, 0, 0) < 0)
228                                 bb_perror_msg("cap_ambient_lower");
229                 }
230                 cap = strtok(NULL, ",");
231         }
232 }
233 #endif /* FEATURE_SETPRIV_CAPABILITIES */
234
235 #if ENABLE_FEATURE_SETPRIV_DUMP
236 # if !ENABLE_FEATURE_SETPRIV_CAPABILITY_NAMES
237 #  define printf_cap(pfx, cap_no) printf("%scap_%u", (pfx), (cap_no))
238 # endif
239
240 static int dump(void)
241 {
242         IF_FEATURE_SETPRIV_CAPABILITIES(struct caps caps;)
243         const char *fmt;
244         uid_t ruid, euid, suid;
245         gid_t rgid, egid, sgid;
246         gid_t *gids;
247         int i, ngids, nnp;
248
249         getresuid(&ruid, &euid, &suid); /* never fails in Linux */
250         getresgid(&rgid, &egid, &sgid); /* never fails in Linux */
251         ngids = 0;
252         gids = bb_getgroups(&ngids, NULL); /* never fails in Linux */
253
254         nnp = prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0);
255         if (nnp < 0)
256                 bb_perror_msg_and_die("prctl: %s", "GET_NO_NEW_PRIVS");
257
258         printf("uid: %u\n", (unsigned)ruid);
259         printf("euid: %u\n", (unsigned)euid);
260         printf("gid: %u\n", (unsigned)rgid);
261         printf("egid: %u\n", (unsigned)egid);
262
263         printf("Supplementary groups: ");
264         if (ngids == 0) {
265                 printf("[none]");
266         } else {
267                 fmt = ",%u" + 1;
268                 for (i = 0; i < ngids; i++) {
269                         printf(fmt, (unsigned)gids[i]);
270                         fmt = ",%u";
271                 }
272         }
273         printf("\nno_new_privs: %d\n", nnp);
274
275 # if ENABLE_FEATURE_SETPRIV_CAPABILITIES
276         getcaps(&caps);
277         printf("Inheritable capabilities: ");
278         fmt = "";
279         for (i = 0; cap_valid(i); i++) {
280                 unsigned idx = CAP_TO_INDEX(i);
281                 if (idx >= caps.u32s) {
282                         printf("\nindex: %u u32s: %u capability: %u\n", idx, caps.u32s, i);
283                         bb_error_msg_and_die("unsupported capability");
284                 }
285                 if (caps.data[idx].inheritable & CAP_TO_MASK(i)) {
286                         printf_cap(fmt, i);
287                         fmt = ",";
288                 }
289         }
290         if (!fmt[0])
291                 printf("[none]");
292
293         printf("\nAmbient capabilities: ");
294         fmt = "";
295         for (i = 0; cap_valid(i); i++) {
296                 int ret = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, (unsigned long) i, 0UL, 0UL);
297                 if (ret < 0)
298                         bb_perror_msg_and_die("prctl: %s", "CAP_AMBIENT_IS_SET");
299                 if (ret) {
300                         printf_cap(fmt, i);
301                         fmt = ",";
302                 }
303         }
304         if (i == 0)
305                 printf("[unsupported]");
306         else if (!fmt[0])
307                 printf("[none]");
308
309         printf("\nCapability bounding set: ");
310         fmt = "";
311         for (i = 0; cap_valid(i); i++) {
312                 int ret = prctl(PR_CAPBSET_READ, (unsigned long) i, 0UL, 0UL, 0UL);
313                 if (ret < 0)
314                         bb_perror_msg_and_die("prctl: %s", "CAPBSET_READ");
315                 if (ret) {
316                         printf_cap(fmt, i);
317                         fmt = ",";
318                 }
319         }
320         if (!fmt[0])
321                 printf("[none]");
322         bb_putchar('\n');
323 # endif
324
325         if (ENABLE_FEATURE_CLEAN_UP) {
326                 IF_FEATURE_SETPRIV_CAPABILITIES(free(caps.data);)
327                 free(gids);
328         }
329         return EXIT_SUCCESS;
330 }
331 #endif /* FEATURE_SETPRIV_DUMP */
332
333 int setpriv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
334 int setpriv_main(int argc UNUSED_PARAM, char **argv)
335 {
336         static const char setpriv_longopts[] ALIGN1 =
337                 IF_FEATURE_SETPRIV_DUMP(
338                 "dump\0"         No_argument            "d"
339                 )
340                 "nnp\0"          No_argument            "\xff"
341                 "no-new-privs\0" No_argument            "\xff"
342                 IF_FEATURE_SETPRIV_CAPABILITIES(
343                 "inh-caps\0"     Required_argument      "\xfe"
344                 "ambient-caps\0" Required_argument      "\xfd"
345                 )
346                 ;
347         int opts;
348         IF_FEATURE_SETPRIV_CAPABILITIES(char *inh_caps, *ambient_caps;)
349
350         opts = getopt32long(argv, "+"
351                 IF_FEATURE_SETPRIV_DUMP("d")
352                 IF_FEATURE_SETPRIV_CAPABILITIES("\xfe:\xfd:"),
353                 setpriv_longopts
354                 IF_FEATURE_SETPRIV_CAPABILITIES(, &inh_caps, &ambient_caps)
355         );
356         argv += optind;
357
358 #if ENABLE_FEATURE_SETPRIV_DUMP
359         if (opts & OPT_DUMP) {
360                 if (argv[0] || (opts - OPT_DUMP) != 0)
361                         bb_show_usage();
362                 return dump();
363         }
364 #endif
365         if (opts & OPT_NNP) {
366                 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
367                         bb_perror_msg_and_die("prctl: %s", "SET_NO_NEW_PRIVS");
368         }
369
370 #if ENABLE_FEATURE_SETPRIV_CAPABILITIES
371         if (opts & OPT_INH)
372                 set_inh_caps(inh_caps);
373         if (opts & OPT_AMB)
374                 set_ambient_caps(ambient_caps);
375 #endif
376
377         if (!argv[0])
378                 bb_show_usage();
379         BB_EXECVP_or_die(argv);
380 }