xref: /freebsd/tests/sys/kern/unix_passfd_test.c (revision 22d7dd834bc5cd189810e414701e3ad1e98102e4)
1 /*-
2  * Copyright (c) 2005 Robert N. M. Watson
3  * Copyright (c) 2015 Mark Johnston
4  * Copyright (c) 2022 Gleb Smirnoff <glebius@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include <sys/param.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/sysctl.h>
34 #include <sys/time.h>
35 #include <sys/resource.h>
36 #include <sys/un.h>
37 
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <limits.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 #include <atf-c.h>
47 
48 #if !defined(TEST_PROTO)
49 #error Need TEST_PROTO defined to SOCK_STREAM or SOCK_DGRAM
50 #endif
51 
52 /*
53  * UNIX domain sockets allow file descriptors to be passed via "ancillary
54  * data", or control messages.  This regression test is intended to exercise
55  * this facility, both performing some basic tests that it operates, and also
56  * causing some kernel edge cases to execute, such as garbage collection when
57  * there are cyclic file descriptor references.  Right now we test only with
58  * stream sockets, but ideally we'd also test with datagram sockets.
59  */
60 
61 static void
62 domainsocketpair(int *fdp)
63 {
64 
65 	ATF_REQUIRE_MSG(socketpair(PF_UNIX, TEST_PROTO, 0, fdp) != -1,
66 	    "socketpair(PF_UNIX, %u) failed: %s", TEST_PROTO, strerror(errno));
67 }
68 
69 static void
70 closesocketpair(int *fdp)
71 {
72 
73 	close(fdp[0]);
74 	close(fdp[1]);
75 }
76 
77 static void
78 devnull(int *fdp)
79 {
80 	int fd;
81 
82 	fd = open("/dev/null", O_RDONLY);
83 	ATF_REQUIRE_MSG(fd != -1, "open failed: %s", strerror(errno));
84 	*fdp = fd;
85 }
86 
87 static void
88 tempfile(int *fdp)
89 {
90 	char path[PATH_MAX];
91 	int fd;
92 
93 	snprintf(path, PATH_MAX, "%s/unix_passfd.XXXXXXXXXXXXXXX",
94 	    getenv("TMPDIR") == NULL ? "/tmp" : getenv("TMPDIR"));
95 	fd = mkstemp(path);
96 	ATF_REQUIRE_MSG(fd != -1, "mkstemp(%s) failed", path);
97 	(void)unlink(path);
98 	*fdp = fd;
99 }
100 
101 static void
102 dofstat(int fd, struct stat *sb)
103 {
104 
105 	ATF_REQUIRE_MSG(fstat(fd, sb) == 0,
106 	    "fstat failed: %s", strerror(errno));
107 }
108 
109 static int
110 getnfds(void)
111 {
112 	size_t len;
113 	int mib[4], n, rc;
114 
115 	len = sizeof(n);
116 	mib[0] = CTL_KERN;
117 	mib[1] = KERN_PROC;
118 	mib[2] = KERN_PROC_NFDS;
119 	mib[3] = 0;
120 
121 	rc = sysctl(mib, 4, &n, &len, NULL, 0);
122 	ATF_REQUIRE_MSG(rc != -1, "sysctl(KERN_PROC_NFDS) failed");
123 	return (n);
124 }
125 
126 static int
127 openfiles(void)
128 {
129 	int files;
130 	size_t len = sizeof(files);
131 
132 	ATF_REQUIRE(sysctlbyname("kern.openfiles", &files, &len, NULL, 0) == 0);
133 
134 	return (files);
135 }
136 
137 static void
138 putfds(char *buf, int fd, int nfds)
139 {
140 	struct cmsghdr *cm;
141 	int *fdp, i;
142 
143 	cm = (struct cmsghdr *)buf;
144 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
145 	cm->cmsg_level = SOL_SOCKET;
146 	cm->cmsg_type = SCM_RIGHTS;
147 	for (fdp = (int *)CMSG_DATA(cm), i = 0; i < nfds; i++)
148 		*fdp++ = fd;
149 }
150 
151 static void
152 samefile(struct stat *sb1, struct stat *sb2)
153 {
154 
155 	ATF_REQUIRE_MSG(sb1->st_dev == sb2->st_dev, "different device");
156 	ATF_REQUIRE_MSG(sb1->st_ino == sb2->st_ino, "different inode");
157 }
158 
159 static ssize_t
160 sendfd_payload(int sockfd, int send_fd, void *payload, size_t paylen)
161 {
162 	struct iovec iovec;
163 	char message[CMSG_SPACE(sizeof(int))];
164 	struct msghdr msghdr;
165 
166 	bzero(&msghdr, sizeof(msghdr));
167 	bzero(&message, sizeof(message));
168 
169 	msghdr.msg_control = message;
170 	msghdr.msg_controllen = sizeof(message);
171 
172 	iovec.iov_base = payload;
173 	iovec.iov_len = paylen;
174 
175 	msghdr.msg_iov = &iovec;
176 	msghdr.msg_iovlen = 1;
177 
178 	putfds(message, send_fd, 1);
179 	return (sendmsg(sockfd, &msghdr, 0));
180 }
181 
182 static void
183 sendfd(int sockfd, int send_fd)
184 {
185 	ssize_t len;
186 	char ch;
187 
188 	ch = 0;
189 	len = sendfd_payload(sockfd, send_fd, &ch, sizeof(ch));
190 	ATF_REQUIRE_MSG(len == sizeof(ch),
191 	    "sendmsg: %zd bytes sent; expected %zu; %s", len, sizeof(ch),
192 	    strerror(errno));
193 }
194 
195 static bool
196 localcreds(int sockfd)
197 {
198 	socklen_t sz;
199 	int rc, val;
200 
201 	sz = sizeof(val);
202 	rc = getsockopt(sockfd, 0, LOCAL_CREDS, &val, &sz);
203 	ATF_REQUIRE_MSG(rc != -1, "getsockopt(LOCAL_CREDS) failed: %s",
204 	    strerror(errno));
205 	return (val != 0);
206 }
207 
208 static void
209 recvfd_payload(int sockfd, int *recv_fd, void *buf, size_t buflen,
210     size_t cmsgsz, int recvmsg_flags)
211 {
212 	struct cmsghdr *cmsghdr;
213 	struct msghdr msghdr;
214 	struct iovec iovec;
215 	char *message;
216 	ssize_t len;
217 	bool foundcreds;
218 
219 	bzero(&msghdr, sizeof(msghdr));
220 	message = malloc(cmsgsz);
221 	ATF_REQUIRE(message != NULL);
222 
223 	msghdr.msg_control = message;
224 	msghdr.msg_controllen = cmsgsz;
225 
226 	iovec.iov_base = buf;
227 	iovec.iov_len = buflen;
228 
229 	msghdr.msg_iov = &iovec;
230 	msghdr.msg_iovlen = 1;
231 
232 	len = recvmsg(sockfd, &msghdr, recvmsg_flags);
233 	ATF_REQUIRE_MSG(len != -1, "recvmsg failed: %s", strerror(errno));
234 	ATF_REQUIRE_MSG((size_t)len == buflen,
235 	    "recvmsg: %zd bytes received; expected %zd", len, buflen);
236 
237 	cmsghdr = CMSG_FIRSTHDR(&msghdr);
238 	ATF_REQUIRE_MSG(cmsghdr != NULL,
239 	    "recvmsg: did not receive control message");
240 	foundcreds = false;
241 	*recv_fd = -1;
242 	for (; cmsghdr != NULL; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) {
243 		if (cmsghdr->cmsg_level == SOL_SOCKET &&
244 		    cmsghdr->cmsg_type == SCM_RIGHTS &&
245 		    cmsghdr->cmsg_len == CMSG_LEN(sizeof(int))) {
246 			memcpy(recv_fd, CMSG_DATA(cmsghdr), sizeof(int));
247 			ATF_REQUIRE(*recv_fd != -1);
248 		} else if (cmsghdr->cmsg_level == SOL_SOCKET &&
249 		    cmsghdr->cmsg_type == SCM_CREDS)
250 			foundcreds = true;
251 	}
252 	ATF_REQUIRE_MSG(*recv_fd != -1,
253 	    "recvmsg: did not receive single-fd message");
254 	ATF_REQUIRE_MSG(!localcreds(sockfd) || foundcreds,
255 	    "recvmsg: expected credentials were not received");
256 	ATF_REQUIRE_MSG((msghdr.msg_flags & MSG_TRUNC) == 0,
257 	    "recvmsg: MSG_TRUNC is set while buffer is sufficient");
258 }
259 
260 static void
261 recvfd(int sockfd, int *recv_fd, int flags)
262 {
263 	char ch = 0;
264 
265 	recvfd_payload(sockfd, recv_fd, &ch, sizeof(ch),
266 	    CMSG_SPACE(sizeof(int)), flags);
267 }
268 
269 #if TEST_PROTO == SOCK_STREAM
270 #define	LOCAL_SENDSPACE_SYSCTL	"net.local.stream.sendspace"
271 #define	LOCAL_RECVSPACE_SYSCTL	"net.local.stream.recvspace"
272 #elif TEST_PROTO == SOCK_DGRAM
273 #define	LOCAL_SENDSPACE_SYSCTL	"net.local.dgram.maxdgram"
274 #define	LOCAL_RECVSPACE_SYSCTL	"net.local.dgram.recvspace"
275 #endif
276 
277 static u_long
278 getsendspace(void)
279 {
280 	u_long sendspace;
281 
282 	ATF_REQUIRE_MSG(sysctlbyname(LOCAL_SENDSPACE_SYSCTL, &sendspace,
283             &(size_t){sizeof(u_long)}, NULL, 0) != -1,
284 	    "sysctl %s failed: %s", LOCAL_SENDSPACE_SYSCTL, strerror(errno));
285 
286 	return (sendspace);
287 }
288 
289 static u_long
290 getrecvspace(void)
291 {
292 	u_long recvspace;
293 
294 	ATF_REQUIRE_MSG(sysctlbyname(LOCAL_RECVSPACE_SYSCTL, &recvspace,
295             &(size_t){sizeof(u_long)}, NULL, 0) != -1,
296 	    "sysctl %s failed: %s", LOCAL_RECVSPACE_SYSCTL, strerror(errno));
297 
298 	return (recvspace);
299 }
300 
301 /*
302  * Fill socket to a state when next max sized send would fail with EAGAIN.
303  */
304 static void
305 fill(int fd)
306 {
307 	u_long sendspace;
308 	void *buf;
309 
310 	sendspace = getsendspace();
311 	ATF_REQUIRE((buf = malloc(sendspace)) != NULL);
312 
313 	ATF_REQUIRE_MSG(fcntl(fd, F_SETFL, O_NONBLOCK) != -1,
314 	    "fcntl(O_NONBLOCK) failed: %s", strerror(errno));
315 
316 #if TEST_PROTO == SOCK_STREAM
317 	do {} while (send(fd, buf, sendspace, 0) == (ssize_t)sendspace);
318 #elif TEST_PROTO == SOCK_DGRAM
319 	u_long recvspace = getrecvspace();
320 
321 	for (ssize_t sent = 0;
322 	    sent + sendspace + sizeof(struct sockaddr) < recvspace;
323 	    sent += sendspace + sizeof(struct sockaddr))
324 		ATF_REQUIRE(send(fd, buf, sendspace, 0) == (ssize_t)sendspace);
325 #endif
326 	free(buf);
327 }
328 
329 /*
330  * Put a temporary file into a UNIX domain socket, then take it out and make
331  * sure it's the same file.  First time around, don't close the reference
332  * after sending.
333  */
334 ATF_TC_WITHOUT_HEAD(simple_send_fd);
335 ATF_TC_BODY(simple_send_fd, tc)
336 {
337 	struct stat getfd_stat, putfd_stat;
338 	int fd[2], getfd, putfd;
339 
340 	domainsocketpair(fd);
341 	tempfile(&putfd);
342 	dofstat(putfd, &putfd_stat);
343 	sendfd(fd[0], putfd);
344 	recvfd(fd[1], &getfd, 0);
345 	dofstat(getfd, &getfd_stat);
346 	samefile(&putfd_stat, &getfd_stat);
347 	close(putfd);
348 	close(getfd);
349 	closesocketpair(fd);
350 }
351 
352 /*
353  * Like simple_send_fd but also sets MSG_CMSG_CLOEXEC and checks that the
354  * received file descriptor has the FD_CLOEXEC flag set.
355  */
356 ATF_TC_WITHOUT_HEAD(simple_send_fd_msg_cmsg_cloexec);
357 ATF_TC_BODY(simple_send_fd_msg_cmsg_cloexec, tc)
358 {
359 	struct stat getfd_stat, putfd_stat;
360 	int fd[2], getfd, putfd;
361 
362 	domainsocketpair(fd);
363 	tempfile(&putfd);
364 	dofstat(putfd, &putfd_stat);
365 	sendfd(fd[0], putfd);
366 	recvfd(fd[1], &getfd, MSG_CMSG_CLOEXEC);
367 	dofstat(getfd, &getfd_stat);
368 	samefile(&putfd_stat, &getfd_stat);
369 	ATF_REQUIRE_EQ_MSG(fcntl(getfd, F_GETFD) & FD_CLOEXEC, FD_CLOEXEC,
370 	    "FD_CLOEXEC not set on the received file descriptor");
371 	close(putfd);
372 	close(getfd);
373 	closesocketpair(fd);
374 }
375 
376 /*
377  * Same as simple_send_fd, only close the file reference after sending, so that
378  * the only reference is the descriptor in the UNIX domain socket buffer.
379  */
380 ATF_TC_WITHOUT_HEAD(send_and_close);
381 ATF_TC_BODY(send_and_close, tc)
382 {
383 	struct stat getfd_stat, putfd_stat;
384 	int fd[2], getfd, putfd;
385 
386 	domainsocketpair(fd);
387 	tempfile(&putfd);
388 	dofstat(putfd, &putfd_stat);
389 	sendfd(fd[0], putfd);
390 	close(putfd);
391 	recvfd(fd[1], &getfd, 0);
392 	dofstat(getfd, &getfd_stat);
393 	samefile(&putfd_stat, &getfd_stat);
394 	close(getfd);
395 	closesocketpair(fd);
396 }
397 
398 /*
399  * Put a temporary file into a UNIX domain socket, then close both endpoints
400  * causing garbage collection to kick off.
401  */
402 ATF_TC_WITHOUT_HEAD(send_and_cancel);
403 ATF_TC_BODY(send_and_cancel, tc)
404 {
405 	int fd[2], putfd;
406 
407 	domainsocketpair(fd);
408 	tempfile(&putfd);
409 	sendfd(fd[0], putfd);
410 	close(putfd);
411 	closesocketpair(fd);
412 }
413 
414 /*
415  * Send file then shutdown receive side to exercise unp_dispose() call
416  * via soshutdown().  Check that shutdown(SHUT_RD) would gc the file
417  * reference sitting in the receive buffer.  There is no good way of
418  * checking that except using global open file count.
419  */
420 ATF_TC_WITHOUT_HEAD(send_and_shutdown);
421 ATF_TC_BODY(send_and_shutdown, tc)
422 {
423 	int fd[2], putfd, nfiles;
424 
425 	domainsocketpair(fd);
426 	tempfile(&putfd);
427 	sendfd(fd[0], putfd);
428 	nfiles = openfiles();
429 	close(putfd);
430 	ATF_REQUIRE(openfiles() == nfiles);
431 	shutdown(fd[1], SHUT_RD);
432 	ATF_REQUIRE(openfiles() == nfiles - 1);
433 	closesocketpair(fd);
434 }
435 
436 /*
437  * Send maximum possible SCM_RIGHTS message.
438  * Internally the file descriptors are converted from integers to pointers
439  * and stored in a single mbuf cluster.  Check that we can not send too much
440  * and that we can successfully send maximum possible amount.  Check that we
441  * can not exploit getrlimit(3).
442  */
443 #define	MAXFDS	((MCLBYTES - _ALIGN(sizeof(struct cmsghdr)))/sizeof(void *))
444 ATF_TC_WITHOUT_HEAD(send_a_lot);
445 ATF_TC_BODY(send_a_lot, tc)
446 {
447 	struct msghdr msghdr;
448 	struct iovec iov;
449 	struct rlimit rlim;
450 	int fd[2], nfds;
451 	char *cmsg, ch;
452 
453 	domainsocketpair(fd);
454 	cmsg = malloc(CMSG_SPACE((MAXFDS + 1) * sizeof(int)));
455 	ATF_REQUIRE(cmsg != NULL);
456 	iov.iov_base = &ch;
457 	iov.iov_len = sizeof(ch);
458 	msghdr = (struct msghdr ){
459 		.msg_control = cmsg,
460 		.msg_controllen = CMSG_LEN((MAXFDS + 1) * sizeof(int)),
461 		.msg_iov = &iov,
462 		.msg_iovlen = 1,
463 	};
464 
465 	/* Sending too much fails. */
466 	putfds(cmsg, fd[0], MAXFDS + 1);
467 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == -1);
468 	ATF_REQUIRE(errno == EMSGSIZE);
469 
470 	/* Sending just the right amount works and everything is received. */
471 	putfds(cmsg, fd[0], MAXFDS);
472 	msghdr.msg_controllen = CMSG_LEN(MAXFDS * sizeof(int));
473 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == 1);
474 	nfds = getnfds();
475 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == 1);
476 	ATF_REQUIRE(getnfds() == (int)(nfds + MAXFDS));
477 
478 	/* Limit our process open files... */
479 	ATF_REQUIRE(getrlimit(RLIMIT_NOFILE, &rlim) == 0);
480 	nfds = rlim.rlim_cur = getnfds();
481 	ATF_REQUIRE(setrlimit(RLIMIT_NOFILE, &rlim) == 0);
482 
483 	/* ... and try to receive a single descriptor. */
484 	putfds(cmsg, fd[0], 1);
485 	msghdr.msg_controllen = CMSG_LEN(sizeof(int));
486 	ATF_REQUIRE(sendmsg(fd[0], &msghdr, 0) == 1);
487 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == -1);
488 	/* Such attempt shall fail with EMFILE. */
489 	ATF_REQUIRE(errno == EMFILE);
490 	ATF_REQUIRE(getnfds() == nfds);
491 #if TEST_PROTO == SOCK_STREAM
492 	/*
493 	 * For the SOCK_STREAM the above attempt shall free the control in
494 	 * the kernel, so that socket isn't left in a stuck state.  Next read
495 	 * shall bring us the normal data only.  The stream data shall not
496 	 * miss a byte.
497 	 */
498 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, 0) == 1);
499 	ATF_REQUIRE(msghdr.msg_controllen == 0);
500 #elif TEST_PROTO == SOCK_DGRAM
501 	/*
502 	 * For SOCK_DGRAM there are two options for the previously failed
503 	 * syscall: strip the control leaving datagram in the socket or
504 	 * drop the whole datagram.  Our implementation drops the whole
505 	 * datagram.
506 	 */
507 	ATF_REQUIRE(recvmsg(fd[1], &msghdr, MSG_DONTWAIT) == -1);
508 	ATF_REQUIRE(errno == EAGAIN);
509 #endif
510 }
511 
512 /*
513  * Exersize condition when SCM_RIGHTS is successfully internalized, but
514  * message delivery fails due to receive buffer overflow.  Check that no
515  * file descriptors are leaked.
516  */
517 ATF_TC_WITHOUT_HEAD(send_overflow);
518 ATF_TC_BODY(send_overflow, tc)
519 {
520 	void *buf;
521 	ssize_t len;
522 	int fd[2], putfd, nfiles;
523 	int sendspace;
524 
525 	sendspace = (int)getsendspace();
526 	ATF_REQUIRE((buf = malloc(sendspace)) != NULL);
527 
528 	domainsocketpair(fd);
529 	fill(fd[0]);
530 	nfiles = openfiles();
531 	tempfile(&putfd);
532 	len = sendfd_payload(fd[0], putfd, buf, sendspace);
533 #if TEST_PROTO == SOCK_STREAM
534 	ATF_REQUIRE_MSG(len == -1 && errno == EAGAIN,
535 	    "sendmsg: %zd bytes sent, errno %d", len, errno);
536 #elif TEST_PROTO == SOCK_DGRAM
537 	ATF_REQUIRE_MSG(len == -1 && errno == ENOBUFS,
538 	    "sendmsg: %zd bytes sent, errno %d", len, errno);
539 #endif
540 	close(putfd);
541 	ATF_REQUIRE(nfiles == openfiles());
542 	closesocketpair(fd);
543 }
544 
545 
546 /*
547  * Send two files.  Then receive them.  Make sure they are returned in the
548  * right order, and both get there.
549  */
550 ATF_TC_WITHOUT_HEAD(two_files);
551 ATF_TC_BODY(two_files, tc)
552 {
553 	struct stat getfd_1_stat, getfd_2_stat, putfd_1_stat, putfd_2_stat;
554 	int fd[2], getfd_1, getfd_2, putfd_1, putfd_2;
555 
556 	domainsocketpair(fd);
557 	tempfile(&putfd_1);
558 	tempfile(&putfd_2);
559 	dofstat(putfd_1, &putfd_1_stat);
560 	dofstat(putfd_2, &putfd_2_stat);
561 	sendfd(fd[0], putfd_1);
562 	sendfd(fd[0], putfd_2);
563 	close(putfd_1);
564 	close(putfd_2);
565 	recvfd(fd[1], &getfd_1, 0);
566 	recvfd(fd[1], &getfd_2, 0);
567 	dofstat(getfd_1, &getfd_1_stat);
568 	dofstat(getfd_2, &getfd_2_stat);
569 	samefile(&putfd_1_stat, &getfd_1_stat);
570 	samefile(&putfd_2_stat, &getfd_2_stat);
571 	close(getfd_1);
572 	close(getfd_2);
573 	closesocketpair(fd);
574 }
575 
576 /*
577  * Big bundling test.  Send an endpoint of the UNIX domain socket over itself,
578  * closing the door behind it.
579  */
580 ATF_TC_WITHOUT_HEAD(bundle);
581 ATF_TC_BODY(bundle, tc)
582 {
583 	int fd[2], getfd;
584 
585 	domainsocketpair(fd);
586 
587 	sendfd(fd[0], fd[0]);
588 	close(fd[0]);
589 	recvfd(fd[1], &getfd, 0);
590 	close(getfd);
591 	close(fd[1]);
592 }
593 
594 /*
595  * Big bundling test part two: Send an endpoint of the UNIX domain socket over
596  * itself, close the door behind it, and never remove it from the other end.
597  */
598 ATF_TC_WITHOUT_HEAD(bundle_cancel);
599 ATF_TC_BODY(bundle_cancel, tc)
600 {
601 	int fd[2];
602 
603 	domainsocketpair(fd);
604 	sendfd(fd[0], fd[0]);
605 	sendfd(fd[1], fd[0]);
606 	closesocketpair(fd);
607 }
608 
609 /*
610  * Test for PR 151758: Send an character device over the UNIX domain socket
611  * and then close both sockets to orphan the device.
612  */
613 ATF_TC_WITHOUT_HEAD(devfs_orphan);
614 ATF_TC_BODY(devfs_orphan, tc)
615 {
616 	int fd[2], putfd;
617 
618 	domainsocketpair(fd);
619 	devnull(&putfd);
620 	sendfd(fd[0], putfd);
621 	close(putfd);
622 	closesocketpair(fd);
623 }
624 
625 /*
626  * Test for PR 181741. Receiver sets LOCAL_CREDS, and kernel prepends a
627  * control message to the data. Sender sends large payload using a non-blocking
628  * socket. Payload + SCM_RIGHTS + LOCAL_CREDS hit socket buffer limit, and
629  * receiver receives truncated data.
630  */
631 ATF_TC_WITHOUT_HEAD(rights_creds_payload);
632 ATF_TC_BODY(rights_creds_payload, tc)
633 {
634 	const int on = 1;
635 	u_long sendspace;
636 	ssize_t len;
637 	void *buf;
638 	int fd[2], getfd, putfd, rc;
639 
640 	sendspace = getsendspace();
641 	buf = calloc(1, sendspace);
642 	ATF_REQUIRE(buf != NULL);
643 
644 	domainsocketpair(fd);
645 	tempfile(&putfd);
646 
647 	rc = fcntl(fd[0], F_SETFL, O_NONBLOCK);
648 	ATF_REQUIRE_MSG(rc != -1, "fcntl(O_NONBLOCK) failed: %s",
649 	    strerror(errno));
650 	rc = setsockopt(fd[1], 0, LOCAL_CREDS, &on, sizeof(on));
651 	ATF_REQUIRE_MSG(rc != -1, "setsockopt(LOCAL_CREDS) failed: %s",
652 	    strerror(errno));
653 
654 	len = sendfd_payload(fd[0], putfd, buf, sendspace);
655 #if TEST_PROTO == SOCK_STREAM
656 	ATF_REQUIRE_MSG(len != -1 , "sendmsg failed: %s", strerror(errno));
657 	ATF_REQUIRE_MSG((size_t)len < sendspace,
658 	    "sendmsg: %zd bytes sent", len);
659 	recvfd_payload(fd[1], &getfd, buf, len,
660 	    CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) + CMSG_SPACE(sizeof(int)), 0);
661 #endif
662 #if TEST_PROTO == SOCK_DGRAM
663 	ATF_REQUIRE_MSG(len != -1 , "sendmsg failed: %s", strerror(errno));
664 	ATF_REQUIRE_MSG((size_t)len == sendspace,
665 	    "sendmsg: %zd bytes sent", len);
666 	recvfd_payload(fd[1], &getfd, buf, len,
667 	    CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) + CMSG_SPACE(sizeof(int)), 0);
668 #endif
669 
670 	close(putfd);
671 	close(getfd);
672 	closesocketpair(fd);
673 }
674 
675 static void
676 send_cmsg(int sockfd, void *cmsg, size_t cmsgsz)
677 {
678 	struct iovec iov;
679 	struct msghdr msghdr;
680 	ssize_t len;
681 	char ch;
682 
683 	ch = 0;
684 	bzero(&msghdr, sizeof(msghdr));
685 
686 	iov.iov_base = &ch;
687 	iov.iov_len = sizeof(ch);
688 	msghdr.msg_control = cmsg;
689 	msghdr.msg_controllen = cmsgsz;
690 	msghdr.msg_iov = &iov;
691 	msghdr.msg_iovlen = 1;
692 
693 	len = sendmsg(sockfd, &msghdr, 0);
694 	ATF_REQUIRE_MSG(len != -1,
695 	    "sendmsg failed: %s", strerror(errno));
696 	ATF_REQUIRE_MSG(len == sizeof(ch),
697 	    "sendmsg: %zd bytes sent; expected %zu", len, sizeof(ch));
698 }
699 
700 static void
701 recv_cmsg(int sockfd, char *cmsg, size_t cmsgsz, int flags)
702 {
703 	struct iovec iov;
704 	struct msghdr msghdr;
705 	ssize_t len;
706 	char ch;
707 
708 	ch = 0;
709 	bzero(&msghdr, sizeof(msghdr));
710 
711 	iov.iov_base = &ch;
712 	iov.iov_len = sizeof(ch);
713 	msghdr.msg_control = cmsg;
714 	msghdr.msg_controllen = cmsgsz;
715 	msghdr.msg_iov = &iov;
716 	msghdr.msg_iovlen = 1;
717 
718 	len = recvmsg(sockfd, &msghdr, 0);
719 	ATF_REQUIRE_MSG(len != -1,
720 	    "recvmsg failed: %s", strerror(errno));
721 	ATF_REQUIRE_MSG(len == sizeof(ch),
722 	    "recvmsg: %zd bytes received; expected %zu", len, sizeof(ch));
723 	ATF_REQUIRE_MSG((msghdr.msg_flags & flags) == flags,
724 	    "recvmsg: got flags %#x; expected %#x", msghdr.msg_flags, flags);
725 }
726 
727 /*
728  * Test for PR 131876.  Receiver uses a control message buffer that is too
729  * small for the incoming SCM_RIGHTS message, so the message is truncated.
730  * The kernel must not leak the copied right into the receiver's namespace.
731  */
732 ATF_TC_WITHOUT_HEAD(truncated_rights);
733 ATF_TC_BODY(truncated_rights, tc)
734 {
735 	char *message;
736 	int fd[2], nfds, putfd, rc;
737 
738 	domainsocketpair(fd);
739 	devnull(&putfd);
740 	nfds = getnfds();
741 
742 	/*
743 	 * Case 1: Send a single descriptor and truncate the message.
744 	 */
745 	message = malloc(CMSG_SPACE(sizeof(int)));
746 	ATF_REQUIRE(message != NULL);
747 	putfds(message, putfd, 1);
748 	send_cmsg(fd[0], message, CMSG_LEN(sizeof(int)));
749 	recv_cmsg(fd[1], message, CMSG_LEN(0), MSG_CTRUNC);
750 	ATF_REQUIRE(getnfds() == nfds);
751 	free(message);
752 
753 	/*
754 	 * Case 2a: Send two descriptors in separate messages, and truncate at
755 	 *          the boundary between the two messages.  We should still
756 	 *          receive the first message.
757 	 */
758 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
759 	ATF_REQUIRE(message != NULL);
760 	putfds(message, putfd, 1);
761 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
762 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
763 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
764 	rc = close(*(int *)CMSG_DATA(message));
765 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
766 	ATF_REQUIRE(getnfds() == nfds);
767 	free(message);
768 
769 	/*
770 	 * Case 2b: Send two descriptors in separate messages, and truncate
771 	 *          before the end of the first message.
772 	 */
773 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
774 	ATF_REQUIRE(message != NULL);
775 	putfds(message, putfd, 1);
776 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
777 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
778 	recv_cmsg(fd[1], message, CMSG_SPACE(0), MSG_CTRUNC);
779 	ATF_REQUIRE(getnfds() == nfds);
780 	free(message);
781 
782 	/*
783 	 * Case 2c: Send two descriptors in separate messages, and truncate
784 	 *          after the end of the first message.  We should still
785 	 *          receive the first message.
786 	 */
787 	message = malloc(CMSG_SPACE(sizeof(int)) * 2);
788 	ATF_REQUIRE(message != NULL);
789 	putfds(message, putfd, 1);
790 	putfds(message + CMSG_SPACE(sizeof(int)), putfd, 1);
791 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int)) * 2);
792 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)) + CMSG_SPACE(0),
793 	    MSG_CTRUNC);
794 	rc = close(*(int *)CMSG_DATA(message));
795 	ATF_REQUIRE_MSG(rc == 0, "close failed: %s", strerror(errno));
796 	ATF_REQUIRE(getnfds() == nfds);
797 	free(message);
798 
799 	/*
800 	 * Case 3: Send three descriptors in the same message, and leave space
801 	 *         only for the first when receiving the message.
802 	 */
803 	message = malloc(CMSG_SPACE(sizeof(int) * 3));
804 	ATF_REQUIRE(message != NULL);
805 	putfds(message, putfd, 3);
806 	send_cmsg(fd[0], message, CMSG_SPACE(sizeof(int) * 3));
807 	recv_cmsg(fd[1], message, CMSG_SPACE(sizeof(int)), MSG_CTRUNC);
808 	ATF_REQUIRE(getnfds() == nfds);
809 	free(message);
810 
811 	close(putfd);
812 	closesocketpair(fd);
813 }
814 
815 /*
816  * Ensure that an attempt to copy a SCM_RIGHTS message to the recipient
817  * fails.  In this case the kernel must dispose of the externalized rights
818  * rather than leaking them into the recipient's file descriptor table.
819  */
820 ATF_TC_WITHOUT_HEAD(copyout_rights_error);
821 ATF_TC_BODY(copyout_rights_error, tc)
822 {
823 	struct iovec iovec;
824 	struct msghdr msghdr;
825 	char buf[16];
826 	ssize_t len;
827 	int fd[2], error, nfds, putfd;
828 
829 	memset(buf, 0, sizeof(buf));
830 	domainsocketpair(fd);
831 	devnull(&putfd);
832 	nfds = getnfds();
833 
834 	len = sendfd_payload(fd[0], putfd, buf, sizeof(buf));
835 	ATF_REQUIRE_MSG(len != -1, "sendmsg failed: %s", strerror(errno));
836 
837 	bzero(&msghdr, sizeof(msghdr));
838 
839 	iovec.iov_base = buf;
840 	iovec.iov_len = sizeof(buf);
841 	msghdr.msg_control = (char *)-1; /* trigger EFAULT */
842 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
843 	msghdr.msg_iov = &iovec;
844 	msghdr.msg_iovlen = 1;
845 
846 	len = recvmsg(fd[1], &msghdr, 0);
847 	error = errno;
848 	ATF_REQUIRE_MSG(len == -1, "recvmsg succeeded: %zd", len);
849 	ATF_REQUIRE_MSG(errno == EFAULT, "expected EFAULT, got %d (%s)",
850 	    error, strerror(errno));
851 
852 	/* Verify that no FDs were leaked. */
853 	ATF_REQUIRE(getnfds() == nfds);
854 
855 	close(putfd);
856 	closesocketpair(fd);
857 }
858 
859 /*
860  * Verify that we can handle empty rights messages.
861  */
862 ATF_TC_WITHOUT_HEAD(empty_rights_message);
863 ATF_TC_BODY(empty_rights_message, tc)
864 {
865 	struct iovec iov;
866 	struct msghdr msghdr;
867 	struct cmsghdr cmsg;
868 	char *cm, message[CMSG_SPACE(0) + CMSG_SPACE(sizeof(int))];
869 	ssize_t len;
870 	int error, fd[2], putfd;
871 
872 	domainsocketpair(fd);
873 	devnull(&putfd);
874 
875 	memset(&msghdr, 0, sizeof(msghdr));
876 	iov.iov_base = NULL;
877 	iov.iov_len = 0;
878 	msghdr.msg_iov = &iov;
879 	msghdr.msg_iovlen = 1;
880 
881 	/*
882 	 * Try sending incorrect empty message.  On 64-bit platforms, where
883 	 * CMSG_SPACE(0) > sizeof(struct cmsghdr), this will exercise
884 	 * an edge case.
885 	 */
886 	cmsg = (struct cmsghdr ){
887 	    .cmsg_len = sizeof(struct cmsghdr),	/* not CMSG_LEN(0)! */
888 	    .cmsg_level = SOL_SOCKET,
889 	    .cmsg_type = SCM_RIGHTS,
890 	};
891 	msghdr.msg_control = &cmsg;
892 	msghdr.msg_controllen = CMSG_SPACE(0);
893 
894 	len = sendmsg(fd[0], &msghdr, 0);
895 	if (CMSG_LEN(0) != sizeof(struct cmsghdr))
896 		ATF_REQUIRE(len == -1 && errno == EINVAL);
897 	else
898 		ATF_REQUIRE(len == 0);
899 
900 	/*
901 	 * Try sending an empty message followed by a non-empty message.
902 	 */
903 	cm = message;
904 	putfds(cm, -1, 0);
905 	cm += CMSG_SPACE(0);
906 	putfds(cm, putfd, 1);
907 	msghdr.msg_control = message;
908 	msghdr.msg_controllen = sizeof(message);
909 
910 	len = sendmsg(fd[0], &msghdr, 0);
911 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
912 
913 	/* Only the non-empty message should be received. */
914 	len = recvmsg(fd[1], &msghdr, 0);
915 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
916 	ATF_REQUIRE(msghdr.msg_controllen = CMSG_SPACE(sizeof(int)));
917 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
918 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
919 
920 	/*
921 	 * Now try sending with the non-empty message before the empty message.
922 	 */
923 	cm = message;
924 	putfds(cm, putfd, 1);
925 	cm += CMSG_SPACE(sizeof(int));
926 	putfds(cm, -1, 0);
927 
928 	memset(&msghdr, 0, sizeof(msghdr));
929 	iov.iov_base = NULL;
930 	iov.iov_len = 0;
931 	msghdr.msg_control = message;
932 	msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
933 	msghdr.msg_iov = &iov;
934 	msghdr.msg_iovlen = 1;
935 
936 	len = sendmsg(fd[0], &msghdr, 0);
937 	ATF_REQUIRE_MSG(len == 0, "sendmsg failed: %s", strerror(errno));
938 
939 	/* Only the non-empty message should be received. */
940 	len = recvmsg(fd[1], &msghdr, 0);
941 	ATF_REQUIRE_MSG(len == 0, "recvmsg failed: %s", strerror(errno));
942 	ATF_REQUIRE(msghdr.msg_controllen = CMSG_SPACE(sizeof(int)));
943 	error = close(*(int *)CMSG_DATA(msghdr.msg_control));
944 	ATF_REQUIRE_MSG(error == 0, "close failed: %s", strerror(errno));
945 
946 	(void)close(putfd);
947 }
948 
949 ATF_TP_ADD_TCS(tp)
950 {
951 
952 	ATF_TP_ADD_TC(tp, simple_send_fd);
953 	ATF_TP_ADD_TC(tp, simple_send_fd_msg_cmsg_cloexec);
954 	ATF_TP_ADD_TC(tp, send_and_close);
955 	ATF_TP_ADD_TC(tp, send_and_cancel);
956 	ATF_TP_ADD_TC(tp, send_and_shutdown);
957 	ATF_TP_ADD_TC(tp, send_a_lot);
958 	ATF_TP_ADD_TC(tp, send_overflow);
959 	ATF_TP_ADD_TC(tp, two_files);
960 	ATF_TP_ADD_TC(tp, bundle);
961 	ATF_TP_ADD_TC(tp, bundle_cancel);
962 	ATF_TP_ADD_TC(tp, devfs_orphan);
963 	ATF_TP_ADD_TC(tp, rights_creds_payload);
964 	ATF_TP_ADD_TC(tp, truncated_rights);
965 	ATF_TP_ADD_TC(tp, copyout_rights_error);
966 	ATF_TP_ADD_TC(tp, empty_rights_message);
967 
968 	return (atf_no_error());
969 }
970