@@ -1,4 +1,3 @@
1−#define _GNU_SOURCE
21#include <stdlib.h>
32#include <stdio.h>
43#include <string.h>
@@ -162,34 +161,22 @@ static int make_caps_ambient(const char *selfPath)
162161
163162int main(int argc, char * * argv)
164163{
165− // O_PATH | O_NOFOLLOW gives us a fd pointing to the symlink
166− int selfExe = open("/proc/self/exe", O_PATH | O_CLOEXEC | O_NOFOLLOW);
167− assert(selfExe != -1);
168− struct stat st;
169− assert(fstat(selfExe, &st) != -1);
170− size_t selfPathCap = st.st_size + 1;
171− char *selfPath = malloc(selfPathCap);
172− assert(selfPath);
173− int selfPathSize = readlinkat(selfExe, "", selfPath, selfPathCap);
164+ // I *think* it's safe to assume that a path from a symbolic link
165+ // should safely fit within the PATH_MAX system limit. Though I'm
166+ // not positive it's safe...
167+ char selfPath[PATH_MAX];
168+ int selfPathSize = readlink("/proc/self/exe", selfPath, sizeof(selfPath));
174169
175170 assert(selfPathSize > 0);
176171
177172 // Assert we have room for the zero byte, this ensures the path
178173 // isn't being truncated because it's too big for the buffer.
179174 //
180− // selfPathSize is the number of bytes readlinkat put into the
181− // buffer, which does *not* append a null byte. selfPathCap is the
182− // capacity of the buffer, which was set to the number of bytes in
183− // the link contents (again, without the null byte) plus one for
184− // the null byte.
185− //
186− // I don't think it's possible for the link contents to change
187− // between opening a symlink fd and readlinkat on it, so this is
188− // probably not necessary. Doubly so since this is /proc/self/exe,
189− // not a normal symlink. But it's trivial to check.
190− assert(selfPathSize < selfPathCap);
191−
192− assert(close(selfExe));
175+ // A better way to handle this might be to use something like the
176+ // whereami library (https://github.com/gpakosz/whereami) or a
177+ // loop that resizes the buffer and re-reads the link if the
178+ // contents are being truncated.
179+ assert(selfPathSize < sizeof(selfPath));
193180
194181 // Set the zero byte since readlink doesn't do that for us.
195182 selfPath[selfPathSize] = '\0';
@@ -210,6 +197,7 @@ int main(int argc, char * * argv)
210197 // `selfPath', and not, say, as some other setuid program. That
211198 // is, our effective uid/gid should match the uid/gid of
212199 // `selfPath'.
200+ struct stat st;
213201 assert(lstat(selfPath, &st) != -1);
214202
215203 assert(!(st.st_mode & S_ISUID) || (st.st_uid == geteuid()));
@@ -240,8 +228,6 @@ int main(int argc, char * * argv)
240228 // capabilities too!
241229 make_caps_ambient(selfPath);
242230
243− free(selfPath);
244−
245231 execve(sourceProg, argv, environ);
246232
247233 fprintf(stderr, "%s: cannot run `%s': %s\n",