2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
31 * Extensively modified from /usr/src/usr.sbin/gssd.c r344402 for
32 * the server side of kernel RPC-over-TLS by Rick Macklem.
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
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>
44 #include <sys/sysctl.h>
45 #include <sys/syslog.h>
62 #include <rpc/rpc_com.h>
63 #include <rpc/rpcsec_tls.h>
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>
72 #include "rpc.tlscommon.h"
74 #ifndef _PATH_RPCTLSSDSOCK
75 #define _PATH_RPCTLSSDSOCK "/var/run/rpc.tlsservd.sock"
77 #ifndef _PATH_CERTANDKEY
78 #define _PATH_CERTANDKEY "/etc/rpc.tlsservd/"
80 #ifndef _PATH_RPCTLSSDPID
81 #define _PATH_RPCTLSSDPID "/var/run/rpc.tlsservd.pid"
83 #ifndef _PREFERRED_CIPHERS
84 #define _PREFERRED_CIPHERS "AES128-GCM-SHA256"
87 /* Global variables also used by rpc.tlscommon.c. */
88 int rpctls_debug_level;
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;
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;
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);
125 extern void rpctlssd_1(struct svc_req *rqstp, SVCXPRT *transp);
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' },
147 main(int argc, char **argv)
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
154 struct sockaddr_un sun;
155 int ch, fd, i, mypos, oldmask;
159 char hostname[MAXHOSTNAMELEN + 2];
162 size_t tls_enable_len;
165 /* Check that another rpctlssd isn't already running. */
166 rpctls_pfh = pidfile_open(_PATH_RPCTLSSDPID, 0600, &otherpid);
167 if (rpctls_pfh == NULL) {
169 errx(1, "rpctlssd already running, pid: %d.", otherpid);
170 warn("cannot open or create pidfile");
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");
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;
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;
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");
198 rpctls_verbose = false;
199 while ((ch = getopt_long(argc, argv, "2C:D:dhl:N:n:mp:r:uvWw", longopts,
203 rpctls_mintls = TLS1_2_VERSION;
206 rpctls_ciphers = optarg;
209 rpctls_certdir = optarg;
212 rpctls_debug_level++;
215 rpctls_comparehost = true;
218 rpctls_verify_cafile = optarg;
221 rpctls_do_mutual = true;
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);
232 strlcpy(&hostname[1], optarg, MAXHOSTNAMELEN + 1);
233 rpctls_dnsname = hostname;
236 rpctls_verify_capath = optarg;
239 rpctls_crlfile = optarg;
242 rpctls_cnuser = true;
245 rpctls_verbose = true;
248 if (rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS)
249 errx(1, "options -w and -W are mutually "
251 rpctls_wildcard = X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS;
254 if (rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS)
255 errx(1, "options -w and -W are mutually "
260 fprintf(stderr, "usage: %s "
261 "[-2/--allowtls1_2] "
262 "[-C/--ciphers available_ciphers] "
263 "[-D/--certdir certdir] [-d/--debuglevel] "
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]);
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");
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");
296 for (i = 0; i < rpctls_procs - 1; i++)
297 rpctls_workers[i] = -1;
300 if (rpctls_debug_level == 0) {
302 * Temporarily block SIGTERM and SIGCHLD, so workers[] can't
305 sigemptyset(&signew);
306 sigaddset(&signew, SIGTERM);
307 sigaddset(&signew, SIGCHLD);
308 sigprocmask(SIG_BLOCK, &signew, NULL);
310 if (daemon(0, 0) != 0)
311 err(1, "Can't daemonize");
312 signal(SIGINT, SIG_IGN);
313 signal(SIGQUIT, SIG_IGN);
315 signal(SIGPIPE, SIG_IGN);
316 signal(SIGHUP, rpctls_huphandler);
317 signal(SIGTERM, rpctls_cleanup_term);
318 signal(SIGCHLD, rpctls_cleanup_term);
320 pidfile_write(rpctls_pfh);
322 rpctls_syscall(RPCTLS_SYSC_SRVSTARTUP, "");
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;
331 setproctitle("server");
333 } else if (rpctls_workers[i] < 0) {
334 syslog(LOG_ERR, "fork: %m");
338 if (!rpctls_im_a_worker && rpctls_procs > 1)
339 setproctitle("master");
341 sigemptyset(&signew);
342 sigaddset(&signew, SIGTERM);
343 sigaddset(&signew, SIGCHLD);
344 sigprocmask(SIG_UNBLOCK, &signew, NULL);
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);
353 if (rpctls_debug_level == 0) {
354 syslog(LOG_ERR, "Can't create local rpctlssd socket");
357 err(1, "Can't create local rpctlssd socket");
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");
365 err(1, "Can't bind local rpctlssd socket");
368 if (listen(fd, SOMAXCONN) < 0) {
369 if (rpctls_debug_level == 0) {
371 "Can't listen on local rpctlssd socket");
374 err(1, "Can't listen on local rpctlssd socket");
376 xprt = svc_vc_create(fd, RPC_MAXDATASIZE, RPC_MAXDATASIZE);
378 if (rpctls_debug_level == 0) {
380 "Can't create transport for local rpctlssd socket");
383 err(1, "Can't create transport for local rpctlssd socket");
385 if (!svc_reg(xprt, RPCTLSSD, RPCTLSSDVERS, rpctlssd_1, NULL)) {
386 if (rpctls_debug_level == 0) {
388 "Can't register service for local rpctlssd socket");
391 err(1, "Can't register service for local rpctlssd socket");
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");
400 err(1, "Can't create SSL context");
402 rpctls_gothup = false;
403 LIST_INIT(&rpctls_ssllist);
405 if (rpctls_syscall(RPCTLS_SYSC_SRVSETPATH, rpctls_sockname[mypos]) < 0){
406 if (rpctls_debug_level == 0) {
408 "Can't set upcall socket path=%s errno=%d",
409 rpctls_sockname[mypos], errno);
412 err(1, "Can't set upcall socket path=%s",
413 rpctls_sockname[mypos]);
418 SSL_CTX_free(rpctls_ctx);
424 rpctlssd_null_1_svc(__unused void *argp, __unused void *result,
425 __unused struct svc_req *rqstp)
428 rpctls_verbose_out("rpctlssd_null_svc: done\n");
433 rpctlssd_connect_1_svc(__unused void *argp,
434 struct rpctlssd_connect_res *result, __unused struct svc_req *rqstp)
439 struct ssl_entry *newslp;
444 rpctls_verbose_out("rpctlsd_connect_svc: started\n");
445 memset(result, 0, sizeof(*result));
446 /* Get the socket fd from the kernel. */
447 s = rpctls_syscall(RPCTLS_SYSC_SRVSOCKET, "");
451 /* Do the server side of a TLS handshake. */
452 gidp = calloc(NGROUPS, sizeof(*gidp));
453 ssl = rpctls_server(rpctls_ctx, s, &flags, &uid, &ngrps, gidp, &cert);
456 rpctls_verbose_out("rpctlssd_connect_svc: ssl "
459 * For RPC-over-TLS, this upcall is expected
460 * to close off the socket upon handshake failure.
465 rpctls_verbose_out("rpctlssd_connect_svc: "
466 "succeeded flags=0x%x\n", flags);
467 result->flags = flags;
468 result->sec = rpctls_ssl_sec;
469 result->usec = rpctls_ssl_usec;
470 result->ssl = ++rpctls_ssl_refno;
471 /* Hard to believe this could ever wrap around.. */
472 if (rpctls_ssl_refno == 0)
473 result->ssl = ++rpctls_ssl_refno;
474 if ((flags & RPCTLS_FLAGS_CERTUSER) != 0) {
476 result->gid.gid_len = ngrps;
477 result->gid.gid_val = gidp;
480 result->gid.gid_len = 0;
481 result->gid.gid_val = gidp;
485 /* Maintain list of all current SSL *'s */
486 newslp = malloc(sizeof(*newslp));
489 newslp->shutoff = false;
490 newslp->refno = rpctls_ssl_refno;
492 LIST_INSERT_HEAD(&rpctls_ssllist, newslp, next);
497 rpctlssd_handlerecord_1_svc(struct rpctlssd_handlerecord_arg *argp,
498 struct rpctlssd_handlerecord_res *result, __unused struct svc_req *rqstp)
500 struct ssl_entry *slp;
505 if (argp->sec == rpctls_ssl_sec && argp->usec ==
507 LIST_FOREACH(slp, &rpctls_ssllist, next) {
508 if (slp->refno == argp->ssl)
514 rpctls_verbose_out("rpctlssd_handlerecord fd=%d\n",
517 * An SSL_read() of 0 bytes should fail, but it should
518 * handle the non-application data record before doing so.
520 ret = SSL_read(slp->ssl, &junk, 0);
522 /* Check to see if this was a close alert. */
523 ret = SSL_get_shutdown(slp->ssl);
524 if ((ret & (SSL_SENT_SHUTDOWN |
525 SSL_RECEIVED_SHUTDOWN)) == SSL_RECEIVED_SHUTDOWN)
526 SSL_shutdown(slp->ssl);
528 if (rpctls_debug_level == 0)
529 syslog(LOG_ERR, "SSL_read returned %d", ret);
531 fprintf(stderr, "SSL_read returned %d\n", ret);
533 result->reterr = RPCTLSERR_OK;
535 result->reterr = RPCTLSERR_NOSSL;
540 rpctlssd_disconnect_1_svc(struct rpctlssd_disconnect_arg *argp,
541 struct rpctlssd_disconnect_res *result, __unused struct svc_req *rqstp)
543 struct ssl_entry *slp;
547 if (argp->sec == rpctls_ssl_sec && argp->usec ==
549 LIST_FOREACH(slp, &rpctls_ssllist, next) {
550 if (slp->refno == argp->ssl)
556 rpctls_verbose_out("rpctlssd_disconnect fd=%d closed\n",
558 LIST_REMOVE(slp, next);
560 ret = SSL_get_shutdown(slp->ssl);
562 * Do an SSL_shutdown() unless a close alert has
565 if ((ret & SSL_SENT_SHUTDOWN) == 0)
566 SSL_shutdown(slp->ssl);
569 if (slp->cert != NULL)
570 X509_free(slp->cert);
572 * For RPC-over-TLS, this upcall is expected
573 * to close off the socket.
576 shutdown(slp->s, SHUT_WR);
579 result->reterr = RPCTLSERR_OK;
581 result->reterr = RPCTLSERR_NOCLOSE;
586 rpctlssd_1_freeresult(__unused SVCXPRT *transp, xdrproc_t xdr_result,
589 rpctlssd_connect_res *res;
591 if (xdr_result == (xdrproc_t)xdr_rpctlssd_connect_res) {
592 res = (rpctlssd_connect_res *)(void *)result;
593 free(res->gid.gid_val);
599 * cleanup_term() called via SIGTERM (or SIGCHLD if a child dies).
602 rpctls_cleanup_term(int sig)
604 struct ssl_entry *slp;
607 if (rpctls_im_a_worker && sig == SIGCHLD)
609 LIST_FOREACH(slp, &rpctls_ssllist, next)
610 shutdown(slp->s, SHUT_RD);
611 SSL_CTX_free(rpctls_ctx);
614 if (rpctls_im_a_worker)
617 /* I'm the server, so terminate the workers. */
619 for (i = 0; i < rpctls_procs - 1; i++) {
620 if (rpctls_workers[i] != -1) {
622 kill(rpctls_workers[i], SIGTERM);
627 * Wait for them to die.
629 for (i = 0; i < cnt; i++)
630 wait3(NULL, 0, NULL);
632 rpctls_syscall(RPCTLS_SYSC_SRVSHUTDOWN, "");
633 pidfile_remove(rpctls_pfh);
638 /* Allow the handshake to proceed. */
640 rpctls_verify_callback(__unused int preverify_ok,
641 __unused X509_STORE_CTX *x509_ctx)
648 rpctls_setup_ssl(const char *certdir)
656 SSL_load_error_strings();
657 OpenSSL_add_all_algorithms();
659 ctx = SSL_CTX_new(TLS_server_method());
661 rpctls_verbose_out("rpctls_setup_ssl: SSL_CTX_new failed\n");
664 SSL_CTX_set_ecdh_auto(ctx, 1);
666 if (rpctls_ciphers != NULL) {
668 * Set available ciphers, since KERN_TLS only supports a
669 * few of them. Normally, not doing this should be ok,
670 * since the library defaults will work.
672 ret = SSL_CTX_set_ciphersuites(ctx, rpctls_ciphers);
674 rpctls_verbose_out("rpctls_setup_ssl: "
675 "SSL_CTX_set_ciphersuites failed: %s\n",
682 ret = SSL_CTX_set_min_proto_version(ctx, rpctls_mintls);
684 rpctls_verbose_out("rpctls_setup_ssl: "
685 "SSL_CTX_set_min_proto_version failed\n");
689 ret = SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
691 rpctls_verbose_out("rpctls_setup_ssl: "
692 "SSL_CTX_set_max_proto_version failed\n");
697 /* Get the cert.pem and certkey.pem files from the directory certdir. */
698 len = strlcpy(path, certdir, sizeof(path));
699 rlen = sizeof(path) - len;
700 if (strlcpy(&path[len], "cert.pem", rlen) != 8) {
704 ret = SSL_CTX_use_certificate_file(ctx, path, SSL_FILETYPE_PEM);
706 rpctls_verbose_out("rpctls_setup_ssl: can't use certificate "
707 "file path=%s ret=%d\n", path, ret);
711 if (strlcpy(&path[len], "certkey.pem", rlen) != 11) {
715 ret = SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM);
717 rpctls_verbose_out("rpctls_setup_ssl: Can't use private "
718 "key path=%s ret=%d\n", path, ret);
723 /* Set Mutual authentication, as required. */
724 if (rpctls_do_mutual) {
725 if (rpctls_verify_cafile != NULL ||
726 rpctls_verify_capath != NULL) {
727 if (rpctls_crlfile != NULL) {
728 ret = rpctls_loadcrlfile(ctx);
730 rpctls_verbose_out("rpctls_setup_ssl:"
731 " Load CRLfile failed\n");
736 #if OPENSSL_VERSION_NUMBER >= 0x30000000
738 if (rpctls_verify_cafile != NULL)
739 ret = SSL_CTX_load_verify_file(ctx,
740 rpctls_verify_cafile);
741 if (ret != 0 && rpctls_verify_capath != NULL)
742 ret = SSL_CTX_load_verify_dir(ctx,
743 rpctls_verify_capath);
745 ret = SSL_CTX_load_verify_locations(ctx,
746 rpctls_verify_cafile, rpctls_verify_capath);
749 rpctls_verbose_out("rpctls_setup_ssl: "
750 "Can't load verify locations\n");
754 if (rpctls_verify_cafile != NULL)
755 SSL_CTX_set_client_CA_list(ctx,
756 SSL_load_client_CA_file(
757 rpctls_verify_cafile));
759 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
760 rpctls_verify_callback);
762 #ifdef SSL_OP_ENABLE_KTLS
763 SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
765 #ifdef SSL_MODE_NO_KTLS_TX
766 SSL_CTX_clear_mode(ctx, SSL_MODE_NO_KTLS_TX | SSL_MODE_NO_KTLS_RX);
772 rpctls_server(SSL_CTX *ctx, int s, uint32_t *flags, uint32_t *uidp,
773 int *ngrps, uint32_t *gidp, X509 **certp)
777 struct sockaddr *sad;
778 struct sockaddr_storage ad;
779 char hostnam[NI_MAXHOST];
786 sad = (struct sockaddr *)&ad;
789 rpctls_verbose_out("rpctls_server: SSL_new failed\n");
792 if (SSL_set_fd(ssl, s) != 1) {
793 rpctls_verbose_out("rpctls_server: SSL_set_fd failed\n");
797 ret = SSL_accept(ssl);
799 rpctls_verbose_out("rpctls_server: SSL_accept "
800 "failed ret=%d\n", ret);
804 *flags |= RPCTLS_FLAGS_HANDSHAKE;
805 if (rpctls_verbose) {
806 gethostret = rpctls_gethost(s, sad, hostnam, sizeof(hostnam));
809 rpctls_verbose_out("rpctls_server: SSL handshake ok for host %s"
810 " <%s %s>\n", hostnam, SSL_get_version(ssl),
811 SSL_get_cipher(ssl));
813 if (rpctls_do_mutual) {
814 cert = SSL_get_peer_certificate(ssl);
816 if (!rpctls_verbose) {
817 gethostret = rpctls_gethost(s, sad, hostnam,
822 cp2 = X509_NAME_oneline(
823 X509_get_subject_name(cert), NULL, 0);
824 *flags |= RPCTLS_FLAGS_GOTCERT;
825 verfret = SSL_get_verify_result(ssl);
826 if (verfret != X509_V_OK) {
827 cp = X509_NAME_oneline(
828 X509_get_issuer_name(cert), NULL, 0);
829 if (rpctls_debug_level == 0)
830 syslog(LOG_INFO | LOG_DAEMON,
831 "rpctls_server: client IP %s "
832 "issuerName=%s subjectName=%s"
833 " verify failed %s\n", hostnam,
835 X509_verify_cert_error_string(
839 "rpctls_server: client IP %s "
840 "issuerName=%s subjectName=%s"
841 " verify failed %s\n", hostnam,
843 X509_verify_cert_error_string(
847 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
848 verfret == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN)
849 *flags |= RPCTLS_FLAGS_SELFSIGNED;
850 else if (verfret == X509_V_OK) {
851 if (rpctls_comparehost) {
854 ret = rpctls_checkhost(sad,
855 cert, rpctls_wildcard);
858 RPCTLS_FLAGS_DISABLED;
866 ret = rpctls_cnname(cert, uidp,
869 *flags |= RPCTLS_FLAGS_CERTUSER;
871 *flags |= RPCTLS_FLAGS_VERIFIED;
878 rpctls_verbose_out("rpctls_server: "
879 "No peer certificate\n");
882 /* Check to see that ktls is working for the connection. */
883 ret = BIO_get_ktls_send(SSL_get_wbio(ssl));
884 rpctls_verbose_out("rpctls_server: BIO_get_ktls_send=%d\n", ret);
886 ret = BIO_get_ktls_recv(SSL_get_rbio(ssl));
887 rpctls_verbose_out("rpctls_server: BIO_get_ktls_recv=%d\n",
891 if (rpctls_debug_level == 0)
892 syslog(LOG_ERR, "ktls not working");
894 fprintf(stderr, "ktls not working\n");
896 * The handshake has completed, so all that can be
897 * done is disable the connection.
899 *flags |= RPCTLS_FLAGS_DISABLED;
906 * Acquire the dnsname for this server.
909 rpctls_getdnsname(char *hostname)
912 struct addrinfo *aip, hints;
916 if (gethostname(hostname, MAXHOSTNAMELEN) == 0) {
917 if ((cp = strchr(hostname, '.')) != NULL &&
922 memset((void *)&hints, 0, sizeof (hints));
923 hints.ai_flags = AI_CANONNAME;
924 error = getaddrinfo(hostname, NULL, &hints, &aip);
926 if (aip->ai_canonname != NULL &&
927 (cp = strchr(aip->ai_canonname, '.')) !=
928 NULL && *(cp + 1) != '\0') {
930 strlcpy(&hostname[1], cp + 1,
942 * Check for an otherName component of subjectAltName where the OID
943 * matches and the "domain" matches that of this server.
944 * If found, map "user" to a <uid, gidlist> for it.
947 rpctls_cnname(X509 *cert, uint32_t *uidp, int *ngrps, uint32_t *gidp)
949 char *cp, usern[1024 + 1];
953 GENERAL_NAMES *genlist;
954 GENERAL_NAME *genname;
958 /* First, find the otherName in the subjectAltName. */
959 genlist = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
963 for (i = 0; i < sk_GENERAL_NAME_num(genlist); i++) {
964 genname = sk_GENERAL_NAME_value(genlist, i);
965 if (genname->type != GEN_OTHERNAME)
967 val = genname->d.otherName;
969 /* Check to see that it is the correct OID. */
970 slen = i2t_ASN1_OBJECT(usern, sizeof(usern), val->type_id);
971 if (slen != strlen(rpctls_cnuseroid) || memcmp(usern,
972 rpctls_cnuseroid, slen) != 0)
975 /* Sanity check the otherName. */
976 if (val->value->type != V_ASN1_UTF8STRING ||
977 val->value->value.utf8string->length < 3 ||
978 (size_t)val->value->value.utf8string->length > sizeof(usern)
980 rpctls_verbose_out("rpctls_cnname: invalid cnuser "
981 "type=%d\n", val->value->type);
985 /* Look for a "user" in the otherName */
986 memcpy(usern, val->value->value.utf8string->data,
987 val->value->value.utf8string->length);
988 usern[val->value->value.utf8string->length] = '\0';
990 /* Now, look for the @dnsname suffix in the commonName. */
991 cp = strcasestr(usern, rpctls_dnsname);
994 if (*(cp + strlen(rpctls_dnsname)) != '\0') {
1004 /* See if the "user" is in the passwd database. */
1005 pwd = getpwnam(usern);
1008 *uidp = pwd->pw_uid;
1010 if (getgrouplist(pwd->pw_name, pwd->pw_gid, gids, ngrps) < 0)
1012 rpctls_verbose_out("mapped user=%s ngrps=%d uid=%d\n", pwd->pw_name,
1013 *ngrps, pwd->pw_uid);
1014 for (j = 0; j < *ngrps; j++)
1020 rpctls_huphandler(int sig __unused)
1023 rpctls_gothup = true;