2 * Copyright 2001-2010 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * DynamicMetadataProvider.cpp
20 * Advanced implementation of a dynamic caching MetadataProvider.
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "metadata/MetadataProviderCriteria.h"
29 #include <xercesc/framework/Wrapper4InputSource.hpp>
30 #include <xercesc/util/XMLUniDefs.hpp>
31 #include <xsec/framework/XSECDefs.hpp>
32 #include <saml/version.h>
33 #include <saml/binding/SAMLArtifact.h>
34 #include <saml/saml2/metadata/Metadata.h>
35 #include <saml/saml2/metadata/DynamicMetadataProvider.h>
36 #include <xmltooling/logging.h>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/security/Credential.h>
39 #include <xmltooling/security/CredentialCriteria.h>
40 #include <xmltooling/security/CredentialResolver.h>
41 #include <xmltooling/security/X509TrustEngine.h>
42 #include <xmltooling/soap/HTTPSOAPTransport.h>
43 #include <xmltooling/util/NDC.h>
44 #include <xmltooling/util/ParserPool.h>
45 #include <xmltooling/util/URLEncoder.h>
46 #include <xmltooling/util/XMLHelper.h>
48 using namespace shibsp;
49 using namespace opensaml;
50 using namespace xmltooling::logging;
51 using namespace xmltooling;
55 class SAML_DLLLOCAL DummyCredentialResolver : public CredentialResolver
58 DummyCredentialResolver() {}
59 ~DummyCredentialResolver() {}
61 Lockable* lock() {return this;}
64 const Credential* resolve(const CredentialCriteria* criteria=nullptr) const {return nullptr;}
65 vector<const Credential*>::size_type resolve(
66 vector<const Credential*>& results, const CredentialCriteria* criteria=nullptr
70 class SHIBSP_DLLLOCAL DynamicMetadataProvider : public saml2md::DynamicMetadataProvider
73 DynamicMetadataProvider(const xercesc::DOMElement* e=nullptr);
75 virtual ~DynamicMetadataProvider() {
80 saml2md::EntityDescriptor* resolve(const saml2md::MetadataProvider::Criteria& criteria) const;
83 bool m_verifyHost,m_ignoreTransport,m_encoded;
84 string m_subst, m_match, m_regex;
85 X509TrustEngine* m_trust;
89 saml2md::MetadataProvider* SHIBSP_DLLLOCAL DynamicMetadataProviderFactory(const DOMElement* const & e)
91 return new DynamicMetadataProvider(e);
94 static const XMLCh encoded[] = UNICODE_LITERAL_7(e,n,c,o,d,e,d);
95 static const XMLCh ignoreTransport[] = UNICODE_LITERAL_15(i,g,n,o,r,e,T,r,a,n,s,p,o,r,t);
96 static const XMLCh match[] = UNICODE_LITERAL_5(m,a,t,c,h);
97 static const XMLCh Regex[] = UNICODE_LITERAL_5(R,e,g,e,x);
98 static const XMLCh Subst[] = UNICODE_LITERAL_5(S,u,b,s,t);
99 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
100 static const XMLCh type[] = UNICODE_LITERAL_4(t,y,p,e);
101 static const XMLCh verifyHost[] = UNICODE_LITERAL_10(v,e,r,i,f,y,H,o,s,t);
104 DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
105 : saml2md::DynamicMetadataProvider(e),
106 m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)),
107 m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)),
108 m_encoded(true), m_trust(nullptr)
110 const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst);
111 if (child && child->hasChildNodes()) {
112 auto_ptr_char s(child->getFirstChild()->getNodeValue());
113 if (s.get() && *s.get()) {
115 m_encoded = XMLHelper::getAttrBool(child, true, encoded);
119 if (m_subst.empty()) {
120 child = XMLHelper::getFirstChildElement(e, Regex);
121 if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) {
122 m_match = XMLHelper::getAttrString(child, nullptr, match);
123 auto_ptr_char repl(child->getFirstChild()->getNodeValue());
124 if (repl.get() && *repl.get())
125 m_regex = repl.get();
129 if (!ignoreTransport) {
130 child = XMLHelper::getFirstChildElement(e, _TrustEngine);
131 string t = XMLHelper::getAttrString(child, nullptr, type);
133 TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
134 if (!(m_trust = dynamic_cast<X509TrustEngine*>(trust))) {
136 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
141 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
145 saml2md::EntityDescriptor* DynamicMetadataProvider::resolve(const saml2md::MetadataProvider::Criteria& criteria) const
148 xmltooling::NDC("resolve");
150 Category& log=Category::getInstance(SHIBSP_LOGCAT".MetadataProvider.Dynamic");
153 if (criteria.entityID_ascii) {
154 name = criteria.entityID_ascii;
156 else if (criteria.entityID_unicode) {
157 auto_ptr_char temp(criteria.entityID_unicode);
160 else if (criteria.artifact) {
161 throw saml2md::MetadataException("Unable to resolve metadata dynamically from an artifact.");
164 // Possibly transform the input into a different URL to use.
165 if (!m_subst.empty()) {
166 string::size_type pos = m_subst.find("$entityID");
167 if (pos != string::npos) {
168 string name2 = m_subst;
169 name2.replace(pos, 9, m_encoded ? XMLToolingConfig::getConfig().getURLEncoder()->encode(name.c_str()) : name);
170 log.info("transformed location from (%s) to (%s)", name.c_str(), name2.c_str());
174 else if (!m_match.empty() && !m_regex.empty()) {
176 RegularExpression exp(m_match.c_str());
177 XMLCh* temp = exp.replace(name.c_str(), m_regex.c_str());
179 auto_ptr_char narrow(temp);
180 XMLString::release(&temp);
182 // For some reason it returns the match string if it doesn't match the expression.
183 if (name != narrow.get()) {
184 log.info("transformed location from (%s) to (%s)", name.c_str(), narrow.get());
189 catch (XMLException& ex) {
190 auto_ptr_char msg(ex.getMessage());
191 log.error("caught error applying regular expression: %s", msg.get());
195 // Establish networking properties based on calling application.
196 const MetadataProviderCriteria* mpc = dynamic_cast<const MetadataProviderCriteria*>(&criteria);
198 throw saml2md::MetadataException("Dynamic MetadataProvider requires Shibboleth-aware lookup criteria, check calling code.");
199 const PropertySet* relyingParty;
200 if (criteria.entityID_unicode)
201 relyingParty = mpc->application.getRelyingParty(criteria.entityID_unicode);
203 auto_ptr_XMLCh temp2(name.c_str());
204 relyingParty = mpc->application.getRelyingParty(temp2.get());
207 // Prepare a transport object addressed appropriately.
208 SOAPTransport::Address addr(relyingParty->getString("entityID").second, name.c_str(), name.c_str());
209 const char* pch = strchr(addr.m_endpoint,':');
211 throw IOException("location was not a URL.");
212 string scheme(addr.m_endpoint, pch-addr.m_endpoint);
213 SOAPTransport* transport=nullptr;
215 transport = XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr);
217 catch (exception& ex) {
218 log.error("exception while building transport object to resolve URL: %s", ex.what());
219 throw IOException("Unable to resolve entityID with a known transport protocol.");
221 auto_ptr<SOAPTransport> transportwrapper(transport);
223 // Apply properties as directed.
224 transport->setVerifyHost(m_verifyHost);
225 DummyCredentialResolver dcr;
226 if (m_trust && !transport->setTrustEngine(m_trust, &dcr))
227 throw IOException("Unable to install X509TrustEngine into metadata resolver.");
229 Locker credlocker(nullptr, false);
230 CredentialResolver* credResolver = nullptr;
231 pair<bool,const char*> authType=relyingParty->getString("authType");
232 if (!authType.first || !strcmp(authType.second,"TLS")) {
233 credResolver = mpc->application.getCredentialResolver();
235 credlocker.assign(credResolver);
237 CredentialCriteria cc;
238 cc.setUsage(Credential::TLS_CREDENTIAL);
239 authType = relyingParty->getString("keyName");
241 cc.getKeyNames().insert(authType.second);
242 const Credential* cred = credResolver->resolve(&cc);
243 cc.getKeyNames().clear();
245 if (!transport->setCredential(cred))
246 log.error("failed to load Credential into metadata resolver");
249 log.error("no TLS credential supplied");
253 log.error("no CredentialResolver available for TLS");
257 SOAPTransport::transport_auth_t type=SOAPTransport::transport_auth_none;
258 pair<bool,const char*> username=relyingParty->getString("authUsername");
259 pair<bool,const char*> password=relyingParty->getString("authPassword");
260 if (!username.first || !password.first)
261 log.error("transport authType (%s) specified but authUsername or authPassword was missing", authType.second);
262 else if (!strcmp(authType.second,"basic"))
263 type = SOAPTransport::transport_auth_basic;
264 else if (!strcmp(authType.second,"digest"))
265 type = SOAPTransport::transport_auth_digest;
266 else if (!strcmp(authType.second,"ntlm"))
267 type = SOAPTransport::transport_auth_ntlm;
268 else if (!strcmp(authType.second,"gss"))
269 type = SOAPTransport::transport_auth_gss;
270 else if (strcmp(authType.second,"none"))
271 log.error("unknown authType (%s) specified for RelyingParty", authType.second);
272 if (type > SOAPTransport::transport_auth_none) {
273 if (transport->setAuth(type,username.second,password.second))
274 log.debug("configured for transport authentication (method=%s, username=%s)", authType.second, username.second);
276 log.error("failed to configure transport authentication (method=%s)", authType.second);
280 pair<bool,unsigned int> timeout = relyingParty->getUnsignedInt("connectTimeout");
281 transport->setConnectTimeout(timeout.first ? timeout.second : 10);
282 timeout = relyingParty->getUnsignedInt("timeout");
283 transport->setTimeout(timeout.first ? timeout.second : 20);
284 mpc->application.getServiceProvider().setTransportOptions(*transport);
286 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(transport);
288 pair<bool,bool> flag = relyingParty->getBool("chunkedEncoding");
289 http->useChunkedEncoding(flag.first && flag.second);
290 http->setRequestHeader("Xerces-C", XERCES_FULLVERSIONDOT);
291 http->setRequestHeader("XML-Security-C", XSEC_FULLVERSIONDOT);
292 http->setRequestHeader("OpenSAML-C", OPENSAML_FULLVERSIONDOT);
293 http->setRequestHeader("User-Agent", PACKAGE_NAME);
294 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
298 // Use a nullptr stream to trigger a body-less "GET" operation.
300 istream& msg = transport->receive();
302 DOMDocument* doc=nullptr;
303 StreamInputSource src(msg, "DynamicMetadataProvider");
304 Wrapper4InputSource dsrc(&src,false);
306 doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
308 doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
310 // Wrap the document for now.
311 XercesJanitor<DOMDocument> docjanitor(doc);
313 // Unmarshall objects, binding the document.
314 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
315 docjanitor.release();
317 // Make sure it's metadata.
318 saml2md::EntityDescriptor* entity = dynamic_cast<saml2md::EntityDescriptor*>(xmlObject.get());
320 throw saml2md::MetadataException(
321 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
327 catch (XMLException& e) {
328 auto_ptr_char msg(e.getMessage());
329 log.error("Xerces error while resolving location (%s): %s", name.c_str(), msg.get());
330 throw saml2md::MetadataException(msg.get());