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