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
100 DBG_CTX(
"CRL refresh started.")
114 DBG_CTX(
"CRL refresh ending by request!");
120 DBG_CTX(
"CRL refresh will happen in " <<sleepTime <<
" seconds.");
130 if (!ctxImpl->
owner)
break;
141 if (!newctx || !newctx->
isOK())
142 {
XrdTls::Emsg(
"CrlRefresh:",
"Refresh of context failed!!!",
false);
149 doreplace = (ctxImpl->
ctxnew != 0);
150 if (doreplace)
delete ctxImpl->
ctxnew;
156 if (doreplace) {
DBG_CTX(
"CRL refresh created replacement x509 store.");}
157 else {
DBG_CTX(
"CRL refresh created new x509 store.");}
166 if (!keepctx)
delete ctxImpl;
185 time_t tStart, tWaited;
186 int flushT, waitT, hits, miss, sesn, tmos;
196 waitT = flushT = ctxImpl->
flushT;
201 DBG_CTX(
"Cache flusher started; interval="<<flushT<<
" seconds.");
207 tWaited= time(0) - tStart;
212 if (!ctxImpl->
owner)
break;
216 if (flushT != ctxImpl->
flushT && tWaited < ctxImpl->flushT-1)
217 {waitT = ctxImpl->
flushT - tWaited;
224 waitT = flushT = ctxImpl->
flushT;
229 sesn = SSL_CTX_sess_number(ctxImpl->
ctx);
230 hits = SSL_CTX_sess_hits(ctxImpl->
ctx);
231 miss = SSL_CTX_sess_misses(ctxImpl->
ctx);
232 tmos = SSL_CTX_sess_timeouts(ctxImpl->
ctx);
237 SSL_CTX_flush_sessions(ctxImpl->
ctx, tNow);
243 snprintf(mBuff,
sizeof(mBuff),
"sess=%d hits=%d miss=%d timeouts=%d",
244 sesn, hits, miss, tmos);
245 DBG_CTX(
"Cache flushed; " <<mBuff);
254 if (!keepctx)
delete ctxImpl;
284 0,
"Cache Flusher")))
286 snprintf(eBuff,
sizeof(eBuff),
287 "Unable to start cache flusher thread; rc=%d", rc);
295 SSL_CTX_set_session_cache_mode(pImpl->
ctx, SSL_SESS_CACHE_NO_AUTO_CLEAR);
313 #if OPENSSL_VERSION_NUMBER < 0x10100000L && defined(OPENSSL_THREADS)
316 #define XRDTLS_SET_CALLBACKS 1
325 struct tlsmix<false> {
326 static unsigned long mixer(
unsigned long x) {
329 x *= 0xbf58476d1ce4e5b9UL;
331 x *= 0x94d049bb133111ebUL;
338 struct tlsmix<true> {
339 static unsigned long mixer(
unsigned long x) {
350 unsigned long sslTLS_id_callback(
void)
359 return tlsmix<
sizeof(
unsigned long)==4>::mixer(x);
364 void sslTLS_lock(
int mode,
int n,
const char *file,
int line)
369 if (mode & CRYPTO_LOCK) MutexVector[n].
Lock();
370 else MutexVector[n].
UnLock();
377 #undef XRDTLS_SET_CALLBACKS
391 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
392 const char *sslCiphers =
"ECDHE-ECDSA-AES128-GCM-SHA256:"
393 "ECDHE-RSA-AES128-GCM-SHA256:"
394 "ECDHE-ECDSA-AES256-GCM-SHA384:"
395 "ECDHE-RSA-AES256-GCM-SHA384:"
396 "ECDHE-ECDSA-CHACHA20-POLY1305:"
397 "ECDHE-RSA-CHACHA20-POLY1305:"
398 "DHE-RSA-AES128-GCM-SHA256:"
399 "DHE-RSA-AES256-GCM-SHA384";
401 const char *sslCiphers =
"ALL:!LOW:!EXP:!MD5:!MD2";
406 bool initTlsDone{
false };
419 if (initTlsDone)
return;
425 OpenSSL_add_all_algorithms();
426 SSL_load_error_strings();
427 OpenSSL_add_all_ciphers();
428 #if OPENSSL_VERSION_NUMBER < 0x30000000L
429 ERR_load_BIO_strings();
431 ERR_load_crypto_strings();
435 #ifdef XRDTLS_SET_CALLBACKS
437 int n = CRYPTO_num_locks();
440 CRYPTO_set_locking_callback(sslTLS_lock);
442 CRYPTO_set_id_callback(sslTLS_id_callback);
451 void Fatal(std::string *
eMsg,
const char *msg,
bool sslmsg=
false)
467 const char *GetTlsMethod(
const SSL_METHOD *&meth)
469 #if OPENSSL_VERSION_NUMBER > 0x1010000fL
472 meth = SSLv23_method();
474 if (meth == 0)
return "No negotiable TLS method available.";
482 bool VerPaths(
const char *cert,
const char *pkey,
483 const char *cadr,
const char *cafl, std::string &
eMsg)
485 static const mode_t cert_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
486 static const mode_t pkey_mode = S_IRUSR | S_IWUSR;
487 static const mode_t cadr_mode = S_IRWXU | S_IRGRP | S_IXGRP
489 static const mode_t cafl_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
496 {
eMsg =
"Unable to use CA cert directory ";
505 {
eMsg =
"Unable to use CA cert file ";
514 {
eMsg =
"Unable to use key file ";
524 {mode_t cmode = (pkey ? cert_mode : pkey_mode);
526 {
if (pkey)
eMsg =
"Unable to use cert file ";
527 else eMsg =
"Unable to use cert+key file ";
544 int VerCB(
int aOK, X509_STORE_CTX *x509P)
547 {X509 *cert = X509_STORE_CTX_get_current_cert(x509P);
548 int depth = X509_STORE_CTX_get_error_depth(x509P);
549 int err = X509_STORE_CTX_get_error(x509P);
550 char name[512], info[1024];
552 X509_NAME_oneline(X509_get_subject_name(cert), name,
sizeof(name));
553 snprintf(info,
sizeof(info),
"Cert verification failed for DN=%s",name);
556 X509_NAME_oneline(X509_get_issuer_name(cert), name,
sizeof(name));
557 snprintf(info,
sizeof(info),
"Failing cert issuer=%s", name);
560 snprintf(info,
sizeof(info),
"Error %d at depth %d [%s]", err, depth,
561 X509_verify_cert_error_string(err));
575 #define KILL_CTX(x) if (x) {SSL_CTX_free(x); x = 0;}
577 #define FATAL(msg) {Fatal(eMsg, msg); KILL_CTX(pImpl->ctx); return;}
579 #define FATAL_SSL(msg) {Fatal(eMsg, msg, true); KILL_CTX(pImpl->ctx); return;}
582 const char *caDir,
const char *caFile,
589 void Keep() {ctxLoc = 0;}
591 ctx_helper(SSL_CTX **ctxP) : ctxLoc(ctxP) {}
592 ~ctx_helper() {
if (ctxLoc && *ctxLoc)
593 {SSL_CTX_free(*ctxLoc); *ctxLoc = 0;}
597 } ctx_tracker(&pImpl->
ctx);
601 static const uint64_t sslOpts = SSL_OP_ALL
604 | SSL_OP_NO_COMPRESSION
605 #ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
606 | SSL_OP_IGNORE_UNEXPECTED_EOF
608 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
609 | SSL_OP_NO_RENEGOTIATION
613 std::string certFN, eText;
627 if (!(
opts &
servr) && (dbg = getenv(
"XRDTLS_DEBUG")))
646 {
if (!caDir && !caFile)
647 {caDir = getenv(
"X509_CERT_DIR");
648 caFile = getenv(
"X509_CERT_FILE");
649 if (!caDir && !caFile)
650 FATAL(
"No CA cert specified; host identity cannot be verified.");
652 if (!key) key = getenv(
"X509_USER_KEY");
653 if (!cert) cert = getenv(
"X509_USER_PROXY");
656 long long int uid =
static_cast<long long int>(getuid());
657 certFN = std::string(
"/tmp/x509up_u") + std::to_string(uid);
658 if (!
stat(certFN.c_str(), &
Stat)) cert = certFN.c_str();
665 if (!VerPaths(cert, key, caDir, caFile, eText))
FATAL( eText.c_str());
686 const SSL_METHOD *meth;
687 emsg = GetTlsMethod(meth);
690 pImpl->
ctx = SSL_CTX_new(meth);
694 if (pImpl->
ctx == 0)
FATAL_SSL(
"Unable to allocate TLS context!");
698 SSL_CTX_set_options(pImpl->
ctx, sslOpts);
706 SSL_CTX_set_session_cache_mode(pImpl->
ctx, SSL_SESS_CACHE_OFF);
713 {
if (!SSL_CTX_load_verify_locations(pImpl->
ctx, caFile, caDir))
714 FATAL_SSL(
"Unable to load the CA cert file or directory.");
717 SSL_CTX_set_verify_depth(pImpl->
ctx, (vDepth ? vDepth : 9));
720 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, (LogVF ? VerCB : 0));
722 unsigned long xFlags = (
opts &
nopxy ? 0 : X509_V_FLAG_ALLOW_PROXY_CERTS);
724 {xFlags |= X509_V_FLAG_CRL_CHECK;
725 if (
opts &
crlFC) xFlags |= X509_V_FLAG_CRL_CHECK_ALL;
727 if (
opts) X509_STORE_set_flags(SSL_CTX_get_cert_store(pImpl->
ctx),xFlags);
729 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_NONE, 0);
734 if (!SSL_CTX_set_cipher_list(pImpl->
ctx, sslCiphers))
735 FATAL_SSL(
"Unable to set SSL cipher list; no supported ciphers.");
740 #if SSL_CTRL_SET_ECDH_AUTO
741 SSL_CTX_set_ecdh_auto(pImpl->
ctx, 1);
748 if (
opts &
artON) SSL_CTX_set_mode(pImpl->
ctx, SSL_MODE_AUTO_RETRY);
760 if (!key) key = cert;
764 if (SSL_CTX_use_certificate_chain_file(pImpl->
ctx, cert) != 1)
765 FATAL_SSL(
"Unable to create TLS context; invalid certificate.");
769 if (SSL_CTX_use_PrivateKey_file(pImpl->
ctx, key, SSL_FILETYPE_PEM) != 1 )
770 FATAL_SSL(
"Unable to create TLS context; invalid private key.");
774 if (SSL_CTX_check_private_key(pImpl->
ctx) != 1 )
775 FATAL_SSL(
"Unable to create TLS context; cert-key mismatch.");
808 const char *cert = (my.
cert.size() ? my.
cert.c_str() : 0);
809 const char *pkey = (my.
pkey.size() ? my.
pkey.c_str() : 0);
810 const char *caD = (my.
cadir.size() ? my.
cadir.c_str() : 0);
811 const char *caF = (my.
cafile.size() ? my.
cafile.c_str() : 0);
815 if (!full) caD = caF = 0;
870 #ifndef OPENSSL_THREADS
871 return "Installed OpenSSL lacks the required thread support!";
886 return pImpl->
ctx != 0;
901 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
911 {ssl = SSL_new(pImpl->
ctx);
925 {ssl = SSL_new(pImpl->
ctx);
932 DBG_CTX(
"Replacing x509 store with new contents.");
949 SSL_CTX_free(pImpl->
ctx);
950 pImpl->
ctx = ctxnew->pImpl->
ctx;
955 ctxnew->pImpl->
ctx = 0;
964 ssl = SSL_new(pImpl->
ctx);
977 return SSL_new(pImpl->
ctx);
996 if (pImpl->
ctx == 0)
return 0;
1001 {
if (
opts &
scOff) sslopt = SSL_SESS_CACHE_OFF;
1002 else {
if (
opts &
scSrvr) sslopt = SSL_SESS_CACHE_SERVER;
1003 if (
opts &
scClnt) sslopt |= SSL_SESS_CACHE_CLIENT;
1009 if (!(
opts & doSet)) sslopt = SSL_CTX_get_session_cache_mode(pImpl->
ctx);
1010 else {sslopt = SSL_CTX_set_session_cache_mode(pImpl->
ctx, sslopt);
1011 if (
opts &
scOff) SSL_CTX_set_options(pImpl->
ctx, SSL_OP_NO_TICKET);
1017 if (sslopt & SSL_SESS_CACHE_SERVER)
opts |=
scSrvr;
1018 if (sslopt & SSL_SESS_CACHE_CLIENT)
opts |=
scClnt;
1020 if (sslopt & SSL_SESS_CACHE_NO_AUTO_CLEAR)
opts |=
scKeep;
1025 if (
id && idlen > 0)
1026 {
if (!SSL_CTX_set_session_id_context(pImpl->
ctx,
1027 (
unsigned const char *)id,
1034 if (flushT && flushT != pImpl->
flushT)
1048 if (pImpl->
ctx && SSL_CTX_set_cipher_list(pImpl->
ctx, ciphers))
return true;
1051 snprintf(eBuff,
sizeof(eBuff),
"Unable to set context ciphers '%s'",ciphers);
1052 Fatal(0, eBuff,
true);
1062 sslCiphers = ciphers;
1071 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1097 snprintf(eBuff,
sizeof(eBuff),
1098 "Unable to start CRL refresh thread; rc=%d", rc);
1100 pImpl->crlMutex.UnLock();
1102 }
else pImpl->crlRunning =
true;
1103 pImpl->crlMutex.UnLock();
1115 XrdTls::Emsg(
"CrlRefresh:",
"Refreshing CRLs only supported in "
1116 "OpenSSL version >= 1.02; CRL refresh disabled!",
false);
1131 const std::string certPath = pImpl->
Parm.
cert;
1132 if(certPath.empty()) {
1136 time_t modificationTime;
1149 bool LogVF = (pImpl->
opts &
logVF) != 0;
1152 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, (LogVF ? VerCB : 0));
1155 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_NONE, 0);
void Fatal(const char *op, const char *target)
int emsg(int rc, char *msg)
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 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.
bool SetTlsClientAuth(ClientAuthSetting setting)
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)
bool SetCrlRefresh(int refsec=-1)
static const int scSrvr
Turn on cache server mode (default)
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.