20#include <openssl/bio.h>
21#include <openssl/crypto.h>
22#include <openssl/err.h>
23#include <openssl/ssl.h>
24#include <openssl/opensslv.h>
37#if OPENSSL_VERSION_NUMBER >= 0x30400010
38#define SSL_CTX_flush_sessions SSL_CTX_flush_sessions_ex
113 DBG_CTX(
"CRL refresh ending by request!");
119 DBG_CTX(
"CRL refresh will happen in " <<sleepTime <<
" seconds.");
129 if (!ctxImpl->
owner)
break;
140 if (!newctx || !newctx->
isOK())
141 {
XrdTls::Emsg(
"CrlRefresh:",
"Refresh of context failed!!!",
false);
148 doreplace = (ctxImpl->
ctxnew != 0);
149 if (doreplace)
delete ctxImpl->
ctxnew;
155 if (doreplace) {
DBG_CTX(
"CRL refresh created replacement x509 store.");}
156 else {
DBG_CTX(
"CRL refresh created new x509 store.");}
165 if (!keepctx)
delete ctxImpl;
184 time_t tStart, tWaited;
185 int flushT, waitT, hits, miss, sesn, tmos;
195 waitT = flushT = ctxImpl->
flushT;
200 DBG_CTX(
"Cache flusher started; interval="<<flushT<<
" seconds.");
206 tWaited= time(0) - tStart;
211 if (!ctxImpl->
owner)
break;
215 if (flushT != ctxImpl->
flushT && tWaited < ctxImpl->flushT-1)
216 {waitT = ctxImpl->
flushT - tWaited;
223 waitT = flushT = ctxImpl->
flushT;
228 sesn = SSL_CTX_sess_number(ctxImpl->
ctx);
229 hits = SSL_CTX_sess_hits(ctxImpl->
ctx);
230 miss = SSL_CTX_sess_misses(ctxImpl->
ctx);
231 tmos = SSL_CTX_sess_timeouts(ctxImpl->
ctx);
236 SSL_CTX_flush_sessions(ctxImpl->
ctx, tNow);
242 snprintf(mBuff,
sizeof(mBuff),
"sess=%d hits=%d miss=%d timeouts=%d",
243 sesn, hits, miss, tmos);
244 DBG_CTX(
"Cache flushed; " <<mBuff);
253 if (!keepctx)
delete ctxImpl;
283 0,
"Cache Flusher")))
285 snprintf(eBuff,
sizeof(eBuff),
286 "Unable to start cache flusher thread; rc=%d", rc);
294 SSL_CTX_set_session_cache_mode(pImpl->
ctx, SSL_SESS_CACHE_NO_AUTO_CLEAR);
317 static unsigned long mixer(
unsigned long x) {
320 x *= 0xbf58476d1ce4e5b9UL;
322 x *= 0x94d049bb133111ebUL;
330 static unsigned long mixer(
unsigned long x) {
350 return tlsmix<
sizeof(
unsigned long)==4>::mixer(x);
372const char *sslCiphers =
"ECDHE-ECDSA-AES128-GCM-SHA256:"
373 "ECDHE-RSA-AES128-GCM-SHA256:"
374 "ECDHE-ECDSA-AES256-GCM-SHA384:"
375 "ECDHE-RSA-AES256-GCM-SHA384:"
376 "ECDHE-ECDSA-CHACHA20-POLY1305:"
377 "ECDHE-RSA-CHACHA20-POLY1305:"
378 "DHE-RSA-AES128-GCM-SHA256:"
379 "DHE-RSA-AES256-GCM-SHA384";
383bool initTlsDone{
false };
396 if (initTlsDone)
return;
402 OpenSSL_add_all_algorithms();
403 SSL_load_error_strings();
404 OpenSSL_add_all_ciphers();
405#if OPENSSL_VERSION_NUMBER < 0x30000000L
406 ERR_load_BIO_strings();
408 ERR_load_crypto_strings();
415void Fatal(std::string *
eMsg,
const char *msg,
bool sslmsg=
false)
431const char *GetTlsMethod(
const SSL_METHOD *&meth)
434 if (meth == 0)
return "No negotiable TLS method available.";
442bool VerPaths(
const char *cert,
const char *pkey,
443 const char *cadr,
const char *cafl, std::string &
eMsg)
445 static const mode_t cert_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
446 static const mode_t pkey_mode = S_IRUSR | S_IWUSR;
447 static const mode_t cadr_mode = S_IRWXU | S_IRGRP | S_IXGRP
449 static const mode_t cafl_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
456 {
eMsg =
"Unable to use CA cert directory ";
465 {
eMsg =
"Unable to use CA cert file ";
474 {
eMsg =
"Unable to use key file ";
484 {mode_t cmode = (pkey ? cert_mode : pkey_mode);
486 {
if (pkey)
eMsg =
"Unable to use cert file ";
487 else eMsg =
"Unable to use cert+key file ";
508int verifyPeerCB(
int aOK, X509_STORE_CTX *x509P) {
510 SSL *ssl = (SSL*)X509_STORE_CTX_get_ex_data(x509P, SSL_get_ex_data_X509_STORE_CTX_idx());
511 SSL_CTX *sslCtx = SSL_get_SSL_CTX(ssl);
515 if (crlAllowMissingCA) {
516 int err = X509_STORE_CTX_get_error(x509P);
517 if (err == X509_V_ERR_UNABLE_TO_GET_CRL) {
518 X509_STORE_CTX_set_error(x509P, X509_V_OK);
523 X509 *cert = X509_STORE_CTX_get_current_cert(x509P);
524 int depth = X509_STORE_CTX_get_error_depth(x509P);
525 int err = X509_STORE_CTX_get_error(x509P);
526 char name[512], info[1024];
528 X509_NAME_oneline(X509_get_subject_name(cert), name,
sizeof(name));
529 snprintf(info,
sizeof(info),
"Cert verification failed for DN=%s",name);
532 X509_NAME_oneline(X509_get_issuer_name(cert), name,
sizeof(name));
533 snprintf(info,
sizeof(info),
"Failing cert issuer=%s", name);
536 snprintf(info,
sizeof(info),
"Error %d at depth %d [%s]", err, depth,
537 X509_verify_cert_error_string(err));
552#define KILL_CTX(x) if (x) {SSL_CTX_free(x); x = 0;}
554#define FATAL(msg) {Fatal(eMsg, msg); KILL_CTX(pImpl->ctx); return;}
556#define FATAL_SSL(msg) {Fatal(eMsg, msg, true); KILL_CTX(pImpl->ctx); return;}
561 const char *caDir,
const char *caFile,
568 void Keep() {ctxLoc = 0;}
570 ctx_helper(SSL_CTX **ctxP) : ctxLoc(ctxP) {}
571 ~ctx_helper() {
if (ctxLoc && *ctxLoc)
572 {SSL_CTX_free(*ctxLoc); *ctxLoc = 0;}
576 } ctx_tracker(&pImpl->ctx);
578 static const uint64_t sslOpts = SSL_OP_ALL
581 | SSL_OP_NO_COMPRESSION
582 | SSL_OP_NO_RENEGOTIATION
583#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
584 | SSL_OP_IGNORE_UNEXPECTED_EOF
588 std::string certFN, eText;
602 if (!(
opts &
servr) && (dbg = getenv(
"XRDTLS_DEBUG")))
621 {
if (!caDir && !caFile)
622 {caDir = getenv(
"X509_CERT_DIR");
623 caFile = getenv(
"X509_CERT_FILE");
624 if (!caDir && !caFile)
625 FATAL(
"No CA cert specified; host identity cannot be verified.");
627 if (!key) key = getenv(
"X509_USER_KEY");
628 if (!cert) cert = getenv(
"X509_USER_PROXY");
631 long long int uid =
static_cast<long long int>(getuid());
632 certFN = std::string(
"/tmp/x509up_u") + std::to_string(uid);
633 if (!
stat(certFN.c_str(), &
Stat)) cert = certFN.c_str();
640 if (!VerPaths(cert, key, caDir, caFile, eText))
FATAL( eText.c_str());
645 pImpl->Parm.cert = cert;
649 if (key) pImpl->Parm.pkey = key;
650 if (caDir) pImpl->Parm.cadir = caDir;
651 if (caFile) pImpl->Parm.cafile = caFile;
652 pImpl->Parm.opts =
opts;
655 pImpl->Parm.crlRT =
static_cast<int>((
opts &
crlRF) >>
crlRS) * 60;
661 const SSL_METHOD *meth;
662 emsg = GetTlsMethod(meth);
665 pImpl->ctx = SSL_CTX_new(meth);
669 if (pImpl->ctx == 0)
FATAL_SSL(
"Unable to allocate TLS context!");
672 SSL_CTX_set_ex_data(pImpl->ctx,
ctxIndex,
this);
676 SSL_CTX_set_options(pImpl->ctx, sslOpts);
684 SSL_CTX_set_session_cache_mode(pImpl->ctx, SSL_SESS_CACHE_OFF);
690 if ((caDir || caFile) && !(
opts &
clcOF))
691 {
if (!SSL_CTX_load_verify_locations(pImpl->ctx, caFile, caDir))
692 FATAL_SSL(
"Unable to load the CA cert file or directory.");
695 SSL_CTX_set_verify_depth(pImpl->ctx, (vDepth ? vDepth : 9));
698 bool crlAllowMissingCA = (
opts &
crlAM) != 0;
700 if (crlAllowMissingCA || LogVF) {
701 SSL_CTX_set_verify(pImpl->ctx, SSL_VERIFY_PEER, verifyPeerCB);
703 SSL_CTX_set_verify(pImpl->ctx, SSL_VERIFY_PEER, 0);
706 unsigned long xFlags = (
opts &
nopxy ? 0 : X509_V_FLAG_ALLOW_PROXY_CERTS);
708 {xFlags |= X509_V_FLAG_CRL_CHECK;
709 if (
opts &
crlFC) xFlags |= X509_V_FLAG_CRL_CHECK_ALL;
711 if (
opts) X509_STORE_set_flags(SSL_CTX_get_cert_store(pImpl->ctx),xFlags);
713 SSL_CTX_set_verify(pImpl->ctx, SSL_VERIFY_NONE, 0);
718 if (!SSL_CTX_set_cipher_list(pImpl->ctx, sslCiphers))
719 FATAL_SSL(
"Unable to set SSL cipher list; no supported ciphers.");
724#if SSL_CTRL_SET_ECDH_AUTO
725 SSL_CTX_set_ecdh_auto(pImpl->ctx, 1);
732 if (
opts &
artON) SSL_CTX_set_mode(pImpl->ctx, SSL_MODE_AUTO_RETRY);
744 if (!key) key = cert;
748 if (SSL_CTX_use_certificate_chain_file(pImpl->ctx, cert) != 1)
749 FATAL_SSL(
"Unable to create TLS context; invalid certificate.");
753 if (SSL_CTX_use_PrivateKey_file(pImpl->ctx, key, SSL_FILETYPE_PEM) != 1 )
754 FATAL_SSL(
"Unable to create TLS context; invalid private key.");
758 if (SSL_CTX_check_private_key(pImpl->ctx) != 1 )
759 FATAL_SSL(
"Unable to create TLS context; cert-key mismatch.");
778 if (pImpl->crlRunning | pImpl->flsRunning)
779 {pImpl->crlMutex.WriteLock();
781 pImpl->crlMutex.UnLock();
792 const char *cert = (my.
cert.size() ? my.
cert.c_str() : 0);
793 const char *pkey = (my.
pkey.size() ? my.
pkey.c_str() : 0);
794 const char *caD = (my.
cadir.size() ? my.
cadir.c_str() : 0);
795 const char *caF = (my.
cafile.size() ? my.
cafile.c_str() : 0);
799 if (!full) caD = caF = 0;
814 if(pImpl->sessionCacheOpts != -1){
816 xtc->
SessionCache(pImpl->sessionCacheOpts,pImpl->sessionCacheId.c_str(),pImpl->sessionCacheId.size());
854#ifndef OPENSSL_THREADS
855 return "Installed OpenSSL lacks the required thread support!";
870 return pImpl->ctx != 0;
891 pImpl->crlMutex.ReadLock();
892 if (!(pImpl->ctxnew))
893 {ssl = SSL_new(pImpl->ctx);
894 pImpl->crlMutex.UnLock();
901 pImpl->crlMutex.UnLock();
902 pImpl->crlMutex.WriteLock();
906 if (!(pImpl->ctxnew))
907 {ssl = SSL_new(pImpl->ctx);
908 pImpl->crlMutex.UnLock();
914 DBG_CTX(
"Replacing x509 store with new contents.");
931 SSL_CTX_free(pImpl->ctx);
932 pImpl->ctx = ctxnew->pImpl->
ctx;
936 SSL_CTX_set_ex_data(pImpl->ctx,
ctxIndex,
this);
942 ctxnew->pImpl->
ctx = 0;
951 ssl = SSL_new(pImpl->ctx);
955 pImpl->crlMutex.UnLock();
970 pImpl->sessionCacheOpts =
opts;
971 pImpl->sessionCacheId = id;
975 if (pImpl->ctx == 0)
return 0;
980 {
if (
opts &
scOff) sslopt = SSL_SESS_CACHE_OFF;
981 else {
if (
opts &
scSrvr) sslopt = SSL_SESS_CACHE_SERVER;
982 if (
opts &
scClnt) sslopt |= SSL_SESS_CACHE_CLIENT;
988 if (!(
opts & doSet)) sslopt = SSL_CTX_get_session_cache_mode(pImpl->ctx);
989 else {sslopt = SSL_CTX_set_session_cache_mode(pImpl->ctx, sslopt);
990 if (
opts &
scOff) SSL_CTX_set_options(pImpl->ctx, SSL_OP_NO_TICKET);
996 if (sslopt & SSL_SESS_CACHE_SERVER)
opts |=
scSrvr;
997 if (sslopt & SSL_SESS_CACHE_CLIENT)
opts |=
scClnt;
999 if (sslopt & SSL_SESS_CACHE_NO_AUTO_CLEAR)
opts |=
scKeep;
1000 opts |= (
static_cast<int>(pImpl->flushT) &
scFMax);
1004 if (
id && idlen > 0)
1005 {
if (!SSL_CTX_set_session_id_context(pImpl->ctx,
1006 (
unsigned const char *)
id,
1013 if (flushT && flushT != pImpl->flushT)
1027 if (pImpl->ctx && SSL_CTX_set_cipher_list(pImpl->ctx, ciphers))
return true;
1030 snprintf(eBuff,
sizeof(eBuff),
"Unable to set context ciphers '%s'",ciphers);
1031 Fatal(0, eBuff,
true);
1041 sslCiphers = ciphers;
1056 {pImpl->crlMutex.WriteLock();
1057 refsec = pImpl->Parm.crlRT;
1058 pImpl->crlMutex.UnLock();
1068 pImpl->crlMutex.WriteLock();
1069 pImpl->Parm.crlRT = refsec;
1070 if (!pImpl->crlRunning)
1074 snprintf(eBuff,
sizeof(eBuff),
1075 "Unable to start CRL refresh thread; rc=%d", rc);
1077 pImpl->crlMutex.UnLock();
1079 }
else pImpl->crlRunning =
true;
1080 pImpl->crlMutex.UnLock();
1094 return !(pImpl->Parm.cadir.empty()) || !(pImpl->Parm.cafile.empty());
1098 const std::string certPath = pImpl->Parm.cert;
1099 if(certPath.empty()) {
1103 time_t modificationTime;
1105 if (pImpl->lastCertModTime != modificationTime) {
1107 pImpl->lastCertModTime = modificationTime;
1116 {pImpl->Parm.opts &=
~clcOF;
1117 bool LogVF = (pImpl->Parm.opts &
logVF) != 0;
1118 bool crlAllowMissingCA = (pImpl->Parm.opts &
crlAM) != 0;
1120 if (LogVF || crlAllowMissingCA)
1121 SSL_CTX_set_verify(pImpl->ctx, SSL_VERIFY_PEER, verifyPeerCB);
1123 SSL_CTX_set_verify(pImpl->ctx, SSL_VERIFY_PEER, 0);
1125 {pImpl->Parm.opts |=
clcOF;
1126 SSL_CTX_set_verify(pImpl->ctx, SSL_VERIFY_NONE, 0);
void Fatal(const char *op, const char *target)
int emsg(int rc, char *msg)
void sslTLS_lock(int mode, int n, const char *file, int line)
XrdSysMutex * MutexVector
unsigned long sslTLS_id_callback(void)
static int getModificationTime(const char *path, time_t &modificationTime)
static const char * ValPath(const char *path, mode_t allow, bool isdir)
static int Run(pthread_t *, void *(*proc)(void *), void *arg, int opts=0, const char *desc=0)
static pthread_t ID(void)
static void Snooze(int seconds)
static const int scIdErr
Info: Id not set, is too long.
XrdTlsContext * Clone(bool full=true, bool startCRLRefresh=false)
~XrdTlsContext()
Destructor.
static const uint64_t vdept
Mask to isolate vdept.
static const int crlRS
Bits to shift vdept.
int SessionCache(int opts=scNone, const char *id=0, int idlen=0)
static void SetDefaultCiphers(const char *ciphers)
XrdTlsContext(const char *cert=0, const char *key=0, const char *cadir=0, const char *cafile=0, uint64_t opts=0, std::string *eMsg=0)
static const uint64_t clcOF
Disable client certificate request.
static const int scClnt
Turn on cache client mode.
static const int DEFAULT_CRL_REF_INT_SEC
Default CRL refresh interval in seconds.
static const uint64_t servr
This is a server context.
static const uint64_t rfCRL
Turn on the CRL refresh thread.
static const int scKeep
Info: TLS-controlled flush disabled.
static const uint64_t nopxy
Do not allow proxy certs.
static const int scNone
Do not change any option settings.
static const uint64_t logVF
Log verify failures.
static const uint64_t crlFC
Full crl chain checking.
static const uint64_t crlON
Enables crl checking.
static const uint64_t artON
Auto retry Handshake.
static const int vdepS
Bits to shift vdept.
const CTX_Params * GetParams()
static const int scOff
Turn off cache.
static const char * Init()
bool newHostCertificateDetected()
bool SetContextCiphers(const char *ciphers)
static const uint64_t crlAM
Allow CA validation when CRL is missing (CRL soft-fail).
bool SetCrlRefresh(int refsec=-1)
static const int scSrvr
Turn on cache server mode (default).
void SetTlsClientAuth(bool setting)
static const uint64_t crlRF
Mask to isolate crl refresh in min.
static const int dbgSIO
Turn debugging in for socket I/O.
static const int dbgSOK
Turn debugging in for socket operations.
static const int dbgOUT
Force msgs to stderr for easier client debug.
static void Emsg(const char *tid, const char *msg=0, bool flush=true)
static const int dbgALL
Turn debugging for everything.
static const int dbgCTX
Turn debugging in for context operations.
static void SetDebug(int opts, XrdSysLogger *logP=0)
void * Refresh(void *parg)
bool Setup_Flusher(XrdTlsContextImpl *pImpl, int flushT)
void * Flusher(void *parg)
XrdSysTrace SysTrace("TLS", 0)
XrdTlsContextImpl(XrdTlsContext *p)
std::string sessionCacheId
XrdTlsContext::CTX_Params Parm
std::string cafile
-> ca cert file.
uint64_t opts
Options as passed to the constructor.
std::string cadir
-> ca cert directory.
int crlRT
crl refresh interval time in seconds
std::string pkey
-> private key path.
std::string cert
-> certificate path.
static unsigned long mixer(unsigned long x)
static unsigned long mixer(unsigned long x)