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 <xercesc/util/regx/RegularExpression.hpp>
32 #include <xsec/framework/XSECDefs.hpp>
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>
50 using namespace shibsp;
51 using namespace opensaml;
52 using namespace xmltooling::logging;
53 using namespace xmltooling;
57 class SAML_DLLLOCAL DummyCredentialResolver : public CredentialResolver
60 DummyCredentialResolver() {}
61 ~DummyCredentialResolver() {}
63 Lockable* lock() {return this;}
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
72 class SHIBSP_DLLLOCAL DynamicMetadataProvider : public saml2md::DynamicMetadataProvider
75 DynamicMetadataProvider(const xercesc::DOMElement* e=nullptr);
77 virtual ~DynamicMetadataProvider() {
82 saml2md::EntityDescriptor* resolve(const saml2md::MetadataProvider::Criteria& criteria) const;
85 bool m_verifyHost,m_ignoreTransport,m_encoded;
86 string m_subst, m_match, m_regex;
87 X509TrustEngine* m_trust;
91 saml2md::MetadataProvider* SHIBSP_DLLLOCAL DynamicMetadataProviderFactory(const DOMElement* const & e)
93 return new DynamicMetadataProvider(e);
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);
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)
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()) {
117 m_encoded = XMLHelper::getAttrBool(child, true, encoded);
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();
131 if (!m_ignoreTransport) {
132 child = XMLHelper::getFirstChildElement(e, _TrustEngine);
133 string t = XMLHelper::getAttrString(child, nullptr, type);
135 TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
136 if (!(m_trust = dynamic_cast<X509TrustEngine*>(trust))) {
138 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
143 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
147 saml2md::EntityDescriptor* DynamicMetadataProvider::resolve(const saml2md::MetadataProvider::Criteria& criteria) const
150 xmltooling::NDC("resolve");
152 Category& log=Category::getInstance(SHIBSP_LOGCAT".MetadataProvider.Dynamic");
155 if (criteria.entityID_ascii) {
156 name = criteria.entityID_ascii;
158 else if (criteria.entityID_unicode) {
159 auto_ptr_char temp(criteria.entityID_unicode);
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();
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());
178 else if (!m_match.empty() && !m_regex.empty()) {
180 RegularExpression exp(m_match.c_str());
181 XMLCh* temp = exp.replace(name.c_str(), m_regex.c_str());
183 auto_ptr_char narrow(temp);
184 XMLString::release(&temp);
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());
193 catch (XMLException& ex) {
194 auto_ptr_char msg(ex.getMessage());
195 log.error("caught error applying regular expression: %s", msg.get());
199 // Establish networking properties based on calling application.
200 const MetadataProviderCriteria* mpc = dynamic_cast<const MetadataProviderCriteria*>(&criteria);
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);
209 auto_ptr_XMLCh temp2(name.c_str());
210 relyingParty = mpc->application.getRelyingParty(temp2.get());
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,':');
217 throw IOException("location was not a URL.");
218 string scheme(addr.m_endpoint, pch-addr.m_endpoint);
219 SOAPTransport* transport=nullptr;
221 transport = XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr);
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.");
227 auto_ptr<SOAPTransport> transportwrapper(transport);
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.");
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();
241 credlocker.assign(credResolver);
243 CredentialCriteria cc;
244 cc.setUsage(Credential::TLS_CREDENTIAL);
245 authType = relyingParty->getString("keyName");
247 cc.getKeyNames().insert(authType.second);
248 const Credential* cred = credResolver->resolve(&cc);
249 cc.getKeyNames().clear();
251 if (!transport->setCredential(cred))
252 log.error("failed to load Credential into metadata resolver");
255 log.error("no TLS credential supplied");
259 log.error("no CredentialResolver available for TLS");
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);
282 log.error("failed to configure transport authentication (method=%s)", authType.second);
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);
292 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(transport);
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);
304 // Use a nullptr stream to trigger a body-less "GET" operation.
306 istream& msg = transport->receive();
308 DOMDocument* doc=nullptr;
309 StreamInputSource src(msg, "DynamicMetadataProvider");
310 Wrapper4InputSource dsrc(&src,false);
312 doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
314 doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
316 // Wrap the document for now.
317 XercesJanitor<DOMDocument> docjanitor(doc);
319 // Unmarshall objects, binding the document.
320 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
321 docjanitor.release();
323 // Make sure it's metadata.
324 saml2md::EntityDescriptor* entity = dynamic_cast<saml2md::EntityDescriptor*>(xmlObject.get());
326 throw saml2md::MetadataException(
327 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
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());