2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * CURLSOAPTransport.cpp
24 * libcurl-based SOAPTransport implementation.
28 #include "exceptions.h"
30 #include "security/CredentialCriteria.h"
31 #include "security/OpenSSLTrustEngine.h"
32 #include "security/OpenSSLCredential.h"
33 #include "soap/HTTPSOAPTransport.h"
34 #include "soap/OpenSSLSOAPTransport.h"
36 #include "util/Threads.h"
39 #include <curl/curl.h>
40 #include <openssl/x509_vfy.h>
42 using namespace xmltooling::logging;
43 using namespace xmltooling;
46 namespace xmltooling {
48 // Manages cache of socket connections via CURL handles.
49 class XMLTOOL_DLLLOCAL CURLPool
52 CURLPool() : m_size(0), m_lock(Mutex::create()),
53 m_log(Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL")) {}
56 CURL* get(const SOAPTransport::Address& addr);
57 void put(const char* from, const char* to, const char* endpoint, CURL* handle);
60 typedef map<string,vector<CURL*> > poolmap_t;
61 poolmap_t m_bindingMap;
62 list< vector<CURL*>* > m_pools;
68 static XMLTOOL_DLLLOCAL CURLPool* g_CURLPool = nullptr;
70 class XMLTOOL_DLLLOCAL CURLSOAPTransport : public HTTPSOAPTransport, public OpenSSLSOAPTransport
73 CURLSOAPTransport(const Address& addr)
74 : m_sender(addr.m_from ? addr.m_from : ""), m_peerName(addr.m_to ? addr.m_to : ""), m_endpoint(addr.m_endpoint),
75 m_handle(nullptr), m_keepHandle(false), m_headers(nullptr),
76 #ifdef HAVE_CURLINFO_TLS_SSL_PTR
77 m_cipherLogged(false),
79 #ifndef XMLTOOLING_NO_XMLSEC
80 m_cred(nullptr), m_trustEngine(nullptr), m_peerResolver(nullptr), m_mandatory(false),
82 m_openssl_ops(SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3), m_ssl_callback(nullptr), m_ssl_userptr(nullptr),
83 m_chunked(true), m_authenticated(false), m_cacheTag(nullptr) {
84 m_handle = g_CURLPool->get(addr);
85 curl_easy_setopt(m_handle,CURLOPT_URL,addr.m_endpoint);
86 curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,15);
87 curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,30);
88 curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0);
89 curl_easy_setopt(m_handle,CURLOPT_USERPWD,0);
90 curl_easy_setopt(m_handle,CURLOPT_SSL_VERIFYHOST,2);
91 curl_easy_setopt(m_handle,CURLOPT_HEADERDATA,this);
92 m_headers=curl_slist_append(m_headers,"Content-Type: text/xml");
95 virtual ~CURLSOAPTransport() {
96 curl_slist_free_all(m_headers);
98 curl_easy_setopt(m_handle, CURLOPT_USERAGENT, 0);
99 curl_easy_setopt(m_handle, CURLOPT_ERRORBUFFER, 0);
100 curl_easy_setopt(m_handle, CURLOPT_PRIVATE, m_authenticated ? "secure" : 0); // Save off security "state".
101 g_CURLPool->put(m_sender.c_str(), m_peerName.c_str(), m_endpoint.c_str(), m_handle);
104 curl_easy_cleanup(m_handle);
108 bool isConfidential() const {
109 return m_endpoint.find("https")==0;
112 bool setConnectTimeout(long timeout) {
113 return (curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,timeout)==CURLE_OK);
116 bool setTimeout(long timeout) {
117 return (curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,timeout)==CURLE_OK);
120 bool setAuth(transport_auth_t authType, const char* username=nullptr, const char* password=nullptr);
122 bool setVerifyHost(bool verify) {
123 return (curl_easy_setopt(m_handle,CURLOPT_SSL_VERIFYHOST,verify ? 2 : 0)==CURLE_OK);
126 #ifndef XMLTOOLING_NO_XMLSEC
127 bool setCredential(const Credential* cred=nullptr) {
128 const OpenSSLCredential* down = dynamic_cast<const OpenSSLCredential*>(cred);
131 return (cred==nullptr);
138 const X509TrustEngine* trustEngine=nullptr,
139 const CredentialResolver* peerResolver=nullptr,
140 CredentialCriteria* criteria=nullptr,
143 const OpenSSLTrustEngine* down = dynamic_cast<const OpenSSLTrustEngine*>(trustEngine);
145 m_trustEngine = nullptr;
146 m_peerResolver = nullptr;
147 m_criteria = nullptr;
148 return (trustEngine==nullptr);
150 m_trustEngine = down;
151 m_peerResolver = peerResolver;
152 m_criteria = criteria;
153 m_mandatory = mandatory;
159 bool useChunkedEncoding(bool chunked=true) {
164 bool followRedirects(bool follow, unsigned int maxRedirs) {
166 curl_easy_setopt(m_handle, CURLOPT_FOLLOWLOCATION, (follow ? 1 : 0)) == CURLE_OK &&
167 curl_easy_setopt(m_handle, CURLOPT_MAXREDIRS, (follow ? maxRedirs : 0)) == CURLE_OK
171 bool setCacheTag(string* cacheTag) {
172 m_cacheTag = cacheTag;
176 bool setProviderOption(const char* provider, const char* option, const char* value);
178 void send(istream& in) {
182 void send(istream* in=nullptr);
188 bool isAuthenticated() const {
189 return m_authenticated;
192 void setAuthenticated(bool auth) {
193 m_authenticated = auth;
196 string getContentType() const;
197 long getStatusCode() const;
199 bool setRequestHeader(const char* name, const char* val) {
201 temp=temp + ": " + val;
202 m_headers=curl_slist_append(m_headers,temp.c_str());
206 const vector<string>& getResponseHeader(const char* val) const;
208 bool setSSLCallback(ssl_ctx_callback_fn fn, void* userptr=nullptr) {
210 m_ssl_userptr=userptr;
214 bool setCipherSuites(const char* cipherlist) {
215 return (curl_easy_setopt(m_handle,CURLOPT_SSL_CIPHER_LIST,cipherlist)==CURLE_OK);
220 string m_sender,m_peerName,m_endpoint,m_simplecreds;
223 stringstream m_stream;
224 struct curl_slist* m_headers;
226 map<string,vector<string> > m_response_headers;
227 vector<string> m_saved_options;
228 #ifdef HAVE_CURLINFO_TLS_SSL_PTR
231 #ifndef XMLTOOLING_NO_XMLSEC
232 const OpenSSLCredential* m_cred;
233 const OpenSSLTrustEngine* m_trustEngine;
234 const CredentialResolver* m_peerResolver;
235 CredentialCriteria* m_criteria;
239 ssl_ctx_callback_fn m_ssl_callback;
242 bool m_authenticated;
245 friend size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
246 friend CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
247 friend int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
250 // libcurl callback functions
251 size_t XMLTOOL_DLLLOCAL curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream);
252 size_t XMLTOOL_DLLLOCAL curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream);
253 size_t XMLTOOL_DLLLOCAL curl_read_hook( void *ptr, size_t size, size_t nmemb, void *stream);
254 int XMLTOOL_DLLLOCAL curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr);
255 CURLcode XMLTOOL_DLLLOCAL xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr);
256 #ifndef XMLTOOLING_NO_XMLSEC
257 int XMLTOOL_DLLLOCAL verify_callback(X509_STORE_CTX* x509_ctx, void* arg);
260 SOAPTransport* CURLSOAPTransportFactory(const SOAPTransport::Address& addr)
262 return new CURLSOAPTransport(addr);
266 void xmltooling::initSOAPTransports()
268 g_CURLPool=new CURLPool();
271 void xmltooling::termSOAPTransports()
274 g_CURLPool = nullptr;
277 CURLPool::~CURLPool()
279 for (poolmap_t::iterator i=m_bindingMap.begin(); i!=m_bindingMap.end(); i++) {
280 for (vector<CURL*>::iterator j=i->second.begin(); j!=i->second.end(); j++)
281 curl_easy_cleanup(*j);
286 CURL* CURLPool::get(const SOAPTransport::Address& addr)
289 xmltooling::NDC("get");
291 m_log.debug("getting connection handle to %s", addr.m_endpoint);
292 string key(addr.m_endpoint);
294 key = key + '|' + addr.m_from;
296 key = key + '|' + addr.m_to;
298 poolmap_t::iterator i=m_bindingMap.find(key);
300 if (i!=m_bindingMap.end()) {
301 // Move this pool to the front of the list.
302 m_pools.remove(&(i->second));
303 m_pools.push_front(&(i->second));
305 // If a free connection exists, return it.
306 if (!(i->second.empty())) {
307 CURL* handle=i->second.back();
308 i->second.pop_back();
311 m_log.debug("returning existing connection handle from pool");
317 m_log.debug("nothing free in pool, returning new connection handle");
319 // Create a new connection and set non-varying options.
320 CURL* handle=curl_easy_init();
323 curl_easy_setopt(handle,CURLOPT_NOPROGRESS,1);
324 curl_easy_setopt(handle,CURLOPT_NOSIGNAL,1);
325 curl_easy_setopt(handle,CURLOPT_FAILONERROR,1);
326 // This may (but probably won't) help with < 7.20 bug in DNS caching.
327 curl_easy_setopt(handle,CURLOPT_DNS_CACHE_TIMEOUT,120);
328 curl_easy_setopt(handle,CURLOPT_SSL_CIPHER_LIST,"ALL:!aNULL:!LOW:!EXPORT:!RC4:!SSLv2");
329 // Verification of the peer is via TrustEngine only.
330 curl_easy_setopt(handle,CURLOPT_SSL_VERIFYPEER,0);
331 curl_easy_setopt(handle,CURLOPT_CAINFO,0);
332 curl_easy_setopt(handle,CURLOPT_HEADERFUNCTION,&curl_header_hook);
333 curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION,&curl_write_hook);
334 curl_easy_setopt(handle,CURLOPT_DEBUGFUNCTION,&curl_debug_hook);
338 void CURLPool::put(const char* from, const char* to, const char* endpoint, CURL* handle)
340 string key(endpoint);
342 key = key + '|' + from;
344 key = key + '|' + to;
346 poolmap_t::iterator i=m_bindingMap.find(key);
347 if (i==m_bindingMap.end())
348 m_pools.push_front(&(m_bindingMap.insert(poolmap_t::value_type(key,vector<CURL*>(1,handle))).first->second));
350 i->second.push_back(handle);
352 CURL* killit=nullptr;
353 if (++m_size > 256) {
354 // Kick a handle out from the back of the bus.
356 vector<CURL*>* corpse=m_pools.back();
357 if (!corpse->empty()) {
358 killit=corpse->back();
364 // Move an empty pool up to the front so we don't keep hitting it.
366 m_pools.push_front(corpse);
371 curl_easy_cleanup(killit);
373 xmltooling::NDC("put");
375 m_log.info("conn_pool_max limit reached, dropping an old connection");
379 bool CURLSOAPTransport::setAuth(transport_auth_t authType, const char* username, const char* password)
381 if (authType==transport_auth_none) {
382 if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0)!=CURLE_OK)
384 return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,0)==CURLE_OK);
388 case transport_auth_basic: flag = CURLAUTH_BASIC; break;
389 case transport_auth_digest: flag = CURLAUTH_DIGEST; break;
390 case transport_auth_ntlm: flag = CURLAUTH_NTLM; break;
391 case transport_auth_gss: flag = CURLAUTH_GSSNEGOTIATE; break;
392 default: return false;
394 if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,flag)!=CURLE_OK)
396 m_simplecreds = string(username ? username : "") + ':' + (password ? password : "");
397 return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,m_simplecreds.c_str())==CURLE_OK);
400 bool CURLSOAPTransport::setProviderOption(const char* provider, const char* option, const char* value)
402 if (!provider || !option || !value) {
405 else if (!strcmp(provider, "OpenSSL")) {
406 if (!strcmp(option, "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION") && (*value=='1' || *value=='t')) {
407 // If the new option to enable buggy rengotiation is available, set it.
408 // Otherwise, signal false if this is newer than 0.9.8k, because that
409 // means it's 0.9.8l, which blocks renegotiation, and therefore will
410 // not honor this request. Older versions are buggy, so behave as though
411 // the flag was set anyway, so we signal true.
412 #if defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
413 m_openssl_ops |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
415 #elif (OPENSSL_VERSION_NUMBER > 0x009080bfL)
423 else if (strcmp(provider, "CURL")) {
427 // For libcurl, the option is an enum and the value type depends on the option.
428 CURLoption opt = static_cast<CURLoption>(strtol(option, nullptr, 10));
429 if (opt < CURLOPTTYPE_OBJECTPOINT)
430 return (curl_easy_setopt(m_handle, opt, strtol(value, nullptr, 10)) == CURLE_OK);
431 #ifdef CURLOPTTYPE_OFF_T
432 else if (opt < CURLOPTTYPE_OFF_T) {
434 m_saved_options.push_back(value);
435 return (curl_easy_setopt(m_handle, opt, value ? m_saved_options.back().c_str() : 0) == CURLE_OK);
437 # ifdef HAVE_CURL_OFF_T
438 else if (sizeof(curl_off_t) == sizeof(long))
439 return (curl_easy_setopt(m_handle, opt, strtol(value, nullptr, 10)) == CURLE_OK);
441 else if (sizeof(off_t) == sizeof(long))
442 return (curl_easy_setopt(m_handle, opt, strtol(value, nullptr, 10)) == CURLE_OK);
448 m_saved_options.push_back(value);
449 return (curl_easy_setopt(m_handle, opt, value ? m_saved_options.back().c_str() : 0) == CURLE_OK);
454 const vector<string>& CURLSOAPTransport::getResponseHeader(const char* name) const
456 static vector<string> emptyVector;
458 map<string,vector<string> >::const_iterator i=m_response_headers.find(name);
459 if (i!=m_response_headers.end())
462 for (map<string,vector<string> >::const_iterator j=m_response_headers.begin(); j!=m_response_headers.end(); j++) {
463 #ifdef HAVE_STRCASECMP
464 if (!strcasecmp(j->first.c_str(), name))
466 if (!stricmp(j->first.c_str(), name))
474 string CURLSOAPTransport::getContentType() const
476 char* content_type=nullptr;
477 curl_easy_getinfo(m_handle,CURLINFO_CONTENT_TYPE,&content_type);
478 return content_type ? content_type : "";
481 long CURLSOAPTransport::getStatusCode() const
484 if (curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &code) != CURLE_OK)
489 void CURLSOAPTransport::send(istream* in)
492 xmltooling::NDC ndc("send");
494 Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL");
495 Category& log_curl=Category::getInstance(XMLTOOLING_LOGCAT ".libcurl");
497 // For this implementation, it's sufficient to check for https as a sign of transport security.
498 if (m_mandatory && !isConfidential())
499 throw IOException("Blocking unprotected HTTP request, transport authentication by server required.");
503 // By this time, the handle has been prepared with the URL to use and the
504 // caller should have executed any set functions to manipulate it.
506 // Setup standard per-call curl properties.
507 curl_easy_setopt(m_handle,CURLOPT_DEBUGDATA,&log_curl);
508 curl_easy_setopt(m_handle,CURLOPT_FILE,&m_stream);
509 if (m_chunked && in) {
510 curl_easy_setopt(m_handle,CURLOPT_POST,1);
511 m_headers=curl_slist_append(m_headers,"Transfer-Encoding: chunked");
512 curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,&curl_read_hook);
513 curl_easy_setopt(m_handle,CURLOPT_READDATA,in);
519 msg.append(buf,in->gcount());
521 curl_easy_setopt(m_handle,CURLOPT_POST,1);
522 curl_easy_setopt(m_handle,CURLOPT_READFUNCTION,0);
523 curl_easy_setopt(m_handle,CURLOPT_POSTFIELDS,msg.c_str());
524 curl_easy_setopt(m_handle,CURLOPT_POSTFIELDSIZE,msg.length());
527 curl_easy_setopt(m_handle,CURLOPT_HTTPGET,1);
528 curl_easy_setopt(m_handle,CURLOPT_FOLLOWLOCATION,1);
529 curl_easy_setopt(m_handle,CURLOPT_MAXREDIRS,6);
532 char curl_errorbuf[CURL_ERROR_SIZE];
534 curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,curl_errorbuf);
535 if (log_curl.isDebugEnabled())
536 curl_easy_setopt(m_handle,CURLOPT_VERBOSE,1);
538 // Check for cache tag.
539 if (m_cacheTag && !m_cacheTag->empty()) {
540 string hdr("If-None-Match: ");
542 m_headers = curl_slist_append(m_headers, hdr.c_str());
545 m_useragent = XMLToolingConfig::getConfig().user_agent;
546 if (!m_useragent.empty()) {
547 curl_version_info_data* curlver = curl_version_info(CURLVERSION_NOW);
550 m_useragent = m_useragent + " libcurl/" + curlver->version + ' ' + curlver->ssl_version;
553 curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_useragent.c_str());
556 // Set request headers.
557 curl_easy_setopt(m_handle,CURLOPT_HTTPHEADER,m_headers);
559 #ifndef XMLTOOLING_NO_XMLSEC
560 if (m_ssl_callback || m_cred || m_trustEngine) {
562 if (m_ssl_callback) {
564 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,xml_ssl_ctx_callback);
565 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,this);
567 // Restore security "state". Necessary because the callback only runs
568 // when handshakes occur. Even new TCP connections won't execute it.
570 curl_easy_getinfo(m_handle,CURLINFO_PRIVATE,&priv);
572 m_authenticated=true;
575 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,0);
576 curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,0);
580 log.debug("sending SOAP message to %s", m_endpoint.c_str());
581 CURLcode code = curl_easy_perform(m_handle);
583 if (code != CURLE_OK) {
584 if (code == CURLE_SSL_CIPHER) {
585 log.error("on Red Hat 6+, make sure libcurl used is built with OpenSSL");
588 string("CURLSOAPTransport failed while contacting SOAP endpoint (") + m_endpoint + "): " +
589 (curl_errorbuf[0] ? curl_errorbuf : "no further information available"));
592 // This won't prevent every possible failed connection from being kept, but it's something.
595 // Check for outgoing cache tag.
597 const vector<string>& tags = getResponseHeader("ETag");
599 *m_cacheTag = tags.front();
603 // callback to buffer headers from server
604 size_t xmltooling::curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
606 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(stream);
608 #ifdef HAVE_CURLINFO_TLS_SSL_PTR
609 if (!ctx->m_cipherLogged) {
610 Category& log = Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL");
611 if (log.isDebugEnabled()) {
612 struct curl_tlssessioninfo* tlsinfo = nullptr;
613 CURLcode infocode = curl_easy_getinfo(ctx->m_handle, CURLINFO_TLS_SSL_PTR, &tlsinfo);
614 if (infocode == CURLE_OK && tlsinfo && tlsinfo->backend == CURLSSLBACKEND_OPENSSL && tlsinfo->internals) {
615 SSL* ssl = reinterpret_cast<SSL*>(tlsinfo->internals);
616 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl);
617 log.debug("SSL version: %s, cipher: %s", SSL_get_version(ssl), cipher ? SSL_CIPHER_get_name(cipher) : "unknown");
620 ctx->m_cipherLogged = true;
624 // only handle single-byte data
627 char* buf = (char*)malloc(nmemb + 1);
629 memset(buf,0,nmemb + 1);
630 memcpy(buf,ptr,nmemb);
631 char* sep=(char*)strchr(buf,':');
636 char* white=buf+nmemb-1;
637 while (isspace(*white))
639 ctx->m_response_headers[buf].push_back(sep);
647 // callback to send data to server
648 size_t xmltooling::curl_read_hook(void* ptr, size_t size, size_t nmemb, void* stream)
650 // stream is actually an istream pointer
651 istream* buf=reinterpret_cast<istream*>(stream);
652 buf->read(reinterpret_cast<char*>(ptr),size*nmemb);
653 return buf->gcount();
656 // callback to buffer data from server
657 size_t xmltooling::curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream)
659 size_t len = size*nmemb;
660 reinterpret_cast<stringstream*>(stream)->write(reinterpret_cast<const char*>(ptr),len);
664 // callback for curl debug data
665 int xmltooling::curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr)
667 // *ptr is actually a logging object
669 CategoryStream log=reinterpret_cast<Category*>(ptr)->debugStream();
670 for (unsigned char* ch=(unsigned char*)data; len && (isprint(*ch) || isspace(*ch)); len--)
675 #ifndef XMLTOOLING_NO_XMLSEC
676 int xmltooling::verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
678 Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL");
679 if (log.isDebugEnabled()) {
680 log.debug("invoking custom X.509 verify callback");
681 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
683 CategoryStream logstr = log.debugStream();
684 logstr << "ciphers offered by client";
685 for (int i = 0;; ++i) {
686 const char* p = SSL_get_cipher_list(ssl, i);
695 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
696 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(arg);
698 // Yes, this sucks. I'd use TLS, but there's no really obvious spot to put the thread key
699 // and global variables suck too. We can't access the X509_STORE_CTX depth directly because
700 // OpenSSL only copies it into the context if it's >=0, and the unsigned pointer may be
701 // negative in the SSL structure's int member.
702 CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(
703 SSL_get_verify_depth(
704 reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx,SSL_get_ex_data_X509_STORE_CTX_idx()))
710 if (ctx->m_criteria) {
711 ctx->m_criteria->setUsage(Credential::TLS_CREDENTIAL);
712 // Bypass name check (handled for us by curl).
713 ctx->m_criteria->setPeerName(nullptr);
714 success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),ctx->m_criteria);
717 // Bypass name check (handled for us by curl).
718 CredentialCriteria cc;
719 cc.setUsage(Credential::TLS_CREDENTIAL);
720 success = ctx->m_trustEngine->validate(x509_ctx->cert,x509_ctx->untrusted,*(ctx->m_peerResolver),&cc);
724 log.error("supplied TrustEngine failed to validate SSL/TLS server certificate");
725 if (x509_ctx->cert) {
726 BIO* b = BIO_new(BIO_s_mem());
727 X509_print(b, x509_ctx->cert);
728 BUF_MEM* bptr = nullptr;
729 BIO_get_mem_ptr(b, &bptr);
730 if (bptr && bptr->length > 0) {
731 string s(bptr->data, bptr->length);
732 if (ctx->m_mandatory)
739 x509_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION; // generic error, check log for plugin specifics
740 ctx->setAuthenticated(false);
741 return ctx->m_mandatory ? 0 : 1;
744 // Signal success. Hopefully it doesn't matter what's actually in the structure now.
745 ctx->setAuthenticated(true);
750 // callback to invoke a caller-defined SSL callback
751 CURLcode xmltooling::xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
753 CURLSOAPTransport* conf = reinterpret_cast<CURLSOAPTransport*>(userptr);
755 // Default flags manually disable SSLv2 and SSLv3 so we're not dependent on libcurl
756 // to do it. Also disable the ticket option where implemented, since this breaks a
757 // variety of servers. Newer libcurl also does this for us.
758 #ifdef SSL_OP_NO_TICKET
759 SSL_CTX_set_options(ssl_ctx, conf->m_openssl_ops|SSL_OP_NO_TICKET);
761 SSL_CTX_set_options(ssl_ctx, conf->m_openssl_ops);
764 #ifndef XMLTOOLING_NO_XMLSEC
766 conf->m_cred->attach(ssl_ctx);
768 if (conf->m_trustEngine) {
769 SSL_CTX_set_verify(ssl_ctx,SSL_VERIFY_PEER,nullptr);
770 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
771 // With 0.9.7, we can pass a callback argument directly.
772 SSL_CTX_set_cert_verify_callback(ssl_ctx,verify_callback,userptr);
774 // With 0.9.6, there's no argument, so we're going to use a really embarrassing hack and
775 // stuff the argument in the depth property where it will get copied to the context object
776 // that's handed to the callback.
777 SSL_CTX_set_cert_verify_callback(ssl_ctx,reinterpret_cast<int (*)()>(verify_callback),nullptr);
778 SSL_CTX_set_verify_depth(ssl_ctx,reinterpret_cast<int>(userptr));
783 if (conf->m_ssl_callback && !conf->m_ssl_callback(conf, ssl_ctx, conf->m_ssl_userptr))
784 return CURLE_SSL_CERTPROBLEM;