1 /*
2  * Copyright (c) 2014 Google, Inc.
3  *
4  * Licensed under the terms of the GNU GPL License version 2
5  *
6  * Selftests for execveat(2).
7  */
8 
9 #define _GNU_SOURCE  /* to get O_PATH, AT_EMPTY_PATH */
10 #include <sys/sendfile.h>
11 #include <sys/stat.h>
12 #include <sys/syscall.h>
13 #include <sys/types.h>
14 #include <sys/wait.h>
15 #include <errno.h>
16 #include <fcntl.h>
17 #include <limits.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <unistd.h>
22 
23 static char longpath[2 * PATH_MAX] = "";
24 static char *envp[] = { "IN_TEST=yes", NULL, NULL };
25 static char *argv[] = { "execveat", "99", NULL };
26 
27 static int execveat_(int fd, const char *path, char **argv, char **envp,
28 		     int flags)
29 {
30 #ifdef __NR_execveat
31 	return syscall(__NR_execveat, fd, path, argv, envp, flags);
32 #else
33 	errno = ENOSYS;
34 	return -1;
35 #endif
36 }
37 
38 #define check_execveat_fail(fd, path, flags, errno)	\
39 	_check_execveat_fail(fd, path, flags, errno, #errno)
40 static int _check_execveat_fail(int fd, const char *path, int flags,
41 				int expected_errno, const char *errno_str)
42 {
43 	int rc;
44 
45 	errno = 0;
46 	printf("Check failure of execveat(%d, '%s', %d) with %s... ",
47 		fd, path?:"(null)", flags, errno_str);
48 	rc = execveat_(fd, path, argv, envp, flags);
49 
50 	if (rc > 0) {
51 		printf("[FAIL] (unexpected success from execveat(2))\n");
52 		return 1;
53 	}
54 	if (errno != expected_errno) {
55 		printf("[FAIL] (expected errno %d (%s) not %d (%s)\n",
56 			expected_errno, strerror(expected_errno),
57 			errno, strerror(errno));
58 		return 1;
59 	}
60 	printf("[OK]\n");
61 	return 0;
62 }
63 
64 static int check_execveat_invoked_rc(int fd, const char *path, int flags,
65 				     int expected_rc, int expected_rc2)
66 {
67 	int status;
68 	int rc;
69 	pid_t child;
70 	int pathlen = path ? strlen(path) : 0;
71 
72 	if (pathlen > 40)
73 		printf("Check success of execveat(%d, '%.20s...%s', %d)... ",
74 			fd, path, (path + pathlen - 20), flags);
75 	else
76 		printf("Check success of execveat(%d, '%s', %d)... ",
77 			fd, path?:"(null)", flags);
78 	child = fork();
79 	if (child < 0) {
80 		printf("[FAIL] (fork() failed)\n");
81 		return 1;
82 	}
83 	if (child == 0) {
84 		/* Child: do execveat(). */
85 		rc = execveat_(fd, path, argv, envp, flags);
86 		printf("[FAIL]: execveat() failed, rc=%d errno=%d (%s)\n",
87 			rc, errno, strerror(errno));
88 		exit(1);  /* should not reach here */
89 	}
90 	/* Parent: wait for & check child's exit status. */
91 	rc = waitpid(child, &status, 0);
92 	if (rc != child) {
93 		printf("[FAIL] (waitpid(%d,...) returned %d)\n", child, rc);
94 		return 1;
95 	}
96 	if (!WIFEXITED(status)) {
97 		printf("[FAIL] (child %d did not exit cleanly, status=%08x)\n",
98 			child, status);
99 		return 1;
100 	}
101 	if ((WEXITSTATUS(status) != expected_rc) &&
102 	    (WEXITSTATUS(status) != expected_rc2)) {
103 		printf("[FAIL] (child %d exited with %d not %d nor %d)\n",
104 			child, WEXITSTATUS(status), expected_rc, expected_rc2);
105 		return 1;
106 	}
107 	printf("[OK]\n");
108 	return 0;
109 }
110 
111 static int check_execveat(int fd, const char *path, int flags)
112 {
113 	return check_execveat_invoked_rc(fd, path, flags, 99, 99);
114 }
115 
116 static char *concat(const char *left, const char *right)
117 {
118 	char *result = malloc(strlen(left) + strlen(right) + 1);
119 
120 	strcpy(result, left);
121 	strcat(result, right);
122 	return result;
123 }
124 
125 static int open_or_die(const char *filename, int flags)
126 {
127 	int fd = open(filename, flags);
128 
129 	if (fd < 0) {
130 		printf("Failed to open '%s'; "
131 			"check prerequisites are available\n", filename);
132 		exit(1);
133 	}
134 	return fd;
135 }
136 
137 static void exe_cp(const char *src, const char *dest)
138 {
139 	int in_fd = open_or_die(src, O_RDONLY);
140 	int out_fd = open(dest, O_RDWR|O_CREAT|O_TRUNC, 0755);
141 	struct stat info;
142 
143 	fstat(in_fd, &info);
144 	sendfile(out_fd, in_fd, NULL, info.st_size);
145 	close(in_fd);
146 	close(out_fd);
147 }
148 
149 #define XX_DIR_LEN 200
150 static int check_execveat_pathmax(int root_dfd, const char *src, int is_script)
151 {
152 	int fail = 0;
153 	int ii, count, len;
154 	char longname[XX_DIR_LEN + 1];
155 	int fd;
156 
157 	if (*longpath == '\0') {
158 		/* Create a filename close to PATH_MAX in length */
159 		char *cwd = getcwd(NULL, 0);
160 
161 		if (!cwd) {
162 			printf("Failed to getcwd(), errno=%d (%s)\n",
163 			       errno, strerror(errno));
164 			return 2;
165 		}
166 		strcpy(longpath, cwd);
167 		strcat(longpath, "/");
168 		memset(longname, 'x', XX_DIR_LEN - 1);
169 		longname[XX_DIR_LEN - 1] = '/';
170 		longname[XX_DIR_LEN] = '\0';
171 		count = (PATH_MAX - 3 - strlen(cwd)) / XX_DIR_LEN;
172 		for (ii = 0; ii < count; ii++) {
173 			strcat(longpath, longname);
174 			mkdir(longpath, 0755);
175 		}
176 		len = (PATH_MAX - 3 - strlen(cwd)) - (count * XX_DIR_LEN);
177 		if (len <= 0)
178 			len = 1;
179 		memset(longname, 'y', len);
180 		longname[len] = '\0';
181 		strcat(longpath, longname);
182 		free(cwd);
183 	}
184 	exe_cp(src, longpath);
185 
186 	/*
187 	 * Execute as a pre-opened file descriptor, which works whether this is
188 	 * a script or not (because the interpreter sees a filename like
189 	 * "/dev/fd/20").
190 	 */
191 	fd = open(longpath, O_RDONLY);
192 	if (fd > 0) {
193 		printf("Invoke copy of '%s' via filename of length %zu:\n",
194 			src, strlen(longpath));
195 		fail += check_execveat(fd, "", AT_EMPTY_PATH);
196 	} else {
197 		printf("Failed to open length %zu filename, errno=%d (%s)\n",
198 			strlen(longpath), errno, strerror(errno));
199 		fail++;
200 	}
201 
202 	/*
203 	 * Execute as a long pathname relative to "/".  If this is a script,
204 	 * the interpreter will launch but fail to open the script because its
205 	 * name ("/dev/fd/5/xxx....") is bigger than PATH_MAX.
206 	 *
207 	 * The failure code is usually 127 (POSIX: "If a command is not found,
208 	 * the exit status shall be 127."), but some systems give 126 (POSIX:
209 	 * "If the command name is found, but it is not an executable utility,
210 	 * the exit status shall be 126."), so allow either.
211 	 */
212 	if (is_script)
213 		fail += check_execveat_invoked_rc(root_dfd, longpath + 1, 0,
214 						  127, 126);
215 	else
216 		fail += check_execveat(root_dfd, longpath + 1, 0);
217 
218 	return fail;
219 }
220 
221 static int run_tests(void)
222 {
223 	int fail = 0;
224 	char *fullname = realpath("execveat", NULL);
225 	char *fullname_script = realpath("script", NULL);
226 	char *fullname_symlink = concat(fullname, ".symlink");
227 	int subdir_dfd = open_or_die("subdir", O_DIRECTORY|O_RDONLY);
228 	int subdir_dfd_ephemeral = open_or_die("subdir.ephemeral",
229 					       O_DIRECTORY|O_RDONLY);
230 	int dot_dfd = open_or_die(".", O_DIRECTORY|O_RDONLY);
231 	int root_dfd = open_or_die("/", O_DIRECTORY|O_RDONLY);
232 	int dot_dfd_path = open_or_die(".", O_DIRECTORY|O_RDONLY|O_PATH);
233 	int dot_dfd_cloexec = open_or_die(".", O_DIRECTORY|O_RDONLY|O_CLOEXEC);
234 	int fd = open_or_die("execveat", O_RDONLY);
235 	int fd_path = open_or_die("execveat", O_RDONLY|O_PATH);
236 	int fd_symlink = open_or_die("execveat.symlink", O_RDONLY);
237 	int fd_denatured = open_or_die("execveat.denatured", O_RDONLY);
238 	int fd_denatured_path = open_or_die("execveat.denatured",
239 					    O_RDONLY|O_PATH);
240 	int fd_script = open_or_die("script", O_RDONLY);
241 	int fd_ephemeral = open_or_die("execveat.ephemeral", O_RDONLY);
242 	int fd_ephemeral_path = open_or_die("execveat.path.ephemeral",
243 					    O_RDONLY|O_PATH);
244 	int fd_script_ephemeral = open_or_die("script.ephemeral", O_RDONLY);
245 	int fd_cloexec = open_or_die("execveat", O_RDONLY|O_CLOEXEC);
246 	int fd_script_cloexec = open_or_die("script", O_RDONLY|O_CLOEXEC);
247 
248 	/* Check if we have execveat at all, and bail early if not */
249 	errno = 0;
250 	execveat_(-1, NULL, NULL, NULL, 0);
251 	if (errno == ENOSYS) {
252 		printf("[FAIL] ENOSYS calling execveat - no kernel support?\n");
253 		return 1;
254 	}
255 
256 	/* Change file position to confirm it doesn't affect anything */
257 	lseek(fd, 10, SEEK_SET);
258 
259 	/* Normal executable file: */
260 	/*   dfd + path */
261 	fail += check_execveat(subdir_dfd, "../execveat", 0);
262 	fail += check_execveat(dot_dfd, "execveat", 0);
263 	fail += check_execveat(dot_dfd_path, "execveat", 0);
264 	/*   absolute path */
265 	fail += check_execveat(AT_FDCWD, fullname, 0);
266 	/*   absolute path with nonsense dfd */
267 	fail += check_execveat(99, fullname, 0);
268 	/*   fd + no path */
269 	fail += check_execveat(fd, "", AT_EMPTY_PATH);
270 	/*   O_CLOEXEC fd + no path */
271 	fail += check_execveat(fd_cloexec, "", AT_EMPTY_PATH);
272 	/*   O_PATH fd */
273 	fail += check_execveat(fd_path, "", AT_EMPTY_PATH);
274 
275 	/* Mess with executable file that's already open: */
276 	/*   fd + no path to a file that's been renamed */
277 	rename("execveat.ephemeral", "execveat.moved");
278 	fail += check_execveat(fd_ephemeral, "", AT_EMPTY_PATH);
279 	/*   fd + no path to a file that's been deleted */
280 	unlink("execveat.moved"); /* remove the file now fd open */
281 	fail += check_execveat(fd_ephemeral, "", AT_EMPTY_PATH);
282 
283 	/* Mess with executable file that's already open with O_PATH */
284 	/*   fd + no path to a file that's been deleted */
285 	unlink("execveat.path.ephemeral");
286 	fail += check_execveat(fd_ephemeral_path, "", AT_EMPTY_PATH);
287 
288 	/* Invalid argument failures */
289 	fail += check_execveat_fail(fd, "", 0, ENOENT);
290 	fail += check_execveat_fail(fd, NULL, AT_EMPTY_PATH, EFAULT);
291 
292 	/* Symlink to executable file: */
293 	/*   dfd + path */
294 	fail += check_execveat(dot_dfd, "execveat.symlink", 0);
295 	fail += check_execveat(dot_dfd_path, "execveat.symlink", 0);
296 	/*   absolute path */
297 	fail += check_execveat(AT_FDCWD, fullname_symlink, 0);
298 	/*   fd + no path, even with AT_SYMLINK_NOFOLLOW (already followed) */
299 	fail += check_execveat(fd_symlink, "", AT_EMPTY_PATH);
300 	fail += check_execveat(fd_symlink, "",
301 			       AT_EMPTY_PATH|AT_SYMLINK_NOFOLLOW);
302 
303 	/* Symlink fails when AT_SYMLINK_NOFOLLOW set: */
304 	/*   dfd + path */
305 	fail += check_execveat_fail(dot_dfd, "execveat.symlink",
306 				    AT_SYMLINK_NOFOLLOW, ELOOP);
307 	fail += check_execveat_fail(dot_dfd_path, "execveat.symlink",
308 				    AT_SYMLINK_NOFOLLOW, ELOOP);
309 	/*   absolute path */
310 	fail += check_execveat_fail(AT_FDCWD, fullname_symlink,
311 				    AT_SYMLINK_NOFOLLOW, ELOOP);
312 
313 	/* Shell script wrapping executable file: */
314 	/*   dfd + path */
315 	fail += check_execveat(subdir_dfd, "../script", 0);
316 	fail += check_execveat(dot_dfd, "script", 0);
317 	fail += check_execveat(dot_dfd_path, "script", 0);
318 	/*   absolute path */
319 	fail += check_execveat(AT_FDCWD, fullname_script, 0);
320 	/*   fd + no path */
321 	fail += check_execveat(fd_script, "", AT_EMPTY_PATH);
322 	fail += check_execveat(fd_script, "",
323 			       AT_EMPTY_PATH|AT_SYMLINK_NOFOLLOW);
324 	/*   O_CLOEXEC fd fails for a script (as script file inaccessible) */
325 	fail += check_execveat_fail(fd_script_cloexec, "", AT_EMPTY_PATH,
326 				    ENOENT);
327 	fail += check_execveat_fail(dot_dfd_cloexec, "script", 0, ENOENT);
328 
329 	/* Mess with script file that's already open: */
330 	/*   fd + no path to a file that's been renamed */
331 	rename("script.ephemeral", "script.moved");
332 	fail += check_execveat(fd_script_ephemeral, "", AT_EMPTY_PATH);
333 	/*   fd + no path to a file that's been deleted */
334 	unlink("script.moved"); /* remove the file while fd open */
335 	fail += check_execveat(fd_script_ephemeral, "", AT_EMPTY_PATH);
336 
337 	/* Rename a subdirectory in the path: */
338 	rename("subdir.ephemeral", "subdir.moved");
339 	fail += check_execveat(subdir_dfd_ephemeral, "../script", 0);
340 	fail += check_execveat(subdir_dfd_ephemeral, "script", 0);
341 	/* Remove the subdir and its contents */
342 	unlink("subdir.moved/script");
343 	unlink("subdir.moved");
344 	/* Shell loads via deleted subdir OK because name starts with .. */
345 	fail += check_execveat(subdir_dfd_ephemeral, "../script", 0);
346 	fail += check_execveat_fail(subdir_dfd_ephemeral, "script", 0, ENOENT);
347 
348 	/* Flag values other than AT_SYMLINK_NOFOLLOW => EINVAL */
349 	fail += check_execveat_fail(dot_dfd, "execveat", 0xFFFF, EINVAL);
350 	/* Invalid path => ENOENT */
351 	fail += check_execveat_fail(dot_dfd, "no-such-file", 0, ENOENT);
352 	fail += check_execveat_fail(dot_dfd_path, "no-such-file", 0, ENOENT);
353 	fail += check_execveat_fail(AT_FDCWD, "no-such-file", 0, ENOENT);
354 	/* Attempt to execute directory => EACCES */
355 	fail += check_execveat_fail(dot_dfd, "", AT_EMPTY_PATH, EACCES);
356 	/* Attempt to execute non-executable => EACCES */
357 	fail += check_execveat_fail(dot_dfd, "Makefile", 0, EACCES);
358 	fail += check_execveat_fail(fd_denatured, "", AT_EMPTY_PATH, EACCES);
359 	fail += check_execveat_fail(fd_denatured_path, "", AT_EMPTY_PATH,
360 				    EACCES);
361 	/* Attempt to execute nonsense FD => EBADF */
362 	fail += check_execveat_fail(99, "", AT_EMPTY_PATH, EBADF);
363 	fail += check_execveat_fail(99, "execveat", 0, EBADF);
364 	/* Attempt to execute relative to non-directory => ENOTDIR */
365 	fail += check_execveat_fail(fd, "execveat", 0, ENOTDIR);
366 
367 	fail += check_execveat_pathmax(root_dfd, "execveat", 0);
368 	fail += check_execveat_pathmax(root_dfd, "script", 1);
369 	return fail;
370 }
371 
372 static void prerequisites(void)
373 {
374 	int fd;
375 	const char *script = "#!/bin/sh\nexit $*\n";
376 
377 	/* Create ephemeral copies of files */
378 	exe_cp("execveat", "execveat.ephemeral");
379 	exe_cp("execveat", "execveat.path.ephemeral");
380 	exe_cp("script", "script.ephemeral");
381 	mkdir("subdir.ephemeral", 0755);
382 
383 	fd = open("subdir.ephemeral/script", O_RDWR|O_CREAT|O_TRUNC, 0755);
384 	write(fd, script, strlen(script));
385 	close(fd);
386 }
387 
388 int main(int argc, char **argv)
389 {
390 	int ii;
391 	int rc;
392 	const char *verbose = getenv("VERBOSE");
393 
394 	if (argc >= 2) {
395 		/* If we are invoked with an argument, don't run tests. */
396 		const char *in_test = getenv("IN_TEST");
397 
398 		if (verbose) {
399 			printf("  invoked with:");
400 			for (ii = 0; ii < argc; ii++)
401 				printf(" [%d]='%s'", ii, argv[ii]);
402 			printf("\n");
403 		}
404 
405 		/* Check expected environment transferred. */
406 		if (!in_test || strcmp(in_test, "yes") != 0) {
407 			printf("[FAIL] (no IN_TEST=yes in env)\n");
408 			return 1;
409 		}
410 
411 		/* Use the final argument as an exit code. */
412 		rc = atoi(argv[argc - 1]);
413 		fflush(stdout);
414 	} else {
415 		prerequisites();
416 		if (verbose)
417 			envp[1] = "VERBOSE=1";
418 		rc = run_tests();
419 		if (rc > 0)
420 			printf("%d tests failed\n", rc);
421 	}
422 	return rc;
423 }
424