diff --git a/sys/rpc/rpcsec_tls.h b/sys/rpc/rpcsec_tls.h index f8ad131c3946..024fb2fe68ee 100644 --- a/sys/rpc/rpcsec_tls.h +++ b/sys/rpc/rpcsec_tls.h @@ -1,92 +1,89 @@ /*- * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2020 Rick Macklem * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _RPC_RPCSEC_TLS_H_ #define _RPC_RPCSEC_TLS_H_ /* Operation values for rpctls syscall. */ #define RPCTLS_SYSC_CLSOCKET 2 #define RPCTLS_SYSC_SRVSOCKET 5 -/* Max nprocs for SRV startup */ -#define RPCTLS_SRV_MAXNPROCS 16 - /* System call used by the rpctlscd, rpctlssd daemons. */ int rpctls_syscall(int, const char *); /* Flag bits to indicate certificate results. */ #define RPCTLS_FLAGS_HANDSHAKE 0x01 #define RPCTLS_FLAGS_GOTCERT 0x02 #define RPCTLS_FLAGS_SELFSIGNED 0x04 #define RPCTLS_FLAGS_VERIFIED 0x08 #define RPCTLS_FLAGS_DISABLED 0x10 #define RPCTLS_FLAGS_CERTUSER 0x20 #define RPCTLS_FLAGS_HANDSHFAIL 0x40 /* Error return values for upcall rpcs. */ #define RPCTLSERR_OK 0 #define RPCTLSERR_NOCLOSE 1 #define RPCTLSERR_NOSSL 2 #define RPCTLSERR_NOSOCKET 3 #ifdef _KERNEL /* Functions that perform upcalls to the rpctlsd daemon. */ enum clnt_stat rpctls_connect(CLIENT *newclient, char *certname, struct socket *so, uint32_t *reterr); enum clnt_stat rpctls_cl_handlerecord(void *socookie, uint32_t *reterr); enum clnt_stat rpctls_srv_handlerecord(void *socookie, uint32_t *reterr); enum clnt_stat rpctls_cl_disconnect(void *socookie, uint32_t *reterr); enum clnt_stat rpctls_srv_disconnect(void *socookie, uint32_t *reterr); /* Initialization function for rpcsec_tls. */ int rpctls_init(void); /* Get TLS information function. */ bool rpctls_getinfo(u_int *maxlen, bool rpctlscd_run, bool rpctlssd_run); /* String for AUTH_TLS reply verifier. */ #define RPCTLS_START_STRING "STARTTLS" /* Macros for VIMAGE. */ /* Just define the KRPC_VNETxxx() macros as VNETxxx() macros. */ #define KRPC_VNET_NAME(n) VNET_NAME(n) #define KRPC_VNET_DECLARE(t, n) VNET_DECLARE(t, n) #define KRPC_VNET_DEFINE(t, n) VNET_DEFINE(t, n) #define KRPC_VNET_DEFINE_STATIC(t, n) VNET_DEFINE_STATIC(t, n) #define KRPC_VNET(n) VNET(n) #define CTLFLAG_KRPC_VNET CTLFLAG_VNET #define KRPC_CURVNET_SET(n) CURVNET_SET(n) #define KRPC_CURVNET_SET_QUIET(n) CURVNET_SET_QUIET(n) #define KRPC_CURVNET_RESTORE() CURVNET_RESTORE() #define KRPC_TD_TO_VNET(n) TD_TO_VNET(n) #endif /* _KERNEL */ #endif /* _RPC_RPCSEC_TLS_H_ */ diff --git a/usr.sbin/rpc.tlsservd/Makefile b/usr.sbin/rpc.tlsservd/Makefile index 52de80f0c787..f8f4888bae39 100644 --- a/usr.sbin/rpc.tlsservd/Makefile +++ b/usr.sbin/rpc.tlsservd/Makefile @@ -1,27 +1,27 @@ .include PROG= rpc.tlsservd MAN= rpc.tlsservd.8 SRCS= rpc.tlsservd.c rpc.tlscommon.c rpctlssd.h rpctlssd_svc.c rpctlssd_xdr.c CFLAGS+= -I. -LIBADD= ssl crypto util +LIBADD= ssl crypto util pthread CLEANFILES= rpctlssd_svc.c rpctlssd_xdr.c rpctlssd.h RPCSRC= ${SRCTOP}/sys/rpc/rpcsec_tls/rpctlssd.x RPCGEN= RPCGEN_CPP=${CPP:Q} rpcgen -L -C -M rpctlssd_svc.c: ${RPCSRC} rpctlssd.h ${RPCGEN} -m -o ${.TARGET} ${RPCSRC} rpctlssd_xdr.c: ${RPCSRC} rpctlssd.h ${RPCGEN} -c -o ${.TARGET} ${RPCSRC} rpctlssd.h: ${RPCSRC} ${RPCGEN} -h -o ${.TARGET} ${RPCSRC} .PATH: ${SRCTOP}/sys/rpc/rpcsec_tls .include diff --git a/usr.sbin/rpc.tlsservd/rpc.tlsservd.8 b/usr.sbin/rpc.tlsservd/rpc.tlsservd.8 index 6b604c9136b9..4cad4ee8a705 100644 --- a/usr.sbin/rpc.tlsservd/rpc.tlsservd.8 +++ b/usr.sbin/rpc.tlsservd/rpc.tlsservd.8 @@ -1,387 +1,388 @@ .\" Copyright (c) 2008 Isilon Inc http://www.isilon.com/ .\" Authors: Doug Rabson .\" Developed with Red Inc: Alfred Perlstein .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" Modified from gssd.8 for rpc.tlsservd.8 by Rick Macklem. -.Dd November 10, 2022 +.Dd January 25, 2025 .Dt RPC.TLSSERVD 8 .Os .Sh NAME .Nm rpc.tlsservd .Nd "Sun RPC over TLS Server Daemon" .Sh SYNOPSIS .Nm .Op Fl 2 .Op Fl C Ar available_ciphers .Op Fl D Ar certdir .Op Fl d .Op Fl h .Op Fl l Ar CAfile .Op Fl m -.Op Fl N Ar num_servers +.Op Fl N Ar max_threads .Op Fl n Ar domain .Op Fl p Ar CApath .Op Fl r Ar CRLfile .Op Fl u .Op Fl v .Op Fl W .Op Fl w .Sh DESCRIPTION The .Nm program provides support for the server side of the kernel Sun RPC over TLS implementation. This daemon must be running to allow the kernel RPC to perform the TLS handshake after a TCP client has sent the STARTTLS Null RPC request to the server. This daemon requires that the kernel be built with .Dq options KERNEL_TLS and be running on an architecture such as .Dq amd64 that supports a direct map (not i386) with .Xr ktls 4 enabled. Note that the .Fl tls option in the .Xr exports 5 file specifies that the client must use RPC over TLS. The .Fl tlscert option in the .Xr exports 5 file specifies that the client must provide a certificate that verifies. The .Fl tlscertuser option in the .Xr exports 5 file specifies that the client must provide a certificate that verifies and has a otherName:1.3.6.1.4.1.2238.1.1.1;UTF8: field of subjectAltName of the form .Dq user@domain where .Dq domain matches the one for this server and .Dq user is a valid user name that maps to a . For the latter two cases, the .Fl m and either the .Fl l or .Fl p options must be specified. The .Fl tlscertuser option also requires that the .Fl u option on this daemon be specified. .Pp Also, if the IP address used by the client cannot be trusted, the rules in .Xr exports 5 cannot be applied safely. As such, the .Fl h option can be used along with .Fl m and either the .Fl l or .Fl p options to require that the client certificate have the correct Fully Qualified Domain Name (FQDN) in it. .Pp A certificate and associated key must exist in /etc/rpc.tlsservd (or the .Dq certdir specified by the .Fl D option) in files named .Dq cert.pem and .Dq certkey.pem . .Pp If a SIGHUP signal is sent to the daemon it will reload the .Dq CRLfile and will shut down any extant connections that presented certificates during TLS handshake that have been revoked. If the .Fl r option was not specified, the SIGHUP signal will be ignored. .Pp The daemon will log failed certificate verifications via .Xr syslogd 8 using LOG_INFO | LOG_DAEMON when the .Fl m option has been specified. .Pp The options are as follows: .Bl -tag -width indent .It Fl 2 , Fl Fl allowtls1_2 Permit clients to mount using TLS version 1.2. By default, the daemon will only allow mounts using TLS version 1.3, as required by the RFC. However, early .Fx .Pq 13.0 and 13.1 clients require this option, since they use TLS version 1.2. .It Fl C Ar available_ciphers , Fl Fl ciphers= Ns Ar available_ciphers Specify which ciphers are available during TLS handshake. If this option is specified, .Dq SSL_CTX_set_ciphersuites() will be called with .Dq available_ciphers as the argument. If this option is not specified, the cipher will be chosen by .Xr ssl 7 , which should be adequate for most cases. The format for the available ciphers is a simple .So : .Sc separated list, in order of preference. The command .Dq openssl ciphers -s -tls1_3 lists available ciphers. .It Fl D Ar certdir , Fl Fl certdir= Ns Ar certdir Use .Dq certdir instead of /etc/rpc.tlsservd as the location for the certificate in a file called .Dq cert.pem and associated key in .Dq certkey.pem . .It Fl d , Fl Fl debuglevel Run in debug mode. In this mode, .Nm will not fork when it starts. .It Fl h , Fl Fl checkhost This option specifies that the client must provide a certificate that both verifies and has a FQDN that matches the reverse DNS name for the IP address that the client uses to connect to the server. The FQDN should be in the DNS field of the subjectAltName, but is also allowed to be in the CN field of the subjectName in the certificate. By default, a wildcard "*" in the FQDN is not allowed. With this option, a failure to verify the client certificate or match the FQDN will result in the server sending AUTH_REJECTEDCRED replies to all client RPCs. This option requires the .Fl m and either the .Fl l or .Fl p options. .It Fl l Ar CAfile , Fl Fl verifylocs= Ns Ar CAfile This option specifies the path name of a CA certificate(s) file in pem format, which is used to verify client certificates and to set the list of CA(s) sent to the client so that it knows which certificate to send to the server during the TLS handshake. This path name is used in .Dq SSL_CTX_load_verify_locations(ctx,CAfile,NULL) and .Dq SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file(CAfile)) openssl library calls. Note that this is a path name for the file and is not assumed to be in .Dq certdir . Either this option or the .Fl p option must be specified when the .Fl m option is specified so that the daemon can verify the client's certificate. .It Fl m , Fl Fl mutualverf This option specifies that the server is to request a certificate from the client during the TLS handshake. It does not require that the client provide a certificate. It should be specified unless no client doing RPC over TLS is required to have a certificate. For NFS, either the .Xr exports 5 option .Fl tlscert or .Fl tlscertuser may be used to require a client to provide a certificate that verifies. See .Xr exports 5 . -.It Fl N Ar num_servers , Fl Fl numdaemons= Ns Ar num_servers +.It Fl N Ar max_threads , Fl Fl maxthreads= Ns Ar max_threads For a server with a large number of NFS-over-TLS client mounts, this daemon might get overloaded after a reboot, when many clients attempt to do a TLS handshake at the same time. -This option may be used to specify that -.Dq num_servers -daemons are to be run instead of a single daemon. -When this is done, the TLS handshakes are spread across the -.Dq num_servers -daemons in a round robin fashion to spread out the load. +To speed up recovery after reboot, the daemon always processes a TLS handshake +in a separate spawned thread. +By default the maximum number of concurrent threads (and thus +parallel handshakes) is limited to +.Va 1/2 +of available CPUs on a system. +This option may be used to override this default. .It Fl n Ar domain , Fl Fl domain= Ns Ar domain This option specifies what the .Dq domain is for use with the .Fl u option, overriding the domain taken from the .Xr gethostname 2 of the server this daemon is running on. If you have specified the .Fl domain command line option for .Xr nfsuserd 8 then you should specify this option with the same .Dq domain that was specified for .Xr nfsuserd 8 . This option is only meaningful when used with the .Fl u option. .It Fl p Ar CApath , Fl Fl verifydir= Ns Ar CApath This option is similar to the .Fl l option, but specifies the path of a directory with CA certificates in it. When this option is used, .Dq SSL_CTX_set_client_CA_list(ctx,SSL_load_client_CA_file()) is not called, so a list of CA names might not be passed to the client during the TLS handshake. .It Fl r Ar CRLfile , Fl Fl crl= Ns Ar CRLfile This option specifies a Certificate Revocation List (CRL) file that is to be loaded into the verify certificate store and checked during verification. This option is only meaningful when either the .Fl l or .Fl p have been specified. .It Fl u , Fl Fl certuser This option specifies that if the client provides a certificate that both verifies and has a subjectAltName with an otherName component of the form .Dq otherName:1.3.6.1.4.1.2238.1.1.1;UTF8:user@domain where .Dq domain matches the one for this server, then the daemon will attempt to map .Dq user in the above to a user credential . There should only be one of these otherName components for each .Dq domain . If .Dq user is a valid username in the password database, then the for .Dq user will be used for all RPCs on the mount instead of the credentials in the RPC request header. This option requires the .Fl m and either the .Fl l or .Fl p options. Use of this option might not conform to RFC-9289, which does not allow certificates to be used for user authentication. .It Fl v , Fl Fl verbose Run in verbose mode. In this mode, .Nm will log activity messages to .Xr syslogd 8 using LOG_INFO | LOG_DAEMON or to stderr, if the .Fl d option has also been specified. .It Fl W , Fl Fl multiwild This option is used with the .Fl h option to allow use of a wildcard .Dq * that matches multiple components of the reverse DNS name for the client's IP address. For example, the FQDN .Dq *.uoguelph.ca would match both .Dq laptop21.uoguelph.ca and .Dq laptop3.cis.uoguelph.ca . .It Fl w , Fl Fl singlewild Similar to .Fl W but allows the wildcard .Dq * to match a single component of the reverse DNS name. For example, the FQDN .Dq *.uoguelph.ca would match .Dq laptop21.uoguelph.ca but not .Dq laptop3.cis.uoguelph.ca . Only one of the .Fl W and .Fl w options is allowed. .El .Sh EXIT STATUS .Ex -std .Sh SEE ALSO .Xr openssl 1 , .Xr ktls 4 , .Xr exports 5 , .Xr ssl 7 , .Xr mount_nfs 8 , .Xr nfsuserd 8 , .Xr rpc.tlsclntd 8 , .Xr syslogd 8 .Sh STANDARDS The implementation is based on the specification in .Rs .%B "RFC 9289" .%T "Towards Remote Procedure Call Encryption By Default" .Re .Sh HISTORY The .Nm manual page first appeared in .Fx 13.0 . .Sh BUGS This daemon cannot be safely shut down and restarted if there are any active RPC-over-TLS connections. Doing so will orphan the KERNEL_TLS connections, so that they can no longer do upcalls successfully, since the .Dq SSL * structures in userspace have been lost. diff --git a/usr.sbin/rpc.tlsservd/rpc.tlsservd.c b/usr.sbin/rpc.tlsservd/rpc.tlsservd.c index df7e221f2488..61f8601c36f5 100644 --- a/usr.sbin/rpc.tlsservd/rpc.tlsservd.c +++ b/usr.sbin/rpc.tlsservd/rpc.tlsservd.c @@ -1,929 +1,966 @@ /*- * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2008 Isilon Inc http://www.isilon.com/ * Authors: Doug Rabson * Developed with Red Inc: Alfred Perlstein + * Copyright (c) 2025 Gleb Smirnoff * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Extensively modified from /usr/src/usr.sbin/gssd.c r344402 for * the server side of kernel RPC-over-TLS by Rick Macklem. */ -#include #include #include #include #include -#include #include #include -#include -#include +#include #include #include #include #include +#include #include -#include -#include -#include -#include #include -#include #include #include #include #include #include #include #include #include #include #include "rpctlssd.h" #include "rpc.tlscommon.h" #ifndef _PATH_CERTANDKEY #define _PATH_CERTANDKEY "/etc/rpc.tlsservd/" #endif #ifndef _PATH_RPCTLSSDPID #define _PATH_RPCTLSSDPID "/var/run/rpc.tlsservd.pid" #endif #ifndef _PREFERRED_CIPHERS #define _PREFERRED_CIPHERS "AES128-GCM-SHA256" #endif /* Global variables also used by rpc.tlscommon.c. */ int rpctls_debug_level; bool rpctls_verbose; SSL_CTX *rpctls_ctx = NULL; const char *rpctls_verify_cafile = NULL; const char *rpctls_verify_capath = NULL; char *rpctls_crlfile = NULL; bool rpctls_gothup = false; + +static SVCXPRT *xprt; +static pthread_key_t xidkey; struct ssl_list rpctls_ssllist; +static pthread_rwlock_t rpctls_rwlock; +static u_int rpctls_nthreads = 0; +static pthread_mutex_t rpctls_mtx; +static pthread_cond_t rpctls_cv; static struct pidfh *rpctls_pfh = NULL; static bool rpctls_do_mutual = false; static const char *rpctls_certdir = _PATH_CERTANDKEY; static bool rpctls_comparehost = false; static unsigned int rpctls_wildcard = X509_CHECK_FLAG_NO_WILDCARDS; static bool rpctls_cnuser = false; static char *rpctls_dnsname; static const char *rpctls_cnuseroid = "1.3.6.1.4.1.2238.1.1.1"; static const char *rpctls_ciphers = NULL; static int rpctls_mintls = TLS1_3_VERSION; -static int rpctls_procs = 1; -static pid_t rpctls_workers[RPCTLS_SRV_MAXNPROCS - 1]; -static bool rpctls_im_a_worker = false; +static u_int rpctls_maxthreads; static void rpctls_cleanup_term(int sig); static SSL_CTX *rpctls_setup_ssl(const char *certdir); static SSL *rpctls_server(SSL_CTX *ctx, int s, uint32_t *flags, uint32_t *uidp, int *ngrps, uint32_t *gidp, X509 **certp); static int rpctls_cnname(X509 *cert, uint32_t *uidp, int *ngrps, uint32_t *gidp); static char *rpctls_getdnsname(char *dnsname); static void rpctls_huphandler(int sig __unused); extern void rpctlssd_2(struct svc_req *rqstp, SVCXPRT *transp); +static void *dummy_thread(void *v __unused) { return (NULL); } + static struct option longopts[] = { { "allowtls1_2", no_argument, NULL, '2' }, { "ciphers", required_argument, NULL, 'C' }, { "certdir", required_argument, NULL, 'D' }, { "debuglevel", no_argument, NULL, 'd' }, { "checkhost", no_argument, NULL, 'h' }, { "verifylocs", required_argument, NULL, 'l' }, { "mutualverf", no_argument, NULL, 'm' }, - { "numdaemons", required_argument, NULL, 'N' }, + { "maxthreads", required_argument, NULL, 'N' }, { "domain", required_argument, NULL, 'n' }, { "verifydir", required_argument, NULL, 'p' }, { "crl", required_argument, NULL, 'r' }, { "certuser", no_argument, NULL, 'u' }, { "verbose", no_argument, NULL, 'v' }, { "multiwild", no_argument, NULL, 'W' }, { "singlewild", no_argument, NULL, 'w' }, { NULL, 0, NULL, 0 } }; int main(int argc, char **argv) { - int ch, i; - SVCXPRT *xprt; + int ch; char hostname[MAXHOSTNAMELEN + 2]; pid_t otherpid; + pthread_t tid; bool tls_enable; size_t tls_enable_len; - sigset_t signew; + u_int ncpu; /* Check that another rpctlssd isn't already running. */ rpctls_pfh = pidfile_open(_PATH_RPCTLSSDPID, 0600, &otherpid); if (rpctls_pfh == NULL) { if (errno == EEXIST) errx(1, "rpctlssd already running, pid: %d.", otherpid); warn("cannot open or create pidfile"); } /* Check to see that the ktls is enabled. */ tls_enable_len = sizeof(tls_enable); if (sysctlbyname("kern.ipc.tls.enable", &tls_enable, &tls_enable_len, NULL, 0) != 0 || !tls_enable) errx(1, "Kernel TLS not enabled"); /* Set the dns name for the server. */ rpctls_dnsname = rpctls_getdnsname(hostname); if (rpctls_dnsname == NULL) { strcpy(hostname, "@default.domain"); rpctls_dnsname = hostname; } rpctls_verbose = false; + rpctls_maxthreads = (ncpu = (u_int)sysconf(_SC_NPROCESSORS_ONLN)) / 2; + while ((ch = getopt_long(argc, argv, "2C:D:dhl:N:n:mp:r:uvWw", longopts, NULL)) != -1) { switch (ch) { case '2': rpctls_mintls = TLS1_2_VERSION; break; case 'C': rpctls_ciphers = optarg; break; case 'D': rpctls_certdir = optarg; break; case 'd': rpctls_debug_level++; break; case 'h': rpctls_comparehost = true; break; case 'l': rpctls_verify_cafile = optarg; break; case 'm': rpctls_do_mutual = true; break; case 'N': - rpctls_procs = atoi(optarg); - if (rpctls_procs < 1 || - rpctls_procs > RPCTLS_SRV_MAXNPROCS) - errx(1, "numdaemons/-N must be between 1 and " - "%d", RPCTLS_SRV_MAXNPROCS); + rpctls_maxthreads = atoi(optarg); + if (rpctls_maxthreads < 1 || rpctls_maxthreads > ncpu) + errx(1, "maximum threads must be between 1 and " + "number of CPUs (%d)", ncpu); break; case 'n': hostname[0] = '@'; strlcpy(&hostname[1], optarg, MAXHOSTNAMELEN + 1); rpctls_dnsname = hostname; break; case 'p': rpctls_verify_capath = optarg; break; case 'r': rpctls_crlfile = optarg; break; case 'u': rpctls_cnuser = true; break; case 'v': rpctls_verbose = true; break; case 'W': if (rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS) errx(1, "options -w and -W are mutually " "exclusive"); rpctls_wildcard = X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS; break; case 'w': if (rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS) errx(1, "options -w and -W are mutually " "exclusive"); rpctls_wildcard = 0; break; default: fprintf(stderr, "usage: %s " "[-2/--allowtls1_2] " "[-C/--ciphers available_ciphers] " "[-D/--certdir certdir] [-d/--debuglevel] " "[-h/--checkhost] " "[-l/--verifylocs CAfile] [-m/--mutualverf] " - "[-N/--numdaemons num] " "[-n/--domain domain_name] " "[-p/--verifydir CApath] [-r/--crl CRLfile] " "[-u/--certuser] [-v/--verbose] [-W/--multiwild] " "[-w/--singlewild]\n", argv[0]); exit(1); } } if (rpctls_do_mutual && rpctls_verify_cafile == NULL && rpctls_verify_capath == NULL) errx(1, "-m requires the -l and/or " "-p options"); if (rpctls_comparehost && (!rpctls_do_mutual || (rpctls_verify_cafile == NULL && rpctls_verify_capath == NULL))) errx(1, "-h requires the -m plus the " "-l and/or -p options"); if (!rpctls_comparehost && rpctls_wildcard != X509_CHECK_FLAG_NO_WILDCARDS) errx(1, "The -w or -W options require the -h option"); if (rpctls_cnuser && (!rpctls_do_mutual || (rpctls_verify_cafile == NULL && rpctls_verify_capath == NULL))) errx(1, "-u requires the -m plus the " "-l and/or -p options"); if (modfind("krpc") < 0) { /* Not present in kernel, try loading it */ if (kldload("krpc") < 0 || modfind("krpc") < 0) errx(1, "Kernel RPC is not available"); } - - for (i = 0; i < rpctls_procs - 1; i++) - rpctls_workers[i] = -1; - - if (rpctls_debug_level == 0) { - /* - * Temporarily block SIGTERM and SIGCHLD, so workers[] can't - * end up bogus. - */ - sigemptyset(&signew); - sigaddset(&signew, SIGTERM); - sigaddset(&signew, SIGCHLD); - sigprocmask(SIG_BLOCK, &signew, NULL); - - if (daemon(0, 0) != 0) - err(1, "Can't daemonize"); - signal(SIGINT, SIG_IGN); - signal(SIGQUIT, SIG_IGN); - } signal(SIGPIPE, SIG_IGN); signal(SIGHUP, rpctls_huphandler); signal(SIGTERM, rpctls_cleanup_term); - signal(SIGCHLD, rpctls_cleanup_term); + if (rpctls_debug_level == 0 && daemon(0, 0) != 0) + err(1, "Can't daemonize"); pidfile_write(rpctls_pfh); - if (rpctls_debug_level == 0) { - /* Fork off the worker daemons. */ - for (i = 0; i < rpctls_procs - 1; i++) { - rpctls_workers[i] = fork(); - if (rpctls_workers[i] == 0) { - rpctls_im_a_worker = true; - setproctitle("server"); - break; - } else if (rpctls_workers[i] < 0) { - syslog(LOG_ERR, "fork: %m"); - } - } - - if (!rpctls_im_a_worker && rpctls_procs > 1) - setproctitle("master"); - } - sigemptyset(&signew); - sigaddset(&signew, SIGTERM); - sigaddset(&signew, SIGCHLD); - sigprocmask(SIG_UNBLOCK, &signew, NULL); - + /* + * XXX: Push libc internal state into threaded mode before creating + * the threaded svc_nl xprt. + */ + (void)pthread_create(&tid, NULL, dummy_thread, NULL); + (void)pthread_join(tid, NULL); if ((xprt = svc_nl_create("tlsserv")) == NULL) { if (rpctls_debug_level == 0) { syslog(LOG_ERR, "Can't create transport for local rpctlssd socket"); exit(1); } err(1, "Can't create transport for local rpctlssd socket"); } + if (!SVC_CONTROL(xprt, SVCNL_GET_XIDKEY, &xidkey)) + err(1, "Failed to obtain pthread key for xid from svc_nl"); if (!svc_reg(xprt, RPCTLSSD, RPCTLSSDVERS, rpctlssd_2, NULL)) { if (rpctls_debug_level == 0) { syslog(LOG_ERR, "Can't register service for local rpctlssd socket"); exit(1); } err(1, "Can't register service for local rpctlssd socket"); } rpctls_ctx = rpctls_setup_ssl(rpctls_certdir); if (rpctls_ctx == NULL) { if (rpctls_debug_level == 0) { syslog(LOG_ERR, "Can't create SSL context"); exit(1); } err(1, "Can't create SSL context"); } rpctls_gothup = false; + pthread_rwlock_init(&rpctls_rwlock, NULL); + pthread_mutex_init(&rpctls_mtx, NULL); + pthread_cond_init(&rpctls_cv, NULL); LIST_INIT(&rpctls_ssllist); rpctls_svc_run(); SSL_CTX_free(rpctls_ctx); return (0); } bool_t rpctlssd_null_2_svc(__unused void *argp, __unused void *result, __unused struct svc_req *rqstp) { rpctls_verbose_out("rpctlssd_null_svc: done\n"); return (TRUE); } +/* + * To parallelize SSL handshakes we will launch a thread per handshake. Thread + * creation/destruction shall be order(s) of magnitude cheaper than a crypto + * handshake, so we are not keeping a pool of workers here. + * + * Marrying rpc(3) and pthread(3): + * + * Normally the rpcgen(1) generated rpctlssd_V() calls rpctlssd_connect_V_svc(), + * and the latter processes the RPC all the way to the end and returns a TRUE + * value and populates the result. The generated code immediately calls + * svc_sendreply() transmitting the result back. + * + * We will make a private copy of arguments and return FALSE. Then it is our + * obligation to call svc_sendreply() once we do the work in the thread. + */ + +static void * rpctlssd_connect_thread(void *); +struct rpctlssd_connect_thread_ctx { + struct rpctlssd_connect_arg arg; + uint32_t xid; +}; + bool_t rpctlssd_connect_2_svc(struct rpctlssd_connect_arg *argp, - struct rpctlssd_connect_res *result, __unused struct svc_req *rqstp) + struct rpctlssd_connect_res *result __unused, struct svc_req *rqstp) { + struct rpctlssd_connect_thread_ctx *ctx; + pthread_t tid; + + assert(rqstp->rq_xprt == xprt); + + ctx = malloc(sizeof(*ctx)); + memcpy(&ctx->arg, argp, sizeof(ctx->arg)); + ctx->xid = *(uint32_t *)pthread_getspecific(xidkey); + + pthread_mutex_lock(&rpctls_mtx); + while (rpctls_nthreads >= rpctls_maxthreads) + pthread_cond_wait(&rpctls_cv, &rpctls_mtx); + rpctls_nthreads++; + pthread_mutex_unlock(&rpctls_mtx); + + rpctls_verbose_out("rpctlsd_connect_svc: xid %u thread %u\n", + ctx->xid, rpctls_nthreads); + + if (pthread_create(&tid, NULL, rpctlssd_connect_thread, ctx) != 0) + warn("failed to start handshake thread"); + + /* Intentionally, so that RPC generated code doesn't try to reply. */ + return (FALSE); +} + +static void * +rpctlssd_connect_thread(void *v) +{ + struct rpctlssd_connect_thread_ctx *ctx = v; + struct rpctlssd_connect_res result; + uint64_t socookie; int ngrps, s; SSL *ssl; uint32_t flags; struct ssl_entry *newslp; - uint32_t uid; + uint32_t xid, uid; uint32_t *gidp; X509 *cert; - rpctls_verbose_out("rpctlsd_connect_svc: started\n"); - memset(result, 0, sizeof(*result)); + socookie = ctx->arg.socookie; + xid = ctx->xid; + free(ctx); + ctx = NULL; + pthread_detach(pthread_self()); + + if (pthread_setspecific(xidkey, &xid) != 0) { + rpctls_verbose_out("rpctlssd_connect_svc: pthread_setspecific " + "failed\n"); + goto out; + } + /* Get the socket fd from the kernel. */ - s = rpctls_syscall(RPCTLS_SYSC_SRVSOCKET, (char *)argp->socookie); - if (s < 0) - return (FALSE); + s = rpctls_syscall(RPCTLS_SYSC_SRVSOCKET, (char *)socookie); + if (s < 0) { + rpctls_verbose_out("rpctlssd_connect_svc: rpctls_syscall " + "accept failed\n"); + goto out; + } /* Do the server side of a TLS handshake. */ gidp = calloc(NGROUPS, sizeof(*gidp)); ssl = rpctls_server(rpctls_ctx, s, &flags, &uid, &ngrps, gidp, &cert); if (ssl == NULL) { free(gidp); rpctls_verbose_out("rpctlssd_connect_svc: ssl " "accept failed\n"); /* * For RPC-over-TLS, this upcall is expected * to close off the socket upon handshake failure. */ close(s); - return (FALSE); + goto out; } else { rpctls_verbose_out("rpctlssd_connect_svc: " "succeeded flags=0x%x\n", flags); - result->flags = flags; - if ((flags & RPCTLS_FLAGS_CERTUSER) != 0) { - result->uid = uid; - result->gid.gid_len = ngrps; - result->gid.gid_val = gidp; - } else { - result->uid = 0; - result->gid.gid_len = 0; - result->gid.gid_val = gidp; - } + if ((flags & RPCTLS_FLAGS_CERTUSER) != 0) + result = (struct rpctlssd_connect_res){ + .flags = flags, + .uid = uid, + .gid.gid_len = ngrps, + .gid.gid_val = gidp, + }; + else + result = (struct rpctlssd_connect_res){ + .flags = flags, + .uid = 0, + .gid.gid_len = 0, + .gid.gid_val = gidp, + }; } /* Maintain list of all current SSL *'s */ newslp = malloc(sizeof(*newslp)); newslp->ssl = ssl; newslp->s = s; newslp->shutoff = false; - newslp->cookie = argp->socookie; + newslp->cookie = socookie; newslp->cert = cert; + pthread_rwlock_wrlock(&rpctls_rwlock); LIST_INSERT_HEAD(&rpctls_ssllist, newslp, next); - return (TRUE); + pthread_rwlock_unlock(&rpctls_rwlock); + + if (!svc_sendreply(xprt, (xdrproc_t)xdr_rpctlssd_connect_res, &result)) + svcerr_systemerr(xprt); + + free(result.gid.gid_val); + rpctls_verbose_out("rpctlsd_connect_svc: xid %u: thread finished\n", + xid); + +out: + pthread_mutex_lock(&rpctls_mtx); + if (rpctls_nthreads-- >= rpctls_maxthreads) { + pthread_mutex_unlock(&rpctls_mtx); + pthread_cond_signal(&rpctls_cv); + } else + pthread_mutex_unlock(&rpctls_mtx); + return (NULL); } bool_t rpctlssd_handlerecord_2_svc(struct rpctlssd_handlerecord_arg *argp, struct rpctlssd_handlerecord_res *result, __unused struct svc_req *rqstp) { struct ssl_entry *slp; int ret; char junk; + pthread_rwlock_rdlock(&rpctls_rwlock); LIST_FOREACH(slp, &rpctls_ssllist, next) if (slp->cookie == argp->socookie) break; + pthread_rwlock_unlock(&rpctls_rwlock); if (slp != NULL) { rpctls_verbose_out("rpctlssd_handlerecord fd=%d\n", slp->s); /* * An SSL_read() of 0 bytes should fail, but it should * handle the non-application data record before doing so. */ ret = SSL_read(slp->ssl, &junk, 0); if (ret <= 0) { /* Check to see if this was a close alert. */ ret = SSL_get_shutdown(slp->ssl); if ((ret & (SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN)) == SSL_RECEIVED_SHUTDOWN) SSL_shutdown(slp->ssl); } else { if (rpctls_debug_level == 0) syslog(LOG_ERR, "SSL_read returned %d", ret); else fprintf(stderr, "SSL_read returned %d\n", ret); } result->reterr = RPCTLSERR_OK; } else result->reterr = RPCTLSERR_NOSSL; return (TRUE); } bool_t rpctlssd_disconnect_2_svc(struct rpctlssd_disconnect_arg *argp, struct rpctlssd_disconnect_res *result, __unused struct svc_req *rqstp) { struct ssl_entry *slp; int ret; + pthread_rwlock_wrlock(&rpctls_rwlock); LIST_FOREACH(slp, &rpctls_ssllist, next) - if (slp->cookie == argp->socookie) + if (slp->cookie == argp->socookie) { + LIST_REMOVE(slp, next); break; + } + pthread_rwlock_unlock(&rpctls_rwlock); if (slp != NULL) { rpctls_verbose_out("rpctlssd_disconnect fd=%d closed\n", slp->s); - LIST_REMOVE(slp, next); if (!slp->shutoff) { ret = SSL_get_shutdown(slp->ssl); /* * Do an SSL_shutdown() unless a close alert has * already been sent. */ if ((ret & SSL_SENT_SHUTDOWN) == 0) SSL_shutdown(slp->ssl); } SSL_free(slp->ssl); if (slp->cert != NULL) X509_free(slp->cert); /* * For RPC-over-TLS, this upcall is expected * to close off the socket. */ if (!slp->shutoff) shutdown(slp->s, SHUT_WR); close(slp->s); free(slp); result->reterr = RPCTLSERR_OK; } else result->reterr = RPCTLSERR_NOCLOSE; return (TRUE); } int -rpctlssd_2_freeresult(__unused SVCXPRT *transp, xdrproc_t xdr_result, - caddr_t result) +rpctlssd_2_freeresult(__unused SVCXPRT *transp, xdrproc_t xdr_result __unused, + caddr_t result __unused) { - rpctlssd_connect_res *res; - - if (xdr_result == (xdrproc_t)xdr_rpctlssd_connect_res) { - res = (rpctlssd_connect_res *)(void *)result; - free(res->gid.gid_val); - } return (TRUE); } /* * cleanup_term() called via SIGTERM (or SIGCHLD if a child dies). */ static void -rpctls_cleanup_term(int sig) +rpctls_cleanup_term(int sig __unused) { struct ssl_entry *slp; - int i, cnt; - if (rpctls_im_a_worker && sig == SIGCHLD) - return; LIST_FOREACH(slp, &rpctls_ssllist, next) shutdown(slp->s, SHUT_RD); SSL_CTX_free(rpctls_ctx); EVP_cleanup(); - - if (rpctls_im_a_worker) - exit(0); - - /* I'm the server, so terminate the workers. */ - cnt = 0; - for (i = 0; i < rpctls_procs - 1; i++) { - if (rpctls_workers[i] != -1) { - cnt++; - kill(rpctls_workers[i], SIGTERM); - } - } - - /* - * Wait for them to die. - */ - for (i = 0; i < cnt; i++) - wait3(NULL, 0, NULL); - pidfile_remove(rpctls_pfh); exit(0); } /* Allow the handshake to proceed. */ static int rpctls_verify_callback(__unused int preverify_ok, __unused X509_STORE_CTX *x509_ctx) { return (1); } static SSL_CTX * rpctls_setup_ssl(const char *certdir) { SSL_CTX *ctx; char path[PATH_MAX]; size_t len, rlen; int ret; ctx = SSL_CTX_new(TLS_server_method()); if (ctx == NULL) { rpctls_verbose_out("rpctls_setup_ssl: SSL_CTX_new failed\n"); return (NULL); } if (rpctls_ciphers != NULL) { /* * Set available ciphers, since KERN_TLS only supports a * few of them. Normally, not doing this should be ok, * since the library defaults will work. */ ret = SSL_CTX_set_ciphersuites(ctx, rpctls_ciphers); if (ret == 0) { rpctls_verbose_out("rpctls_setup_ssl: " "SSL_CTX_set_ciphersuites failed: %s\n", rpctls_ciphers); SSL_CTX_free(ctx); return (NULL); } } ret = SSL_CTX_set_min_proto_version(ctx, rpctls_mintls); if (ret == 0) { rpctls_verbose_out("rpctls_setup_ssl: " "SSL_CTX_set_min_proto_version failed\n"); SSL_CTX_free(ctx); return (NULL); } ret = SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION); if (ret == 0) { rpctls_verbose_out("rpctls_setup_ssl: " "SSL_CTX_set_max_proto_version failed\n"); SSL_CTX_free(ctx); return (NULL); } /* Get the cert.pem and certkey.pem files from the directory certdir. */ len = strlcpy(path, certdir, sizeof(path)); rlen = sizeof(path) - len; if (strlcpy(&path[len], "cert.pem", rlen) != 8) { SSL_CTX_free(ctx); return (NULL); } ret = SSL_CTX_use_certificate_file(ctx, path, SSL_FILETYPE_PEM); if (ret != 1) { rpctls_verbose_out("rpctls_setup_ssl: can't use certificate " "file path=%s ret=%d\n", path, ret); SSL_CTX_free(ctx); return (NULL); } if (strlcpy(&path[len], "certkey.pem", rlen) != 11) { SSL_CTX_free(ctx); return (NULL); } ret = SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM); if (ret != 1) { rpctls_verbose_out("rpctls_setup_ssl: Can't use private " "key path=%s ret=%d\n", path, ret); SSL_CTX_free(ctx); return (NULL); } /* Set Mutual authentication, as required. */ if (rpctls_do_mutual) { if (rpctls_verify_cafile != NULL || rpctls_verify_capath != NULL) { if (rpctls_crlfile != NULL) { ret = rpctls_loadcrlfile(ctx); if (ret == 0) { rpctls_verbose_out("rpctls_setup_ssl:" " Load CRLfile failed\n"); SSL_CTX_free(ctx); return (NULL); } } #if OPENSSL_VERSION_NUMBER >= 0x30000000 ret = 1; if (rpctls_verify_cafile != NULL) ret = SSL_CTX_load_verify_file(ctx, rpctls_verify_cafile); if (ret != 0 && rpctls_verify_capath != NULL) ret = SSL_CTX_load_verify_dir(ctx, rpctls_verify_capath); #else ret = SSL_CTX_load_verify_locations(ctx, rpctls_verify_cafile, rpctls_verify_capath); #endif if (ret == 0) { rpctls_verbose_out("rpctls_setup_ssl: " "Can't load verify locations\n"); SSL_CTX_free(ctx); return (NULL); } if (rpctls_verify_cafile != NULL) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file( rpctls_verify_cafile)); } SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, rpctls_verify_callback); } #ifdef SSL_OP_ENABLE_KTLS SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS); #endif #ifdef SSL_MODE_NO_KTLS_TX SSL_CTX_clear_mode(ctx, SSL_MODE_NO_KTLS_TX | SSL_MODE_NO_KTLS_RX); #endif return (ctx); } static SSL * rpctls_server(SSL_CTX *ctx, int s, uint32_t *flags, uint32_t *uidp, int *ngrps, uint32_t *gidp, X509 **certp) { SSL *ssl; X509 *cert; struct sockaddr *sad; struct sockaddr_storage ad; char hostnam[NI_MAXHOST]; int gethostret, ret; char *cp, *cp2; long verfret; *flags = 0; *certp = NULL; sad = (struct sockaddr *)&ad; ssl = SSL_new(ctx); if (ssl == NULL) { rpctls_verbose_out("rpctls_server: SSL_new failed\n"); return (NULL); } if (SSL_set_fd(ssl, s) != 1) { rpctls_verbose_out("rpctls_server: SSL_set_fd failed\n"); SSL_free(ssl); return (NULL); } ret = SSL_accept(ssl); if (ret != 1) { rpctls_verbose_out("rpctls_server: SSL_accept " "failed ret=%d\n", ret); SSL_free(ssl); return (NULL); } *flags |= RPCTLS_FLAGS_HANDSHAKE; if (rpctls_verbose) { gethostret = rpctls_gethost(s, sad, hostnam, sizeof(hostnam)); if (gethostret == 0) hostnam[0] = '\0'; rpctls_verbose_out("rpctls_server: SSL handshake ok for host %s" " <%s %s>\n", hostnam, SSL_get_version(ssl), SSL_get_cipher(ssl)); } if (rpctls_do_mutual) { #if OPENSSL_VERSION_NUMBER >= 0x30000000 cert = SSL_get1_peer_certificate(ssl); #else cert = SSL_get_peer_certificate(ssl); #endif if (cert != NULL) { if (!rpctls_verbose) { gethostret = rpctls_gethost(s, sad, hostnam, sizeof(hostnam)); if (gethostret == 0) hostnam[0] = '\0'; } cp2 = X509_NAME_oneline( X509_get_subject_name(cert), NULL, 0); *flags |= RPCTLS_FLAGS_GOTCERT; verfret = SSL_get_verify_result(ssl); if (verfret != X509_V_OK) { cp = X509_NAME_oneline( X509_get_issuer_name(cert), NULL, 0); if (rpctls_debug_level == 0) syslog(LOG_INFO | LOG_DAEMON, "rpctls_server: client IP %s " "issuerName=%s subjectName=%s" " verify failed %s\n", hostnam, cp, cp2, X509_verify_cert_error_string( verfret)); else fprintf(stderr, "rpctls_server: client IP %s " "issuerName=%s subjectName=%s" " verify failed %s\n", hostnam, cp, cp2, X509_verify_cert_error_string( verfret)); } if (verfret == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT || verfret == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) *flags |= RPCTLS_FLAGS_SELFSIGNED; else if (verfret == X509_V_OK) { if (rpctls_comparehost) { ret = 0; if (gethostret != 0) ret = rpctls_checkhost(sad, cert, rpctls_wildcard); if (ret != 1) { *flags |= RPCTLS_FLAGS_DISABLED; rpctls_verbose_out( "rpctls_server: " "checkhost " "failed\n"); } } if (rpctls_cnuser) { ret = rpctls_cnname(cert, uidp, ngrps, gidp); if (ret != 0) *flags |= RPCTLS_FLAGS_CERTUSER; } *flags |= RPCTLS_FLAGS_VERIFIED; *certp = cert; cert = NULL; } if (cert != NULL) X509_free(cert); } else rpctls_verbose_out("rpctls_server: " "No peer certificate\n"); } /* Check to see that ktls is working for the connection. */ ret = BIO_get_ktls_send(SSL_get_wbio(ssl)); rpctls_verbose_out("rpctls_server: BIO_get_ktls_send=%d\n", ret); if (ret != 0) { ret = BIO_get_ktls_recv(SSL_get_rbio(ssl)); rpctls_verbose_out("rpctls_server: BIO_get_ktls_recv=%d\n", ret); } if (ret == 0) { if (rpctls_debug_level == 0) syslog(LOG_ERR, "ktls not working"); else fprintf(stderr, "ktls not working\n"); /* * The handshake has completed, so all that can be * done is disable the connection. */ *flags |= RPCTLS_FLAGS_DISABLED; } return (ssl); } /* * Acquire the dnsname for this server. */ static char * rpctls_getdnsname(char *hostname) { char *cp, *dnsname; struct addrinfo *aip, hints; int error; dnsname = NULL; if (gethostname(hostname, MAXHOSTNAMELEN) == 0) { if ((cp = strchr(hostname, '.')) != NULL && *(cp + 1) != '\0') { *cp = '@'; dnsname = cp; } else { memset((void *)&hints, 0, sizeof (hints)); hints.ai_flags = AI_CANONNAME; error = getaddrinfo(hostname, NULL, &hints, &aip); if (error == 0) { if (aip->ai_canonname != NULL && (cp = strchr(aip->ai_canonname, '.')) != NULL && *(cp + 1) != '\0') { hostname[0] = '@'; strlcpy(&hostname[1], cp + 1, MAXHOSTNAMELEN + 1); dnsname = hostname; } freeaddrinfo(aip); } } } return (dnsname); } /* * Check for an otherName component of subjectAltName where the OID * matches and the "domain" matches that of this server. * If found, map "user" to a for it. */ static int rpctls_cnname(X509 *cert, uint32_t *uidp, int *ngrps, uint32_t *gidp) { char *cp, usern[1024 + 1]; struct passwd *pwd; gid_t gids[NGROUPS]; int i, j; GENERAL_NAMES *genlist; GENERAL_NAME *genname; OTHERNAME *val; size_t slen; /* First, find the otherName in the subjectAltName. */ genlist = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL); if (genlist == NULL) return (0); cp = NULL; for (i = 0; i < sk_GENERAL_NAME_num(genlist); i++) { genname = sk_GENERAL_NAME_value(genlist, i); if (genname->type != GEN_OTHERNAME) continue; val = genname->d.otherName; /* Check to see that it is the correct OID. */ slen = i2t_ASN1_OBJECT(usern, sizeof(usern), val->type_id); if (slen != strlen(rpctls_cnuseroid) || memcmp(usern, rpctls_cnuseroid, slen) != 0) continue; /* Sanity check the otherName. */ if (val->value->type != V_ASN1_UTF8STRING || val->value->value.utf8string->length < 3 || (size_t)val->value->value.utf8string->length > sizeof(usern) - 1) { rpctls_verbose_out("rpctls_cnname: invalid cnuser " "type=%d\n", val->value->type); continue; } /* Look for a "user" in the otherName */ memcpy(usern, val->value->value.utf8string->data, val->value->value.utf8string->length); usern[val->value->value.utf8string->length] = '\0'; /* Now, look for the @dnsname suffix in the commonName. */ cp = strcasestr(usern, rpctls_dnsname); if (cp == NULL) continue; if (*(cp + strlen(rpctls_dnsname)) != '\0') { cp = NULL; continue; } *cp = '\0'; break; } if (cp == NULL) return (0); /* See if the "user" is in the passwd database. */ pwd = getpwnam(usern); if (pwd == NULL) return (0); *uidp = pwd->pw_uid; *ngrps = NGROUPS; if (getgrouplist(pwd->pw_name, pwd->pw_gid, gids, ngrps) < 0) return (0); rpctls_verbose_out("mapped user=%s ngrps=%d uid=%d\n", pwd->pw_name, *ngrps, pwd->pw_uid); for (j = 0; j < *ngrps; j++) gidp[j] = gids[j]; return (1); } static void rpctls_huphandler(int sig __unused) { rpctls_gothup = true; }