Missing header, fix ignoreTransport check.
[shibboleth/sp.git] / shibsp / metadata / DynamicMetadataProvider.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * DynamicMetadataProvider.cpp
19  *
20  * Advanced implementation of a dynamic caching MetadataProvider.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "metadata/MetadataProviderCriteria.h"
28
29 #include <xercesc/framework/Wrapper4InputSource.hpp>
30 #include <xercesc/util/XMLUniDefs.hpp>
31 #include <xercesc/util/regx/RegularExpression.hpp>
32 #include <xsec/framework/XSECDefs.hpp>
33
34 #include <saml/version.h>
35 #include <saml/binding/SAMLArtifact.h>
36 #include <saml/saml2/metadata/Metadata.h>
37 #include <saml/saml2/metadata/DynamicMetadataProvider.h>
38 #include <xmltooling/logging.h>
39 #include <xmltooling/XMLToolingConfig.h>
40 #include <xmltooling/security/Credential.h>
41 #include <xmltooling/security/CredentialCriteria.h>
42 #include <xmltooling/security/CredentialResolver.h>
43 #include <xmltooling/security/X509TrustEngine.h>
44 #include <xmltooling/soap/HTTPSOAPTransport.h>
45 #include <xmltooling/util/NDC.h>
46 #include <xmltooling/util/ParserPool.h>
47 #include <xmltooling/util/URLEncoder.h>
48 #include <xmltooling/util/XMLHelper.h>
49
50 using namespace shibsp;
51 using namespace opensaml;
52 using namespace xmltooling::logging;
53 using namespace xmltooling;
54 using namespace std;
55
56 namespace shibsp {
57     class SAML_DLLLOCAL DummyCredentialResolver : public CredentialResolver
58     {
59     public:
60         DummyCredentialResolver() {}
61         ~DummyCredentialResolver() {}
62
63         Lockable* lock() {return this;}
64         void unlock() {}
65
66         const Credential* resolve(const CredentialCriteria* criteria=nullptr) const {return nullptr;}
67         vector<const Credential*>::size_type resolve(
68             vector<const Credential*>& results, const CredentialCriteria* criteria=nullptr
69             ) const {return 0;}
70     };
71
72     class SHIBSP_DLLLOCAL DynamicMetadataProvider : public saml2md::DynamicMetadataProvider
73     {
74     public:
75         DynamicMetadataProvider(const xercesc::DOMElement* e=nullptr);
76
77         virtual ~DynamicMetadataProvider() {
78             delete m_trust;
79         }
80
81     protected:
82         saml2md::EntityDescriptor* resolve(const saml2md::MetadataProvider::Criteria& criteria) const;
83
84     private:
85         bool m_verifyHost,m_ignoreTransport,m_encoded;
86         string m_subst, m_match, m_regex;
87         X509TrustEngine* m_trust;
88     };
89
90
91     saml2md::MetadataProvider* SHIBSP_DLLLOCAL DynamicMetadataProviderFactory(const DOMElement* const & e)
92     {
93         return new DynamicMetadataProvider(e);
94     }
95
96     static const XMLCh encoded[] =          UNICODE_LITERAL_7(e,n,c,o,d,e,d);
97     static const XMLCh ignoreTransport[] =  UNICODE_LITERAL_15(i,g,n,o,r,e,T,r,a,n,s,p,o,r,t);
98     static const XMLCh match[] =            UNICODE_LITERAL_5(m,a,t,c,h);
99     static const XMLCh Regex[] =            UNICODE_LITERAL_5(R,e,g,e,x);
100     static const XMLCh Subst[] =            UNICODE_LITERAL_5(S,u,b,s,t);
101     static const XMLCh _TrustEngine[] =     UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
102     static const XMLCh type[] =             UNICODE_LITERAL_4(t,y,p,e);
103     static const XMLCh verifyHost[] =       UNICODE_LITERAL_10(v,e,r,i,f,y,H,o,s,t);
104 };
105
106 DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
107     : saml2md::DynamicMetadataProvider(e),
108         m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)),
109         m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)),
110         m_encoded(true), m_trust(nullptr)
111 {
112     const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst);
113     if (child && child->hasChildNodes()) {
114         auto_ptr_char s(child->getFirstChild()->getNodeValue());
115         if (s.get() && *s.get()) {
116             m_subst = s.get();
117             m_encoded = XMLHelper::getAttrBool(child, true, encoded);
118         }
119     }
120
121     if (m_subst.empty()) {
122         child = XMLHelper::getFirstChildElement(e, Regex);
123         if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) {
124             m_match = XMLHelper::getAttrString(child, nullptr, match);
125             auto_ptr_char repl(child->getFirstChild()->getNodeValue());
126             if (repl.get() && *repl.get())
127                 m_regex = repl.get();
128         }
129     }
130
131     if (!m_ignoreTransport) {
132         child = XMLHelper::getFirstChildElement(e, _TrustEngine);
133         string t = XMLHelper::getAttrString(child, nullptr, type);
134         if (!t.empty()) {
135             TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
136             if (!(m_trust = dynamic_cast<X509TrustEngine*>(trust))) {
137                 delete trust;
138                 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
139             }
140         }
141
142         if (!m_trust)
143             throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
144     }
145 }
146
147 saml2md::EntityDescriptor* DynamicMetadataProvider::resolve(const saml2md::MetadataProvider::Criteria& criteria) const
148 {
149 #ifdef _DEBUG
150     xmltooling::NDC("resolve");
151 #endif
152     Category& log=Category::getInstance(SHIBSP_LOGCAT".MetadataProvider.Dynamic");
153
154     string name;
155     if (criteria.entityID_ascii) {
156         name = criteria.entityID_ascii;
157     }
158     else if (criteria.entityID_unicode) {
159         auto_ptr_char temp(criteria.entityID_unicode);
160         name = temp.get();
161     }
162     else if (criteria.artifact) {
163         if (m_subst.empty() && (m_regex.empty() || m_match.empty()))
164             throw saml2md::MetadataException("Unable to resolve metadata dynamically from an artifact.");
165         name = "{sha1}" + criteria.artifact->getSource();
166     }
167
168     // Possibly transform the input into a different URL to use.
169     if (!m_subst.empty()) {
170         string::size_type pos = m_subst.find("$entityID");
171         if (pos != string::npos) {
172             string name2 = m_subst;
173             name2.replace(pos, 9, m_encoded ? XMLToolingConfig::getConfig().getURLEncoder()->encode(name.c_str()) : name);
174             log.info("transformed location from (%s) to (%s)", name.c_str(), name2.c_str());
175             name = name2;
176         }
177     }
178     else if (!m_match.empty() && !m_regex.empty()) {
179         try {
180             RegularExpression exp(m_match.c_str());
181             XMLCh* temp = exp.replace(name.c_str(), m_regex.c_str());
182             if (temp) {
183                 auto_ptr_char narrow(temp);
184                 XMLString::release(&temp);
185
186                 // For some reason it returns the match string if it doesn't match the expression.
187                 if (name != narrow.get()) {
188                     log.info("transformed location from (%s) to (%s)", name.c_str(), narrow.get());
189                     name = narrow.get();
190                 }
191             }
192         }
193         catch (XMLException& ex) {
194             auto_ptr_char msg(ex.getMessage());
195             log.error("caught error applying regular expression: %s", msg.get());
196         }
197     }
198
199     // Establish networking properties based on calling application.
200     const MetadataProviderCriteria* mpc = dynamic_cast<const MetadataProviderCriteria*>(&criteria);
201     if (!mpc)
202         throw saml2md::MetadataException("Dynamic MetadataProvider requires Shibboleth-aware lookup criteria, check calling code.");
203     const PropertySet* relyingParty;
204     if (criteria.artifact)
205         relyingParty = mpc->application.getRelyingParty((XMLCh*)nullptr);
206     else if (criteria.entityID_unicode)
207         relyingParty = mpc->application.getRelyingParty(criteria.entityID_unicode);
208     else {
209         auto_ptr_XMLCh temp2(name.c_str());
210         relyingParty = mpc->application.getRelyingParty(temp2.get());
211     }
212
213     // Prepare a transport object addressed appropriately.
214     SOAPTransport::Address addr(relyingParty->getString("entityID").second, name.c_str(), name.c_str());
215     const char* pch = strchr(addr.m_endpoint,':');
216     if (!pch)
217         throw IOException("location was not a URL.");
218     string scheme(addr.m_endpoint, pch-addr.m_endpoint);
219     SOAPTransport* transport=nullptr;
220     try {
221         transport = XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr);
222     }
223     catch (exception& ex) {
224         log.error("exception while building transport object to resolve URL: %s", ex.what());
225         throw IOException("Unable to resolve entityID with a known transport protocol.");
226     }
227     auto_ptr<SOAPTransport> transportwrapper(transport);
228
229     // Apply properties as directed.
230     transport->setVerifyHost(m_verifyHost);
231     DummyCredentialResolver dcr;
232     if (m_trust && !transport->setTrustEngine(m_trust, &dcr))
233         throw IOException("Unable to install X509TrustEngine into metadata resolver.");
234
235     Locker credlocker(nullptr, false);
236     CredentialResolver* credResolver = nullptr;
237     pair<bool,const char*> authType=relyingParty->getString("authType");
238     if (!authType.first || !strcmp(authType.second,"TLS")) {
239         credResolver = mpc->application.getCredentialResolver();
240         if (credResolver)
241             credlocker.assign(credResolver);
242         if (credResolver) {
243             CredentialCriteria cc;
244             cc.setUsage(Credential::TLS_CREDENTIAL);
245             authType = relyingParty->getString("keyName");
246             if (authType.first)
247                 cc.getKeyNames().insert(authType.second);
248             const Credential* cred = credResolver->resolve(&cc);
249             cc.getKeyNames().clear();
250             if (cred) {
251                 if (!transport->setCredential(cred))
252                     log.error("failed to load Credential into metadata resolver");
253             }
254             else {
255                 log.error("no TLS credential supplied");
256             }
257         }
258         else {
259             log.error("no CredentialResolver available for TLS");
260         }
261     }
262     else {
263         SOAPTransport::transport_auth_t type=SOAPTransport::transport_auth_none;
264         pair<bool,const char*> username=relyingParty->getString("authUsername");
265         pair<bool,const char*> password=relyingParty->getString("authPassword");
266         if (!username.first || !password.first)
267             log.error("transport authType (%s) specified but authUsername or authPassword was missing", authType.second);
268         else if (!strcmp(authType.second,"basic"))
269             type = SOAPTransport::transport_auth_basic;
270         else if (!strcmp(authType.second,"digest"))
271             type = SOAPTransport::transport_auth_digest;
272         else if (!strcmp(authType.second,"ntlm"))
273             type = SOAPTransport::transport_auth_ntlm;
274         else if (!strcmp(authType.second,"gss"))
275             type = SOAPTransport::transport_auth_gss;
276         else if (strcmp(authType.second,"none"))
277             log.error("unknown authType (%s) specified for RelyingParty", authType.second);
278         if (type > SOAPTransport::transport_auth_none) {
279             if (transport->setAuth(type,username.second,password.second))
280                 log.debug("configured for transport authentication (method=%s, username=%s)", authType.second, username.second);
281             else
282                 log.error("failed to configure transport authentication (method=%s)", authType.second);
283         }
284     }
285
286     pair<bool,unsigned int> timeout = relyingParty->getUnsignedInt("connectTimeout");
287     transport->setConnectTimeout(timeout.first ? timeout.second : 10);
288     timeout = relyingParty->getUnsignedInt("timeout");
289     transport->setTimeout(timeout.first ? timeout.second : 20);
290     mpc->application.getServiceProvider().setTransportOptions(*transport);
291
292     HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(transport);
293     if (http) {
294         pair<bool,bool> flag = relyingParty->getBool("chunkedEncoding");
295         http->useChunkedEncoding(flag.first && flag.second);
296         http->setRequestHeader("Xerces-C", XERCES_FULLVERSIONDOT);
297         http->setRequestHeader("XML-Security-C", XSEC_FULLVERSIONDOT);
298         http->setRequestHeader("OpenSAML-C", OPENSAML_FULLVERSIONDOT);
299         http->setRequestHeader("User-Agent", PACKAGE_NAME);
300         http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
301     }
302
303     try {
304         // Use a nullptr stream to trigger a body-less "GET" operation.
305         transport->send();
306         istream& msg = transport->receive();
307
308         DOMDocument* doc=nullptr;
309         StreamInputSource src(msg, "DynamicMetadataProvider");
310         Wrapper4InputSource dsrc(&src,false);
311         if (m_validate)
312             doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
313         else
314             doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
315
316         // Wrap the document for now.
317         XercesJanitor<DOMDocument> docjanitor(doc);
318
319         // Unmarshall objects, binding the document.
320         auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
321         docjanitor.release();
322
323         // Make sure it's metadata.
324         saml2md::EntityDescriptor* entity = dynamic_cast<saml2md::EntityDescriptor*>(xmlObject.get());
325         if (!entity) {
326             throw saml2md::MetadataException(
327                 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
328                 );
329         }
330         xmlObject.release();
331         return entity;
332     }
333     catch (XMLException& e) {
334         auto_ptr_char msg(e.getMessage());
335         log.error("Xerces error while resolving location (%s): %s", name.c_str(), msg.get());
336         throw saml2md::MetadataException(msg.get());
337     }
338 }