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