SSPCPP-641 - add ability to set SSL cipher suites
[shibboleth/cpp-xmltooling.git] / xmltooling / soap / impl / CURLSOAPTransport.cpp
1 /**
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.
6  *
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
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20
21 /**
22  * CURLSOAPTransport.cpp
23  *
24  * libcurl-based SOAPTransport implementation.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "logging.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"
35 #include "util/NDC.h"
36 #include "util/Threads.h"
37
38 #include <list>
39 #include <curl/curl.h>
40 #include <openssl/x509_vfy.h>
41
42 using namespace xmltooling::logging;
43 using namespace xmltooling;
44 using namespace std;
45
46 namespace xmltooling {
47
48     // Manages cache of socket connections via CURL handles.
49     class XMLTOOL_DLLLOCAL CURLPool
50     {
51     public:
52         CURLPool() : m_size(0), m_lock(Mutex::create()),
53             m_log(Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL")) {}
54         ~CURLPool();
55
56         CURL* get(const SOAPTransport::Address& addr);
57         void put(const char* from, const char* to, const char* endpoint, CURL* handle);
58
59     private:
60         typedef map<string,vector<CURL*> > poolmap_t;
61         poolmap_t m_bindingMap;
62         list< vector<CURL*>* > m_pools;
63         long m_size;
64         Mutex* m_lock;
65         Category& m_log;
66     };
67
68     static XMLTOOL_DLLLOCAL CURLPool* g_CURLPool = nullptr;
69
70     class XMLTOOL_DLLLOCAL CURLSOAPTransport : public HTTPSOAPTransport, public OpenSSLSOAPTransport
71     {
72     public:
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),
78 #endif
79 #ifndef XMLTOOLING_NO_XMLSEC
80                     m_cred(nullptr), m_trustEngine(nullptr), m_peerResolver(nullptr), m_mandatory(false),
81 #endif
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");
93         }
94
95         virtual ~CURLSOAPTransport() {
96             curl_slist_free_all(m_headers);
97             if (m_keepHandle) {
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);
102             }
103             else {
104                 curl_easy_cleanup(m_handle);
105             }
106         }
107
108         bool isConfidential() const {
109             return m_endpoint.find("https")==0;
110         }
111
112         bool setConnectTimeout(long timeout) {
113             return (curl_easy_setopt(m_handle,CURLOPT_CONNECTTIMEOUT,timeout)==CURLE_OK);
114         }
115
116         bool setTimeout(long timeout) {
117             return (curl_easy_setopt(m_handle,CURLOPT_TIMEOUT,timeout)==CURLE_OK);
118         }
119
120         bool setAuth(transport_auth_t authType, const char* username=nullptr, const char* password=nullptr);
121
122         bool setVerifyHost(bool verify) {
123             return (curl_easy_setopt(m_handle,CURLOPT_SSL_VERIFYHOST,verify ? 2 : 0)==CURLE_OK);
124         }
125
126 #ifndef XMLTOOLING_NO_XMLSEC
127         bool setCredential(const Credential* cred=nullptr) {
128             const OpenSSLCredential* down = dynamic_cast<const OpenSSLCredential*>(cred);
129             if (!down) {
130                 m_cred = nullptr;
131                 return (cred==nullptr);
132             }
133             m_cred = down;
134             return true;
135         }
136
137         bool setTrustEngine(
138             const X509TrustEngine* trustEngine=nullptr,
139             const CredentialResolver* peerResolver=nullptr,
140             CredentialCriteria* criteria=nullptr,
141             bool mandatory=true
142             ) {
143             const OpenSSLTrustEngine* down = dynamic_cast<const OpenSSLTrustEngine*>(trustEngine);
144             if (!down) {
145                 m_trustEngine = nullptr;
146                 m_peerResolver = nullptr;
147                 m_criteria = nullptr;
148                 return (trustEngine==nullptr);
149             }
150             m_trustEngine = down;
151             m_peerResolver = peerResolver;
152             m_criteria = criteria;
153             m_mandatory = mandatory;
154             return true;
155         }
156
157 #endif
158
159         bool useChunkedEncoding(bool chunked=true) {
160             m_chunked = chunked;
161             return true;
162         }
163
164         bool followRedirects(bool follow, unsigned int maxRedirs) {
165             return (
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
168                 );
169         }
170
171         bool setCacheTag(string* cacheTag) {
172             m_cacheTag = cacheTag;
173             return true;
174         }
175
176         bool setProviderOption(const char* provider, const char* option, const char* value);
177
178         void send(istream& in) {
179             send(&in);
180         }
181
182         void send(istream* in=nullptr);
183
184         istream& receive() {
185             return m_stream;
186         }
187
188         bool isAuthenticated() const {
189             return m_authenticated;
190         }
191
192         void setAuthenticated(bool auth) {
193             m_authenticated = auth;
194         }
195
196         string getContentType() const;
197         long getStatusCode() const;
198
199         bool setRequestHeader(const char* name, const char* val) {
200             string temp(name);
201             temp=temp + ": " + val;
202             m_headers=curl_slist_append(m_headers,temp.c_str());
203             return true;
204         }
205
206         const vector<string>& getResponseHeader(const char* val) const;
207
208         bool setSSLCallback(ssl_ctx_callback_fn fn, void* userptr=nullptr) {
209             m_ssl_callback=fn;
210             m_ssl_userptr=userptr;
211             return true;
212         }
213
214         bool setCipherSuites(const char* cipherlist) {
215             return (curl_easy_setopt(m_handle,CURLOPT_SSL_CIPHER_LIST,cipherlist)==CURLE_OK);
216         }
217
218     private:
219         // per-call state
220         string m_sender,m_peerName,m_endpoint,m_simplecreds;
221         CURL* m_handle;
222         bool m_keepHandle;
223         stringstream m_stream;
224         struct curl_slist* m_headers;
225                 string m_useragent;
226         map<string,vector<string> > m_response_headers;
227         vector<string> m_saved_options;
228 #ifdef HAVE_CURLINFO_TLS_SSL_PTR
229         bool m_cipherLogged;
230 #endif
231 #ifndef XMLTOOLING_NO_XMLSEC
232         const OpenSSLCredential* m_cred;
233         const OpenSSLTrustEngine* m_trustEngine;
234         const CredentialResolver* m_peerResolver;
235         CredentialCriteria* m_criteria;
236         bool m_mandatory;
237 #endif
238         int m_openssl_ops;
239         ssl_ctx_callback_fn m_ssl_callback;
240         void* m_ssl_userptr;
241         bool m_chunked;
242         bool m_authenticated;
243         string* m_cacheTag;
244
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);
248     };
249
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);
258 #endif
259
260     SOAPTransport* CURLSOAPTransportFactory(const SOAPTransport::Address& addr)
261     {
262         return new CURLSOAPTransport(addr);
263     }
264 };
265
266 void xmltooling::initSOAPTransports()
267 {
268     g_CURLPool=new CURLPool();
269 }
270
271 void xmltooling::termSOAPTransports()
272 {
273     delete g_CURLPool;
274     g_CURLPool = nullptr;
275 }
276
277 CURLPool::~CURLPool()
278 {
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);
282     }
283     delete m_lock;
284 }
285
286 CURL* CURLPool::get(const SOAPTransport::Address& addr)
287 {
288 #ifdef _DEBUG
289     xmltooling::NDC("get");
290 #endif
291     m_log.debug("getting connection handle to %s", addr.m_endpoint);
292     string key(addr.m_endpoint);
293     if (addr.m_from)
294         key = key + '|' + addr.m_from;
295     if (addr.m_to)
296         key = key + '|' + addr.m_to;
297     m_lock->lock();
298     poolmap_t::iterator i=m_bindingMap.find(key);
299
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));
304
305         // If a free connection exists, return it.
306         if (!(i->second.empty())) {
307             CURL* handle=i->second.back();
308             i->second.pop_back();
309             m_size--;
310             m_lock->unlock();
311             m_log.debug("returning existing connection handle from pool");
312             return handle;
313         }
314     }
315
316     m_lock->unlock();
317     m_log.debug("nothing free in pool, returning new connection handle");
318
319     // Create a new connection and set non-varying options.
320     CURL* handle=curl_easy_init();
321     if (!handle)
322         return nullptr;
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);
335     return handle;
336 }
337
338 void CURLPool::put(const char* from, const char* to, const char* endpoint, CURL* handle)
339 {
340     string key(endpoint);
341     if (from)
342         key = key + '|' + from;
343     if (to)
344         key = key + '|' + to;
345     m_lock->lock();
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));
349     else
350         i->second.push_back(handle);
351
352     CURL* killit=nullptr;
353     if (++m_size > 256) {
354         // Kick a handle out from the back of the bus.
355         while (true) {
356             vector<CURL*>* corpse=m_pools.back();
357             if (!corpse->empty()) {
358                 killit=corpse->back();
359                 corpse->pop_back();
360                 m_size--;
361                 break;
362             }
363
364             // Move an empty pool up to the front so we don't keep hitting it.
365             m_pools.pop_back();
366             m_pools.push_front(corpse);
367         }
368     }
369     m_lock->unlock();
370     if (killit) {
371         curl_easy_cleanup(killit);
372 #ifdef _DEBUG
373         xmltooling::NDC("put");
374 #endif
375         m_log.info("conn_pool_max limit reached, dropping an old connection");
376     }
377 }
378
379 bool CURLSOAPTransport::setAuth(transport_auth_t authType, const char* username, const char* password)
380 {
381     if (authType==transport_auth_none) {
382         if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,0)!=CURLE_OK)
383             return false;
384         return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,0)==CURLE_OK);
385     }
386     long flag=0;
387     switch (authType) {
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;
393     }
394     if (curl_easy_setopt(m_handle,CURLOPT_HTTPAUTH,flag)!=CURLE_OK)
395         return false;
396     m_simplecreds = string(username ? username : "") + ':' + (password ? password : "");
397     return (curl_easy_setopt(m_handle,CURLOPT_USERPWD,m_simplecreds.c_str())==CURLE_OK);
398 }
399
400 bool CURLSOAPTransport::setProviderOption(const char* provider, const char* option, const char* value)
401 {
402     if (!provider || !option || !value) {
403         return false;
404     }
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;
414             return true;
415 #elif (OPENSSL_VERSION_NUMBER > 0x009080bfL)
416             return false;
417 #else
418             return true;
419 #endif
420         }
421         return false;
422     }
423     else if (strcmp(provider, "CURL")) {
424         return false;
425     }
426
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) {
433         if (value)
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);
436     }
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);
440 # else
441     else if (sizeof(off_t) == sizeof(long))
442         return (curl_easy_setopt(m_handle, opt, strtol(value, nullptr, 10)) == CURLE_OK);
443 # endif
444     return false;
445 #else
446     else {
447         if (value)
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);
450     }
451 #endif
452 }
453
454 const vector<string>& CURLSOAPTransport::getResponseHeader(const char* name) const
455 {
456     static vector<string> emptyVector;
457
458     map<string,vector<string> >::const_iterator i=m_response_headers.find(name);
459     if (i!=m_response_headers.end())
460         return i->second;
461
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))
465 #else
466         if (!stricmp(j->first.c_str(), name))
467 #endif
468             return j->second;
469     }
470
471     return emptyVector;
472 }
473
474 string CURLSOAPTransport::getContentType() const
475 {
476     char* content_type=nullptr;
477     curl_easy_getinfo(m_handle,CURLINFO_CONTENT_TYPE,&content_type);
478     return content_type ? content_type : "";
479 }
480
481 long CURLSOAPTransport::getStatusCode() const
482 {
483     long code=200;
484     if (curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &code) != CURLE_OK)
485         code = 200;
486     return code;
487 }
488
489 void CURLSOAPTransport::send(istream* in)
490 {
491 #ifdef _DEBUG
492     xmltooling::NDC ndc("send");
493 #endif
494     Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".SOAPTransport.CURL");
495     Category& log_curl=Category::getInstance(XMLTOOLING_LOGCAT ".libcurl");
496
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.");
500
501     string msg;
502
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.
505
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);
514     }
515     else if (in) {
516         char buf[1024];
517         while (*in) {
518             in->read(buf,1024);
519             msg.append(buf,in->gcount());
520         }
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());
525     }
526     else {
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);
530     }
531
532     char curl_errorbuf[CURL_ERROR_SIZE];
533     curl_errorbuf[0]=0;
534     curl_easy_setopt(m_handle,CURLOPT_ERRORBUFFER,curl_errorbuf);
535     if (log_curl.isDebugEnabled())
536         curl_easy_setopt(m_handle,CURLOPT_VERBOSE,1);
537
538     // Check for cache tag.
539     if (m_cacheTag && !m_cacheTag->empty()) {
540         string hdr("If-None-Match: ");
541         hdr += *m_cacheTag;
542         m_headers = curl_slist_append(m_headers, hdr.c_str());
543     }
544
545     m_useragent = XMLToolingConfig::getConfig().user_agent;
546     if (!m_useragent.empty()) {
547         curl_version_info_data* curlver = curl_version_info(CURLVERSION_NOW);
548
549         if (curlver) {
550             m_useragent = m_useragent + " libcurl/" + curlver->version + ' ' + curlver->ssl_version;
551         }
552
553         curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_useragent.c_str());
554     }
555
556     // Set request headers.
557     curl_easy_setopt(m_handle,CURLOPT_HTTPHEADER,m_headers);
558
559 #ifndef XMLTOOLING_NO_XMLSEC
560     if (m_ssl_callback || m_cred || m_trustEngine) {
561 #else
562     if (m_ssl_callback) {
563 #endif
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);
566
567         // Restore security "state". Necessary because the callback only runs
568         // when handshakes occur. Even new TCP connections won't execute it.
569         char* priv=nullptr;
570         curl_easy_getinfo(m_handle,CURLINFO_PRIVATE,&priv);
571         if (priv)
572             m_authenticated=true;
573     }
574     else {
575         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_FUNCTION,0);
576         curl_easy_setopt(m_handle,CURLOPT_SSL_CTX_DATA,0);
577     }
578
579     // Make the call.
580     log.debug("sending SOAP message to %s", m_endpoint.c_str());
581     CURLcode code = curl_easy_perform(m_handle);
582
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");
586         }
587         throw IOException(
588             string("CURLSOAPTransport failed while contacting SOAP endpoint (") + m_endpoint + "): " +
589                 (curl_errorbuf[0] ? curl_errorbuf : "no further information available"));
590     }
591
592     // This won't prevent every possible failed connection from being kept, but it's something.
593     m_keepHandle = true;
594
595     // Check for outgoing cache tag.
596     if (m_cacheTag) {
597         const vector<string>& tags = getResponseHeader("ETag");
598         if (!tags.empty())
599             *m_cacheTag = tags.front();
600     }
601 }
602
603 // callback to buffer headers from server
604 size_t xmltooling::curl_header_hook(void* ptr, size_t size, size_t nmemb, void* stream)
605 {
606     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(stream);
607
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");
618             }
619         }
620         ctx->m_cipherLogged = true;
621 #endif
622     }
623
624     // only handle single-byte data
625     if (size!=1)
626         return 0;
627     char* buf = (char*)malloc(nmemb + 1);
628     if (buf) {
629         memset(buf,0,nmemb + 1);
630         memcpy(buf,ptr,nmemb);
631         char* sep=(char*)strchr(buf,':');
632         if (sep) {
633             *(sep++)=0;
634             while (*sep==' ')
635                 *(sep++)=0;
636             char* white=buf+nmemb-1;
637             while (isspace(*white))
638                 *(white--)=0;
639             ctx->m_response_headers[buf].push_back(sep);
640         }
641         free(buf);
642         return nmemb;
643     }
644     return 0;
645 }
646
647 // callback to send data to server
648 size_t xmltooling::curl_read_hook(void* ptr, size_t size, size_t nmemb, void* stream)
649 {
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();
654 }
655
656 // callback to buffer data from server
657 size_t xmltooling::curl_write_hook(void* ptr, size_t size, size_t nmemb, void* stream)
658 {
659     size_t len = size*nmemb;
660     reinterpret_cast<stringstream*>(stream)->write(reinterpret_cast<const char*>(ptr),len);
661     return len;
662 }
663
664 // callback for curl debug data
665 int xmltooling::curl_debug_hook(CURL* handle, curl_infotype type, char* data, size_t len, void* ptr)
666 {
667     // *ptr is actually a logging object
668     if (!ptr) return 0;
669     CategoryStream log=reinterpret_cast<Category*>(ptr)->debugStream();
670     for (unsigned char* ch=(unsigned char*)data; len && (isprint(*ch) || isspace(*ch)); len--)
671         log << *ch++;
672     return 0;
673 }
674
675 #ifndef XMLTOOLING_NO_XMLSEC
676 int xmltooling::verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
677 {
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()));
682         if (ssl) {
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);
687                 if (!p)
688                     break;
689                 logstr << ':' << p;
690             }
691             logstr << eol;
692         }
693     }
694
695 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
696     CURLSOAPTransport* ctx = reinterpret_cast<CURLSOAPTransport*>(arg);
697 #else
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()))
705             )
706         );
707 #endif
708
709     bool success=false;
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);
715     }
716     else {
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);
721     }
722
723     if (!success) {
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)
733                     log.error(s);
734                 else
735                     log.debug(s);
736             }
737             BIO_free(b);
738         }
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;
742     }
743
744     // Signal success. Hopefully it doesn't matter what's actually in the structure now.
745     ctx->setAuthenticated(true);
746     return 1;
747 }
748 #endif
749
750 // callback to invoke a caller-defined SSL callback
751 CURLcode xmltooling::xml_ssl_ctx_callback(CURL* curl, SSL_CTX* ssl_ctx, void* userptr)
752 {
753     CURLSOAPTransport* conf = reinterpret_cast<CURLSOAPTransport*>(userptr);
754
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);
760 #else
761     SSL_CTX_set_options(ssl_ctx, conf->m_openssl_ops);
762 #endif
763
764 #ifndef XMLTOOLING_NO_XMLSEC
765     if (conf->m_cred)
766         conf->m_cred->attach(ssl_ctx);
767
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);
773 #else
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));
779 #endif
780     }
781 #endif
782
783     if (conf->m_ssl_callback && !conf->m_ssl_callback(conf, ssl_ctx, conf->m_ssl_userptr))
784         return CURLE_SSL_CERTPROBLEM;
785
786     return CURLE_OK;
787 }