xref: /freebsd/usr.sbin/rpc.tlsservd/rpc.tlsservd.c (revision 690b7ea081790eef2c890f63a4fe7e195cf51df0)
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 <err.h>
48 #include <getopt.h>
49 #include <libutil.h>
50 #include <netdb.h>
51 #include <pwd.h>
52 #include <signal.h>
53 #include <stdarg.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <stdbool.h>
57 #include <string.h>
58 #include <unistd.h>
59 
60 #include <rpc/rpc.h>
61 #include <rpc/rpc_com.h>
62 #include <rpc/rpcsec_tls.h>
63 
64 #include <openssl/opensslconf.h>
65 #include <openssl/bio.h>
66 #include <openssl/ssl.h>
67 #include <openssl/err.h>
68 #include <openssl/x509v3.h>
69 
70 #include "rpctlssd.h"
71 #include "rpc.tlscommon.h"
72 
73 #ifndef _PATH_RPCTLSSDSOCK
74 #define _PATH_RPCTLSSDSOCK	"/var/run/rpc.tlsservd.sock"
75 #endif
76 #ifndef	_PATH_CERTANDKEY
77 #define	_PATH_CERTANDKEY	"/etc/rpc.tlsservd/"
78 #endif
79 #ifndef	_PATH_RPCTLSSDPID
80 #define	_PATH_RPCTLSSDPID	"/var/run/rpc.tlsservd.pid"
81 #endif
82 #ifndef	_PREFERRED_CIPHERS
83 #define	_PREFERRED_CIPHERS	"AES128-GCM-SHA256"
84 #endif
85 
86 /* Global variables also used by rpc.tlscommon.c. */
87 int			rpctls_debug_level;
88 bool			rpctls_verbose;
89 SSL_CTX			*rpctls_ctx = NULL;
90 const char		*rpctls_verify_cafile = NULL;
91 const char		*rpctls_verify_capath = NULL;
92 char			*rpctls_crlfile = NULL;
93 bool			rpctls_gothup = false;
94 struct ssl_list		rpctls_ssllist;
95 
96 static struct pidfh	*rpctls_pfh = NULL;
97 static bool		rpctls_do_mutual = false;
98 static const char	*rpctls_certdir = _PATH_CERTANDKEY;
99 static bool		rpctls_comparehost = false;
100 static unsigned int	rpctls_wildcard = X509_CHECK_FLAG_NO_WILDCARDS;
101 static uint64_t		rpctls_ssl_refno = 0;
102 static uint64_t		rpctls_ssl_sec = 0;
103 static uint64_t		rpctls_ssl_usec = 0;
104 static bool		rpctls_cnuser = false;
105 static char		*rpctls_dnsname;
106 static const char	*rpctls_cnuseroid = "1.3.6.1.4.1.2238.1.1.1";
107 
108 static void		rpctlssd_terminate(int);
109 static SSL_CTX		*rpctls_setup_ssl(const char *certdir);
110 static SSL		*rpctls_server(SSL_CTX *ctx, int s,
111 			    uint32_t *flags, uint32_t *uidp,
112 			    int *ngrps, uint32_t *gidp, X509 **certp);
113 static int		rpctls_cnname(X509 *cert, uint32_t *uidp,
114 			    int *ngrps, uint32_t *gidp);
115 static char		*rpctls_getdnsname(char *dnsname);
116 static void		rpctls_huphandler(int sig __unused);
117 
118 extern void		rpctlssd_1(struct svc_req *rqstp, SVCXPRT *transp);
119 
120 static struct option longopts[] = {
121 	{ "certdir",		required_argument,	NULL,	'D' },
122 	{ "debuglevel",		no_argument,		NULL,	'd' },
123 	{ "checkhost",		no_argument,		NULL,	'h' },
124 	{ "verifylocs",		required_argument,	NULL,	'l' },
125 	{ "mutualverf",		no_argument,		NULL,	'm' },
126 	{ "domain",		required_argument,	NULL,	'n' },
127 	{ "verifydir",		required_argument,	NULL,	'p' },
128 	{ "crl",		required_argument,	NULL,	'r' },
129 	{ "certuser",		no_argument,		NULL,	'u' },
130 	{ "verbose",		no_argument,		NULL,	'v' },
131 	{ "multiwild",		no_argument,		NULL,	'W' },
132 	{ "singlewild",		no_argument,		NULL,	'w' },
133 	{ NULL,			0,			NULL,	0  }
134 };
135 
136 int
137 main(int argc, char **argv)
138 {
139 	/*
140 	 * We provide an RPC service on a local-domain socket. The
141 	 * kernel rpctls code will upcall to this daemon to do the initial
142 	 * TLS handshake.
143 	 */
144 	struct sockaddr_un sun;
145 	int ch, fd, oldmask;
146 	SVCXPRT *xprt;
147 	struct timeval tm;
148 	struct timezone tz;
149 	char hostname[MAXHOSTNAMELEN + 2];
150 	pid_t otherpid;
151 	bool tls_enable;
152 	size_t tls_enable_len;
153 
154 	/* Check that another rpctlssd isn't already running. */
155 	rpctls_pfh = pidfile_open(_PATH_RPCTLSSDPID, 0600, &otherpid);
156 	if (rpctls_pfh == NULL) {
157 		if (errno == EEXIST)
158 			errx(1, "rpctlssd already running, pid: %d.", otherpid);
159 		warn("cannot open or create pidfile");
160 	}
161 
162 	/* Check to see that the ktls is enabled. */
163 	tls_enable_len = sizeof(tls_enable);
164 	if (sysctlbyname("kern.ipc.tls.enable", &tls_enable, &tls_enable_len,
165 	    NULL, 0) != 0 || !tls_enable)
166 		errx(1, "Kernel TLS not enabled");
167 
168 	/* Get the time when this daemon is started. */
169 	gettimeofday(&tm, &tz);
170 	rpctls_ssl_sec = tm.tv_sec;
171 	rpctls_ssl_usec = tm.tv_usec;
172 
173 	/* Set the dns name for the server. */
174 	rpctls_dnsname = rpctls_getdnsname(hostname);
175 	if (rpctls_dnsname == NULL) {
176 		strcpy(hostname, "@default.domain");
177 		rpctls_dnsname = hostname;
178 	}
179 
180 	rpctls_verbose = false;
181 	while ((ch = getopt_long(argc, argv, "D:dhl:n:mp:r:uvWw", longopts,
182 	    NULL)) != -1) {
183 		switch (ch) {
184 		case 'D':
185 			rpctls_certdir = optarg;
186 			break;
187 		case 'd':
188 			rpctls_debug_level++;
189 			break;
190 		case 'h':
191 			rpctls_comparehost = true;
192 			break;
193 		case 'l':
194 			rpctls_verify_cafile = optarg;
195 			break;
196 		case 'm':
197 			rpctls_do_mutual = true;
198 			break;
199 		case 'n':
200 			hostname[0] = '@';
201 			strlcpy(&hostname[1], optarg, MAXHOSTNAMELEN + 1);
202 			rpctls_dnsname = hostname;
203 			break;
204 		case 'p':
205 			rpctls_verify_capath = optarg;
206 			break;
207 		case 'r':
208 			rpctls_crlfile = optarg;
209 			break;
210 		case 'u':
211 			rpctls_cnuser = true;
212 			break;
213 		case 'v':
214 			rpctls_verbose = true;
215 			break;
216 		case 'W':
217 			if (rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS)
218 				errx(1, "options -w and -W are mutually "
219 				    "exclusive");
220 			rpctls_wildcard = X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS;
221 			break;
222 		case 'w':
223 			if (rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS)
224 				errx(1, "options -w and -W are mutually "
225 				    "exclusive");
226 			rpctls_wildcard = 0;
227 			break;
228 		default:
229 			fprintf(stderr, "usage: %s "
230 			    "[-D/--certdir certdir] [-d/--debuglevel] "
231 			    "[-h/--checkhost] "
232 			    "[-l/--verifylocs CAfile] [-m/--mutualverf] "
233 			    "[-n/--domain domain_name] "
234 			    "[-p/--verifydir CApath] [-r/--crl CRLfile] "
235 			    "[-u/--certuser] [-v/--verbose] [-W/--multiwild] "
236 			    "[-w/--singlewild]\n", argv[0]);
237 			exit(1);
238 		}
239 	}
240 	if (rpctls_do_mutual && rpctls_verify_cafile == NULL &&
241 	    rpctls_verify_capath == NULL)
242 		errx(1, "-m requires the -l <CAfile> and/or "
243 		    "-p <CApath> options");
244 	if (rpctls_comparehost && (!rpctls_do_mutual ||
245 	    (rpctls_verify_cafile == NULL && rpctls_verify_capath == NULL)))
246 		errx(1, "-h requires the -m plus the "
247 		    "-l <CAfile> and/or -p <CApath> options");
248 	if (!rpctls_comparehost && rpctls_wildcard !=
249 	    X509_CHECK_FLAG_NO_WILDCARDS)
250 		errx(1, "The -w or -W options require the -h option");
251 	if (rpctls_cnuser && (!rpctls_do_mutual ||
252 	    (rpctls_verify_cafile == NULL && rpctls_verify_capath == NULL)))
253 		errx(1, "-u requires the -m plus the "
254 		    "-l <CAfile> and/or -p <CApath> options");
255 
256 	if (modfind("krpc") < 0) {
257 		/* Not present in kernel, try loading it */
258 		if (kldload("krpc") < 0 || modfind("krpc") < 0)
259 			errx(1, "Kernel RPC is not available");
260 	}
261 
262 	if (rpctls_debug_level == 0) {
263 		if (daemon(0, 0) != 0)
264 			err(1, "Can't daemonize");
265 		signal(SIGINT, SIG_IGN);
266 		signal(SIGQUIT, SIG_IGN);
267 		signal(SIGHUP, SIG_IGN);
268 	}
269 	signal(SIGTERM, rpctlssd_terminate);
270 	signal(SIGPIPE, SIG_IGN);
271 	signal(SIGHUP, rpctls_huphandler);
272 
273 	pidfile_write(rpctls_pfh);
274 
275 	memset(&sun, 0, sizeof sun);
276 	sun.sun_family = AF_LOCAL;
277 	unlink(_PATH_RPCTLSSDSOCK);
278 	strcpy(sun.sun_path, _PATH_RPCTLSSDSOCK);
279 	sun.sun_len = SUN_LEN(&sun);
280 	fd = socket(AF_LOCAL, SOCK_STREAM, 0);
281 	if (fd < 0) {
282 		if (rpctls_debug_level == 0) {
283 			syslog(LOG_ERR, "Can't create local rpctlssd socket");
284 			exit(1);
285 		}
286 		err(1, "Can't create local rpctlssd socket");
287 	}
288 	oldmask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
289 	if (bind(fd, (struct sockaddr *)&sun, sun.sun_len) < 0) {
290 		if (rpctls_debug_level == 0) {
291 			syslog(LOG_ERR, "Can't bind local rpctlssd socket");
292 			exit(1);
293 		}
294 		err(1, "Can't bind local rpctlssd socket");
295 	}
296 	umask(oldmask);
297 	if (listen(fd, SOMAXCONN) < 0) {
298 		if (rpctls_debug_level == 0) {
299 			syslog(LOG_ERR,
300 			    "Can't listen on local rpctlssd socket");
301 			exit(1);
302 		}
303 		err(1, "Can't listen on local rpctlssd socket");
304 	}
305 	xprt = svc_vc_create(fd, RPC_MAXDATASIZE, RPC_MAXDATASIZE);
306 	if (!xprt) {
307 		if (rpctls_debug_level == 0) {
308 			syslog(LOG_ERR,
309 			    "Can't create transport for local rpctlssd socket");
310 			exit(1);
311 		}
312 		err(1, "Can't create transport for local rpctlssd socket");
313 	}
314 	if (!svc_reg(xprt, RPCTLSSD, RPCTLSSDVERS, rpctlssd_1, NULL)) {
315 		if (rpctls_debug_level == 0) {
316 			syslog(LOG_ERR,
317 			    "Can't register service for local rpctlssd socket");
318 			exit(1);
319 		}
320 		err(1, "Can't register service for local rpctlssd socket");
321 	}
322 
323 	rpctls_ctx = rpctls_setup_ssl(rpctls_certdir);
324 	if (rpctls_ctx == NULL) {
325 		if (rpctls_debug_level == 0) {
326 			syslog(LOG_ERR, "Can't create SSL context");
327 			exit(1);
328 		}
329 		err(1, "Can't create SSL context");
330 	}
331 	rpctls_gothup = false;
332 	LIST_INIT(&rpctls_ssllist);
333 
334 	rpctls_syscall(RPCTLS_SYSC_SRVSETPATH, _PATH_RPCTLSSDSOCK);
335 
336 	rpctls_svc_run();
337 
338 	rpctls_syscall(RPCTLS_SYSC_SRVSHUTDOWN, "");
339 
340 	SSL_CTX_free(rpctls_ctx);
341 	EVP_cleanup();
342 	return (0);
343 }
344 
345 bool_t
346 rpctlssd_null_1_svc(__unused void *argp, __unused void *result,
347     __unused struct svc_req *rqstp)
348 {
349 
350 	rpctls_verbose_out("rpctlssd_null_svc: done\n");
351 	return (TRUE);
352 }
353 
354 bool_t
355 rpctlssd_connect_1_svc(__unused void *argp,
356     struct rpctlssd_connect_res *result, __unused struct svc_req *rqstp)
357 {
358 	int ngrps, s;
359 	SSL *ssl;
360 	uint32_t flags;
361 	struct ssl_entry *newslp;
362 	uint32_t uid;
363 	uint32_t *gidp;
364 	X509 *cert;
365 
366 	rpctls_verbose_out("rpctlsd_connect_svc: started\n");
367 	memset(result, 0, sizeof(*result));
368 	/* Get the socket fd from the kernel. */
369 	s = rpctls_syscall(RPCTLS_SYSC_SRVSOCKET, "");
370 	if (s < 0)
371 		return (FALSE);
372 
373 	/* Do the server side of a TLS handshake. */
374 	gidp = calloc(NGROUPS, sizeof(*gidp));
375 	ssl = rpctls_server(rpctls_ctx, s, &flags, &uid, &ngrps, gidp, &cert);
376 	if (ssl == NULL) {
377 		free(gidp);
378 		rpctls_verbose_out("rpctlssd_connect_svc: ssl "
379 		    "accept failed\n");
380 		/*
381 		 * For RPC-over-TLS, this upcall is expected
382 		 * to close off the socket upon handshake failure.
383 		 */
384 		close(s);
385 		return (FALSE);
386 	} else {
387 		rpctls_verbose_out("rpctlssd_connect_svc: "
388 		    "succeeded flags=0x%x\n", flags);
389 		result->flags = flags;
390 		result->sec = rpctls_ssl_sec;
391 		result->usec = rpctls_ssl_usec;
392 		result->ssl = ++rpctls_ssl_refno;
393 		/* Hard to believe this could ever wrap around.. */
394 		if (rpctls_ssl_refno == 0)
395 			result->ssl = ++rpctls_ssl_refno;
396 		if ((flags & RPCTLS_FLAGS_CERTUSER) != 0) {
397 			result->uid = uid;
398 			result->gid.gid_len = ngrps;
399 			result->gid.gid_val = gidp;
400 		} else {
401 			result->uid = 0;
402 			result->gid.gid_len = 0;
403 			result->gid.gid_val = gidp;
404 		}
405 	}
406 
407 	/* Maintain list of all current SSL *'s */
408 	newslp = malloc(sizeof(*newslp));
409 	newslp->ssl = ssl;
410 	newslp->s = s;
411 	newslp->shutoff = false;
412 	newslp->refno = rpctls_ssl_refno;
413 	newslp->cert = cert;
414 	LIST_INSERT_HEAD(&rpctls_ssllist, newslp, next);
415 	return (TRUE);
416 }
417 
418 bool_t
419 rpctlssd_handlerecord_1_svc(struct rpctlssd_handlerecord_arg *argp,
420     struct rpctlssd_handlerecord_res *result, __unused struct svc_req *rqstp)
421 {
422 	struct ssl_entry *slp;
423 	int ret;
424 	char junk;
425 
426 	slp = NULL;
427 	if (argp->sec == rpctls_ssl_sec && argp->usec ==
428 	    rpctls_ssl_usec) {
429 		LIST_FOREACH(slp, &rpctls_ssllist, next) {
430 			if (slp->refno == argp->ssl)
431 				break;
432 		}
433 	}
434 
435 	if (slp != NULL) {
436 		rpctls_verbose_out("rpctlssd_handlerecord fd=%d\n",
437 		    slp->s);
438 		/*
439 		 * An SSL_read() of 0 bytes should fail, but it should
440 		 * handle the non-application data record before doing so.
441 		 */
442 		ret = SSL_read(slp->ssl, &junk, 0);
443 		if (ret <= 0) {
444 			/* Check to see if this was a close alert. */
445 			ret = SSL_get_shutdown(slp->ssl);
446 			if ((ret & (SSL_SENT_SHUTDOWN |
447 			    SSL_RECEIVED_SHUTDOWN)) == SSL_RECEIVED_SHUTDOWN)
448 				SSL_shutdown(slp->ssl);
449 		} else {
450 			if (rpctls_debug_level == 0)
451 				syslog(LOG_ERR, "SSL_read returned %d", ret);
452 			else
453 				fprintf(stderr, "SSL_read returned %d\n", ret);
454 		}
455 		result->reterr = RPCTLSERR_OK;
456 	} else
457 		result->reterr = RPCTLSERR_NOSSL;
458 	return (TRUE);
459 }
460 
461 bool_t
462 rpctlssd_disconnect_1_svc(struct rpctlssd_disconnect_arg *argp,
463     struct rpctlssd_disconnect_res *result, __unused struct svc_req *rqstp)
464 {
465 	struct ssl_entry *slp;
466 	int ret;
467 
468 	slp = NULL;
469 	if (argp->sec == rpctls_ssl_sec && argp->usec ==
470 	    rpctls_ssl_usec) {
471 		LIST_FOREACH(slp, &rpctls_ssllist, next) {
472 			if (slp->refno == argp->ssl)
473 				break;
474 		}
475 	}
476 
477 	if (slp != NULL) {
478 		rpctls_verbose_out("rpctlssd_disconnect fd=%d closed\n",
479 		    slp->s);
480 		LIST_REMOVE(slp, next);
481 		if (!slp->shutoff) {
482 			ret = SSL_get_shutdown(slp->ssl);
483 			/*
484 			 * Do an SSL_shutdown() unless a close alert has
485 			 * already been sent.
486 			 */
487 			if ((ret & SSL_SENT_SHUTDOWN) == 0)
488 				SSL_shutdown(slp->ssl);
489 		}
490 		SSL_free(slp->ssl);
491 		if (slp->cert != NULL)
492 			X509_free(slp->cert);
493 		/*
494 		 * For RPC-over-TLS, this upcall is expected
495 		 * to close off the socket.
496 		 */
497 		if (!slp->shutoff)
498 			shutdown(slp->s, SHUT_WR);
499 		close(slp->s);
500 		free(slp);
501 		result->reterr = RPCTLSERR_OK;
502 	} else
503 		result->reterr = RPCTLSERR_NOCLOSE;
504 	return (TRUE);
505 }
506 
507 int
508 rpctlssd_1_freeresult(__unused SVCXPRT *transp, xdrproc_t xdr_result,
509     caddr_t result)
510 {
511 	rpctlssd_connect_res *res;
512 
513 	if (xdr_result == (xdrproc_t)xdr_rpctlssd_connect_res) {
514 		res = (rpctlssd_connect_res *)(void *)result;
515 		free(res->gid.gid_val);
516 	}
517 	return (TRUE);
518 }
519 
520 static void
521 rpctlssd_terminate(int sig __unused)
522 {
523 	struct ssl_entry *slp;
524 
525 	rpctls_syscall(RPCTLS_SYSC_SRVSHUTDOWN, "");
526 	pidfile_remove(rpctls_pfh);
527 
528 	LIST_FOREACH(slp, &rpctls_ssllist, next)
529 		shutdown(slp->s, SHUT_RD);
530 	exit(0);
531 }
532 
533 /* Allow the handshake to proceed. */
534 static int
535 rpctls_verify_callback(__unused int preverify_ok,
536     __unused X509_STORE_CTX *x509_ctx)
537 {
538 
539 	return (1);
540 }
541 
542 static SSL_CTX *
543 rpctls_setup_ssl(const char *certdir)
544 {
545 	SSL_CTX *ctx;
546 	char path[PATH_MAX];
547 	size_t len, rlen;
548 	int ret;
549 
550 	SSL_library_init();
551 	SSL_load_error_strings();
552 	OpenSSL_add_all_algorithms();
553 
554 	ctx = SSL_CTX_new(TLS_server_method());
555 	if (ctx == NULL) {
556 		rpctls_verbose_out("rpctls_setup_ssl: SSL_CTX_new failed\n");
557 		return (NULL);
558 	}
559 	SSL_CTX_set_ecdh_auto(ctx, 1);
560 
561 	/*
562 	 * Set preferred ciphers, since KERN_TLS only supports a
563 	 * few of them.
564 	 */
565 	ret = SSL_CTX_set_cipher_list(ctx, _PREFERRED_CIPHERS);
566 	if (ret == 0) {
567 		rpctls_verbose_out("rpctls_setup_ssl: "
568 		    "SSL_CTX_set_cipher_list failed to set any ciphers\n");
569 		SSL_CTX_free(ctx);
570 		return (NULL);
571 	}
572 
573 	/* Get the cert.pem and certkey.pem files from the directory certdir. */
574 	len = strlcpy(path, certdir, sizeof(path));
575 	rlen = sizeof(path) - len;
576 	if (strlcpy(&path[len], "cert.pem", rlen) != 8) {
577 		SSL_CTX_free(ctx);
578 		return (NULL);
579 	}
580 	ret = SSL_CTX_use_certificate_file(ctx, path, SSL_FILETYPE_PEM);
581 	if (ret != 1) {
582 		rpctls_verbose_out("rpctls_setup_ssl: can't use certificate "
583 		    "file path=%s ret=%d\n", path, ret);
584 		SSL_CTX_free(ctx);
585 		return (NULL);
586 	}
587 	if (strlcpy(&path[len], "certkey.pem", rlen) != 11) {
588 		SSL_CTX_free(ctx);
589 		return (NULL);
590 	}
591 	ret = SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM);
592 	if (ret != 1) {
593 		rpctls_verbose_out("rpctls_setup_ssl: Can't use private "
594 		    "key path=%s ret=%d\n", path, ret);
595 		SSL_CTX_free(ctx);
596 		return (NULL);
597 	}
598 
599 	/* Set Mutual authentication, as required. */
600 	if (rpctls_do_mutual) {
601 		if (rpctls_verify_cafile != NULL ||
602 		    rpctls_verify_capath != NULL) {
603 			if (rpctls_crlfile != NULL) {
604 				ret = rpctls_loadcrlfile(ctx);
605 				if (ret == 0) {
606 					rpctls_verbose_out("rpctls_setup_ssl:"
607 					    " Load CRLfile failed\n");
608 					SSL_CTX_free(ctx);
609 					return (NULL);
610 				}
611 			}
612 #if OPENSSL_VERSION_NUMBER >= 0x30000000
613 			ret = 1;
614 			if (rpctls_verify_cafile != NULL)
615 				ret = SSL_CTX_load_verify_file(ctx,
616 				    rpctls_verify_cafile);
617 			if (ret != 0 && rpctls_verify_capath != NULL)
618 				ret = SSL_CTX_load_verify_dir(ctx,
619 				    rpctls_verify_capath);
620 #else
621 			ret = SSL_CTX_load_verify_locations(ctx,
622 			    rpctls_verify_cafile, rpctls_verify_capath);
623 #endif
624 			if (ret == 0) {
625 				rpctls_verbose_out("rpctls_setup_ssl: "
626 				    "Can't load verify locations\n");
627 				SSL_CTX_free(ctx);
628 				return (NULL);
629 			}
630 			if (rpctls_verify_cafile != NULL)
631 				SSL_CTX_set_client_CA_list(ctx,
632 				    SSL_load_client_CA_file(
633 			    rpctls_verify_cafile));
634 		}
635 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
636 		    rpctls_verify_callback);
637 	}
638 #ifdef SSL_OP_ENABLE_KTLS
639 	SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
640 #endif
641 #ifdef SSL_MODE_NO_KTLS_TX
642 	SSL_CTX_clear_mode(ctx, SSL_MODE_NO_KTLS_TX | SSL_MODE_NO_KTLS_RX);
643 #endif
644 	return (ctx);
645 }
646 
647 static SSL *
648 rpctls_server(SSL_CTX *ctx, int s, uint32_t *flags, uint32_t *uidp,
649     int *ngrps, uint32_t *gidp, X509 **certp)
650 {
651 	SSL *ssl;
652 	X509 *cert;
653 	struct sockaddr *sad;
654 	struct sockaddr_storage ad;
655 	char hostnam[NI_MAXHOST];
656 	int gethostret, ret;
657 	char *cp, *cp2;
658 	long verfret;
659 
660 	*flags = 0;
661 	*certp = NULL;
662 	sad = (struct sockaddr *)&ad;
663 	ssl = SSL_new(ctx);
664 	if (ssl == NULL) {
665 		rpctls_verbose_out("rpctls_server: SSL_new failed\n");
666 		return (NULL);
667 	}
668 	if (SSL_set_fd(ssl, s) != 1) {
669 		rpctls_verbose_out("rpctls_server: SSL_set_fd failed\n");
670 		SSL_free(ssl);
671 		return (NULL);
672 	}
673 	ret = SSL_accept(ssl);
674 	if (ret != 1) {
675 		rpctls_verbose_out("rpctls_server: SSL_accept "
676 		    "failed ret=%d\n", ret);
677 		SSL_free(ssl);
678 		return (NULL);
679 	}
680 	*flags |= RPCTLS_FLAGS_HANDSHAKE;
681 	if (rpctls_do_mutual) {
682 		cert = SSL_get_peer_certificate(ssl);
683 		if (cert != NULL) {
684 			gethostret = rpctls_gethost(s, sad, hostnam,
685 			    sizeof(hostnam));
686 			if (gethostret == 0)
687 				hostnam[0] = '\0';
688 			cp2 = X509_NAME_oneline(
689 			    X509_get_subject_name(cert), NULL, 0);
690 			*flags |= RPCTLS_FLAGS_GOTCERT;
691 			verfret = SSL_get_verify_result(ssl);
692 			if (verfret != X509_V_OK) {
693 				cp = X509_NAME_oneline(
694 				    X509_get_issuer_name(cert), NULL, 0);
695 				if (rpctls_debug_level == 0)
696 					syslog(LOG_INFO | LOG_DAEMON,
697 					    "rpctls_server: client IP %s "
698 					    "issuerName=%s subjectName=%s"
699 					    " verify failed %s\n", hostnam,
700 					    cp, cp2,
701 					    X509_verify_cert_error_string(
702 					    verfret));
703 				else
704 					fprintf(stderr,
705 					    "rpctls_server: client IP %s "
706 					    "issuerName=%s subjectName=%s"
707 					    " verify failed %s\n", hostnam,
708 					    cp, cp2,
709 					    X509_verify_cert_error_string(
710 					    verfret));
711 			}
712 			if (verfret ==
713 			    X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
714 			    verfret == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN)
715 				*flags |= RPCTLS_FLAGS_SELFSIGNED;
716 			else if (verfret == X509_V_OK) {
717 				if (rpctls_comparehost) {
718 					ret = 0;
719 					if (gethostret != 0)
720 						ret = rpctls_checkhost(sad,
721 						    cert, rpctls_wildcard);
722 					if (ret != 1) {
723 						*flags |=
724 						    RPCTLS_FLAGS_DISABLED;
725 						rpctls_verbose_out(
726 						    "rpctls_server: "
727 						    "checkhost "
728 						    "failed\n");
729 					}
730 				}
731 				if (rpctls_cnuser) {
732 					ret = rpctls_cnname(cert, uidp,
733 					    ngrps, gidp);
734 					if (ret != 0)
735 						*flags |= RPCTLS_FLAGS_CERTUSER;
736 				}
737 				*flags |= RPCTLS_FLAGS_VERIFIED;
738 				*certp = cert;
739 				cert = NULL;
740 			}
741 			if (cert != NULL)
742 				X509_free(cert);
743 		} else
744 			rpctls_verbose_out("rpctls_server: "
745 			    "No peer certificate\n");
746 	}
747 
748 	/* Check to see that ktls is working for the connection. */
749 	ret = BIO_get_ktls_send(SSL_get_wbio(ssl));
750 	rpctls_verbose_out("rpctls_server: BIO_get_ktls_send=%d\n", ret);
751 	if (ret != 0) {
752 		ret = BIO_get_ktls_recv(SSL_get_rbio(ssl));
753 		rpctls_verbose_out("rpctls_server: BIO_get_ktls_recv=%d\n",
754 		    ret);
755 	}
756 	if (ret == 0) {
757 		if (rpctls_debug_level == 0)
758 			syslog(LOG_ERR, "ktls not working");
759 		else
760 			fprintf(stderr, "ktls not working\n");
761 		/*
762 		 * The handshake has completed, so all that can be
763 		 * done is disable the connection.
764 		 */
765 		*flags |= RPCTLS_FLAGS_DISABLED;
766 	}
767 
768 	return (ssl);
769 }
770 
771 /*
772  * Acquire the dnsname for this server.
773  */
774 static char *
775 rpctls_getdnsname(char *hostname)
776 {
777 	char *cp, *dnsname;
778 	struct addrinfo *aip, hints;
779 	int error;
780 
781 	dnsname = NULL;
782 	if (gethostname(hostname, MAXHOSTNAMELEN) == 0) {
783 		if ((cp = strchr(hostname, '.')) != NULL &&
784 		    *(cp + 1) != '\0') {
785 			*cp = '@';
786 			dnsname = cp;
787 		} else {
788 			memset((void *)&hints, 0, sizeof (hints));
789 			hints.ai_flags = AI_CANONNAME;
790 			error = getaddrinfo(hostname, NULL, &hints, &aip);
791 			if (error == 0) {
792 				if (aip->ai_canonname != NULL &&
793 				    (cp = strchr(aip->ai_canonname, '.')) !=
794 				    NULL && *(cp + 1) != '\0') {
795 					hostname[0] = '@';
796 					strlcpy(&hostname[1], cp + 1,
797 					    MAXHOSTNAMELEN + 1);
798 					dnsname = hostname;
799 				}
800 				freeaddrinfo(aip);
801 			}
802 		}
803 	}
804 	return (dnsname);
805 }
806 
807 /*
808  * Check for an otherName component of subjectAltName where the OID
809  * matches and the "domain" matches that of this server.
810  * If found, map "user" to a <uid, gidlist> for it.
811  */
812 static int
813 rpctls_cnname(X509 *cert, uint32_t *uidp, int *ngrps, uint32_t *gidp)
814 {
815 	char *cp, usern[1024 + 1];
816 	struct passwd *pwd;
817 	gid_t gids[NGROUPS];
818 	int i, j;
819 	GENERAL_NAMES *genlist;
820 	GENERAL_NAME *genname;
821 	OTHERNAME *val;
822 	size_t slen;
823 
824 	/* First, find the otherName in the subjectAltName. */
825 	genlist = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
826 	if (genlist == NULL)
827 		return (0);
828 	cp = NULL;
829 	for (i = 0; i < sk_GENERAL_NAME_num(genlist); i++) {
830 		genname = sk_GENERAL_NAME_value(genlist, i);
831 		if (genname->type != GEN_OTHERNAME)
832 			continue;
833 		val = genname->d.otherName;
834 
835 		/* Check to see that it is the correct OID. */
836 		slen = i2t_ASN1_OBJECT(usern, sizeof(usern), val->type_id);
837 		if (slen != strlen(rpctls_cnuseroid) || memcmp(usern,
838 		    rpctls_cnuseroid, slen) != 0)
839 			continue;
840 
841 		/* Sanity check the otherName. */
842 		if (val->value->type != V_ASN1_UTF8STRING ||
843 		    val->value->value.utf8string->length < 3 ||
844 		    (size_t)val->value->value.utf8string->length > sizeof(usern)
845 		    - 1) {
846 			rpctls_verbose_out("rpctls_cnname: invalid cnuser "
847 			    "type=%d\n", val->value->type);
848 			continue;
849 		}
850 
851 		/* Look for a "user" in the otherName */
852 		memcpy(usern, val->value->value.utf8string->data,
853 		    val->value->value.utf8string->length);
854 		usern[val->value->value.utf8string->length] = '\0';
855 
856 		/* Now, look for the @dnsname suffix in the commonName. */
857 		cp = strcasestr(usern, rpctls_dnsname);
858 		if (cp == NULL)
859 			continue;
860 		if (*(cp + strlen(rpctls_dnsname)) != '\0') {
861 			cp = NULL;
862 			continue;
863 		}
864 		*cp = '\0';
865 		break;
866 	}
867 	if (cp == NULL)
868 		return (0);
869 
870 	/* See if the "user" is in the passwd database. */
871 	pwd = getpwnam(usern);
872 	if (pwd == NULL)
873 		return (0);
874 	*uidp = pwd->pw_uid;
875 	*ngrps = NGROUPS;
876 	if (getgrouplist(pwd->pw_name, pwd->pw_gid, gids, ngrps) < 0)
877 		return (0);
878 	rpctls_verbose_out("mapped user=%s ngrps=%d uid=%d\n", pwd->pw_name,
879 	    *ngrps, pwd->pw_uid);
880 	for (j = 0; j < *ngrps; j++)
881 		gidp[j] = gids[j];
882 	return (1);
883 }
884 
885 static void
886 rpctls_huphandler(int sig __unused)
887 {
888 
889 	rpctls_gothup = true;
890 }
891