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>
110 DBG_CTX(
"CRL refresh ending by request!");
116 DBG_CTX(
"CRL refresh will happen in " <<sleepTime <<
" seconds.");
126 if (!ctxImpl->
owner)
break;
137 if (!newctx || !newctx->
isOK())
138 {
XrdTls::Emsg(
"CrlRefresh:",
"Refresh of context failed!!!",
false);
145 doreplace = (ctxImpl->
ctxnew != 0);
146 if (doreplace)
delete ctxImpl->
ctxnew;
152 if (doreplace) {
DBG_CTX(
"CRL refresh created replacement x509 store.");}
153 else {
DBG_CTX(
"CRL refresh created new x509 store.");}
162 if (!keepctx)
delete ctxImpl;
181 time_t tStart, tWaited;
182 int flushT, waitT, hits, miss, sesn, tmos;
192 waitT = flushT = ctxImpl->
flushT;
197 DBG_CTX(
"Cache flusher started; interval="<<flushT<<
" seconds.");
203 tWaited= time(0) - tStart;
208 if (!ctxImpl->
owner)
break;
212 if (flushT != ctxImpl->
flushT && tWaited < ctxImpl->flushT-1)
213 {waitT = ctxImpl->
flushT - tWaited;
220 waitT = flushT = ctxImpl->
flushT;
225 sesn = SSL_CTX_sess_number(ctxImpl->
ctx);
226 hits = SSL_CTX_sess_hits(ctxImpl->
ctx);
227 miss = SSL_CTX_sess_misses(ctxImpl->
ctx);
228 tmos = SSL_CTX_sess_timeouts(ctxImpl->
ctx);
233 SSL_CTX_flush_sessions(ctxImpl->
ctx, tNow);
239 snprintf(mBuff,
sizeof(mBuff),
"sess=%d hits=%d miss=%d timeouts=%d",
240 sesn, hits, miss, tmos);
241 DBG_CTX(
"Cache flushed; " <<mBuff);
250 if (!keepctx)
delete ctxImpl;
280 0,
"Cache Flusher")))
282 snprintf(eBuff,
sizeof(eBuff),
283 "Unable to start cache flusher thread; rc=%d", rc);
291 SSL_CTX_set_session_cache_mode(pImpl->
ctx, SSL_SESS_CACHE_NO_AUTO_CLEAR);
309 #if OPENSSL_VERSION_NUMBER < 0x10100000L && defined(OPENSSL_THREADS)
312 #define XRDTLS_SET_CALLBACKS 1
321 struct tlsmix<false> {
322 static unsigned long mixer(
unsigned long x) {
325 x *= 0xbf58476d1ce4e5b9UL;
327 x *= 0x94d049bb133111ebUL;
334 struct tlsmix<true> {
335 static unsigned long mixer(
unsigned long x) {
346 unsigned long sslTLS_id_callback(
void)
355 return tlsmix<
sizeof(
unsigned long)==4>::mixer(x);
360 void sslTLS_lock(
int mode,
int n,
const char *file,
int line)
365 if (mode & CRYPTO_LOCK) MutexVector[n].
Lock();
366 else MutexVector[n].
UnLock();
373 #undef XRDTLS_SET_CALLBACKS
387 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
388 const char *sslCiphers =
"ECDHE-ECDSA-AES128-GCM-SHA256:"
389 "ECDHE-RSA-AES128-GCM-SHA256:"
390 "ECDHE-ECDSA-AES256-GCM-SHA384:"
391 "ECDHE-RSA-AES256-GCM-SHA384:"
392 "ECDHE-ECDSA-CHACHA20-POLY1305:"
393 "ECDHE-RSA-CHACHA20-POLY1305:"
394 "DHE-RSA-AES128-GCM-SHA256:"
395 "DHE-RSA-AES256-GCM-SHA384";
397 const char *sslCiphers =
"ALL:!LOW:!EXP:!MD5:!MD2";
402 bool initTlsDone{
false };
415 if (initTlsDone)
return;
421 OpenSSL_add_all_algorithms();
422 SSL_load_error_strings();
423 OpenSSL_add_all_ciphers();
424 #if OPENSSL_VERSION_NUMBER < 0x30000000L
425 ERR_load_BIO_strings();
427 ERR_load_crypto_strings();
431 #ifdef XRDTLS_SET_CALLBACKS
433 int n = CRYPTO_num_locks();
436 CRYPTO_set_locking_callback(sslTLS_lock);
438 CRYPTO_set_id_callback(sslTLS_id_callback);
447 void Fatal(std::string *
eMsg,
const char *msg,
bool sslmsg=
false)
463 const char *GetTlsMethod(
const SSL_METHOD *&meth)
465 #if OPENSSL_VERSION_NUMBER > 0x1010000fL
468 meth = SSLv23_method();
470 if (meth == 0)
return "No negotiable TLS method available.";
478 bool VerPaths(
const char *cert,
const char *pkey,
479 const char *cadr,
const char *cafl, std::string &
eMsg)
481 static const mode_t cert_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
482 static const mode_t pkey_mode = S_IRUSR | S_IWUSR;
483 static const mode_t cadr_mode = S_IRWXU | S_IRGRP | S_IXGRP
485 static const mode_t cafl_mode = S_IRUSR | S_IWUSR | S_IRWXG | S_IROTH;
492 {
eMsg =
"Unable to use CA cert directory ";
501 {
eMsg =
"Unable to use CA cert file ";
510 {
eMsg =
"Unable to use key file ";
520 {mode_t cmode = (pkey ? cert_mode : pkey_mode);
522 {
if (pkey)
eMsg =
"Unable to use cert file ";
523 else eMsg =
"Unable to use cert+key file ";
540 int VerCB(
int aOK, X509_STORE_CTX *x509P)
543 {X509 *cert = X509_STORE_CTX_get_current_cert(x509P);
544 int depth = X509_STORE_CTX_get_error_depth(x509P);
545 int err = X509_STORE_CTX_get_error(x509P);
546 char name[512], info[1024];
548 X509_NAME_oneline(X509_get_subject_name(cert), name,
sizeof(name));
549 snprintf(info,
sizeof(info),
"Cert verification failed for DN=%s",name);
552 X509_NAME_oneline(X509_get_issuer_name(cert), name,
sizeof(name));
553 snprintf(info,
sizeof(info),
"Failing cert issuer=%s", name);
556 snprintf(info,
sizeof(info),
"Error %d at depth %d [%s]", err, depth,
557 X509_verify_cert_error_string(err));
571 #define KILL_CTX(x) if (x) {SSL_CTX_free(x); x = 0;}
573 #define FATAL(msg) {Fatal(eMsg, msg); KILL_CTX(pImpl->ctx); return;}
575 #define FATAL_SSL(msg) {Fatal(eMsg, msg, true); KILL_CTX(pImpl->ctx); return;}
578 const char *caDir,
const char *caFile,
585 void Keep() {ctxLoc = 0;}
587 ctx_helper(SSL_CTX **ctxP) : ctxLoc(ctxP) {}
588 ~ctx_helper() {
if (ctxLoc && *ctxLoc)
589 {SSL_CTX_free(*ctxLoc); *ctxLoc = 0;}
593 } ctx_tracker(&pImpl->
ctx);
597 static const uint64_t sslOpts = SSL_OP_ALL
600 | SSL_OP_NO_COMPRESSION
601 #ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
602 | SSL_OP_IGNORE_UNEXPECTED_EOF
604 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
605 | SSL_OP_NO_RENEGOTIATION
609 std::string certFN, eText;
623 if (!(
opts &
servr) && (dbg = getenv(
"XRDTLS_DEBUG")))
642 {
if (!caDir && !caFile)
643 {caDir = getenv(
"X509_CERT_DIR");
644 caFile = getenv(
"X509_CERT_FILE");
645 if (!caDir && !caFile)
646 FATAL(
"No CA cert specified; host identity cannot be verified.");
648 if (!key) key = getenv(
"X509_USER_KEY");
649 if (!cert) cert = getenv(
"X509_USER_PROXY");
652 long long int uid =
static_cast<long long int>(getuid());
653 certFN = std::string(
"/tmp/x509up_u") + std::to_string(uid);
654 if (!
stat(certFN.c_str(), &
Stat)) cert = certFN.c_str();
661 if (!VerPaths(cert, key, caDir, caFile, eText))
FATAL( eText.c_str());
682 const SSL_METHOD *meth;
683 emsg = GetTlsMethod(meth);
686 pImpl->
ctx = SSL_CTX_new(meth);
690 if (pImpl->
ctx == 0)
FATAL_SSL(
"Unable to allocate TLS context!");
694 SSL_CTX_set_options(pImpl->
ctx, sslOpts);
702 SSL_CTX_set_session_cache_mode(pImpl->
ctx, SSL_SESS_CACHE_OFF);
709 {
if (!SSL_CTX_load_verify_locations(pImpl->
ctx, caFile, caDir))
710 FATAL_SSL(
"Unable to load the CA cert file or directory.");
713 SSL_CTX_set_verify_depth(pImpl->
ctx, (vDepth ? vDepth : 9));
716 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, (LogVF ? VerCB : 0));
718 unsigned long xFlags = (
opts &
nopxy ? 0 : X509_V_FLAG_ALLOW_PROXY_CERTS);
720 {xFlags |= X509_V_FLAG_CRL_CHECK;
721 if (
opts &
crlFC) xFlags |= X509_V_FLAG_CRL_CHECK_ALL;
723 if (
opts) X509_STORE_set_flags(SSL_CTX_get_cert_store(pImpl->
ctx),xFlags);
725 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_NONE, 0);
730 if (!SSL_CTX_set_cipher_list(pImpl->
ctx, sslCiphers))
731 FATAL_SSL(
"Unable to set SSL cipher list; no supported ciphers.");
736 #if SSL_CTRL_SET_ECDH_AUTO
737 SSL_CTX_set_ecdh_auto(pImpl->
ctx, 1);
744 if (
opts &
artON) SSL_CTX_set_mode(pImpl->
ctx, SSL_MODE_AUTO_RETRY);
756 if (!key) key = cert;
760 if (SSL_CTX_use_certificate_chain_file(pImpl->
ctx, cert) != 1)
761 FATAL_SSL(
"Unable to create TLS context; invalid certificate.");
765 if (SSL_CTX_use_PrivateKey_file(pImpl->
ctx, key, SSL_FILETYPE_PEM) != 1 )
766 FATAL_SSL(
"Unable to create TLS context; invalid private key.");
770 if (SSL_CTX_check_private_key(pImpl->
ctx) != 1 )
771 FATAL_SSL(
"Unable to create TLS context; cert-key mismatch.");
804 const char *cert = (my.
cert.size() ? my.
cert.c_str() : 0);
805 const char *pkey = (my.
pkey.size() ? my.
pkey.c_str() : 0);
806 const char *caD = (my.
cadir.size() ? my.
cadir.c_str() : 0);
807 const char *caF = (my.
cafile.size() ? my.
cafile.c_str() : 0);
811 if (!full) caD = caF = 0;
866 #ifndef OPENSSL_THREADS
867 return "Installed OpenSSL lacks the required thread support!";
882 return pImpl->
ctx != 0;
897 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
907 {ssl = SSL_new(pImpl->
ctx);
921 {ssl = SSL_new(pImpl->
ctx);
928 DBG_CTX(
"Replacing x509 store with new contents.");
945 SSL_CTX_free(pImpl->
ctx);
946 pImpl->
ctx = ctxnew->pImpl->
ctx;
951 ctxnew->pImpl->
ctx = 0;
960 ssl = SSL_new(pImpl->
ctx);
973 return SSL_new(pImpl->
ctx);
992 if (pImpl->
ctx == 0)
return 0;
997 {
if (
opts &
scOff) sslopt = SSL_SESS_CACHE_OFF;
998 else {
if (
opts &
scSrvr) sslopt = SSL_SESS_CACHE_SERVER;
999 if (
opts &
scClnt) sslopt |= SSL_SESS_CACHE_CLIENT;
1005 if (!(
opts & doSet)) sslopt = SSL_CTX_get_session_cache_mode(pImpl->
ctx);
1006 else {sslopt = SSL_CTX_set_session_cache_mode(pImpl->
ctx, sslopt);
1007 if (
opts &
scOff) SSL_CTX_set_options(pImpl->
ctx, SSL_OP_NO_TICKET);
1013 if (sslopt & SSL_SESS_CACHE_SERVER)
opts |=
scSrvr;
1014 if (sslopt & SSL_SESS_CACHE_CLIENT)
opts |=
scClnt;
1016 if (sslopt & SSL_SESS_CACHE_NO_AUTO_CLEAR)
opts |=
scKeep;
1021 if (
id && idlen > 0)
1022 {
if (!SSL_CTX_set_session_id_context(pImpl->
ctx,
1023 (
unsigned const char *)id,
1030 if (flushT && flushT != pImpl->
flushT)
1044 if (pImpl->
ctx && SSL_CTX_set_cipher_list(pImpl->
ctx, ciphers))
return true;
1047 snprintf(eBuff,
sizeof(eBuff),
"Unable to set context ciphers '%s'",ciphers);
1048 Fatal(0, eBuff,
true);
1058 sslCiphers = ciphers;
1067 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1093 snprintf(eBuff,
sizeof(eBuff),
1094 "Unable to start CRL refresh thread; rc=%d", rc);
1096 pImpl->crlMutex.UnLock();
1098 }
else pImpl->crlRunning =
true;
1099 pImpl->crlMutex.UnLock();
1111 XrdTls::Emsg(
"CrlRefresh:",
"Refreshing CRLs only supported in "
1112 "OpenSSL version >= 1.02; CRL refresh disabled!",
false);
1127 const std::string certPath = pImpl->
Parm.
cert;
1128 if(certPath.empty()) {
1132 time_t modificationTime;
1145 bool LogVF = (pImpl->
opts &
logVF) != 0;
1148 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_PEER, (LogVF ? VerCB : 0));
1151 SSL_CTX_set_verify(pImpl->
ctx, SSL_VERIFY_NONE, 0);
void Fatal(const char *op, const char *target)
int stat(const char *path, struct stat *buf)
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.