1 // SPDX-License-Identifier: GPL-2.0
2 
3 #define _GNU_SOURCE
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <pthread.h>
7 #include <sched.h>
8 #include <stdbool.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/fsuid.h>
13 #include <sys/ioctl.h>
14 #include <sys/mount.h>
15 #include <sys/socket.h>
16 #include <sys/stat.h>
17 #include <sys/sysinfo.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <unistd.h>
21 #include <linux/android/binder.h>
22 #include <linux/android/binderfs.h>
23 
24 #include "../../kselftest_harness.h"
25 
26 #define DEFAULT_THREADS 4
27 
28 #define PTR_TO_INT(p) ((int)((intptr_t)(p)))
29 #define INT_TO_PTR(u) ((void *)((intptr_t)(u)))
30 
31 #define close_prot_errno_disarm(fd) \
32 	if (fd >= 0) {              \
33 		int _e_ = errno;    \
34 		close(fd);          \
35 		errno = _e_;        \
36 		fd = -EBADF;        \
37 	}
38 
39 static void change_mountns(struct __test_metadata *_metadata)
40 {
41 	int ret;
42 
43 	ret = unshare(CLONE_NEWNS);
44 	ASSERT_EQ(ret, 0) {
45 		TH_LOG("%s - Failed to unshare mount namespace",
46 			strerror(errno));
47 	}
48 
49 	ret = mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0);
50 	ASSERT_EQ(ret, 0) {
51 		TH_LOG("%s - Failed to mount / as private",
52 			strerror(errno));
53 	}
54 }
55 
56 static int __do_binderfs_test(struct __test_metadata *_metadata)
57 {
58 	int fd, ret, saved_errno, result = 1;
59 	size_t len;
60 	ssize_t wret;
61 	struct binderfs_device device = { 0 };
62 	struct binder_version version = { 0 };
63 	char binderfs_mntpt[] = P_tmpdir "/binderfs_XXXXXX",
64 		device_path[sizeof(P_tmpdir "/binderfs_XXXXXX/") + BINDERFS_MAX_NAME];
65 
66 	change_mountns(_metadata);
67 
68 	EXPECT_NE(mkdtemp(binderfs_mntpt), NULL) {
69 		TH_LOG("%s - Failed to create binderfs mountpoint",
70 			strerror(errno));
71 		goto out;
72 	}
73 
74 	ret = mount(NULL, binderfs_mntpt, "binder", 0, 0);
75 	EXPECT_EQ(ret, 0) {
76 		if (errno == ENODEV)
77 			SKIP(goto out, "binderfs missing");
78 		TH_LOG("%s - Failed to mount binderfs", strerror(errno));
79 		goto rmdir;
80 	}
81 
82 	/* success: binderfs mounted */
83 
84 	memcpy(device.name, "my-binder", strlen("my-binder"));
85 
86 	snprintf(device_path, sizeof(device_path), "%s/binder-control", binderfs_mntpt);
87 	fd = open(device_path, O_RDONLY | O_CLOEXEC);
88 	EXPECT_GE(fd, 0) {
89 		TH_LOG("%s - Failed to open binder-control device",
90 			strerror(errno));
91 		goto umount;
92 	}
93 
94 	ret = ioctl(fd, BINDER_CTL_ADD, &device);
95 	saved_errno = errno;
96 	close(fd);
97 	errno = saved_errno;
98 	EXPECT_GE(ret, 0) {
99 		TH_LOG("%s - Failed to allocate new binder device",
100 			strerror(errno));
101 		goto umount;
102 	}
103 
104 	TH_LOG("Allocated new binder device with major %d, minor %d, and name %s",
105 		device.major, device.minor, device.name);
106 
107 	/* success: binder device allocation */
108 
109 	snprintf(device_path, sizeof(device_path), "%s/my-binder", binderfs_mntpt);
110 	fd = open(device_path, O_CLOEXEC | O_RDONLY);
111 	EXPECT_GE(fd, 0) {
112 		TH_LOG("%s - Failed to open my-binder device",
113 			strerror(errno));
114 		goto umount;
115 	}
116 
117 	ret = ioctl(fd, BINDER_VERSION, &version);
118 	saved_errno = errno;
119 	close(fd);
120 	errno = saved_errno;
121 	EXPECT_GE(ret, 0) {
122 		TH_LOG("%s - Failed to open perform BINDER_VERSION request",
123 			strerror(errno));
124 		goto umount;
125 	}
126 
127 	TH_LOG("Detected binder version: %d", version.protocol_version);
128 
129 	/* success: binder transaction with binderfs binder device */
130 
131 	ret = unlink(device_path);
132 	EXPECT_EQ(ret, 0) {
133 		TH_LOG("%s - Failed to delete binder device",
134 			strerror(errno));
135 		goto umount;
136 	}
137 
138 	/* success: binder device removal */
139 
140 	snprintf(device_path, sizeof(device_path), "%s/binder-control", binderfs_mntpt);
141 	ret = unlink(device_path);
142 	EXPECT_NE(ret, 0) {
143 		TH_LOG("Managed to delete binder-control device");
144 		goto umount;
145 	}
146 	EXPECT_EQ(errno, EPERM) {
147 		TH_LOG("%s - Failed to delete binder-control device but exited with unexpected error code",
148 			strerror(errno));
149 		goto umount;
150 	}
151 
152 	/* success: binder-control device removal failed as expected */
153 	result = 0;
154 
155 umount:
156 	ret = umount2(binderfs_mntpt, MNT_DETACH);
157 	EXPECT_EQ(ret, 0) {
158 		TH_LOG("%s - Failed to unmount binderfs", strerror(errno));
159 	}
160 rmdir:
161 	ret = rmdir(binderfs_mntpt);
162 	EXPECT_EQ(ret, 0) {
163 		TH_LOG("%s - Failed to rmdir binderfs mount", strerror(errno));
164 	}
165 out:
166 	return result;
167 }
168 
169 static int wait_for_pid(pid_t pid)
170 {
171 	int status, ret;
172 
173 again:
174 	ret = waitpid(pid, &status, 0);
175 	if (ret == -1) {
176 		if (errno == EINTR)
177 			goto again;
178 
179 		return -1;
180 	}
181 
182 	if (!WIFEXITED(status))
183 		return -1;
184 
185 	return WEXITSTATUS(status);
186 }
187 
188 static int setid_userns_root(void)
189 {
190 	if (setuid(0))
191 		return -1;
192 	if (setgid(0))
193 		return -1;
194 
195 	setfsuid(0);
196 	setfsgid(0);
197 
198 	return 0;
199 }
200 
201 enum idmap_type {
202 	UID_MAP,
203 	GID_MAP,
204 };
205 
206 static ssize_t read_nointr(int fd, void *buf, size_t count)
207 {
208 	ssize_t ret;
209 again:
210 	ret = read(fd, buf, count);
211 	if (ret < 0 && errno == EINTR)
212 		goto again;
213 
214 	return ret;
215 }
216 
217 static ssize_t write_nointr(int fd, const void *buf, size_t count)
218 {
219 	ssize_t ret;
220 again:
221 	ret = write(fd, buf, count);
222 	if (ret < 0 && errno == EINTR)
223 		goto again;
224 
225 	return ret;
226 }
227 
228 static int write_id_mapping(enum idmap_type type, pid_t pid, const char *buf,
229 			    size_t buf_size)
230 {
231 	int fd;
232 	int ret;
233 	char path[4096];
234 
235 	if (type == GID_MAP) {
236 		int setgroups_fd;
237 
238 		snprintf(path, sizeof(path), "/proc/%d/setgroups", pid);
239 		setgroups_fd = open(path, O_WRONLY | O_CLOEXEC | O_NOFOLLOW);
240 		if (setgroups_fd < 0 && errno != ENOENT)
241 			return -1;
242 
243 		if (setgroups_fd >= 0) {
244 			ret = write_nointr(setgroups_fd, "deny", sizeof("deny") - 1);
245 			close_prot_errno_disarm(setgroups_fd);
246 			if (ret != sizeof("deny") - 1)
247 				return -1;
248 		}
249 	}
250 
251 	switch (type) {
252 	case UID_MAP:
253 		ret = snprintf(path, sizeof(path), "/proc/%d/uid_map", pid);
254 		break;
255 	case GID_MAP:
256 		ret = snprintf(path, sizeof(path), "/proc/%d/gid_map", pid);
257 		break;
258 	default:
259 		return -1;
260 	}
261 	if (ret < 0 || ret >= sizeof(path))
262 		return -E2BIG;
263 
264 	fd = open(path, O_WRONLY | O_CLOEXEC | O_NOFOLLOW);
265 	if (fd < 0)
266 		return -1;
267 
268 	ret = write_nointr(fd, buf, buf_size);
269 	close_prot_errno_disarm(fd);
270 	if (ret != buf_size)
271 		return -1;
272 
273 	return 0;
274 }
275 
276 static void change_userns(struct __test_metadata *_metadata, int syncfds[2])
277 {
278 	int ret;
279 	char buf;
280 
281 	close_prot_errno_disarm(syncfds[1]);
282 
283 	ret = unshare(CLONE_NEWUSER);
284 	ASSERT_EQ(ret, 0) {
285 		TH_LOG("%s - Failed to unshare user namespace",
286 			strerror(errno));
287 	}
288 
289 	ret = write_nointr(syncfds[0], "1", 1);
290 	ASSERT_EQ(ret, 1) {
291 		TH_LOG("write_nointr() failed");
292 	}
293 
294 	ret = read_nointr(syncfds[0], &buf, 1);
295 	ASSERT_EQ(ret, 1) {
296 		TH_LOG("read_nointr() failed");
297 	}
298 
299 	close_prot_errno_disarm(syncfds[0]);
300 
301 	ASSERT_EQ(setid_userns_root(), 0) {
302 		TH_LOG("setid_userns_root() failed");
303 	}
304 }
305 
306 static void change_idmaps(struct __test_metadata *_metadata, int syncfds[2], pid_t pid)
307 {
308 	int ret;
309 	char buf;
310 	char id_map[4096];
311 
312 	close_prot_errno_disarm(syncfds[0]);
313 
314 	ret = read_nointr(syncfds[1], &buf, 1);
315 	ASSERT_EQ(ret, 1) {
316 		TH_LOG("read_nointr() failed");
317 	}
318 
319 	snprintf(id_map, sizeof(id_map), "0 %d 1\n", getuid());
320 	ret = write_id_mapping(UID_MAP, pid, id_map, strlen(id_map));
321 	ASSERT_EQ(ret, 0) {
322 		TH_LOG("write_id_mapping(UID_MAP) failed");
323 	}
324 
325 	snprintf(id_map, sizeof(id_map), "0 %d 1\n", getgid());
326 	ret = write_id_mapping(GID_MAP, pid, id_map, strlen(id_map));
327 	ASSERT_EQ(ret, 0) {
328 		TH_LOG("write_id_mapping(GID_MAP) failed");
329 	}
330 
331 	ret = write_nointr(syncfds[1], "1", 1);
332 	ASSERT_EQ(ret, 1) {
333 		TH_LOG("write_nointr() failed");
334 	}
335 
336 	close_prot_errno_disarm(syncfds[1]);
337 }
338 
339 struct __test_metadata *_thread_metadata;
340 static void *binder_version_thread(void *data)
341 {
342 	struct __test_metadata *_metadata = _thread_metadata;
343 	int fd = PTR_TO_INT(data);
344 	struct binder_version version = { 0 };
345 	int ret;
346 
347 	ret = ioctl(fd, BINDER_VERSION, &version);
348 	if (ret < 0)
349 		TH_LOG("%s - Failed to open perform BINDER_VERSION request\n",
350 			strerror(errno));
351 
352 	pthread_exit(data);
353 }
354 
355 /*
356  * Regression test:
357  * 2669b8b0c798 ("binder: prevent UAF for binderfs devices")
358  * f0fe2c0f050d ("binder: prevent UAF for binderfs devices II")
359  * 211b64e4b5b6 ("binderfs: use refcount for binder control devices too")
360  */
361 TEST(binderfs_stress)
362 {
363 	int fds[1000];
364 	int syncfds[2];
365 	pid_t pid;
366 	int fd, ret;
367 	size_t len;
368 	struct binderfs_device device = { 0 };
369 	char binderfs_mntpt[] = P_tmpdir "/binderfs_XXXXXX",
370 		device_path[sizeof(P_tmpdir "/binderfs_XXXXXX/") + BINDERFS_MAX_NAME];
371 
372 	ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, syncfds);
373 	ASSERT_EQ(ret, 0) {
374 		TH_LOG("%s - Failed to create socket pair", strerror(errno));
375 	}
376 
377 	pid = fork();
378 	ASSERT_GE(pid, 0) {
379 		TH_LOG("%s - Failed to fork", strerror(errno));
380 		close_prot_errno_disarm(syncfds[0]);
381 		close_prot_errno_disarm(syncfds[1]);
382 	}
383 
384 	if (pid == 0) {
385 		int i, j, k, nthreads;
386 		pthread_attr_t attr;
387 		pthread_t threads[DEFAULT_THREADS];
388 		change_userns(_metadata, syncfds);
389 		change_mountns(_metadata);
390 
391 		ASSERT_NE(mkdtemp(binderfs_mntpt), NULL) {
392 			TH_LOG("%s - Failed to create binderfs mountpoint",
393 				strerror(errno));
394 		}
395 
396 		ret = mount(NULL, binderfs_mntpt, "binder", 0, 0);
397 		ASSERT_EQ(ret, 0) {
398 			TH_LOG("%s - Failed to mount binderfs", strerror(errno));
399 		}
400 
401 		for (int i = 0; i < ARRAY_SIZE(fds); i++) {
402 
403 			snprintf(device_path, sizeof(device_path),
404 				 "%s/binder-control", binderfs_mntpt);
405 			fd = open(device_path, O_RDONLY | O_CLOEXEC);
406 			ASSERT_GE(fd, 0) {
407 				TH_LOG("%s - Failed to open binder-control device",
408 					strerror(errno));
409 			}
410 
411 			memset(&device, 0, sizeof(device));
412 			snprintf(device.name, sizeof(device.name), "%d", i);
413 			ret = ioctl(fd, BINDER_CTL_ADD, &device);
414 			close_prot_errno_disarm(fd);
415 			ASSERT_EQ(ret, 0) {
416 				TH_LOG("%s - Failed to allocate new binder device",
417 					strerror(errno));
418 			}
419 
420 			snprintf(device_path, sizeof(device_path), "%s/%d",
421 				 binderfs_mntpt, i);
422 			fds[i] = open(device_path, O_RDONLY | O_CLOEXEC);
423 			ASSERT_GE(fds[i], 0) {
424 				TH_LOG("%s - Failed to open binder device", strerror(errno));
425 			}
426 		}
427 
428 		ret = umount2(binderfs_mntpt, MNT_DETACH);
429 		ASSERT_EQ(ret, 0) {
430 			TH_LOG("%s - Failed to unmount binderfs", strerror(errno));
431 			rmdir(binderfs_mntpt);
432 		}
433 
434 		nthreads = get_nprocs_conf();
435 		if (nthreads > DEFAULT_THREADS)
436 			nthreads = DEFAULT_THREADS;
437 
438 		_thread_metadata = _metadata;
439 		pthread_attr_init(&attr);
440 		for (k = 0; k < ARRAY_SIZE(fds); k++) {
441 			for (i = 0; i < nthreads; i++) {
442 				ret = pthread_create(&threads[i], &attr, binder_version_thread, INT_TO_PTR(fds[k]));
443 				if (ret) {
444 					TH_LOG("%s - Failed to create thread %d",
445 						strerror(errno), i);
446 					break;
447 				}
448 			}
449 
450 			for (j = 0; j < i; j++) {
451 				void *fdptr = NULL;
452 
453 				ret = pthread_join(threads[j], &fdptr);
454 				if (ret)
455 					TH_LOG("%s - Failed to join thread %d for fd %d",
456 						strerror(errno), j, PTR_TO_INT(fdptr));
457 			}
458 		}
459 		pthread_attr_destroy(&attr);
460 
461 		for (k = 0; k < ARRAY_SIZE(fds); k++)
462 			close(fds[k]);
463 
464 		exit(EXIT_SUCCESS);
465 	}
466 
467 	change_idmaps(_metadata, syncfds, pid);
468 
469 	ret = wait_for_pid(pid);
470 	ASSERT_EQ(ret, 0) {
471 		TH_LOG("wait_for_pid() failed");
472 	}
473 }
474 
475 TEST(binderfs_test_privileged)
476 {
477 	if (geteuid() != 0)
478 		SKIP(return, "Tests are not run as root. Skipping privileged tests");
479 
480 	if (__do_binderfs_test(_metadata))
481 		SKIP(return, "The Android binderfs filesystem is not available");
482 }
483 
484 TEST(binderfs_test_unprivileged)
485 {
486 	int ret;
487 	int syncfds[2];
488 	pid_t pid;
489 
490 	ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, syncfds);
491 	ASSERT_EQ(ret, 0) {
492 		TH_LOG("%s - Failed to create socket pair", strerror(errno));
493 	}
494 
495 	pid = fork();
496 	ASSERT_GE(pid, 0) {
497 		close_prot_errno_disarm(syncfds[0]);
498 		close_prot_errno_disarm(syncfds[1]);
499 		TH_LOG("%s - Failed to fork", strerror(errno));
500 	}
501 
502 	if (pid == 0) {
503 		change_userns(_metadata, syncfds);
504 		if (__do_binderfs_test(_metadata))
505 			exit(2);
506 		exit(EXIT_SUCCESS);
507 	}
508 
509 	change_idmaps(_metadata, syncfds, pid);
510 
511 	ret = wait_for_pid(pid);
512 	if (ret) {
513 		if (ret == 2)
514 			SKIP(return, "The Android binderfs filesystem is not available");
515 		ASSERT_EQ(ret, 0) {
516 			TH_LOG("wait_for_pid() failed");
517 		}
518 	}
519 }
520 
521 TEST_HARNESS_MAIN
522