24 #include <openssl/opensslconf.h>
25 #include <openssl/opensslv.h>
33 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
34 #define XRDTLS_HAVE_OSSL_STORE 1
35 #include <openssl/store.h>
36 #include <openssl/provider.h>
41 #if !defined(OPENSSL_NO_ENGINE)
42 #define XRDTLS_HAVE_ENGINE 1
43 #include <openssl/engine.h>
46 #include <openssl/bio.h>
47 #include <openssl/crypto.h>
48 #include <openssl/err.h>
49 #include <openssl/conf.h>
50 #include <openssl/ssl.h>
63 #if OPENSSL_VERSION_NUMBER >= 0x30400010
64 #define SSL_CTX_flush_sessions SSL_CTX_flush_sessions_ex
78 #ifndef OPENSSL_NO_CONF
79 bool EnsureOpenSSLConfigLoaded()
81 static std::once_flag configFlag;
82 static bool loadOK =
true;
84 std::call_once(configFlag, []() {
85 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
86 if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG,
nullptr))
89 OPENSSL_config(
nullptr);
95 bool EnsureOpenSSLConfigLoaded()
101 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
104 bool InitIsolatedPKCS11Context(OSSL_LIB_CTX **libCtx, OSSL_PROVIDER **pkcs11Prov, OSSL_PROVIDER **defaultProv)
107 *libCtx = OSSL_LIB_CTX_new();
114 const char *opensslConf = getenv(
"OPENSSL_CONF");
115 if (opensslConf && opensslConf[0]) {
117 if (!OSSL_LIB_CTX_load_config(*libCtx, opensslConf)) {
119 OSSL_LIB_CTX_free(*libCtx);
126 *defaultProv = OSSL_PROVIDER_load(*libCtx,
"default");
128 OSSL_LIB_CTX_free(*libCtx);
134 *pkcs11Prov = OSSL_PROVIDER_load(*libCtx,
"pkcs11");
136 OSSL_PROVIDER_unload(*defaultProv);
137 OSSL_LIB_CTX_free(*libCtx);
139 *defaultProv =
nullptr;
159 #
if OPENSSL_VERSION_NUMBER >= 0x30000000L
160 , pkcs11LibCtx(0), pkcs11Provider(0)
166 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
167 if (pkcs11Provider) OSSL_PROVIDER_unload(pkcs11Provider);
168 if (pkcs11LibCtx) OSSL_LIB_CTX_free(pkcs11LibCtx);
184 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
185 OSSL_LIB_CTX *pkcs11LibCtx;
186 OSSL_PROVIDER *pkcs11Provider;
210 DBG_CTX(
"CRL refresh started.")
224 DBG_CTX(
"CRL refresh ending by request!");
230 DBG_CTX(
"CRL refresh will happen in " <<sleepTime <<
" seconds.");
240 if (!ctxImpl->
owner)
break;
251 if (!newctx || !newctx->
isOK())
252 {
XrdTls::Emsg(
"CrlRefresh:",
"Refresh of context failed!!!",
false);
259 doreplace = (ctxImpl->
ctxnew != 0);
260 if (doreplace)
delete ctxImpl->
ctxnew;
266 if (doreplace) {
DBG_CTX(
"CRL refresh created replacement x509 store.");}
267 else {
DBG_CTX(
"CRL refresh created new x509 store.");}
276 if (!keepctx)
delete ctxImpl;
295 time_t tStart, tWaited;
296 int flushT, waitT, hits, miss, sesn, tmos;
306 waitT = flushT = ctxImpl->
flushT;
311 DBG_CTX(
"Cache flusher started; interval="<<flushT<<
" seconds.");
317 tWaited= time(0) - tStart;
322 if (!ctxImpl->
owner)
break;
326 if (flushT != ctxImpl->
flushT && tWaited < ctxImpl->flushT-1)
327 {waitT = ctxImpl->
flushT - tWaited;
334 waitT = flushT = ctxImpl->
flushT;
339 sesn = SSL_CTX_sess_number(ctxImpl->
ctx);
340 hits = SSL_CTX_sess_hits(ctxImpl->
ctx);
341 miss = SSL_CTX_sess_misses(ctxImpl->
ctx);
342 tmos = SSL_CTX_sess_timeouts(ctxImpl->
ctx);
347 SSL_CTX_flush_sessions(ctxImpl->
ctx, tNow);
353 snprintf(mBuff,
sizeof(mBuff),
"sess=%d hits=%d miss=%d timeouts=%d",
354 sesn, hits, miss, tmos);
355 DBG_CTX(
"Cache flushed; " <<mBuff);
364 if (!keepctx)
delete ctxImpl;
394 0,
"Cache Flusher")))
396 snprintf(eBuff,
sizeof(eBuff),
397 "Unable to start cache flusher thread; rc=%d", rc);
405 SSL_CTX_set_session_cache_mode(pImpl->
ctx, SSL_SESS_CACHE_NO_AUTO_CLEAR);
428 static unsigned long mixer(
unsigned long x) {
431 x *= 0xbf58476d1ce4e5b9UL;
433 x *= 0x94d049bb133111ebUL;
441 static unsigned long mixer(
unsigned long x) {
461 return tlsmix<
sizeof(
unsigned long)==4>::mixer(x);
483 const char *sslCiphers =
"ECDHE-ECDSA-AES128-GCM-SHA256:"
484 "ECDHE-RSA-AES128-GCM-SHA256:"
485 "ECDHE-ECDSA-AES256-GCM-SHA384:"
486 "ECDHE-RSA-AES256-GCM-SHA384:"
487 "ECDHE-ECDSA-CHACHA20-POLY1305:"
488 "ECDHE-RSA-CHACHA20-POLY1305:"
489 "DHE-RSA-AES128-GCM-SHA256:"
490 "DHE-RSA-AES256-GCM-SHA384";
494 bool initTlsDone{
false };
507 if (initTlsDone)
return;
513 OpenSSL_add_all_algorithms();
514 SSL_load_error_strings();
515 OpenSSL_add_all_ciphers();
516 #if OPENSSL_VERSION_NUMBER < 0x30000000L
517 ERR_load_BIO_strings();
519 ERR_load_crypto_strings();
526 void Fatal(std::string *
eMsg,
const char *msg,
bool sslmsg=
false)
542 const char *GetTlsMethod(
const SSL_METHOD *&meth)
545 if (meth == 0)
return "No negotiable TLS method available.";
553 bool VerPaths(
const char *cert,
const char *pkey,
554 const char *cadr,
const char *cafl, std::string &
eMsg)
556 static const mode_t cert_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
557 static const mode_t pkey_mode = S_IRUSR | S_IWUSR;
558 static const mode_t cadr_mode = S_IRWXU | S_IRGRP | S_IXGRP
560 static const mode_t cafl_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
567 {
eMsg =
"Unable to use CA cert directory ";
576 {
eMsg =
"Unable to use CA cert file ";
585 {
eMsg =
"Unable to use key file ";
595 {mode_t cmode = (pkey ? cert_mode : pkey_mode);
597 {
if (pkey)
eMsg =
"Unable to use cert file ";
598 else eMsg =
"Unable to use cert+key file ";
619 int verifyPeerCB(
int aOK, X509_STORE_CTX *x509P) {
621 SSL *ssl = (SSL*)X509_STORE_CTX_get_ex_data(x509P, SSL_get_ex_data_X509_STORE_CTX_idx());
622 SSL_CTX *sslCtx = SSL_get_SSL_CTX(ssl);
626 if (crlAllowMissingCA) {
627 int err = X509_STORE_CTX_get_error(x509P);
628 if (err == X509_V_ERR_UNABLE_TO_GET_CRL) {
629 X509_STORE_CTX_set_error(x509P, X509_V_OK);
634 X509 *cert = X509_STORE_CTX_get_current_cert(x509P);
635 int depth = X509_STORE_CTX_get_error_depth(x509P);
636 int err = X509_STORE_CTX_get_error(x509P);
637 char name[512], info[1024];
639 X509_NAME_oneline(X509_get_subject_name(cert), name,
sizeof(name));
640 snprintf(info,
sizeof(info),
"Cert verification failed for DN=%s",name);
643 X509_NAME_oneline(X509_get_issuer_name(cert), name,
sizeof(name));
644 snprintf(info,
sizeof(info),
"Failing cert issuer=%s", name);
647 snprintf(info,
sizeof(info),
"Error %d at depth %d [%s]", err, depth,
648 X509_verify_cert_error_string(err));
663 #define KILL_CTX(x) if (x) {SSL_CTX_free(x); x = 0;}
665 #define FATAL(msg) {Fatal(eMsg, msg); KILL_CTX(pImpl->ctx); return;}
667 #define FATAL_SSL(msg) {Fatal(eMsg, msg, true); KILL_CTX(pImpl->ctx); return;}
672 const char *caDir,
const char *caFile,
679 void Keep() {ctxLoc = 0;}
681 ctx_helper(SSL_CTX **ctxP) : ctxLoc(ctxP) {}
682 ~ctx_helper() {
if (ctxLoc && *ctxLoc)
683 {SSL_CTX_free(*ctxLoc); *ctxLoc = 0;}
687 } ctx_tracker(&pImpl->
ctx);
689 static const uint64_t sslOpts = SSL_OP_ALL
692 | SSL_OP_NO_COMPRESSION
693 | SSL_OP_NO_RENEGOTIATION
694 #ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
695 | SSL_OP_IGNORE_UNEXPECTED_EOF
699 std::string certFN, eText;
713 if (!(
opts &
servr) && (dbg = getenv(
"XRDTLS_DEBUG")))
732 {
if (!caDir && !caFile)
733 {caDir = getenv(
"X509_CERT_DIR");
734 caFile = getenv(
"X509_CERT_FILE");
735 if (!caDir && !caFile)
736 FATAL(
"No CA cert specified; host identity cannot be verified.");
738 if (!key) key = getenv(
"X509_USER_KEY");
739 if (!cert) cert = getenv(
"X509_USER_PROXY");
742 long long int uid =
static_cast<long long int>(getuid());
743 certFN = std::string(
"/tmp/x509up_u") + std::to_string(uid);
744 if (!
stat(certFN.c_str(), &
Stat)) cert = certFN.c_str();
751 if (!VerPaths(cert, key, caDir, caFile, eText))
FATAL( eText.c_str());
772 const SSL_METHOD *meth;
773 emsg = GetTlsMethod(meth);
776 pImpl->
ctx = SSL_CTX_new(meth);
780 if (pImpl->
ctx == 0)
FATAL_SSL(
"Unable to allocate TLS context!");
787 SSL_CTX_set_options(pImpl->
ctx, sslOpts);
795 SSL_CTX_set_session_cache_mode(pImpl->
ctx, SSL_SESS_CACHE_OFF);
801 if ((caDir || caFile) && !(
opts &
clcOF))
802 {
if (!SSL_CTX_load_verify_locations(pImpl->
ctx, caFile, caDir))
803 FATAL_SSL(
"Unable to load the CA cert file or directory.");
806 SSL_CTX_set_verify_depth(pImpl->
ctx, (vDepth ? vDepth : 9));
809 bool crlAllowMissingCA = (
opts &
crlAM) != 0;
811 if (crlAllowMissingCA || LogVF) {
812 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, verifyPeerCB);
814 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, 0);
817 unsigned long xFlags = (
opts &
nopxy ? 0 : X509_V_FLAG_ALLOW_PROXY_CERTS);
819 {xFlags |= X509_V_FLAG_CRL_CHECK;
820 if (
opts &
crlFC) xFlags |= X509_V_FLAG_CRL_CHECK_ALL;
822 if (
opts) X509_STORE_set_flags(SSL_CTX_get_cert_store(pImpl->
ctx),xFlags);
824 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_NONE, 0);
829 if (!SSL_CTX_set_cipher_list(pImpl->
ctx, sslCiphers))
830 FATAL_SSL(
"Unable to set SSL cipher list; no supported ciphers.");
835 #if SSL_CTRL_SET_ECDH_AUTO
836 SSL_CTX_set_ecdh_auto(pImpl->
ctx, 1);
843 if (
opts &
artON) SSL_CTX_set_mode(pImpl->
ctx, SSL_MODE_AUTO_RETRY);
855 if (!key) key = cert;
859 if (SSL_CTX_use_certificate_chain_file(pImpl->
ctx, cert) != 1)
860 FATAL_SSL(
"Unable to create TLS context; invalid certificate.");
865 if (!EnsureOpenSSLConfigLoaded())
866 FATAL_SSL(
"Unable to load OpenSSL configuration; cannot initialize pkcs11.");
868 #ifdef XRDTLS_HAVE_OSSL_STORE
872 OSSL_PROVIDER *defaultProv =
nullptr;
877 if (!InitIsolatedPKCS11Context(&pImpl->pkcs11LibCtx, &pImpl->pkcs11Provider, &defaultProv)) {
878 FATAL_SSL(
"Failed to initialize isolated PKCS11 context. Check OPENSSL_CONF and pkcs11-provider installation.");
882 OSSL_STORE_CTX *store_ctx = OSSL_STORE_open_ex(key, pImpl->pkcs11LibCtx,
nullptr,
883 nullptr,
nullptr,
nullptr,
nullptr,
nullptr);
885 if (defaultProv) OSSL_PROVIDER_unload(defaultProv);
886 FATAL_SSL(
"Failed to open PKCS11 URI in isolated context.");
889 EVP_PKEY *priv_key =
nullptr;
890 while (!OSSL_STORE_eof(store_ctx)) {
891 OSSL_STORE_INFO *info = OSSL_STORE_load(store_ctx);
893 int type = OSSL_STORE_INFO_get_type(info);
894 if (type == OSSL_STORE_INFO_PKEY) {
895 priv_key = OSSL_STORE_INFO_get1_PKEY(info);
896 OSSL_STORE_INFO_free(info);
899 OSSL_STORE_INFO_free(info);
902 OSSL_STORE_close(store_ctx);
903 if (defaultProv) OSSL_PROVIDER_unload(defaultProv);
906 FATAL_SSL(
"Failed to load private key from PKCS11 URI in isolated context.");
908 if (SSL_CTX_use_PrivateKey(pImpl->
ctx, priv_key) != 1) {
909 EVP_PKEY_free(priv_key);
910 FATAL_SSL(
"Failed to have SSL context use private key");
912 EVP_PKEY_free(priv_key);
914 #elif defined(XRDTLS_HAVE_ENGINE)
916 ENGINE *e = ENGINE_by_id(
"pkcs11");
918 const char* modulePath = getenv(
"PKCS11_MODULE_PATH");
919 if (modulePath && modulePath[0]) {
920 if (!ENGINE_ctrl_cmd_string(e,
"MODULE_PATH", modulePath, 0)) {
922 FATAL_SSL(
"Unable to configure pkcs11 engine MODULE_PATH");
925 if(!ENGINE_init(e)) {
927 FATAL_SSL(
"Unable to initialize pkcs11 engine");
930 FATAL_SSL(
"Unable to create pkcs11 engine");
932 auto priv_key = ENGINE_load_private_key(e, key,
nullptr,
nullptr);
935 FATAL_SSL(
"Failed to load private key through engine");
937 if (SSL_CTX_use_PrivateKey(pImpl->
ctx, priv_key) != 1)
938 FATAL_SSL(
"Failed to have SSL context use private key");
939 EVP_PKEY_free(priv_key);
941 FATAL_SSL(
"PKCS11 support not available.");
944 }
else if (SSL_CTX_use_PrivateKey_file(pImpl->
ctx, key, SSL_FILETYPE_PEM) != 1 )
945 FATAL_SSL(
"Unable to create TLS context; invalid private key.");
949 if (SSL_CTX_check_private_key(pImpl->
ctx) != 1 )
950 FATAL_SSL(
"Unable to create TLS context; cert-key mismatch.");
983 const char *cert = (my.
cert.size() ? my.
cert.c_str() : 0);
984 const char *pkey = (my.
pkey.size() ? my.
pkey.c_str() : 0);
985 const char *caD = (my.
cadir.size() ? my.
cadir.c_str() : 0);
986 const char *caF = (my.
cafile.size() ? my.
cafile.c_str() : 0);
990 if (!full) caD = caF = 0;
1033 return &pImpl->
Parm;
1045 #ifndef OPENSSL_THREADS
1046 return "Installed OpenSSL lacks the required thread support!";
1061 return pImpl->
ctx != 0;
1084 {ssl = SSL_new(pImpl->
ctx);
1098 {ssl = SSL_new(pImpl->
ctx);
1105 DBG_CTX(
"Replacing x509 store with new contents.");
1122 SSL_CTX_free(pImpl->
ctx);
1123 pImpl->
ctx = ctxnew->pImpl->
ctx;
1133 ctxnew->pImpl->
ctx = 0;
1142 ssl = SSL_new(pImpl->
ctx);
1166 if (pImpl->
ctx == 0)
return 0;
1171 {
if (
opts &
scOff) sslopt = SSL_SESS_CACHE_OFF;
1172 else {
if (
opts &
scSrvr) sslopt = SSL_SESS_CACHE_SERVER;
1173 if (
opts &
scClnt) sslopt |= SSL_SESS_CACHE_CLIENT;
1179 if (!(
opts & doSet)) sslopt = SSL_CTX_get_session_cache_mode(pImpl->
ctx);
1180 else {sslopt = SSL_CTX_set_session_cache_mode(pImpl->
ctx, sslopt);
1181 if (
opts &
scOff) SSL_CTX_set_options(pImpl->
ctx, SSL_OP_NO_TICKET);
1187 if (sslopt & SSL_SESS_CACHE_SERVER)
opts |=
scSrvr;
1188 if (sslopt & SSL_SESS_CACHE_CLIENT)
opts |=
scClnt;
1190 if (sslopt & SSL_SESS_CACHE_NO_AUTO_CLEAR)
opts |=
scKeep;
1195 if (
id && idlen > 0)
1196 {
if (!SSL_CTX_set_session_id_context(pImpl->
ctx,
1197 (
unsigned const char *)id,
1204 if (flushT && flushT != pImpl->
flushT)
1218 if (pImpl->
ctx && SSL_CTX_set_cipher_list(pImpl->
ctx, ciphers))
return true;
1221 snprintf(eBuff,
sizeof(eBuff),
"Unable to set context ciphers '%s'",ciphers);
1222 Fatal(0, eBuff,
true);
1232 sslCiphers = ciphers;
1265 snprintf(eBuff,
sizeof(eBuff),
1266 "Unable to start CRL refresh thread; rc=%d", rc);
1268 pImpl->crlMutex.UnLock();
1270 }
else pImpl->crlRunning =
true;
1271 pImpl->crlMutex.UnLock();
1289 const std::string certPath = pImpl->
Parm.
cert;
1290 if(certPath.empty()) {
1294 time_t modificationTime;
1311 if (LogVF || crlAllowMissingCA)
1312 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, verifyPeerCB);
1314 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, 0);
1317 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)
void * Flusher(void *parg)
bool Setup_Flusher(XrdTlsContextImpl *pImpl, int flushT)
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)