1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 	if (rpctls_syscall(RPCTLS_SYSC_SRVSETPATH, rpctls_sockname[mypos]) < 0){
406 		if (rpctls_debug_level == 0) {
407 			syslog(LOG_ERR,
408 			    "Can't set upcall socket path=%s errno=%d",
409 			    rpctls_sockname[mypos], errno);
410 			exit(1);
411 		}
412 		err(1, "Can't set upcall socket path=%s",
413 		    rpctls_sockname[mypos]);
414 	}
415 
416 	rpctls_svc_run();
417 
418 	SSL_CTX_free(rpctls_ctx);
419 	return (0);
420 }
421 
422 bool_t
423 rpctlssd_null_1_svc(__unused void *argp, __unused void *result,
424     __unused struct svc_req *rqstp)
425 {
426 
427 	rpctls_verbose_out("rpctlssd_null_svc: done\n");
428 	return (TRUE);
429 }
430 
431 bool_t
432 rpctlssd_connect_1_svc(__unused void *argp,
433     struct rpctlssd_connect_res *result, __unused struct svc_req *rqstp)
434 {
435 	int ngrps, s;
436 	SSL *ssl;
437 	uint32_t flags;
438 	struct ssl_entry *newslp;
439 	uint32_t uid;
440 	uint32_t *gidp;
441 	X509 *cert;
442 
443 	rpctls_verbose_out("rpctlsd_connect_svc: started\n");
444 	memset(result, 0, sizeof(*result));
445 	/* Get the socket fd from the kernel. */
446 	s = rpctls_syscall(RPCTLS_SYSC_SRVSOCKET, "");
447 	if (s < 0)
448 		return (FALSE);
449 
450 	/* Do the server side of a TLS handshake. */
451 	gidp = calloc(NGROUPS, sizeof(*gidp));
452 	ssl = rpctls_server(rpctls_ctx, s, &flags, &uid, &ngrps, gidp, &cert);
453 	if (ssl == NULL) {
454 		free(gidp);
455 		rpctls_verbose_out("rpctlssd_connect_svc: ssl "
456 		    "accept failed\n");
457 		/*
458 		 * For RPC-over-TLS, this upcall is expected
459 		 * to close off the socket upon handshake failure.
460 		 */
461 		close(s);
462 		return (FALSE);
463 	} else {
464 		rpctls_verbose_out("rpctlssd_connect_svc: "
465 		    "succeeded flags=0x%x\n", flags);
466 		result->flags = flags;
467 		result->sec = rpctls_ssl_sec;
468 		result->usec = rpctls_ssl_usec;
469 		result->ssl = ++rpctls_ssl_refno;
470 		/* Hard to believe this could ever wrap around.. */
471 		if (rpctls_ssl_refno == 0)
472 			result->ssl = ++rpctls_ssl_refno;
473 		if ((flags & RPCTLS_FLAGS_CERTUSER) != 0) {
474 			result->uid = uid;
475 			result->gid.gid_len = ngrps;
476 			result->gid.gid_val = gidp;
477 		} else {
478 			result->uid = 0;
479 			result->gid.gid_len = 0;
480 			result->gid.gid_val = gidp;
481 		}
482 	}
483 
484 	/* Maintain list of all current SSL *'s */
485 	newslp = malloc(sizeof(*newslp));
486 	newslp->ssl = ssl;
487 	newslp->s = s;
488 	newslp->shutoff = false;
489 	newslp->refno = rpctls_ssl_refno;
490 	newslp->cert = cert;
491 	LIST_INSERT_HEAD(&rpctls_ssllist, newslp, next);
492 	return (TRUE);
493 }
494 
495 bool_t
496 rpctlssd_handlerecord_1_svc(struct rpctlssd_handlerecord_arg *argp,
497     struct rpctlssd_handlerecord_res *result, __unused struct svc_req *rqstp)
498 {
499 	struct ssl_entry *slp;
500 	int ret;
501 	char junk;
502 
503 	slp = NULL;
504 	if (argp->sec == rpctls_ssl_sec && argp->usec ==
505 	    rpctls_ssl_usec) {
506 		LIST_FOREACH(slp, &rpctls_ssllist, next) {
507 			if (slp->refno == argp->ssl)
508 				break;
509 		}
510 	}
511 
512 	if (slp != NULL) {
513 		rpctls_verbose_out("rpctlssd_handlerecord fd=%d\n",
514 		    slp->s);
515 		/*
516 		 * An SSL_read() of 0 bytes should fail, but it should
517 		 * handle the non-application data record before doing so.
518 		 */
519 		ret = SSL_read(slp->ssl, &junk, 0);
520 		if (ret <= 0) {
521 			/* Check to see if this was a close alert. */
522 			ret = SSL_get_shutdown(slp->ssl);
523 			if ((ret & (SSL_SENT_SHUTDOWN |
524 			    SSL_RECEIVED_SHUTDOWN)) == SSL_RECEIVED_SHUTDOWN)
525 				SSL_shutdown(slp->ssl);
526 		} else {
527 			if (rpctls_debug_level == 0)
528 				syslog(LOG_ERR, "SSL_read returned %d", ret);
529 			else
530 				fprintf(stderr, "SSL_read returned %d\n", ret);
531 		}
532 		result->reterr = RPCTLSERR_OK;
533 	} else
534 		result->reterr = RPCTLSERR_NOSSL;
535 	return (TRUE);
536 }
537 
538 bool_t
539 rpctlssd_disconnect_1_svc(struct rpctlssd_disconnect_arg *argp,
540     struct rpctlssd_disconnect_res *result, __unused struct svc_req *rqstp)
541 {
542 	struct ssl_entry *slp;
543 	int ret;
544 
545 	slp = NULL;
546 	if (argp->sec == rpctls_ssl_sec && argp->usec ==
547 	    rpctls_ssl_usec) {
548 		LIST_FOREACH(slp, &rpctls_ssllist, next) {
549 			if (slp->refno == argp->ssl)
550 				break;
551 		}
552 	}
553 
554 	if (slp != NULL) {
555 		rpctls_verbose_out("rpctlssd_disconnect fd=%d closed\n",
556 		    slp->s);
557 		LIST_REMOVE(slp, next);
558 		if (!slp->shutoff) {
559 			ret = SSL_get_shutdown(slp->ssl);
560 			/*
561 			 * Do an SSL_shutdown() unless a close alert has
562 			 * already been sent.
563 			 */
564 			if ((ret & SSL_SENT_SHUTDOWN) == 0)
565 				SSL_shutdown(slp->ssl);
566 		}
567 		SSL_free(slp->ssl);
568 		if (slp->cert != NULL)
569 			X509_free(slp->cert);
570 		/*
571 		 * For RPC-over-TLS, this upcall is expected
572 		 * to close off the socket.
573 		 */
574 		if (!slp->shutoff)
575 			shutdown(slp->s, SHUT_WR);
576 		close(slp->s);
577 		free(slp);
578 		result->reterr = RPCTLSERR_OK;
579 	} else
580 		result->reterr = RPCTLSERR_NOCLOSE;
581 	return (TRUE);
582 }
583 
584 int
585 rpctlssd_1_freeresult(__unused SVCXPRT *transp, xdrproc_t xdr_result,
586     caddr_t result)
587 {
588 	rpctlssd_connect_res *res;
589 
590 	if (xdr_result == (xdrproc_t)xdr_rpctlssd_connect_res) {
591 		res = (rpctlssd_connect_res *)(void *)result;
592 		free(res->gid.gid_val);
593 	}
594 	return (TRUE);
595 }
596 
597 /*
598  * cleanup_term() called via SIGTERM (or SIGCHLD if a child dies).
599  */
600 static void
601 rpctls_cleanup_term(int sig)
602 {
603 	struct ssl_entry *slp;
604 	int i, cnt;
605 
606 	if (rpctls_im_a_worker && sig == SIGCHLD)
607 		return;
608 	LIST_FOREACH(slp, &rpctls_ssllist, next)
609 		shutdown(slp->s, SHUT_RD);
610 	SSL_CTX_free(rpctls_ctx);
611 	EVP_cleanup();
612 
613 	if (rpctls_im_a_worker)
614 		exit(0);
615 
616 	/* I'm the server, so terminate the workers. */
617 	cnt = 0;
618 	for (i = 0; i < rpctls_procs - 1; i++) {
619 		if (rpctls_workers[i] != -1) {
620 			cnt++;
621 			kill(rpctls_workers[i], SIGTERM);
622 		}
623 	}
624 
625 	/*
626 	 * Wait for them to die.
627 	 */
628 	for (i = 0; i < cnt; i++)
629 		wait3(NULL, 0, NULL);
630 
631 	rpctls_syscall(RPCTLS_SYSC_SRVSHUTDOWN, "");
632 	pidfile_remove(rpctls_pfh);
633 
634 	exit(0);
635 }
636 
637 /* Allow the handshake to proceed. */
638 static int
639 rpctls_verify_callback(__unused int preverify_ok,
640     __unused X509_STORE_CTX *x509_ctx)
641 {
642 
643 	return (1);
644 }
645 
646 static SSL_CTX *
647 rpctls_setup_ssl(const char *certdir)
648 {
649 	SSL_CTX *ctx;
650 	char path[PATH_MAX];
651 	size_t len, rlen;
652 	int ret;
653 
654 	ctx = SSL_CTX_new(TLS_server_method());
655 	if (ctx == NULL) {
656 		rpctls_verbose_out("rpctls_setup_ssl: SSL_CTX_new failed\n");
657 		return (NULL);
658 	}
659 
660 	if (rpctls_ciphers != NULL) {
661 		/*
662 		 * Set available ciphers, since KERN_TLS only supports a
663 		 * few of them.  Normally, not doing this should be ok,
664 		 * since the library defaults will work.
665 		 */
666 		ret = SSL_CTX_set_ciphersuites(ctx, rpctls_ciphers);
667 		if (ret == 0) {
668 			rpctls_verbose_out("rpctls_setup_ssl: "
669 			    "SSL_CTX_set_ciphersuites failed: %s\n",
670 			    rpctls_ciphers);
671 			SSL_CTX_free(ctx);
672 			return (NULL);
673 		}
674 	}
675 
676 	ret = SSL_CTX_set_min_proto_version(ctx, rpctls_mintls);
677 	if (ret == 0) {
678 		rpctls_verbose_out("rpctls_setup_ssl: "
679 		    "SSL_CTX_set_min_proto_version failed\n");
680 		SSL_CTX_free(ctx);
681 		return (NULL);
682 	}
683 	ret = SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
684 	if (ret == 0) {
685 		rpctls_verbose_out("rpctls_setup_ssl: "
686 		    "SSL_CTX_set_max_proto_version failed\n");
687 		SSL_CTX_free(ctx);
688 		return (NULL);
689 	}
690 
691 	/* Get the cert.pem and certkey.pem files from the directory certdir. */
692 	len = strlcpy(path, certdir, sizeof(path));
693 	rlen = sizeof(path) - len;
694 	if (strlcpy(&path[len], "cert.pem", rlen) != 8) {
695 		SSL_CTX_free(ctx);
696 		return (NULL);
697 	}
698 	ret = SSL_CTX_use_certificate_file(ctx, path, SSL_FILETYPE_PEM);
699 	if (ret != 1) {
700 		rpctls_verbose_out("rpctls_setup_ssl: can't use certificate "
701 		    "file path=%s ret=%d\n", path, ret);
702 		SSL_CTX_free(ctx);
703 		return (NULL);
704 	}
705 	if (strlcpy(&path[len], "certkey.pem", rlen) != 11) {
706 		SSL_CTX_free(ctx);
707 		return (NULL);
708 	}
709 	ret = SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM);
710 	if (ret != 1) {
711 		rpctls_verbose_out("rpctls_setup_ssl: Can't use private "
712 		    "key path=%s ret=%d\n", path, ret);
713 		SSL_CTX_free(ctx);
714 		return (NULL);
715 	}
716 
717 	/* Set Mutual authentication, as required. */
718 	if (rpctls_do_mutual) {
719 		if (rpctls_verify_cafile != NULL ||
720 		    rpctls_verify_capath != NULL) {
721 			if (rpctls_crlfile != NULL) {
722 				ret = rpctls_loadcrlfile(ctx);
723 				if (ret == 0) {
724 					rpctls_verbose_out("rpctls_setup_ssl:"
725 					    " Load CRLfile failed\n");
726 					SSL_CTX_free(ctx);
727 					return (NULL);
728 				}
729 			}
730 #if OPENSSL_VERSION_NUMBER >= 0x30000000
731 			ret = 1;
732 			if (rpctls_verify_cafile != NULL)
733 				ret = SSL_CTX_load_verify_file(ctx,
734 				    rpctls_verify_cafile);
735 			if (ret != 0 && rpctls_verify_capath != NULL)
736 				ret = SSL_CTX_load_verify_dir(ctx,
737 				    rpctls_verify_capath);
738 #else
739 			ret = SSL_CTX_load_verify_locations(ctx,
740 			    rpctls_verify_cafile, rpctls_verify_capath);
741 #endif
742 			if (ret == 0) {
743 				rpctls_verbose_out("rpctls_setup_ssl: "
744 				    "Can't load verify locations\n");
745 				SSL_CTX_free(ctx);
746 				return (NULL);
747 			}
748 			if (rpctls_verify_cafile != NULL)
749 				SSL_CTX_set_client_CA_list(ctx,
750 				    SSL_load_client_CA_file(
751 			    rpctls_verify_cafile));
752 		}
753 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
754 		    rpctls_verify_callback);
755 	}
756 #ifdef SSL_OP_ENABLE_KTLS
757 	SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
758 #endif
759 #ifdef SSL_MODE_NO_KTLS_TX
760 	SSL_CTX_clear_mode(ctx, SSL_MODE_NO_KTLS_TX | SSL_MODE_NO_KTLS_RX);
761 #endif
762 	return (ctx);
763 }
764 
765 static SSL *
766 rpctls_server(SSL_CTX *ctx, int s, uint32_t *flags, uint32_t *uidp,
767     int *ngrps, uint32_t *gidp, X509 **certp)
768 {
769 	SSL *ssl;
770 	X509 *cert;
771 	struct sockaddr *sad;
772 	struct sockaddr_storage ad;
773 	char hostnam[NI_MAXHOST];
774 	int gethostret, ret;
775 	char *cp, *cp2;
776 	long verfret;
777 
778 	*flags = 0;
779 	*certp = NULL;
780 	sad = (struct sockaddr *)&ad;
781 	ssl = SSL_new(ctx);
782 	if (ssl == NULL) {
783 		rpctls_verbose_out("rpctls_server: SSL_new failed\n");
784 		return (NULL);
785 	}
786 	if (SSL_set_fd(ssl, s) != 1) {
787 		rpctls_verbose_out("rpctls_server: SSL_set_fd failed\n");
788 		SSL_free(ssl);
789 		return (NULL);
790 	}
791 	ret = SSL_accept(ssl);
792 	if (ret != 1) {
793 		rpctls_verbose_out("rpctls_server: SSL_accept "
794 		    "failed ret=%d\n", ret);
795 		SSL_free(ssl);
796 		return (NULL);
797 	}
798 	*flags |= RPCTLS_FLAGS_HANDSHAKE;
799 	if (rpctls_verbose) {
800 		gethostret = rpctls_gethost(s, sad, hostnam, sizeof(hostnam));
801 		if (gethostret == 0)
802 			hostnam[0] = '\0';
803 		rpctls_verbose_out("rpctls_server: SSL handshake ok for host %s"
804 		    " <%s %s>\n", hostnam, SSL_get_version(ssl),
805 		    SSL_get_cipher(ssl));
806 	}
807 	if (rpctls_do_mutual) {
808 #if OPENSSL_VERSION_NUMBER >= 0x30000000
809 		cert = SSL_get1_peer_certificate(ssl);
810 #else
811 		cert = SSL_get_peer_certificate(ssl);
812 #endif
813 		if (cert != NULL) {
814 			if (!rpctls_verbose) {
815 				gethostret = rpctls_gethost(s, sad, hostnam,
816 				    sizeof(hostnam));
817 				if (gethostret == 0)
818 					hostnam[0] = '\0';
819 			}
820 			cp2 = X509_NAME_oneline(
821 			    X509_get_subject_name(cert), NULL, 0);
822 			*flags |= RPCTLS_FLAGS_GOTCERT;
823 			verfret = SSL_get_verify_result(ssl);
824 			if (verfret != X509_V_OK) {
825 				cp = X509_NAME_oneline(
826 				    X509_get_issuer_name(cert), NULL, 0);
827 				if (rpctls_debug_level == 0)
828 					syslog(LOG_INFO | LOG_DAEMON,
829 					    "rpctls_server: client IP %s "
830 					    "issuerName=%s subjectName=%s"
831 					    " verify failed %s\n", hostnam,
832 					    cp, cp2,
833 					    X509_verify_cert_error_string(
834 					    verfret));
835 				else
836 					fprintf(stderr,
837 					    "rpctls_server: client IP %s "
838 					    "issuerName=%s subjectName=%s"
839 					    " verify failed %s\n", hostnam,
840 					    cp, cp2,
841 					    X509_verify_cert_error_string(
842 					    verfret));
843 			}
844 			if (verfret ==
845 			    X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
846 			    verfret == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN)
847 				*flags |= RPCTLS_FLAGS_SELFSIGNED;
848 			else if (verfret == X509_V_OK) {
849 				if (rpctls_comparehost) {
850 					ret = 0;
851 					if (gethostret != 0)
852 						ret = rpctls_checkhost(sad,
853 						    cert, rpctls_wildcard);
854 					if (ret != 1) {
855 						*flags |=
856 						    RPCTLS_FLAGS_DISABLED;
857 						rpctls_verbose_out(
858 						    "rpctls_server: "
859 						    "checkhost "
860 						    "failed\n");
861 					}
862 				}
863 				if (rpctls_cnuser) {
864 					ret = rpctls_cnname(cert, uidp,
865 					    ngrps, gidp);
866 					if (ret != 0)
867 						*flags |= RPCTLS_FLAGS_CERTUSER;
868 				}
869 				*flags |= RPCTLS_FLAGS_VERIFIED;
870 				*certp = cert;
871 				cert = NULL;
872 			}
873 			if (cert != NULL)
874 				X509_free(cert);
875 		} else
876 			rpctls_verbose_out("rpctls_server: "
877 			    "No peer certificate\n");
878 	}
879 
880 	/* Check to see that ktls is working for the connection. */
881 	ret = BIO_get_ktls_send(SSL_get_wbio(ssl));
882 	rpctls_verbose_out("rpctls_server: BIO_get_ktls_send=%d\n", ret);
883 	if (ret != 0) {
884 		ret = BIO_get_ktls_recv(SSL_get_rbio(ssl));
885 		rpctls_verbose_out("rpctls_server: BIO_get_ktls_recv=%d\n",
886 		    ret);
887 	}
888 	if (ret == 0) {
889 		if (rpctls_debug_level == 0)
890 			syslog(LOG_ERR, "ktls not working");
891 		else
892 			fprintf(stderr, "ktls not working\n");
893 		/*
894 		 * The handshake has completed, so all that can be
895 		 * done is disable the connection.
896 		 */
897 		*flags |= RPCTLS_FLAGS_DISABLED;
898 	}
899 
900 	return (ssl);
901 }
902 
903 /*
904  * Acquire the dnsname for this server.
905  */
906 static char *
907 rpctls_getdnsname(char *hostname)
908 {
909 	char *cp, *dnsname;
910 	struct addrinfo *aip, hints;
911 	int error;
912 
913 	dnsname = NULL;
914 	if (gethostname(hostname, MAXHOSTNAMELEN) == 0) {
915 		if ((cp = strchr(hostname, '.')) != NULL &&
916 		    *(cp + 1) != '\0') {
917 			*cp = '@';
918 			dnsname = cp;
919 		} else {
920 			memset((void *)&hints, 0, sizeof (hints));
921 			hints.ai_flags = AI_CANONNAME;
922 			error = getaddrinfo(hostname, NULL, &hints, &aip);
923 			if (error == 0) {
924 				if (aip->ai_canonname != NULL &&
925 				    (cp = strchr(aip->ai_canonname, '.')) !=
926 				    NULL && *(cp + 1) != '\0') {
927 					hostname[0] = '@';
928 					strlcpy(&hostname[1], cp + 1,
929 					    MAXHOSTNAMELEN + 1);
930 					dnsname = hostname;
931 				}
932 				freeaddrinfo(aip);
933 			}
934 		}
935 	}
936 	return (dnsname);
937 }
938 
939 /*
940  * Check for an otherName component of subjectAltName where the OID
941  * matches and the "domain" matches that of this server.
942  * If found, map "user" to a <uid, gidlist> for it.
943  */
944 static int
945 rpctls_cnname(X509 *cert, uint32_t *uidp, int *ngrps, uint32_t *gidp)
946 {
947 	char *cp, usern[1024 + 1];
948 	struct passwd *pwd;
949 	gid_t gids[NGROUPS];
950 	int i, j;
951 	GENERAL_NAMES *genlist;
952 	GENERAL_NAME *genname;
953 	OTHERNAME *val;
954 	size_t slen;
955 
956 	/* First, find the otherName in the subjectAltName. */
957 	genlist = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
958 	if (genlist == NULL)
959 		return (0);
960 	cp = NULL;
961 	for (i = 0; i < sk_GENERAL_NAME_num(genlist); i++) {
962 		genname = sk_GENERAL_NAME_value(genlist, i);
963 		if (genname->type != GEN_OTHERNAME)
964 			continue;
965 		val = genname->d.otherName;
966 
967 		/* Check to see that it is the correct OID. */
968 		slen = i2t_ASN1_OBJECT(usern, sizeof(usern), val->type_id);
969 		if (slen != strlen(rpctls_cnuseroid) || memcmp(usern,
970 		    rpctls_cnuseroid, slen) != 0)
971 			continue;
972 
973 		/* Sanity check the otherName. */
974 		if (val->value->type != V_ASN1_UTF8STRING ||
975 		    val->value->value.utf8string->length < 3 ||
976 		    (size_t)val->value->value.utf8string->length > sizeof(usern)
977 		    - 1) {
978 			rpctls_verbose_out("rpctls_cnname: invalid cnuser "
979 			    "type=%d\n", val->value->type);
980 			continue;
981 		}
982 
983 		/* Look for a "user" in the otherName */
984 		memcpy(usern, val->value->value.utf8string->data,
985 		    val->value->value.utf8string->length);
986 		usern[val->value->value.utf8string->length] = '\0';
987 
988 		/* Now, look for the @dnsname suffix in the commonName. */
989 		cp = strcasestr(usern, rpctls_dnsname);
990 		if (cp == NULL)
991 			continue;
992 		if (*(cp + strlen(rpctls_dnsname)) != '\0') {
993 			cp = NULL;
994 			continue;
995 		}
996 		*cp = '\0';
997 		break;
998 	}
999 	if (cp == NULL)
1000 		return (0);
1001 
1002 	/* See if the "user" is in the passwd database. */
1003 	pwd = getpwnam(usern);
1004 	if (pwd == NULL)
1005 		return (0);
1006 	*uidp = pwd->pw_uid;
1007 	*ngrps = NGROUPS;
1008 	if (getgrouplist(pwd->pw_name, pwd->pw_gid, gids, ngrps) < 0)
1009 		return (0);
1010 	rpctls_verbose_out("mapped user=%s ngrps=%d uid=%d\n", pwd->pw_name,
1011 	    *ngrps, pwd->pw_uid);
1012 	for (j = 0; j < *ngrps; j++)
1013 		gidp[j] = gids[j];
1014 	return (1);
1015 }
1016 
1017 static void
1018 rpctls_huphandler(int sig __unused)
1019 {
1020 
1021 	rpctls_gothup = true;
1022 }
1023