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);
312#if OPENSSL_VERSION_NUMBER < 0x10100000L && defined(OPENSSL_THREADS)
315#define XRDTLS_SET_CALLBACKS 1
324struct tlsmix<false> {
325 static unsigned long mixer(
unsigned long x) {
328 x *= 0xbf58476d1ce4e5b9UL;
330 x *= 0x94d049bb133111ebUL;
338 static unsigned long mixer(
unsigned long x) {
349unsigned long sslTLS_id_callback(
void)
358 return tlsmix<
sizeof(
unsigned long)==4>::mixer(x);
363void sslTLS_lock(
int mode,
int n,
const char *file,
int line)
368 if (mode & CRYPTO_LOCK) MutexVector[n].
Lock();
369 else MutexVector[n].
UnLock();
376#undef XRDTLS_SET_CALLBACKS
390#if OPENSSL_VERSION_NUMBER >= 0x10002000L
391const char *sslCiphers =
"ECDHE-ECDSA-AES128-GCM-SHA256:"
392 "ECDHE-RSA-AES128-GCM-SHA256:"
393 "ECDHE-ECDSA-AES256-GCM-SHA384:"
394 "ECDHE-RSA-AES256-GCM-SHA384:"
395 "ECDHE-ECDSA-CHACHA20-POLY1305:"
396 "ECDHE-RSA-CHACHA20-POLY1305:"
397 "DHE-RSA-AES128-GCM-SHA256:"
398 "DHE-RSA-AES256-GCM-SHA384";
400const char *sslCiphers =
"ALL:!LOW:!EXP:!MD5:!MD2";
405bool initTlsDone{
false };
418 if (initTlsDone)
return;
424 OpenSSL_add_all_algorithms();
425 SSL_load_error_strings();
426 OpenSSL_add_all_ciphers();
427#if OPENSSL_VERSION_NUMBER < 0x30000000L
428 ERR_load_BIO_strings();
430 ERR_load_crypto_strings();
434#ifdef XRDTLS_SET_CALLBACKS
436 int n = CRYPTO_num_locks();
439 CRYPTO_set_locking_callback(sslTLS_lock);
441 CRYPTO_set_id_callback(sslTLS_id_callback);
450void Fatal(std::string *
eMsg,
const char *msg,
bool sslmsg=
false)
466const char *GetTlsMethod(
const SSL_METHOD *&meth)
468#if OPENSSL_VERSION_NUMBER > 0x1010000fL
471 meth = SSLv23_method();
473 if (meth == 0)
return "No negotiable TLS method available.";
481bool VerPaths(
const char *cert,
const char *pkey,
482 const char *cadr,
const char *cafl, std::string &
eMsg)
484 static const mode_t cert_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
485 static const mode_t pkey_mode = S_IRUSR | S_IWUSR;
486 static const mode_t cadr_mode = S_IRWXU | S_IRGRP | S_IXGRP
488 static const mode_t cafl_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
495 {
eMsg =
"Unable to use CA cert directory ";
504 {
eMsg =
"Unable to use CA cert file ";
513 {
eMsg =
"Unable to use key file ";
523 {mode_t cmode = (pkey ? cert_mode : pkey_mode);
525 {
if (pkey)
eMsg =
"Unable to use cert file ";
526 else eMsg =
"Unable to use cert+key file ";
543int VerCB(
int aOK, X509_STORE_CTX *x509P)
546 {X509 *cert = X509_STORE_CTX_get_current_cert(x509P);
547 int depth = X509_STORE_CTX_get_error_depth(x509P);
548 int err = X509_STORE_CTX_get_error(x509P);
549 char name[512], info[1024];
551 X509_NAME_oneline(X509_get_subject_name(cert), name,
sizeof(name));
552 snprintf(info,
sizeof(info),
"Cert verification failed for DN=%s",name);
555 X509_NAME_oneline(X509_get_issuer_name(cert), name,
sizeof(name));
556 snprintf(info,
sizeof(info),
"Failing cert issuer=%s", name);
559 snprintf(info,
sizeof(info),
"Error %d at depth %d [%s]", err, depth,
560 X509_verify_cert_error_string(err));
574#define KILL_CTX(x) if (x) {SSL_CTX_free(x); x = 0;}
576#define FATAL(msg) {Fatal(eMsg, msg); KILL_CTX(pImpl->ctx); return;}
578#define FATAL_SSL(msg) {Fatal(eMsg, msg, true); KILL_CTX(pImpl->ctx); return;}
581 const char *caDir,
const char *caFile,
588 void Keep() {ctxLoc = 0;}
590 ctx_helper(SSL_CTX **ctxP) : ctxLoc(ctxP) {}
591 ~ctx_helper() {
if (ctxLoc && *ctxLoc)
592 {SSL_CTX_free(*ctxLoc); *ctxLoc = 0;}
596 } ctx_tracker(&pImpl->
ctx);
598 static const uint64_t sslOpts = SSL_OP_ALL
601 | SSL_OP_NO_COMPRESSION
602#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
603 | SSL_OP_IGNORE_UNEXPECTED_EOF
605#if OPENSSL_VERSION_NUMBER >= 0x10101000L
606 | SSL_OP_NO_RENEGOTIATION
610 std::string certFN, eText;
624 if (!(
opts &
servr) && (dbg = getenv(
"XRDTLS_DEBUG")))
643 {
if (!caDir && !caFile)
644 {caDir = getenv(
"X509_CERT_DIR");
645 caFile = getenv(
"X509_CERT_FILE");
646 if (!caDir && !caFile)
647 FATAL(
"No CA cert specified; host identity cannot be verified.");
649 if (!key) key = getenv(
"X509_USER_KEY");
650 if (!cert) cert = getenv(
"X509_USER_PROXY");
653 long long int uid =
static_cast<long long int>(getuid());
654 certFN = std::string(
"/tmp/x509up_u") + std::to_string(uid);
655 if (!
stat(certFN.c_str(), &
Stat)) cert = certFN.c_str();
662 if (!VerPaths(cert, key, caDir, caFile, eText))
FATAL( eText.c_str());
683 const SSL_METHOD *meth;
684 emsg = GetTlsMethod(meth);
687 pImpl->
ctx = SSL_CTX_new(meth);
691 if (pImpl->
ctx == 0)
FATAL_SSL(
"Unable to allocate TLS context!");
695 SSL_CTX_set_options(pImpl->
ctx, sslOpts);
703 SSL_CTX_set_session_cache_mode(pImpl->
ctx, SSL_SESS_CACHE_OFF);
710 {
if (!SSL_CTX_load_verify_locations(pImpl->
ctx, caFile, caDir))
711 FATAL_SSL(
"Unable to load the CA cert file or directory.");
714 SSL_CTX_set_verify_depth(pImpl->
ctx, (vDepth ? vDepth : 9));
717 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, (LogVF ? VerCB : 0));
719 unsigned long xFlags = (
opts &
nopxy ? 0 : X509_V_FLAG_ALLOW_PROXY_CERTS);
721 {xFlags |= X509_V_FLAG_CRL_CHECK;
722 if (
opts &
crlFC) xFlags |= X509_V_FLAG_CRL_CHECK_ALL;
724 if (
opts) X509_STORE_set_flags(SSL_CTX_get_cert_store(pImpl->
ctx),xFlags);
726 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_NONE, 0);
731 if (!SSL_CTX_set_cipher_list(pImpl->
ctx, sslCiphers))
732 FATAL_SSL(
"Unable to set SSL cipher list; no supported ciphers.");
737#if SSL_CTRL_SET_ECDH_AUTO
738 SSL_CTX_set_ecdh_auto(pImpl->
ctx, 1);
745 if (
opts &
artON) SSL_CTX_set_mode(pImpl->
ctx, SSL_MODE_AUTO_RETRY);
757 if (!key) key = cert;
761 if (SSL_CTX_use_certificate_chain_file(pImpl->
ctx, cert) != 1)
762 FATAL_SSL(
"Unable to create TLS context; invalid certificate.");
766 if (SSL_CTX_use_PrivateKey_file(pImpl->
ctx, key, SSL_FILETYPE_PEM) != 1 )
767 FATAL_SSL(
"Unable to create TLS context; invalid private key.");
771 if (SSL_CTX_check_private_key(pImpl->
ctx) != 1 )
772 FATAL_SSL(
"Unable to create TLS context; cert-key mismatch.");
805 const char *cert = (my.
cert.size() ? my.
cert.c_str() : 0);
806 const char *pkey = (my.
pkey.size() ? my.
pkey.c_str() : 0);
807 const char *caD = (my.
cadir.size() ? my.
cadir.c_str() : 0);
808 const char *caF = (my.
cafile.size() ? my.
cafile.c_str() : 0);
812 if (!full) caD = caF = 0;
867#ifndef OPENSSL_THREADS
868 return "Installed OpenSSL lacks the required thread support!";
883 return pImpl->
ctx != 0;
898#if OPENSSL_VERSION_NUMBER >= 0x10002000L
908 {ssl = SSL_new(pImpl->
ctx);
922 {ssl = SSL_new(pImpl->
ctx);
929 DBG_CTX(
"Replacing x509 store with new contents.");
946 SSL_CTX_free(pImpl->
ctx);
947 pImpl->
ctx = ctxnew->pImpl->
ctx;
952 ctxnew->pImpl->
ctx = 0;
961 ssl = SSL_new(pImpl->
ctx);
974 return SSL_new(pImpl->
ctx);
993 if (pImpl->
ctx == 0)
return 0;
998 {
if (
opts &
scOff) sslopt = SSL_SESS_CACHE_OFF;
999 else {
if (
opts &
scSrvr) sslopt = SSL_SESS_CACHE_SERVER;
1000 if (
opts &
scClnt) sslopt |= SSL_SESS_CACHE_CLIENT;
1006 if (!(
opts & doSet)) sslopt = SSL_CTX_get_session_cache_mode(pImpl->
ctx);
1007 else {sslopt = SSL_CTX_set_session_cache_mode(pImpl->
ctx, sslopt);
1008 if (
opts &
scOff) SSL_CTX_set_options(pImpl->
ctx, SSL_OP_NO_TICKET);
1014 if (sslopt & SSL_SESS_CACHE_SERVER)
opts |=
scSrvr;
1015 if (sslopt & SSL_SESS_CACHE_CLIENT)
opts |=
scClnt;
1017 if (sslopt & SSL_SESS_CACHE_NO_AUTO_CLEAR)
opts |=
scKeep;
1022 if (
id && idlen > 0)
1023 {
if (!SSL_CTX_set_session_id_context(pImpl->
ctx,
1024 (
unsigned const char *)id,
1031 if (flushT && flushT != pImpl->
flushT)
1045 if (pImpl->
ctx && SSL_CTX_set_cipher_list(pImpl->
ctx, ciphers))
return true;
1048 snprintf(eBuff,
sizeof(eBuff),
"Unable to set context ciphers '%s'",ciphers);
1049 Fatal(0, eBuff,
true);
1059 sslCiphers = ciphers;
1068#if OPENSSL_VERSION_NUMBER >= 0x10002000L
1094 snprintf(eBuff,
sizeof(eBuff),
1095 "Unable to start CRL refresh thread; rc=%d", rc);
1097 pImpl->crlMutex.UnLock();
1099 }
else pImpl->crlRunning =
true;
1100 pImpl->crlMutex.UnLock();
1112 XrdTls::Emsg(
"CrlRefresh:",
"Refreshing CRLs only supported in "
1113 "OpenSSL version >= 1.02; CRL refresh disabled!",
false);
1128 const std::string certPath = pImpl->
Parm.
cert;
1129 if(certPath.empty()) {
1133 time_t modificationTime;
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.
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)
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.