xref: /freebsd/usr.sbin/rpc.tlsservd/rpc.tlsservd.c (revision 657729a89dd578d8cfc70d6616f5c65a48a8b33a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2008 Isilon Inc http://www.isilon.com/
5  * Authors: Doug Rabson <dfr@rabson.org>
6  * Developed with Red Inc: Alfred Perlstein <alfred@freebsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * Extensively modified from /usr/src/usr.sbin/gssd.c r344402 for
32  * the server side of kernel RPC-over-TLS by Rick Macklem.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include <sys/param.h>
39 #include <sys/types.h>
40 #include <sys/linker.h>
41 #include <sys/module.h>
42 #include <sys/queue.h>
43 #include <sys/stat.h>
44 #include <sys/sysctl.h>
45 #include <sys/syslog.h>
46 #include <sys/time.h>
47 #include <sys/wait.h>
48 #include <err.h>
49 #include <getopt.h>
50 #include <libutil.h>
51 #include <netdb.h>
52 #include <pwd.h>
53 #include <signal.h>
54 #include <stdarg.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <stdbool.h>
58 #include <string.h>
59 #include <unistd.h>
60 
61 #include <rpc/rpc.h>
62 #include <rpc/rpc_com.h>
63 #include <rpc/rpcsec_tls.h>
64 
65 #include <openssl/opensslconf.h>
66 #include <openssl/bio.h>
67 #include <openssl/ssl.h>
68 #include <openssl/err.h>
69 #include <openssl/x509v3.h>
70 
71 #include "rpctlssd.h"
72 #include "rpc.tlscommon.h"
73 
74 #ifndef _PATH_RPCTLSSDSOCK
75 #define _PATH_RPCTLSSDSOCK	"/var/run/rpc.tlsservd.sock"
76 #endif
77 #ifndef	_PATH_CERTANDKEY
78 #define	_PATH_CERTANDKEY	"/etc/rpc.tlsservd/"
79 #endif
80 #ifndef	_PATH_RPCTLSSDPID
81 #define	_PATH_RPCTLSSDPID	"/var/run/rpc.tlsservd.pid"
82 #endif
83 #ifndef	_PREFERRED_CIPHERS
84 #define	_PREFERRED_CIPHERS	"AES128-GCM-SHA256"
85 #endif
86 
87 /* Global variables also used by rpc.tlscommon.c. */
88 int			rpctls_debug_level;
89 bool			rpctls_verbose;
90 SSL_CTX			*rpctls_ctx = NULL;
91 const char		*rpctls_verify_cafile = NULL;
92 const char		*rpctls_verify_capath = NULL;
93 char			*rpctls_crlfile = NULL;
94 bool			rpctls_gothup = false;
95 struct ssl_list		rpctls_ssllist;
96 
97 static struct pidfh	*rpctls_pfh = NULL;
98 static bool		rpctls_do_mutual = false;
99 static const char	*rpctls_certdir = _PATH_CERTANDKEY;
100 static bool		rpctls_comparehost = false;
101 static unsigned int	rpctls_wildcard = X509_CHECK_FLAG_NO_WILDCARDS;
102 static uint64_t		rpctls_ssl_refno = 0;
103 static uint64_t		rpctls_ssl_sec = 0;
104 static uint64_t		rpctls_ssl_usec = 0;
105 static bool		rpctls_cnuser = false;
106 static char		*rpctls_dnsname;
107 static const char	*rpctls_cnuseroid = "1.3.6.1.4.1.2238.1.1.1";
108 static const char	*rpctls_ciphers = NULL;
109 static int		rpctls_mintls = TLS1_3_VERSION;
110 static int		rpctls_procs = 1;
111 static char		*rpctls_sockname[RPCTLS_SRV_MAXNPROCS];
112 static pid_t		rpctls_workers[RPCTLS_SRV_MAXNPROCS - 1];
113 static bool		rpctls_im_a_worker = false;
114 
115 static void		rpctls_cleanup_term(int sig);
116 static SSL_CTX		*rpctls_setup_ssl(const char *certdir);
117 static SSL		*rpctls_server(SSL_CTX *ctx, int s,
118 			    uint32_t *flags, uint32_t *uidp,
119 			    int *ngrps, uint32_t *gidp, X509 **certp);
120 static int		rpctls_cnname(X509 *cert, uint32_t *uidp,
121 			    int *ngrps, uint32_t *gidp);
122 static char		*rpctls_getdnsname(char *dnsname);
123 static void		rpctls_huphandler(int sig __unused);
124 
125 extern void		rpctlssd_1(struct svc_req *rqstp, SVCXPRT *transp);
126 
127 static struct option longopts[] = {
128 	{ "allowtls1_2",	no_argument,		NULL,	'2' },
129 	{ "ciphers",		required_argument,	NULL,	'C' },
130 	{ "certdir",		required_argument,	NULL,	'D' },
131 	{ "debuglevel",		no_argument,		NULL,	'd' },
132 	{ "checkhost",		no_argument,		NULL,	'h' },
133 	{ "verifylocs",		required_argument,	NULL,	'l' },
134 	{ "mutualverf",		no_argument,		NULL,	'm' },
135 	{ "numdaemons",		required_argument,	NULL,	'N' },
136 	{ "domain",		required_argument,	NULL,	'n' },
137 	{ "verifydir",		required_argument,	NULL,	'p' },
138 	{ "crl",		required_argument,	NULL,	'r' },
139 	{ "certuser",		no_argument,		NULL,	'u' },
140 	{ "verbose",		no_argument,		NULL,	'v' },
141 	{ "multiwild",		no_argument,		NULL,	'W' },
142 	{ "singlewild",		no_argument,		NULL,	'w' },
143 	{ NULL,			0,			NULL,	0  }
144 };
145 
146 int
147 main(int argc, char **argv)
148 {
149 	/*
150 	 * We provide an RPC service on a local-domain socket. The
151 	 * kernel rpctls code will upcall to this daemon to do the initial
152 	 * TLS handshake.
153 	 */
154 	struct sockaddr_un sun;
155 	int ch, fd, i, mypos, oldmask;
156 	SVCXPRT *xprt;
157 	struct timeval tm;
158 	struct timezone tz;
159 	char hostname[MAXHOSTNAMELEN + 2];
160 	pid_t otherpid;
161 	bool tls_enable;
162 	size_t tls_enable_len;
163 	sigset_t signew;
164 
165 	/* Check that another rpctlssd isn't already running. */
166 	rpctls_pfh = pidfile_open(_PATH_RPCTLSSDPID, 0600, &otherpid);
167 	if (rpctls_pfh == NULL) {
168 		if (errno == EEXIST)
169 			errx(1, "rpctlssd already running, pid: %d.", otherpid);
170 		warn("cannot open or create pidfile");
171 	}
172 
173 	/* Check to see that the ktls is enabled. */
174 	tls_enable_len = sizeof(tls_enable);
175 	if (sysctlbyname("kern.ipc.tls.enable", &tls_enable, &tls_enable_len,
176 	    NULL, 0) != 0 || !tls_enable)
177 		errx(1, "Kernel TLS not enabled");
178 
179 	/* Get the time when this daemon is started. */
180 	gettimeofday(&tm, &tz);
181 	rpctls_ssl_sec = tm.tv_sec;
182 	rpctls_ssl_usec = tm.tv_usec;
183 
184 	/* Set the dns name for the server. */
185 	rpctls_dnsname = rpctls_getdnsname(hostname);
186 	if (rpctls_dnsname == NULL) {
187 		strcpy(hostname, "@default.domain");
188 		rpctls_dnsname = hostname;
189 	}
190 
191 	/* Initialize socket names. */
192 	for (i = 0; i < RPCTLS_SRV_MAXNPROCS; i++) {
193 		asprintf(&rpctls_sockname[i], "%s.%d", _PATH_RPCTLSSDSOCK, i);
194 		if (rpctls_sockname[i] == NULL)
195 			errx(1, "Cannot malloc socknames");
196 	}
197 
198 	rpctls_verbose = false;
199 	while ((ch = getopt_long(argc, argv, "2C:D:dhl:N:n:mp:r:uvWw", longopts,
200 	    NULL)) != -1) {
201 		switch (ch) {
202 		case '2':
203 			rpctls_mintls = TLS1_2_VERSION;
204 			break;
205 		case 'C':
206 			rpctls_ciphers = optarg;
207 			break;
208 		case 'D':
209 			rpctls_certdir = optarg;
210 			break;
211 		case 'd':
212 			rpctls_debug_level++;
213 			break;
214 		case 'h':
215 			rpctls_comparehost = true;
216 			break;
217 		case 'l':
218 			rpctls_verify_cafile = optarg;
219 			break;
220 		case 'm':
221 			rpctls_do_mutual = true;
222 			break;
223 		case 'N':
224 			rpctls_procs = atoi(optarg);
225 			if (rpctls_procs < 1 ||
226 			    rpctls_procs > RPCTLS_SRV_MAXNPROCS)
227 				errx(1, "numdaemons/-N must be between 1 and "
228 				    "%d", RPCTLS_SRV_MAXNPROCS);
229 			break;
230 		case 'n':
231 			hostname[0] = '@';
232 			strlcpy(&hostname[1], optarg, MAXHOSTNAMELEN + 1);
233 			rpctls_dnsname = hostname;
234 			break;
235 		case 'p':
236 			rpctls_verify_capath = optarg;
237 			break;
238 		case 'r':
239 			rpctls_crlfile = optarg;
240 			break;
241 		case 'u':
242 			rpctls_cnuser = true;
243 			break;
244 		case 'v':
245 			rpctls_verbose = true;
246 			break;
247 		case 'W':
248 			if (rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS)
249 				errx(1, "options -w and -W are mutually "
250 				    "exclusive");
251 			rpctls_wildcard = X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS;
252 			break;
253 		case 'w':
254 			if (rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS)
255 				errx(1, "options -w and -W are mutually "
256 				    "exclusive");
257 			rpctls_wildcard = 0;
258 			break;
259 		default:
260 			fprintf(stderr, "usage: %s "
261 			    "[-2/--allowtls1_2] "
262 			    "[-C/--ciphers available_ciphers] "
263 			    "[-D/--certdir certdir] [-d/--debuglevel] "
264 			    "[-h/--checkhost] "
265 			    "[-l/--verifylocs CAfile] [-m/--mutualverf] "
266 			    "[-N/--numdaemons num] "
267 			    "[-n/--domain domain_name] "
268 			    "[-p/--verifydir CApath] [-r/--crl CRLfile] "
269 			    "[-u/--certuser] [-v/--verbose] [-W/--multiwild] "
270 			    "[-w/--singlewild]\n", argv[0]);
271 			exit(1);
272 		}
273 	}
274 	if (rpctls_do_mutual && rpctls_verify_cafile == NULL &&
275 	    rpctls_verify_capath == NULL)
276 		errx(1, "-m requires the -l <CAfile> and/or "
277 		    "-p <CApath> options");
278 	if (rpctls_comparehost && (!rpctls_do_mutual ||
279 	    (rpctls_verify_cafile == NULL && rpctls_verify_capath == NULL)))
280 		errx(1, "-h requires the -m plus the "
281 		    "-l <CAfile> and/or -p <CApath> options");
282 	if (!rpctls_comparehost && rpctls_wildcard !=
283 	    X509_CHECK_FLAG_NO_WILDCARDS)
284 		errx(1, "The -w or -W options require the -h option");
285 	if (rpctls_cnuser && (!rpctls_do_mutual ||
286 	    (rpctls_verify_cafile == NULL && rpctls_verify_capath == NULL)))
287 		errx(1, "-u requires the -m plus the "
288 		    "-l <CAfile> and/or -p <CApath> options");
289 
290 	if (modfind("krpc") < 0) {
291 		/* Not present in kernel, try loading it */
292 		if (kldload("krpc") < 0 || modfind("krpc") < 0)
293 			errx(1, "Kernel RPC is not available");
294 	}
295 
296 	for (i = 0; i < rpctls_procs - 1; i++)
297 		rpctls_workers[i] = -1;
298 	mypos = 0;
299 
300 	if (rpctls_debug_level == 0) {
301 		/*
302 		 * Temporarily block SIGTERM and SIGCHLD, so workers[] can't
303 		 * end up bogus.
304 		 */
305 		sigemptyset(&signew);
306 		sigaddset(&signew, SIGTERM);
307 		sigaddset(&signew, SIGCHLD);
308 		sigprocmask(SIG_BLOCK, &signew, NULL);
309 
310 		if (daemon(0, 0) != 0)
311 			err(1, "Can't daemonize");
312 		signal(SIGINT, SIG_IGN);
313 		signal(SIGQUIT, SIG_IGN);
314 	}
315 	signal(SIGPIPE, SIG_IGN);
316 	signal(SIGHUP, rpctls_huphandler);
317 	signal(SIGTERM, rpctls_cleanup_term);
318 	signal(SIGCHLD, rpctls_cleanup_term);
319 
320 	pidfile_write(rpctls_pfh);
321 
322 	rpctls_syscall(RPCTLS_SYSC_SRVSTARTUP, "");
323 
324 	if (rpctls_debug_level == 0) {
325 		/* Fork off the worker daemons. */
326 		for (i = 0; i < rpctls_procs - 1; i++) {
327 			rpctls_workers[i] = fork();
328 			if (rpctls_workers[i] == 0) {
329 				rpctls_im_a_worker = true;
330 				mypos = i + 1;
331 				setproctitle("server");
332 				break;
333 			} else if (rpctls_workers[i] < 0) {
334 				syslog(LOG_ERR, "fork: %m");
335 			}
336 		}
337 
338 		if (!rpctls_im_a_worker && rpctls_procs > 1)
339 			setproctitle("master");
340 	}
341 	sigemptyset(&signew);
342 	sigaddset(&signew, SIGTERM);
343 	sigaddset(&signew, SIGCHLD);
344 	sigprocmask(SIG_UNBLOCK, &signew, NULL);
345 
346 	memset(&sun, 0, sizeof sun);
347 	sun.sun_family = AF_LOCAL;
348 	unlink(rpctls_sockname[mypos]);
349 	strcpy(sun.sun_path, rpctls_sockname[mypos]);
350 	sun.sun_len = SUN_LEN(&sun);
351 	fd = socket(AF_LOCAL, SOCK_STREAM, 0);
352 	if (fd < 0) {
353 		if (rpctls_debug_level == 0) {
354 			syslog(LOG_ERR, "Can't create local rpctlssd socket");
355 			exit(1);
356 		}
357 		err(1, "Can't create local rpctlssd socket");
358 	}
359 	oldmask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
360 	if (bind(fd, (struct sockaddr *)&sun, sun.sun_len) < 0) {
361 		if (rpctls_debug_level == 0) {
362 			syslog(LOG_ERR, "Can't bind local rpctlssd socket");
363 			exit(1);
364 		}
365 		err(1, "Can't bind local rpctlssd socket");
366 	}
367 	umask(oldmask);
368 	if (listen(fd, SOMAXCONN) < 0) {
369 		if (rpctls_debug_level == 0) {
370 			syslog(LOG_ERR,
371 			    "Can't listen on local rpctlssd socket");
372 			exit(1);
373 		}
374 		err(1, "Can't listen on local rpctlssd socket");
375 	}
376 	xprt = svc_vc_create(fd, RPC_MAXDATASIZE, RPC_MAXDATASIZE);
377 	if (!xprt) {
378 		if (rpctls_debug_level == 0) {
379 			syslog(LOG_ERR,
380 			    "Can't create transport for local rpctlssd socket");
381 			exit(1);
382 		}
383 		err(1, "Can't create transport for local rpctlssd socket");
384 	}
385 	if (!svc_reg(xprt, RPCTLSSD, RPCTLSSDVERS, rpctlssd_1, NULL)) {
386 		if (rpctls_debug_level == 0) {
387 			syslog(LOG_ERR,
388 			    "Can't register service for local rpctlssd socket");
389 			exit(1);
390 		}
391 		err(1, "Can't register service for local rpctlssd socket");
392 	}
393 
394 	rpctls_ctx = rpctls_setup_ssl(rpctls_certdir);
395 	if (rpctls_ctx == NULL) {
396 		if (rpctls_debug_level == 0) {
397 			syslog(LOG_ERR, "Can't create SSL context");
398 			exit(1);
399 		}
400 		err(1, "Can't create SSL context");
401 	}
402 	rpctls_gothup = false;
403 	LIST_INIT(&rpctls_ssllist);
404 
405 	rpctls_syscall(RPCTLS_SYSC_SRVSETPATH, rpctls_sockname[mypos]);
406 
407 	rpctls_svc_run();
408 
409 	SSL_CTX_free(rpctls_ctx);
410 	EVP_cleanup();
411 	return (0);
412 }
413 
414 bool_t
415 rpctlssd_null_1_svc(__unused void *argp, __unused void *result,
416     __unused struct svc_req *rqstp)
417 {
418 
419 	rpctls_verbose_out("rpctlssd_null_svc: done\n");
420 	return (TRUE);
421 }
422 
423 bool_t
424 rpctlssd_connect_1_svc(__unused void *argp,
425     struct rpctlssd_connect_res *result, __unused struct svc_req *rqstp)
426 {
427 	int ngrps, s;
428 	SSL *ssl;
429 	uint32_t flags;
430 	struct ssl_entry *newslp;
431 	uint32_t uid;
432 	uint32_t *gidp;
433 	X509 *cert;
434 
435 	rpctls_verbose_out("rpctlsd_connect_svc: started\n");
436 	memset(result, 0, sizeof(*result));
437 	/* Get the socket fd from the kernel. */
438 	s = rpctls_syscall(RPCTLS_SYSC_SRVSOCKET, "");
439 	if (s < 0)
440 		return (FALSE);
441 
442 	/* Do the server side of a TLS handshake. */
443 	gidp = calloc(NGROUPS, sizeof(*gidp));
444 	ssl = rpctls_server(rpctls_ctx, s, &flags, &uid, &ngrps, gidp, &cert);
445 	if (ssl == NULL) {
446 		free(gidp);
447 		rpctls_verbose_out("rpctlssd_connect_svc: ssl "
448 		    "accept failed\n");
449 		/*
450 		 * For RPC-over-TLS, this upcall is expected
451 		 * to close off the socket upon handshake failure.
452 		 */
453 		close(s);
454 		return (FALSE);
455 	} else {
456 		rpctls_verbose_out("rpctlssd_connect_svc: "
457 		    "succeeded flags=0x%x\n", flags);
458 		result->flags = flags;
459 		result->sec = rpctls_ssl_sec;
460 		result->usec = rpctls_ssl_usec;
461 		result->ssl = ++rpctls_ssl_refno;
462 		/* Hard to believe this could ever wrap around.. */
463 		if (rpctls_ssl_refno == 0)
464 			result->ssl = ++rpctls_ssl_refno;
465 		if ((flags & RPCTLS_FLAGS_CERTUSER) != 0) {
466 			result->uid = uid;
467 			result->gid.gid_len = ngrps;
468 			result->gid.gid_val = gidp;
469 		} else {
470 			result->uid = 0;
471 			result->gid.gid_len = 0;
472 			result->gid.gid_val = gidp;
473 		}
474 	}
475 
476 	/* Maintain list of all current SSL *'s */
477 	newslp = malloc(sizeof(*newslp));
478 	newslp->ssl = ssl;
479 	newslp->s = s;
480 	newslp->shutoff = false;
481 	newslp->refno = rpctls_ssl_refno;
482 	newslp->cert = cert;
483 	LIST_INSERT_HEAD(&rpctls_ssllist, newslp, next);
484 	return (TRUE);
485 }
486 
487 bool_t
488 rpctlssd_handlerecord_1_svc(struct rpctlssd_handlerecord_arg *argp,
489     struct rpctlssd_handlerecord_res *result, __unused struct svc_req *rqstp)
490 {
491 	struct ssl_entry *slp;
492 	int ret;
493 	char junk;
494 
495 	slp = NULL;
496 	if (argp->sec == rpctls_ssl_sec && argp->usec ==
497 	    rpctls_ssl_usec) {
498 		LIST_FOREACH(slp, &rpctls_ssllist, next) {
499 			if (slp->refno == argp->ssl)
500 				break;
501 		}
502 	}
503 
504 	if (slp != NULL) {
505 		rpctls_verbose_out("rpctlssd_handlerecord fd=%d\n",
506 		    slp->s);
507 		/*
508 		 * An SSL_read() of 0 bytes should fail, but it should
509 		 * handle the non-application data record before doing so.
510 		 */
511 		ret = SSL_read(slp->ssl, &junk, 0);
512 		if (ret <= 0) {
513 			/* Check to see if this was a close alert. */
514 			ret = SSL_get_shutdown(slp->ssl);
515 			if ((ret & (SSL_SENT_SHUTDOWN |
516 			    SSL_RECEIVED_SHUTDOWN)) == SSL_RECEIVED_SHUTDOWN)
517 				SSL_shutdown(slp->ssl);
518 		} else {
519 			if (rpctls_debug_level == 0)
520 				syslog(LOG_ERR, "SSL_read returned %d", ret);
521 			else
522 				fprintf(stderr, "SSL_read returned %d\n", ret);
523 		}
524 		result->reterr = RPCTLSERR_OK;
525 	} else
526 		result->reterr = RPCTLSERR_NOSSL;
527 	return (TRUE);
528 }
529 
530 bool_t
531 rpctlssd_disconnect_1_svc(struct rpctlssd_disconnect_arg *argp,
532     struct rpctlssd_disconnect_res *result, __unused struct svc_req *rqstp)
533 {
534 	struct ssl_entry *slp;
535 	int ret;
536 
537 	slp = NULL;
538 	if (argp->sec == rpctls_ssl_sec && argp->usec ==
539 	    rpctls_ssl_usec) {
540 		LIST_FOREACH(slp, &rpctls_ssllist, next) {
541 			if (slp->refno == argp->ssl)
542 				break;
543 		}
544 	}
545 
546 	if (slp != NULL) {
547 		rpctls_verbose_out("rpctlssd_disconnect fd=%d closed\n",
548 		    slp->s);
549 		LIST_REMOVE(slp, next);
550 		if (!slp->shutoff) {
551 			ret = SSL_get_shutdown(slp->ssl);
552 			/*
553 			 * Do an SSL_shutdown() unless a close alert has
554 			 * already been sent.
555 			 */
556 			if ((ret & SSL_SENT_SHUTDOWN) == 0)
557 				SSL_shutdown(slp->ssl);
558 		}
559 		SSL_free(slp->ssl);
560 		if (slp->cert != NULL)
561 			X509_free(slp->cert);
562 		/*
563 		 * For RPC-over-TLS, this upcall is expected
564 		 * to close off the socket.
565 		 */
566 		if (!slp->shutoff)
567 			shutdown(slp->s, SHUT_WR);
568 		close(slp->s);
569 		free(slp);
570 		result->reterr = RPCTLSERR_OK;
571 	} else
572 		result->reterr = RPCTLSERR_NOCLOSE;
573 	return (TRUE);
574 }
575 
576 int
577 rpctlssd_1_freeresult(__unused SVCXPRT *transp, xdrproc_t xdr_result,
578     caddr_t result)
579 {
580 	rpctlssd_connect_res *res;
581 
582 	if (xdr_result == (xdrproc_t)xdr_rpctlssd_connect_res) {
583 		res = (rpctlssd_connect_res *)(void *)result;
584 		free(res->gid.gid_val);
585 	}
586 	return (TRUE);
587 }
588 
589 /*
590  * cleanup_term() called via SIGTERM (or SIGCHLD if a child dies).
591  */
592 static void
593 rpctls_cleanup_term(int sig)
594 {
595 	struct ssl_entry *slp;
596 	int i, cnt;
597 
598 	if (rpctls_im_a_worker && sig == SIGCHLD)
599 		return;
600 	LIST_FOREACH(slp, &rpctls_ssllist, next)
601 		shutdown(slp->s, SHUT_RD);
602 	SSL_CTX_free(rpctls_ctx);
603 	EVP_cleanup();
604 
605 	if (rpctls_im_a_worker)
606 		exit(0);
607 
608 	/* I'm the server, so terminate the workers. */
609 	cnt = 0;
610 	for (i = 0; i < rpctls_procs - 1; i++) {
611 		if (rpctls_workers[i] != -1) {
612 			cnt++;
613 			kill(rpctls_workers[i], SIGTERM);
614 		}
615 	}
616 
617 	/*
618 	 * Wait for them to die.
619 	 */
620 	for (i = 0; i < cnt; i++)
621 		wait3(NULL, 0, NULL);
622 
623 	rpctls_syscall(RPCTLS_SYSC_SRVSHUTDOWN, "");
624 	pidfile_remove(rpctls_pfh);
625 
626 	exit(0);
627 }
628 
629 /* Allow the handshake to proceed. */
630 static int
631 rpctls_verify_callback(__unused int preverify_ok,
632     __unused X509_STORE_CTX *x509_ctx)
633 {
634 
635 	return (1);
636 }
637 
638 static SSL_CTX *
639 rpctls_setup_ssl(const char *certdir)
640 {
641 	SSL_CTX *ctx;
642 	char path[PATH_MAX];
643 	size_t len, rlen;
644 	int ret;
645 
646 	SSL_library_init();
647 	SSL_load_error_strings();
648 	OpenSSL_add_all_algorithms();
649 
650 	ctx = SSL_CTX_new(TLS_server_method());
651 	if (ctx == NULL) {
652 		rpctls_verbose_out("rpctls_setup_ssl: SSL_CTX_new failed\n");
653 		return (NULL);
654 	}
655 	SSL_CTX_set_ecdh_auto(ctx, 1);
656 
657 	if (rpctls_ciphers != NULL) {
658 		/*
659 		 * Set available ciphers, since KERN_TLS only supports a
660 		 * few of them.  Normally, not doing this should be ok,
661 		 * since the library defaults will work.
662 		 */
663 		ret = SSL_CTX_set_ciphersuites(ctx, rpctls_ciphers);
664 		if (ret == 0) {
665 			rpctls_verbose_out("rpctls_setup_ssl: "
666 			    "SSL_CTX_set_ciphersuites failed: %s\n",
667 			    rpctls_ciphers);
668 			SSL_CTX_free(ctx);
669 			return (NULL);
670 		}
671 	}
672 
673 	ret = SSL_CTX_set_min_proto_version(ctx, rpctls_mintls);
674 	if (ret == 0) {
675 		rpctls_verbose_out("rpctls_setup_ssl: "
676 		    "SSL_CTX_set_min_proto_version failed\n");
677 		SSL_CTX_free(ctx);
678 		return (NULL);
679 	}
680 	ret = SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
681 	if (ret == 0) {
682 		rpctls_verbose_out("rpctls_setup_ssl: "
683 		    "SSL_CTX_set_max_proto_version failed\n");
684 		SSL_CTX_free(ctx);
685 		return (NULL);
686 	}
687 
688 	/* Get the cert.pem and certkey.pem files from the directory certdir. */
689 	len = strlcpy(path, certdir, sizeof(path));
690 	rlen = sizeof(path) - len;
691 	if (strlcpy(&path[len], "cert.pem", rlen) != 8) {
692 		SSL_CTX_free(ctx);
693 		return (NULL);
694 	}
695 	ret = SSL_CTX_use_certificate_file(ctx, path, SSL_FILETYPE_PEM);
696 	if (ret != 1) {
697 		rpctls_verbose_out("rpctls_setup_ssl: can't use certificate "
698 		    "file path=%s ret=%d\n", path, ret);
699 		SSL_CTX_free(ctx);
700 		return (NULL);
701 	}
702 	if (strlcpy(&path[len], "certkey.pem", rlen) != 11) {
703 		SSL_CTX_free(ctx);
704 		return (NULL);
705 	}
706 	ret = SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM);
707 	if (ret != 1) {
708 		rpctls_verbose_out("rpctls_setup_ssl: Can't use private "
709 		    "key path=%s ret=%d\n", path, ret);
710 		SSL_CTX_free(ctx);
711 		return (NULL);
712 	}
713 
714 	/* Set Mutual authentication, as required. */
715 	if (rpctls_do_mutual) {
716 		if (rpctls_verify_cafile != NULL ||
717 		    rpctls_verify_capath != NULL) {
718 			if (rpctls_crlfile != NULL) {
719 				ret = rpctls_loadcrlfile(ctx);
720 				if (ret == 0) {
721 					rpctls_verbose_out("rpctls_setup_ssl:"
722 					    " Load CRLfile failed\n");
723 					SSL_CTX_free(ctx);
724 					return (NULL);
725 				}
726 			}
727 #if OPENSSL_VERSION_NUMBER >= 0x30000000
728 			ret = 1;
729 			if (rpctls_verify_cafile != NULL)
730 				ret = SSL_CTX_load_verify_file(ctx,
731 				    rpctls_verify_cafile);
732 			if (ret != 0 && rpctls_verify_capath != NULL)
733 				ret = SSL_CTX_load_verify_dir(ctx,
734 				    rpctls_verify_capath);
735 #else
736 			ret = SSL_CTX_load_verify_locations(ctx,
737 			    rpctls_verify_cafile, rpctls_verify_capath);
738 #endif
739 			if (ret == 0) {
740 				rpctls_verbose_out("rpctls_setup_ssl: "
741 				    "Can't load verify locations\n");
742 				SSL_CTX_free(ctx);
743 				return (NULL);
744 			}
745 			if (rpctls_verify_cafile != NULL)
746 				SSL_CTX_set_client_CA_list(ctx,
747 				    SSL_load_client_CA_file(
748 			    rpctls_verify_cafile));
749 		}
750 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
751 		    rpctls_verify_callback);
752 	}
753 #ifdef SSL_OP_ENABLE_KTLS
754 	SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
755 #endif
756 #ifdef SSL_MODE_NO_KTLS_TX
757 	SSL_CTX_clear_mode(ctx, SSL_MODE_NO_KTLS_TX | SSL_MODE_NO_KTLS_RX);
758 #endif
759 	return (ctx);
760 }
761 
762 static SSL *
763 rpctls_server(SSL_CTX *ctx, int s, uint32_t *flags, uint32_t *uidp,
764     int *ngrps, uint32_t *gidp, X509 **certp)
765 {
766 	SSL *ssl;
767 	X509 *cert;
768 	struct sockaddr *sad;
769 	struct sockaddr_storage ad;
770 	char hostnam[NI_MAXHOST];
771 	int gethostret, ret;
772 	char *cp, *cp2;
773 	long verfret;
774 
775 	*flags = 0;
776 	*certp = NULL;
777 	sad = (struct sockaddr *)&ad;
778 	ssl = SSL_new(ctx);
779 	if (ssl == NULL) {
780 		rpctls_verbose_out("rpctls_server: SSL_new failed\n");
781 		return (NULL);
782 	}
783 	if (SSL_set_fd(ssl, s) != 1) {
784 		rpctls_verbose_out("rpctls_server: SSL_set_fd failed\n");
785 		SSL_free(ssl);
786 		return (NULL);
787 	}
788 	ret = SSL_accept(ssl);
789 	if (ret != 1) {
790 		rpctls_verbose_out("rpctls_server: SSL_accept "
791 		    "failed ret=%d\n", ret);
792 		SSL_free(ssl);
793 		return (NULL);
794 	}
795 	*flags |= RPCTLS_FLAGS_HANDSHAKE;
796 	if (rpctls_verbose) {
797 		gethostret = rpctls_gethost(s, sad, hostnam, sizeof(hostnam));
798 		if (gethostret == 0)
799 			hostnam[0] = '\0';
800 		rpctls_verbose_out("rpctls_server: SSL handshake ok for host %s"
801 		    " <%s %s>\n", hostnam, SSL_get_version(ssl),
802 		    SSL_get_cipher(ssl));
803 	}
804 	if (rpctls_do_mutual) {
805 		cert = SSL_get_peer_certificate(ssl);
806 		if (cert != NULL) {
807 			if (!rpctls_verbose) {
808 				gethostret = rpctls_gethost(s, sad, hostnam,
809 				    sizeof(hostnam));
810 				if (gethostret == 0)
811 					hostnam[0] = '\0';
812 			}
813 			cp2 = X509_NAME_oneline(
814 			    X509_get_subject_name(cert), NULL, 0);
815 			*flags |= RPCTLS_FLAGS_GOTCERT;
816 			verfret = SSL_get_verify_result(ssl);
817 			if (verfret != X509_V_OK) {
818 				cp = X509_NAME_oneline(
819 				    X509_get_issuer_name(cert), NULL, 0);
820 				if (rpctls_debug_level == 0)
821 					syslog(LOG_INFO | LOG_DAEMON,
822 					    "rpctls_server: client IP %s "
823 					    "issuerName=%s subjectName=%s"
824 					    " verify failed %s\n", hostnam,
825 					    cp, cp2,
826 					    X509_verify_cert_error_string(
827 					    verfret));
828 				else
829 					fprintf(stderr,
830 					    "rpctls_server: client IP %s "
831 					    "issuerName=%s subjectName=%s"
832 					    " verify failed %s\n", hostnam,
833 					    cp, cp2,
834 					    X509_verify_cert_error_string(
835 					    verfret));
836 			}
837 			if (verfret ==
838 			    X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
839 			    verfret == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN)
840 				*flags |= RPCTLS_FLAGS_SELFSIGNED;
841 			else if (verfret == X509_V_OK) {
842 				if (rpctls_comparehost) {
843 					ret = 0;
844 					if (gethostret != 0)
845 						ret = rpctls_checkhost(sad,
846 						    cert, rpctls_wildcard);
847 					if (ret != 1) {
848 						*flags |=
849 						    RPCTLS_FLAGS_DISABLED;
850 						rpctls_verbose_out(
851 						    "rpctls_server: "
852 						    "checkhost "
853 						    "failed\n");
854 					}
855 				}
856 				if (rpctls_cnuser) {
857 					ret = rpctls_cnname(cert, uidp,
858 					    ngrps, gidp);
859 					if (ret != 0)
860 						*flags |= RPCTLS_FLAGS_CERTUSER;
861 				}
862 				*flags |= RPCTLS_FLAGS_VERIFIED;
863 				*certp = cert;
864 				cert = NULL;
865 			}
866 			if (cert != NULL)
867 				X509_free(cert);
868 		} else
869 			rpctls_verbose_out("rpctls_server: "
870 			    "No peer certificate\n");
871 	}
872 
873 	/* Check to see that ktls is working for the connection. */
874 	ret = BIO_get_ktls_send(SSL_get_wbio(ssl));
875 	rpctls_verbose_out("rpctls_server: BIO_get_ktls_send=%d\n", ret);
876 	if (ret != 0) {
877 		ret = BIO_get_ktls_recv(SSL_get_rbio(ssl));
878 		rpctls_verbose_out("rpctls_server: BIO_get_ktls_recv=%d\n",
879 		    ret);
880 	}
881 	if (ret == 0) {
882 		if (rpctls_debug_level == 0)
883 			syslog(LOG_ERR, "ktls not working");
884 		else
885 			fprintf(stderr, "ktls not working\n");
886 		/*
887 		 * The handshake has completed, so all that can be
888 		 * done is disable the connection.
889 		 */
890 		*flags |= RPCTLS_FLAGS_DISABLED;
891 	}
892 
893 	return (ssl);
894 }
895 
896 /*
897  * Acquire the dnsname for this server.
898  */
899 static char *
900 rpctls_getdnsname(char *hostname)
901 {
902 	char *cp, *dnsname;
903 	struct addrinfo *aip, hints;
904 	int error;
905 
906 	dnsname = NULL;
907 	if (gethostname(hostname, MAXHOSTNAMELEN) == 0) {
908 		if ((cp = strchr(hostname, '.')) != NULL &&
909 		    *(cp + 1) != '\0') {
910 			*cp = '@';
911 			dnsname = cp;
912 		} else {
913 			memset((void *)&hints, 0, sizeof (hints));
914 			hints.ai_flags = AI_CANONNAME;
915 			error = getaddrinfo(hostname, NULL, &hints, &aip);
916 			if (error == 0) {
917 				if (aip->ai_canonname != NULL &&
918 				    (cp = strchr(aip->ai_canonname, '.')) !=
919 				    NULL && *(cp + 1) != '\0') {
920 					hostname[0] = '@';
921 					strlcpy(&hostname[1], cp + 1,
922 					    MAXHOSTNAMELEN + 1);
923 					dnsname = hostname;
924 				}
925 				freeaddrinfo(aip);
926 			}
927 		}
928 	}
929 	return (dnsname);
930 }
931 
932 /*
933  * Check for an otherName component of subjectAltName where the OID
934  * matches and the "domain" matches that of this server.
935  * If found, map "user" to a <uid, gidlist> for it.
936  */
937 static int
938 rpctls_cnname(X509 *cert, uint32_t *uidp, int *ngrps, uint32_t *gidp)
939 {
940 	char *cp, usern[1024 + 1];
941 	struct passwd *pwd;
942 	gid_t gids[NGROUPS];
943 	int i, j;
944 	GENERAL_NAMES *genlist;
945 	GENERAL_NAME *genname;
946 	OTHERNAME *val;
947 	size_t slen;
948 
949 	/* First, find the otherName in the subjectAltName. */
950 	genlist = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
951 	if (genlist == NULL)
952 		return (0);
953 	cp = NULL;
954 	for (i = 0; i < sk_GENERAL_NAME_num(genlist); i++) {
955 		genname = sk_GENERAL_NAME_value(genlist, i);
956 		if (genname->type != GEN_OTHERNAME)
957 			continue;
958 		val = genname->d.otherName;
959 
960 		/* Check to see that it is the correct OID. */
961 		slen = i2t_ASN1_OBJECT(usern, sizeof(usern), val->type_id);
962 		if (slen != strlen(rpctls_cnuseroid) || memcmp(usern,
963 		    rpctls_cnuseroid, slen) != 0)
964 			continue;
965 
966 		/* Sanity check the otherName. */
967 		if (val->value->type != V_ASN1_UTF8STRING ||
968 		    val->value->value.utf8string->length < 3 ||
969 		    (size_t)val->value->value.utf8string->length > sizeof(usern)
970 		    - 1) {
971 			rpctls_verbose_out("rpctls_cnname: invalid cnuser "
972 			    "type=%d\n", val->value->type);
973 			continue;
974 		}
975 
976 		/* Look for a "user" in the otherName */
977 		memcpy(usern, val->value->value.utf8string->data,
978 		    val->value->value.utf8string->length);
979 		usern[val->value->value.utf8string->length] = '\0';
980 
981 		/* Now, look for the @dnsname suffix in the commonName. */
982 		cp = strcasestr(usern, rpctls_dnsname);
983 		if (cp == NULL)
984 			continue;
985 		if (*(cp + strlen(rpctls_dnsname)) != '\0') {
986 			cp = NULL;
987 			continue;
988 		}
989 		*cp = '\0';
990 		break;
991 	}
992 	if (cp == NULL)
993 		return (0);
994 
995 	/* See if the "user" is in the passwd database. */
996 	pwd = getpwnam(usern);
997 	if (pwd == NULL)
998 		return (0);
999 	*uidp = pwd->pw_uid;
1000 	*ngrps = NGROUPS;
1001 	if (getgrouplist(pwd->pw_name, pwd->pw_gid, gids, ngrps) < 0)
1002 		return (0);
1003 	rpctls_verbose_out("mapped user=%s ngrps=%d uid=%d\n", pwd->pw_name,
1004 	    *ngrps, pwd->pw_uid);
1005 	for (j = 0; j < *ngrps; j++)
1006 		gidp[j] = gids[j];
1007 	return (1);
1008 }
1009 
1010 static void
1011 rpctls_huphandler(int sig __unused)
1012 {
1013 
1014 	rpctls_gothup = true;
1015 }
1016