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