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 client 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/queue.h>
41 #include <sys/linker.h>
42 #include <sys/module.h>
44 #include <sys/sysctl.h>
45 #include <sys/syslog.h>
60 #include <rpc/rpc_com.h>
61 #include <rpc/rpcsec_tls.h>
63 #include <openssl/opensslconf.h>
64 #include <openssl/bio.h>
65 #include <openssl/ssl.h>
66 #include <openssl/err.h>
67 #include <openssl/x509v3.h>
70 #include "rpc.tlscommon.h"
72 #ifndef _PATH_RPCTLSCDSOCK
73 #define _PATH_RPCTLSCDSOCK "/var/run/rpc.tlsclntd.sock"
75 #ifndef _PATH_CERTANDKEY
76 #define _PATH_CERTANDKEY "/etc/rpc.tlsclntd/"
78 #ifndef _PATH_RPCTLSCDPID
79 #define _PATH_RPCTLSCDPID "/var/run/rpc.tlsclntd.pid"
82 /* Global variables also used by rpc.tlscommon.c. */
83 int rpctls_debug_level;
85 SSL_CTX *rpctls_ctx = NULL;
86 const char *rpctls_verify_cafile = NULL;
87 const char *rpctls_verify_capath = NULL;
88 char *rpctls_crlfile = NULL;
89 bool rpctls_cert = false;
90 bool rpctls_gothup = false;
91 struct ssl_list rpctls_ssllist;
93 static struct pidfh *rpctls_pfh = NULL;
94 static const char *rpctls_certdir = _PATH_CERTANDKEY;
95 static const char *rpctls_ciphers = NULL;
96 static uint64_t rpctls_ssl_refno = 0;
97 static uint64_t rpctls_ssl_sec = 0;
98 static uint64_t rpctls_ssl_usec = 0;
100 static void rpctlscd_terminate(int);
101 static SSL_CTX *rpctls_setupcl_ssl(void);
102 static SSL *rpctls_connect(SSL_CTX *ctx, int s, char *certname,
103 u_int certlen, X509 **certp);
104 static void rpctls_huphandler(int sig __unused);
106 extern void rpctlscd_1(struct svc_req *rqstp, SVCXPRT *transp);
108 static struct option longopts[] = {
109 { "certdir", required_argument, NULL, 'D' },
110 { "ciphers", required_argument, NULL, 'C' },
111 { "debuglevel", no_argument, NULL, 'd' },
112 { "verifylocs", required_argument, NULL, 'l' },
113 { "mutualverf", no_argument, NULL, 'm' },
114 { "verifydir", required_argument, NULL, 'p' },
115 { "crl", required_argument, NULL, 'r' },
116 { "verbose", no_argument, NULL, 'v' },
121 main(int argc, char **argv)
124 * We provide an RPC service on a local-domain socket. The
125 * kernel rpctls code will upcall to this daemon to do the initial
128 struct sockaddr_un sun;
135 size_t tls_enable_len;
137 /* Check that another rpctlscd isn't already running. */
138 rpctls_pfh = pidfile_open(_PATH_RPCTLSCDPID, 0600, &otherpid);
139 if (rpctls_pfh == NULL) {
141 errx(1, "rpctlscd already running, pid: %d.", otherpid);
142 warn("cannot open or create pidfile");
145 /* Check to see that the ktls is enabled. */
146 tls_enable_len = sizeof(tls_enable);
147 if (sysctlbyname("kern.ipc.tls.enable", &tls_enable, &tls_enable_len,
148 NULL, 0) != 0 || !tls_enable)
149 errx(1, "Kernel TLS not enabled");
151 /* Get the time when this daemon is started. */
152 gettimeofday(&tm, &tz);
153 rpctls_ssl_sec = tm.tv_sec;
154 rpctls_ssl_usec = tm.tv_usec;
156 rpctls_verbose = false;
157 while ((ch = getopt_long(argc, argv, "CD:dl:mp:r:v", longopts, NULL)) !=
161 rpctls_ciphers = optarg;
164 rpctls_certdir = optarg;
167 rpctls_debug_level++;
170 rpctls_verify_cafile = optarg;
176 rpctls_verify_capath = optarg;
179 rpctls_crlfile = optarg;
182 rpctls_verbose = true;
185 fprintf(stderr, "usage: %s "
186 "[-C/--ciphers preferred_ciphers] "
187 "[-D/--certdir certdir] [-d/--debuglevel] "
188 "[-l/--verifylocs CAfile] [-m/--mutualverf] "
189 "[-p/--verifydir CApath] [-r/--crl CRLfile] "
190 "[-v/--verbose]\n", argv[0]);
195 if (rpctls_crlfile != NULL && rpctls_verify_cafile == NULL &&
196 rpctls_verify_capath == NULL)
197 errx(1, "-r requires the -l <CAfile> and/or "
198 "-p <CApath> options");
200 if (modfind("krpc") < 0) {
201 /* Not present in kernel, try loading it */
202 if (kldload("krpc") < 0 || modfind("krpc") < 0)
203 errx(1, "Kernel RPC is not available");
207 * Set up the SSL_CTX *.
208 * Do it now, before daemonizing, in case the private key
209 * is encrypted and requires a passphrase to be entered.
211 rpctls_ctx = rpctls_setupcl_ssl();
212 if (rpctls_ctx == NULL) {
213 if (rpctls_debug_level == 0) {
214 syslog(LOG_ERR, "Can't set up TLS context");
217 err(1, "Can't set up TLS context");
219 LIST_INIT(&rpctls_ssllist);
221 if (!rpctls_debug_level) {
222 if (daemon(0, 0) != 0)
223 err(1, "Can't daemonize");
224 signal(SIGINT, SIG_IGN);
225 signal(SIGQUIT, SIG_IGN);
226 signal(SIGHUP, SIG_IGN);
228 signal(SIGTERM, rpctlscd_terminate);
229 signal(SIGPIPE, SIG_IGN);
230 signal(SIGHUP, rpctls_huphandler);
232 pidfile_write(rpctls_pfh);
234 memset(&sun, 0, sizeof sun);
235 sun.sun_family = AF_LOCAL;
236 unlink(_PATH_RPCTLSCDSOCK);
237 strcpy(sun.sun_path, _PATH_RPCTLSCDSOCK);
238 sun.sun_len = SUN_LEN(&sun);
239 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
241 if (rpctls_debug_level == 0) {
242 syslog(LOG_ERR, "Can't create local rpctlscd socket");
245 err(1, "Can't create local rpctlscd socket");
247 oldmask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
248 if (bind(fd, (struct sockaddr *)&sun, sun.sun_len) < 0) {
249 if (rpctls_debug_level == 0) {
250 syslog(LOG_ERR, "Can't bind local rpctlscd socket");
253 err(1, "Can't bind local rpctlscd socket");
256 if (listen(fd, SOMAXCONN) < 0) {
257 if (rpctls_debug_level == 0) {
259 "Can't listen on local rpctlscd socket");
262 err(1, "Can't listen on local rpctlscd socket");
264 xprt = svc_vc_create(fd, RPC_MAXDATASIZE, RPC_MAXDATASIZE);
266 if (rpctls_debug_level == 0) {
268 "Can't create transport for local rpctlscd socket");
271 err(1, "Can't create transport for local rpctlscd socket");
273 if (!svc_reg(xprt, RPCTLSCD, RPCTLSCDVERS, rpctlscd_1, NULL)) {
274 if (rpctls_debug_level == 0) {
276 "Can't register service for local rpctlscd socket");
279 err(1, "Can't register service for local rpctlscd socket");
282 rpctls_syscall(RPCTLS_SYSC_CLSETPATH, _PATH_RPCTLSCDSOCK);
286 rpctls_syscall(RPCTLS_SYSC_CLSHUTDOWN, "");
288 SSL_CTX_free(rpctls_ctx);
294 rpctlscd_null_1_svc(__unused void *argp, __unused void *result,
295 __unused struct svc_req *rqstp)
298 rpctls_verbose_out("rpctlscd_null: done\n");
303 rpctlscd_connect_1_svc(struct rpctlscd_connect_arg *argp,
304 struct rpctlscd_connect_res *result, __unused struct svc_req *rqstp)
308 struct ssl_entry *newslp;
311 rpctls_verbose_out("rpctlsd_connect: started\n");
312 /* Get the socket fd from the kernel. */
313 s = rpctls_syscall(RPCTLS_SYSC_CLSOCKET, "");
315 result->reterr = RPCTLSERR_NOSOCKET;
319 /* Do a TLS connect handshake. */
320 ssl = rpctls_connect(rpctls_ctx, s, argp->certname.certname_val,
321 argp->certname.certname_len, &cert);
323 rpctls_verbose_out("rpctlsd_connect: can't do TLS "
325 result->reterr = RPCTLSERR_NOSSL;
327 result->reterr = RPCTLSERR_OK;
328 result->sec = rpctls_ssl_sec;
329 result->usec = rpctls_ssl_usec;
330 result->ssl = ++rpctls_ssl_refno;
331 /* Hard to believe this will ever wrap around.. */
332 if (rpctls_ssl_refno == 0)
333 result->ssl = ++rpctls_ssl_refno;
338 * For RPC-over-TLS, this upcall is expected
339 * to close off the socket.
345 /* Maintain list of all current SSL *'s */
346 newslp = malloc(sizeof(*newslp));
347 newslp->refno = rpctls_ssl_refno;
349 newslp->shutoff = false;
352 LIST_INSERT_HEAD(&rpctls_ssllist, newslp, next);
357 rpctlscd_handlerecord_1_svc(struct rpctlscd_handlerecord_arg *argp,
358 struct rpctlscd_handlerecord_res *result, __unused struct svc_req *rqstp)
360 struct ssl_entry *slp;
365 if (argp->sec == rpctls_ssl_sec && argp->usec ==
367 LIST_FOREACH(slp, &rpctls_ssllist, next) {
368 if (slp->refno == argp->ssl)
374 rpctls_verbose_out("rpctlscd_handlerecord fd=%d\n",
377 * An SSL_read() of 0 bytes should fail, but it should
378 * handle the non-application data record before doing so.
380 ret = SSL_read(slp->ssl, &junk, 0);
382 /* Check to see if this was a close alert. */
383 ret = SSL_get_shutdown(slp->ssl);
384 if ((ret & (SSL_SENT_SHUTDOWN |
385 SSL_RECEIVED_SHUTDOWN)) == SSL_RECEIVED_SHUTDOWN)
386 SSL_shutdown(slp->ssl);
388 if (rpctls_debug_level == 0)
389 syslog(LOG_ERR, "SSL_read returned %d", ret);
391 fprintf(stderr, "SSL_read returned %d\n", ret);
393 result->reterr = RPCTLSERR_OK;
395 result->reterr = RPCTLSERR_NOSSL;
400 rpctlscd_disconnect_1_svc(struct rpctlscd_disconnect_arg *argp,
401 struct rpctlscd_disconnect_res *result, __unused struct svc_req *rqstp)
403 struct ssl_entry *slp;
407 if (argp->sec == rpctls_ssl_sec && argp->usec ==
409 LIST_FOREACH(slp, &rpctls_ssllist, next) {
410 if (slp->refno == argp->ssl)
416 rpctls_verbose_out("rpctlscd_disconnect: fd=%d closed\n",
418 LIST_REMOVE(slp, next);
420 ret = SSL_get_shutdown(slp->ssl);
422 * Do an SSL_shutdown() unless a close alert has
425 if ((ret & SSL_SENT_SHUTDOWN) == 0)
426 SSL_shutdown(slp->ssl);
429 if (slp->cert != NULL)
430 X509_free(slp->cert);
432 * For RPC-over-TLS, this upcall is expected
433 * to close off the socket.
436 shutdown(slp->s, SHUT_WR);
439 result->reterr = RPCTLSERR_OK;
441 result->reterr = RPCTLSERR_NOCLOSE;
446 rpctlscd_1_freeresult(__unused SVCXPRT *transp, __unused xdrproc_t xdr_result,
447 __unused caddr_t result)
454 rpctlscd_terminate(int sig __unused)
457 rpctls_syscall(RPCTLS_SYSC_CLSHUTDOWN, "");
458 pidfile_remove(rpctls_pfh);
463 rpctls_setupcl_ssl(void)
472 SSL_load_error_strings();
473 OpenSSL_add_all_algorithms();
475 ctx = SSL_CTX_new(TLS_client_method());
477 rpctls_verbose_out("rpctls_setupcl_ssl: SSL_CTX_new "
481 SSL_CTX_set_ecdh_auto(ctx, 1);
483 if (rpctls_ciphers != NULL) {
485 * Set preferred ciphers, since KERN_TLS only supports a
488 ret = SSL_CTX_set_cipher_list(ctx, rpctls_ciphers);
490 rpctls_verbose_out("rpctls_setupcl_ssl: "
491 "SSL_CTX_set_cipher_list failed: %s\n",
499 * If rpctls_cert is true, a certificate and key exists in
500 * rpctls_certdir, so that it can do mutual authentication.
503 /* Get the cert.pem and certkey.pem files. */
504 len = strlcpy(path, rpctls_certdir, sizeof(path));
505 rlen = sizeof(path) - len;
506 if (strlcpy(&path[len], "cert.pem", rlen) != 8) {
510 ret = SSL_CTX_use_certificate_file(ctx, path,
513 rpctls_verbose_out("rpctls_setupcl_ssl: can't use "
514 "certificate file path=%s ret=%d\n", path, ret);
518 if (strlcpy(&path[len], "certkey.pem", rlen) != 11) {
522 ret = SSL_CTX_use_PrivateKey_file(ctx, path,
525 rpctls_verbose_out("rpctls_setupcl_ssl: Can't use "
526 "private key path=%s ret=%d\n", path, ret);
532 if (rpctls_verify_cafile != NULL || rpctls_verify_capath != NULL) {
533 if (rpctls_crlfile != NULL) {
534 ret = rpctls_loadcrlfile(ctx);
536 rpctls_verbose_out("rpctls_setupcl_ssl: "
537 "Load CRLfile failed\n");
542 #if OPENSSL_VERSION_NUMBER >= 0x30000000
544 if (rpctls_verify_cafile != NULL)
545 ret = SSL_CTX_load_verify_file(ctx,
546 rpctls_verify_cafile);
547 if (ret != 0 && rpctls_verify_capath != NULL)
548 ret = SSL_CTX_load_verify_dir(ctx,
549 rpctls_verify_capath);
551 ret = SSL_CTX_load_verify_locations(ctx,
552 rpctls_verify_cafile, rpctls_verify_capath);
555 rpctls_verbose_out("rpctls_setupcl_ssl: "
556 "Can't load verify locations\n");
561 * The man page says that the
562 * SSL_CTX_set0_CA_list() call is not normally
563 * needed, but I believe it is harmless.
565 if (rpctls_verify_cafile != NULL)
566 SSL_CTX_set0_CA_list(ctx,
567 SSL_load_client_CA_file(rpctls_verify_cafile));
570 /* RPC-over-TLS must use TLSv1.3, according to the IETF draft.*/
572 flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
573 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2;
575 flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1_3;
577 #ifdef SSL_OP_ENABLE_KTLS
578 flags |= SSL_OP_ENABLE_KTLS;
580 SSL_CTX_set_options(ctx, flags);
581 #ifdef SSL_MODE_NO_KTLS_TX
582 SSL_CTX_clear_mode(ctx, SSL_MODE_NO_KTLS_TX | SSL_MODE_NO_KTLS_RX);
588 rpctls_connect(SSL_CTX *ctx, int s, char *certname, u_int certlen, X509 **certp)
592 struct sockaddr_storage ad;
593 struct sockaddr *sad;
594 char hostnam[NI_MAXHOST], path[PATH_MAX];
601 sad = (struct sockaddr *)&ad;
604 rpctls_verbose_out("rpctls_connect: "
608 if (SSL_set_fd(ssl, s) != 1) {
609 rpctls_verbose_out("rpctls_connect: "
610 "SSL_set_fd failed\n");
616 * If rpctls_cert is true and certname is set, a alternate certificate
617 * and key exists in files named <certname>.pem and <certname>key.pem
618 * in rpctls_certdir that is to be used for mutual authentication.
620 if (rpctls_cert && certlen > 0) {
621 len = strlcpy(path, rpctls_certdir, sizeof(path));
622 rlen = sizeof(path) - len;
623 if (rlen <= certlen) {
627 memcpy(&path[len], certname, certlen);
631 if (strlcpy(&path[len], ".pem", rlen) != 4) {
635 ret = SSL_use_certificate_file(ssl, path, SSL_FILETYPE_PEM);
637 rpctls_verbose_out("rpctls_connect: can't use "
638 "certificate file path=%s ret=%d\n", path, ret);
642 if (strlcpy(&path[len], "key.pem", rlen) != 7) {
646 ret = SSL_use_PrivateKey_file(ssl, path, SSL_FILETYPE_PEM);
648 rpctls_verbose_out("rpctls_connect: Can't use "
649 "private key path=%s ret=%d\n", path, ret);
655 ret = SSL_connect(ssl);
657 rpctls_verbose_out("rpctls_connect: "
658 "SSL_connect failed %d\n",
664 cert = SSL_get_peer_certificate(ssl);
666 rpctls_verbose_out("rpctls_connect: get peer"
667 " certificate failed\n");
671 gethostret = rpctls_gethost(s, sad, hostnam, sizeof(hostnam));
674 verfret = SSL_get_verify_result(ssl);
675 if (verfret == X509_V_OK && (rpctls_verify_cafile != NULL ||
676 rpctls_verify_capath != NULL) && (gethostret == 0 ||
677 rpctls_checkhost(sad, cert, X509_CHECK_FLAG_NO_WILDCARDS) != 1))
678 verfret = X509_V_ERR_HOSTNAME_MISMATCH;
679 if (verfret != X509_V_OK && (rpctls_verify_cafile != NULL ||
680 rpctls_verify_capath != NULL)) {
681 if (verfret != X509_V_OK) {
682 cp = X509_NAME_oneline(X509_get_issuer_name(cert),
684 cp2 = X509_NAME_oneline(X509_get_subject_name(cert),
686 if (rpctls_debug_level == 0)
687 syslog(LOG_INFO | LOG_DAEMON,
688 "rpctls_connect: client IP %s "
689 "issuerName=%s subjectName=%s verify "
690 "failed %s\n", hostnam, cp, cp2,
691 X509_verify_cert_error_string(verfret));
694 "rpctls_connect: client IP %s "
695 "issuerName=%s subjectName=%s verify "
696 "failed %s\n", hostnam, cp, cp2,
697 X509_verify_cert_error_string(verfret));
704 /* Check to see if ktls is enabled on the connection. */
705 ret = BIO_get_ktls_send(SSL_get_wbio(ssl));
706 rpctls_verbose_out("rpctls_connect: BIO_get_ktls_send=%d\n", ret);
708 ret = BIO_get_ktls_recv(SSL_get_rbio(ssl));
709 rpctls_verbose_out("rpctls_connect: BIO_get_ktls_recv=%d\n",
713 if (rpctls_debug_level == 0)
714 syslog(LOG_ERR, "ktls not working\n");
716 fprintf(stderr, "ktls not working\n");
721 if (ret == X509_V_OK && (rpctls_verify_cafile != NULL ||
722 rpctls_verify_capath != NULL) && rpctls_crlfile != NULL)
731 rpctls_huphandler(int sig __unused)
734 rpctls_gothup = true;