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