···44#include <unistd.h>
55#include <sys/types.h>
66#include <sys/stat.h>
77+#include <sys/xattr.h>
78#include <fcntl.h>
89#include <dirent.h>
910#include <assert.h>
1011#include <errno.h>
1112#include <linux/capability.h>
1212-#include <sys/capability.h>
1313#include <sys/prctl.h>
1414#include <limits.h>
1515-#include <cap-ng.h>
1515+#include <stdint.h>
1616+#include <syscall.h>
1717+#include <byteswap.h>
16181719// Make sure assertions are not compiled out, we use them to codify
1820// invariants about this program and we want it to fail fast and
···23252426// The WRAPPER_DIR macro is supplied at compile time so that it cannot
2527// be changed at runtime
2626-static char * wrapperDir = WRAPPER_DIR;
2828+static char *wrapper_dir = WRAPPER_DIR;
27292830// Wrapper debug variable name
2929-static char * wrapperDebug = "WRAPPER_DEBUG";
3131+static char *wrapper_debug = "WRAPPER_DEBUG";
30323131-// Update the capabilities of the running process to include the given
3232-// capability in the Ambient set.
3333-static void set_ambient_cap(cap_value_t cap)
3434-{
3535- capng_get_caps_process();
3333+#define CAP_SETPCAP 8
36343737- if (capng_update(CAPNG_ADD, CAPNG_INHERITABLE, (unsigned long) cap))
3838- {
3939- perror("cannot raise the capability into the Inheritable set\n");
4040- exit(1);
4141- }
3535+#if __BYTE_ORDER == __BIG_ENDIAN
3636+#define LE32_TO_H(x) bswap_32(x)
3737+#else
3838+#define LE32_TO_H(x) (x)
3939+#endif
42404343- capng_apply(CAPNG_SELECT_CAPS);
4444-4545- if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, (unsigned long) cap, 0, 0))
4646- {
4747- perror("cannot raise the capability into the Ambient set\n");
4848- exit(1);
4141+int get_last_cap(unsigned *last_cap) {
4242+ FILE* file = fopen("/proc/sys/kernel/cap_last_cap", "r");
4343+ if (file == NULL) {
4444+ int saved_errno = errno;
4545+ fprintf(stderr, "failed to open /proc/sys/kernel/cap_last_cap: %s\n", strerror(errno));
4646+ return -saved_errno;
4947 }
4848+ int res = fscanf(file, "%u", last_cap);
4949+ if (res == EOF) {
5050+ int saved_errno = errno;
5151+ fprintf(stderr, "could not read number from /proc/sys/kernel/cap_last_cap: %s\n", strerror(errno));
5252+ return -saved_errno;
5353+ }
5454+ fclose(file);
5555+ return 0;
5056}
51575258// Given the path to this program, fetch its configured capability set
5359// (as set by `setcap ... /path/to/file`) and raise those capabilities
5460// into the Ambient set.
5555-static int make_caps_ambient(const char *selfPath)
5656-{
5757- cap_t caps = cap_get_file(selfPath);
5858-5959- if(!caps)
6060- {
6161- if(getenv(wrapperDebug))
6262- fprintf(stderr, "no caps set or could not retrieve the caps for this file, not doing anything...");
6161+static int make_caps_ambient(const char *self_path) {
6262+ struct vfs_ns_cap_data data = {};
6363+ int r = getxattr(self_path, "security.capability", &data, sizeof(data));
63646565+ if (r < 0) {
6666+ if (errno == ENODATA) {
6767+ // no capabilities set
6868+ return 0;
6969+ }
7070+ fprintf(stderr, "cannot get capabilities for %s: %s", self_path, strerror(errno));
6471 return 1;
6572 }
66736767- // We use `cap_to_text` and iteration over the tokenized result
6868- // string because, as of libcap's current release, there is no
6969- // facility for retrieving an array of `cap_value_t`'s that can be
7070- // given to `prctl` in order to lift that capability into the
7171- // Ambient set.
7272- //
7373- // Some discussion was had around shot-gunning all of the
7474- // capabilities we know about into the Ambient set but that has a
7575- // security smell and I deemed the risk of the current
7676- // implementation crashing the program to be lower than the risk
7777- // of a privilege escalation security hole being introduced by
7878- // raising all capabilities, even ones we didn't intend for the
7979- // program, into the Ambient set.
8080- //
8181- // `cap_t` which is returned by `cap_get_*` is an opaque type and
8282- // even if we could retrieve the bitmasks (which, as far as I can
8383- // tell we cannot) in order to get the `cap_value_t`
8484- // representation for each capability we would have to take the
8585- // total number of capabilities supported and iterate over the
8686- // sequence of integers up-to that maximum total, testing each one
8787- // against the bitmask ((bitmask >> n) & 1) to see if it's set and
8888- // aggregating each "capability integer n" that is set in the
8989- // bitmask.
9090- //
9191- // That, combined with the fact that we can't easily get the
9292- // bitmask anyway seemed much more brittle than fetching the
9393- // `cap_t`, transforming it into a textual representation,
9494- // tokenizing the string, and using `cap_from_name` on the token
9595- // to get the `cap_value_t` that we need for `prctl`. There is
9696- // indeed risk involved if the output string format of
9797- // `cap_to_text` ever changes but at this time the combination of
9898- // factors involving the below list have led me to the conclusion
9999- // that the best implementation at this time is reading then
100100- // parsing with *lots of documentation* about why we're doing it
101101- // this way.
102102- //
103103- // 1. No explicit API for fetching an array of `cap_value_t`'s or
104104- // for transforming a `cap_t` into such a representation
105105- // 2. The risk of a crash is lower than lifting all capabilities
106106- // into the Ambient set
107107- // 3. libcap is depended on heavily in the Linux ecosystem so
108108- // there is a high chance that the output representation of
109109- // `cap_to_text` will not change which reduces our risk that
110110- // this parsing step will cause a crash
111111- //
112112- // The preferred method, should it ever be available in the
113113- // future, would be to use libcap API's to transform the result
114114- // from a `cap_get_*` into an array of `cap_value_t`'s that can
115115- // then be given to prctl.
116116- //
117117- // - Parnell
118118- ssize_t capLen;
119119- char* capstr = cap_to_text(caps, &capLen);
120120- cap_free(caps);
121121-122122- // TODO: For now, we assume that cap_to_text always starts its
123123- // result string with " =" and that the first capability is listed
124124- // immediately after that. We should verify this.
125125- assert(capLen >= 2);
126126- capstr += 2;
7474+ size_t size;
7575+ uint32_t version = LE32_TO_H(data.magic_etc) & VFS_CAP_REVISION_MASK;
7676+ switch (version) {
7777+ case VFS_CAP_REVISION_1:
7878+ size = VFS_CAP_U32_1;
7979+ break;
8080+ case VFS_CAP_REVISION_2:
8181+ case VFS_CAP_REVISION_3:
8282+ size = VFS_CAP_U32_3;
8383+ break;
8484+ default:
8585+ fprintf(stderr, "BUG! Unsupported capability version 0x%x on %s. Report to NixOS bugtracker\n", version, self_path);
8686+ return 1;
8787+ }
12788128128- char* saveptr = NULL;
129129- for(char* tok = strtok_r(capstr, ",", &saveptr); tok; tok = strtok_r(NULL, ",", &saveptr))
130130- {
131131- cap_value_t capnum;
132132- if (cap_from_name(tok, &capnum))
133133- {
134134- if(getenv(wrapperDebug))
135135- fprintf(stderr, "cap_from_name failed, skipping: %s", tok);
136136- }
137137- else if (capnum == CAP_SETPCAP)
138138- {
139139- // Check for the cap_setpcap capability, we set this on the
140140- // wrapper so it can elevate the capabilities to the Ambient
141141- // set but we do not want to propagate it down into the
142142- // wrapped program.
143143- //
144144- // TODO: what happens if that's the behavior you want
145145- // though???? I'm preferring a strict vs. loose policy here.
146146- if(getenv(wrapperDebug))
147147- fprintf(stderr, "cap_setpcap in set, skipping it\n");
148148- }
149149- else
150150- {
151151- set_ambient_cap(capnum);
8989+ const struct __user_cap_header_struct header = {
9090+ .version = _LINUX_CAPABILITY_VERSION_3,
9191+ .pid = getpid(),
9292+ };
9393+ struct __user_cap_data_struct user_data[2] = {};
15294153153- if(getenv(wrapperDebug))
154154- fprintf(stderr, "raised %s into the Ambient capability set\n", tok);
155155- }
9595+ for (size_t i = 0; i < size; i++) {
9696+ // merge inheritable & permitted into one
9797+ user_data[i].permitted = user_data[i].inheritable =
9898+ LE32_TO_H(data.data[i].inheritable) | LE32_TO_H(data.data[i].permitted);
15699 }
157157- cap_free(capstr);
100100+101101+ if (syscall(SYS_capset, &header, &user_data) < 0) {
102102+ fprintf(stderr, "failed to inherit capabilities: %s", strerror(errno));
103103+ return 1;
104104+ }
105105+ unsigned last_cap;
106106+ r = get_last_cap(&last_cap);
107107+ if (r < 0) {
108108+ return 1;
109109+ }
110110+ uint64_t set = user_data[0].permitted | (uint64_t)user_data[1].permitted << 32;
111111+ for (unsigned cap = 0; cap < last_cap; cap++) {
112112+ if (!(set & (1ULL << cap))) {
113113+ continue;
114114+ }
115115+116116+ // Check for the cap_setpcap capability, we set this on the
117117+ // wrapper so it can elevate the capabilities to the Ambient
118118+ // set but we do not want to propagate it down into the
119119+ // wrapped program.
120120+ //
121121+ // TODO: what happens if that's the behavior you want
122122+ // though???? I'm preferring a strict vs. loose policy here.
123123+ if (cap == CAP_SETPCAP) {
124124+ if(getenv(wrapper_debug)) {
125125+ fprintf(stderr, "cap_setpcap in set, skipping it\n");
126126+ }
127127+ continue;
128128+ }
129129+ if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, (unsigned long) cap, 0, 0)) {
130130+ fprintf(stderr, "cannot raise the capability %d into the ambient set: %s\n", cap, strerror(errno));
131131+ return 1;
132132+ }
133133+ if (getenv(wrapper_debug)) {
134134+ fprintf(stderr, "raised %d into the ambient capability set\n", cap);
135135+ }
136136+ }
158137159138 return 0;
160139}
161140162162-int main(int argc, char * * argv)
163163-{
164164- // I *think* it's safe to assume that a path from a symbolic link
165165- // should safely fit within the PATH_MAX system limit. Though I'm
166166- // not positive it's safe...
167167- char selfPath[PATH_MAX];
168168- int selfPathSize = readlink("/proc/self/exe", selfPath, sizeof(selfPath));
141141+int readlink_malloc(const char *p, char **ret) {
142142+ size_t l = FILENAME_MAX+1;
143143+ int r;
169144170170- assert(selfPathSize > 0);
145145+ for (;;) {
146146+ char *c = calloc(l, sizeof(char));
147147+ if (!c) {
148148+ return -ENOMEM;
149149+ }
150150+151151+ ssize_t n = readlink(p, c, l-1);
152152+ if (n < 0) {
153153+ r = -errno;
154154+ free(c);
155155+ return r;
156156+ }
157157+158158+ if ((size_t) n < l-1) {
159159+ c[n] = 0;
160160+ *ret = c;
161161+ return 0;
162162+ }
171163172172- // Assert we have room for the zero byte, this ensures the path
173173- // isn't being truncated because it's too big for the buffer.
174174- //
175175- // A better way to handle this might be to use something like the
176176- // whereami library (https://github.com/gpakosz/whereami) or a
177177- // loop that resizes the buffer and re-reads the link if the
178178- // contents are being truncated.
179179- assert(selfPathSize < sizeof(selfPath));
164164+ free(c);
165165+ l *= 2;
166166+ }
167167+}
180168181181- // Set the zero byte since readlink doesn't do that for us.
182182- selfPath[selfPathSize] = '\0';
169169+int main(int argc, char **argv) {
170170+ char *self_path = NULL;
171171+ int self_path_size = readlink_malloc("/proc/self/exe", &self_path);
172172+ if (self_path_size < 0) {
173173+ fprintf(stderr, "cannot readlink /proc/self/exe: %s", strerror(-self_path_size));
174174+ }
183175184176 // Make sure that we are being executed from the right location,
185185- // i.e., `safeWrapperDir'. This is to prevent someone from creating
177177+ // i.e., `safe_wrapper_dir'. This is to prevent someone from creating
186178 // hard link `X' from some other location, along with a false
187179 // `X.real' file, to allow arbitrary programs from being executed
188180 // with elevated capabilities.
189189- int len = strlen(wrapperDir);
190190- if (len > 0 && '/' == wrapperDir[len - 1])
181181+ int len = strlen(wrapper_dir);
182182+ if (len > 0 && '/' == wrapper_dir[len - 1])
191183 --len;
192192- assert(!strncmp(selfPath, wrapperDir, len));
193193- assert('/' == wrapperDir[0]);
194194- assert('/' == selfPath[len]);
184184+ assert(!strncmp(self_path, wrapper_dir, len));
185185+ assert('/' == wrapper_dir[0]);
186186+ assert('/' == self_path[len]);
195187196188 // Make *really* *really* sure that we were executed as
197197- // `selfPath', and not, say, as some other setuid program. That
189189+ // `self_path', and not, say, as some other setuid program. That
198190 // is, our effective uid/gid should match the uid/gid of
199199- // `selfPath'.
191191+ // `self_path'.
200192 struct stat st;
201201- assert(lstat(selfPath, &st) != -1);
193193+ assert(lstat(self_path, &st) != -1);
202194203195 assert(!(st.st_mode & S_ISUID) || (st.st_uid == geteuid()));
204196 assert(!(st.st_mode & S_ISGID) || (st.st_gid == getegid()));
···207199 assert(!(st.st_mode & (S_IWGRP | S_IWOTH)));
208200209201 // Read the path of the real (wrapped) program from <self>.real.
210210- char realFN[PATH_MAX + 10];
211211- int realFNSize = snprintf (realFN, sizeof(realFN), "%s.real", selfPath);
212212- assert (realFNSize < sizeof(realFN));
202202+ char real_fn[PATH_MAX + 10];
203203+ int real_fn_size = snprintf(real_fn, sizeof(real_fn), "%s.real", self_path);
204204+ assert(real_fn_size < sizeof(real_fn));
213205214214- int fdSelf = open(realFN, O_RDONLY);
215215- assert (fdSelf != -1);
206206+ int fd_self = open(real_fn, O_RDONLY);
207207+ assert(fd_self != -1);
216208217217- char sourceProg[PATH_MAX];
218218- len = read(fdSelf, sourceProg, PATH_MAX);
219219- assert (len != -1);
220220- assert (len < sizeof(sourceProg));
221221- assert (len > 0);
222222- sourceProg[len] = 0;
209209+ char source_prog[PATH_MAX];
210210+ len = read(fd_self, source_prog, PATH_MAX);
211211+ assert(len != -1);
212212+ assert(len < sizeof(source_prog));
213213+ assert(len > 0);
214214+ source_prog[len] = 0;
223215224224- close(fdSelf);
216216+ close(fd_self);
225217226218 // Read the capabilities set on the wrapper and raise them in to
227227- // the Ambient set so the program we're wrapping receives the
219219+ // the ambient set so the program we're wrapping receives the
228220 // capabilities too!
229229- make_caps_ambient(selfPath);
221221+ if (make_caps_ambient(self_path) != 0) {
222222+ free(self_path);
223223+ return 1;
224224+ }
225225+ free(self_path);
230226231231- execve(sourceProg, argv, environ);
227227+ execve(source_prog, argv, environ);
232228233229 fprintf(stderr, "%s: cannot run `%s': %s\n",
234234- argv[0], sourceProg, strerror(errno));
230230+ argv[0], source_prog, strerror(errno));
235231236236- exit(1);
232232+ return 1;
237233}
238238-239239-