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 * DynamicMetadataProvider.cpp
24 * Advanced implementation of a dynamic caching MetadataProvider.
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "metadata/MetadataProviderCriteria.h"
33 #include <boost/algorithm/string.hpp>
34 #include <xercesc/framework/Wrapper4InputSource.hpp>
35 #include <xercesc/util/XMLUniDefs.hpp>
36 #include <xercesc/util/regx/RegularExpression.hpp>
37 #include <xsec/framework/XSECDefs.hpp>
39 #include <saml/version.h>
40 #include <saml/binding/SAMLArtifact.h>
41 #include <saml/saml2/metadata/Metadata.h>
42 #include <saml/saml2/metadata/DynamicMetadataProvider.h>
43 #include <xmltooling/logging.h>
44 #include <xmltooling/XMLToolingConfig.h>
45 #include <xmltooling/security/Credential.h>
46 #include <xmltooling/security/CredentialCriteria.h>
47 #include <xmltooling/security/CredentialResolver.h>
48 #include <xmltooling/security/X509TrustEngine.h>
49 #include <xmltooling/soap/HTTPSOAPTransport.h>
50 #include <xmltooling/util/NDC.h>
51 #include <xmltooling/util/ParserPool.h>
52 #include <xmltooling/util/URLEncoder.h>
53 #include <xmltooling/util/XMLHelper.h>
55 using namespace shibsp;
56 using namespace opensaml;
57 using namespace xmltooling::logging;
58 using namespace xmltooling;
62 class SHIBSP_DLLLOCAL DynamicMetadataProvider : public saml2md::DynamicMetadataProvider
65 DynamicMetadataProvider(const xercesc::DOMElement* e=nullptr);
67 virtual ~DynamicMetadataProvider() {}
70 saml2md::EntityDescriptor* resolve(const saml2md::MetadataProvider::Criteria& criteria) const;
73 bool m_verifyHost,m_ignoreTransport,m_encoded;
74 string m_subst, m_match, m_regex;
75 boost::scoped_ptr<X509TrustEngine> m_trust;
76 boost::scoped_ptr<CredentialResolver> m_dummyCR;
79 saml2md::MetadataProvider* SHIBSP_DLLLOCAL DynamicMetadataProviderFactory(const DOMElement* const & e)
81 return new DynamicMetadataProvider(e);
84 static const XMLCh encoded[] = UNICODE_LITERAL_7(e,n,c,o,d,e,d);
85 static const XMLCh ignoreTransport[] = UNICODE_LITERAL_15(i,g,n,o,r,e,T,r,a,n,s,p,o,r,t);
86 static const XMLCh match[] = UNICODE_LITERAL_5(m,a,t,c,h);
87 static const XMLCh Regex[] = UNICODE_LITERAL_5(R,e,g,e,x);
88 static const XMLCh Subst[] = UNICODE_LITERAL_5(S,u,b,s,t);
89 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
90 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
91 static const XMLCh verifyHost[] = UNICODE_LITERAL_10(v,e,r,i,f,y,H,o,s,t);
94 DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
95 : saml2md::DynamicMetadataProvider(e),
96 m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)),
97 m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)),
98 m_encoded(true), m_trust(nullptr)
100 const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst);
101 if (child && child->hasChildNodes()) {
102 auto_ptr_char s(child->getFirstChild()->getNodeValue());
103 if (s.get() && *s.get()) {
105 m_encoded = XMLHelper::getAttrBool(child, true, encoded);
109 if (m_subst.empty()) {
110 child = XMLHelper::getFirstChildElement(e, Regex);
111 if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) {
112 m_match = XMLHelper::getAttrString(child, nullptr, match);
113 auto_ptr_char repl(child->getFirstChild()->getNodeValue());
114 if (repl.get() && *repl.get())
115 m_regex = repl.get();
119 if (!m_ignoreTransport) {
120 child = XMLHelper::getFirstChildElement(e, _TrustEngine);
121 string t = XMLHelper::getAttrString(child, nullptr, _type);
123 TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child);
124 if (!dynamic_cast<X509TrustEngine*>(trust)) {
126 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
128 m_trust.reset(dynamic_cast<X509TrustEngine*>(trust));
129 m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr));
132 if (!m_trust.get() || !m_dummyCR.get())
133 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
137 saml2md::EntityDescriptor* DynamicMetadataProvider::resolve(const saml2md::MetadataProvider::Criteria& criteria) const
140 xmltooling::NDC("resolve");
142 Category& log=Category::getInstance(SHIBSP_LOGCAT".MetadataProvider.Dynamic");
145 if (criteria.entityID_ascii) {
146 name = criteria.entityID_ascii;
148 else if (criteria.entityID_unicode) {
149 auto_ptr_char temp(criteria.entityID_unicode);
152 else if (criteria.artifact) {
153 if (m_subst.empty() && (m_regex.empty() || m_match.empty()))
154 throw saml2md::MetadataException("Unable to resolve metadata dynamically from an artifact.");
155 name = "{sha1}" + criteria.artifact->getSource();
158 // Possibly transform the input into a different URL to use.
159 if (!m_subst.empty()) {
160 string name2 = boost::replace_first_copy(m_subst, "$entityID",
161 m_encoded ? XMLToolingConfig::getConfig().getURLEncoder()->encode(name.c_str()) : name);
162 log.info("transformed location from (%s) to (%s)", name.c_str(), name2.c_str());
165 else if (!m_match.empty() && !m_regex.empty()) {
167 RegularExpression exp(m_match.c_str());
168 XMLCh* temp = exp.replace(name.c_str(), m_regex.c_str());
170 auto_ptr_char narrow(temp);
171 XMLString::release(&temp);
173 // For some reason it returns the match string if it doesn't match the expression.
174 if (name != narrow.get()) {
175 log.info("transformed location from (%s) to (%s)", name.c_str(), narrow.get());
180 catch (XMLException& ex) {
181 auto_ptr_char msg(ex.getMessage());
182 log.error("caught error applying regular expression: %s", msg.get());
186 // Establish networking properties based on calling application.
187 const MetadataProviderCriteria* mpc = dynamic_cast<const MetadataProviderCriteria*>(&criteria);
189 throw saml2md::MetadataException("Dynamic MetadataProvider requires Shibboleth-aware lookup criteria, check calling code.");
190 const PropertySet* relyingParty;
191 if (criteria.artifact)
192 relyingParty = mpc->application.getRelyingParty((XMLCh*)nullptr);
193 else if (criteria.entityID_unicode)
194 relyingParty = mpc->application.getRelyingParty(criteria.entityID_unicode);
196 auto_ptr_XMLCh temp2(name.c_str());
197 relyingParty = mpc->application.getRelyingParty(temp2.get());
200 // Prepare a transport object addressed appropriately.
201 SOAPTransport::Address addr(relyingParty->getString("entityID").second, name.c_str(), name.c_str());
202 const char* pch = strchr(addr.m_endpoint,':');
204 throw IOException("location was not a URL.");
205 string scheme(addr.m_endpoint, pch-addr.m_endpoint);
206 boost::scoped_ptr<SOAPTransport> transport;
208 transport.reset(XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr));
210 catch (exception& ex) {
211 log.error("exception while building transport object to resolve URL: %s", ex.what());
212 throw IOException("Unable to resolve entityID with a known transport protocol.");
215 // Apply properties as directed.
216 transport->setVerifyHost(m_verifyHost);
217 if (m_trust.get() && m_dummyCR.get() && !transport->setTrustEngine(m_trust.get(), m_dummyCR.get()))
218 throw IOException("Unable to install X509TrustEngine into transport object.");
220 Locker credlocker(nullptr, false);
221 CredentialResolver* credResolver = nullptr;
222 pair<bool,const char*> authType=relyingParty->getString("authType");
223 if (!authType.first || !strcmp(authType.second,"TLS")) {
224 credResolver = mpc->application.getCredentialResolver();
226 credlocker.assign(credResolver);
228 CredentialCriteria cc;
229 cc.setUsage(Credential::TLS_CREDENTIAL);
230 authType = relyingParty->getString("keyName");
232 cc.getKeyNames().insert(authType.second);
233 const Credential* cred = credResolver->resolve(&cc);
234 cc.getKeyNames().clear();
236 if (!transport->setCredential(cred))
237 log.error("failed to load Credential into metadata resolver");
240 log.error("no TLS credential supplied");
244 log.error("no CredentialResolver available for TLS");
248 SOAPTransport::transport_auth_t type=SOAPTransport::transport_auth_none;
249 pair<bool,const char*> username=relyingParty->getString("authUsername");
250 pair<bool,const char*> password=relyingParty->getString("authPassword");
251 if (!username.first || !password.first)
252 log.error("transport authType (%s) specified but authUsername or authPassword was missing", authType.second);
253 else if (!strcmp(authType.second,"basic"))
254 type = SOAPTransport::transport_auth_basic;
255 else if (!strcmp(authType.second,"digest"))
256 type = SOAPTransport::transport_auth_digest;
257 else if (!strcmp(authType.second,"ntlm"))
258 type = SOAPTransport::transport_auth_ntlm;
259 else if (!strcmp(authType.second,"gss"))
260 type = SOAPTransport::transport_auth_gss;
261 else if (strcmp(authType.second,"none"))
262 log.error("unknown authType (%s) specified for RelyingParty", authType.second);
263 if (type > SOAPTransport::transport_auth_none) {
264 if (transport->setAuth(type,username.second,password.second))
265 log.debug("configured for transport authentication (method=%s, username=%s)", authType.second, username.second);
267 log.error("failed to configure transport authentication (method=%s)", authType.second);
271 pair<bool,unsigned int> timeout = relyingParty->getUnsignedInt("connectTimeout");
272 transport->setConnectTimeout(timeout.first ? timeout.second : 10);
273 timeout = relyingParty->getUnsignedInt("timeout");
274 transport->setTimeout(timeout.first ? timeout.second : 20);
275 mpc->application.getServiceProvider().setTransportOptions(*transport);
277 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(transport.get());
279 pair<bool,bool> flag = relyingParty->getBool("chunkedEncoding");
280 http->useChunkedEncoding(flag.first && flag.second);
281 http->setRequestHeader("Xerces-C", XERCES_FULLVERSIONDOT);
282 http->setRequestHeader("XML-Security-C", XSEC_FULLVERSIONDOT);
283 http->setRequestHeader("OpenSAML-C", gOpenSAMLDotVersionStr);
284 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
288 // Use a nullptr stream to trigger a body-less "GET" operation.
290 istream& msg = transport->receive();
292 DOMDocument* doc=nullptr;
293 StreamInputSource src(msg, "DynamicMetadataProvider");
294 Wrapper4InputSource dsrc(&src,false);
296 doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
298 doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
300 // Wrap the document for now.
301 XercesJanitor<DOMDocument> docjanitor(doc);
303 // Unmarshall objects, binding the document.
304 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
305 docjanitor.release();
307 // Make sure it's metadata.
308 saml2md::EntityDescriptor* entity = dynamic_cast<saml2md::EntityDescriptor*>(xmlObject.get());
310 throw saml2md::MetadataException(
311 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
317 catch (XMLException& e) {
318 auto_ptr_char msg(e.getMessage());
319 log.error("Xerces error while resolving location (%s): %s", name.c_str(), msg.get());
320 throw saml2md::MetadataException(msg.get());