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