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=NULL) const {return NULL;}
65 vector<const Credential*>::size_type resolve(
66 vector<const Credential*>& results, const CredentialCriteria* criteria=NULL
70 class SHIBSP_DLLLOCAL DynamicMetadataProvider : public saml2md::DynamicMetadataProvider
73 DynamicMetadataProvider(const xercesc::DOMElement* e=NULL);
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), m_verifyHost(true), m_ignoreTransport(false), m_encoded(true), m_trust(NULL)
107 const XMLCh* flag = e ? e->getAttributeNS(NULL, verifyHost) : NULL;
108 if (flag && (*flag == chLatin_f || *flag == chDigit_0))
109 m_verifyHost = false;
110 flag = e ? e->getAttributeNS(NULL, ignoreTransport) : NULL;
111 if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
112 m_ignoreTransport = true;
116 const DOMElement* child = e ? XMLHelper::getFirstChildElement(e, Subst) : NULL;
117 if (child && child->hasChildNodes()) {
118 auto_ptr_char s(child->getFirstChild()->getNodeValue());
119 if (s.get() && *s.get()) {
121 flag = child->getAttributeNS(NULL, encoded);
122 if (flag && (*flag == chLatin_f || *flag == chDigit_0))
127 if (m_subst.empty()) {
128 child = e ? XMLHelper::getFirstChildElement(e, Regex) : NULL;
129 if (child && child->hasChildNodes() && child->hasAttributeNS(NULL, match)) {
130 auto_ptr_char m(child->getAttributeNS(NULL, match));
131 auto_ptr_char repl(child->getFirstChild()->getNodeValue());
132 if (m.get() && *m.get() && repl.get() && *repl.get()) {
134 m_regex = repl.get();
139 child = e ? XMLHelper::getFirstChildElement(e, _TrustEngine) : NULL;
140 auto_ptr_char t2(child ? child->getAttributeNS(NULL,type) : NULL);
142 TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t2.get(), child);
143 if (!(m_trust = dynamic_cast<X509TrustEngine*>(trust))) {
145 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin.");
150 throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true.");
153 saml2md::EntityDescriptor* DynamicMetadataProvider::resolve(const saml2md::MetadataProvider::Criteria& criteria) const
156 xmltooling::NDC("resolve");
158 Category& log=Category::getInstance(SHIBSP_LOGCAT".MetadataProvider.Dynamic");
161 if (criteria.entityID_ascii) {
162 name = criteria.entityID_ascii;
164 else if (criteria.entityID_unicode) {
165 auto_ptr_char temp(criteria.entityID_unicode);
168 else if (criteria.artifact) {
169 throw saml2md::MetadataException("Unable to resolve metadata dynamically from an artifact.");
172 // Possibly transform the input into a different URL to use.
173 if (!m_subst.empty()) {
174 string::size_type pos = m_subst.find("$entityID");
175 if (pos != string::npos) {
176 string name2 = m_subst;
177 name2.replace(pos, 9, m_encoded ? XMLToolingConfig::getConfig().getURLEncoder()->encode(name.c_str()) : name);
178 log.info("transformed location from (%s) to (%s)", name.c_str(), name2.c_str());
182 else if (!m_match.empty() && !m_regex.empty()) {
184 RegularExpression exp(m_match.c_str());
185 XMLCh* temp = exp.replace(name.c_str(), m_regex.c_str());
187 auto_ptr_char narrow(temp);
188 XMLString::release(&temp);
190 // For some reason it returns the match string if it doesn't match the expression.
191 if (name != narrow.get()) {
192 log.info("transformed location from (%s) to (%s)", name.c_str(), narrow.get());
197 catch (XMLException& ex) {
198 auto_ptr_char msg(ex.getMessage());
199 log.error("caught error applying regular expression: %s", msg.get());
203 // Establish networking properties based on calling application.
204 const MetadataProviderCriteria* mpc = dynamic_cast<const MetadataProviderCriteria*>(&criteria);
206 throw saml2md::MetadataException("Dynamic MetadataProvider requires Shibboleth-aware lookup criteria, check calling code.");
207 const PropertySet* relyingParty;
208 if (criteria.entityID_unicode)
209 relyingParty = mpc->application.getRelyingParty(criteria.entityID_unicode);
211 auto_ptr_XMLCh temp2(name.c_str());
212 relyingParty = mpc->application.getRelyingParty(temp2.get());
215 // Prepare a transport object addressed appropriately.
216 SOAPTransport::Address addr(relyingParty->getString("entityID").second, name.c_str(), name.c_str());
217 const char* pch = strchr(addr.m_endpoint,':');
219 throw IOException("location was not a URL.");
220 string scheme(addr.m_endpoint, pch-addr.m_endpoint);
221 SOAPTransport* transport=NULL;
223 transport = XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr);
225 catch (exception& ex) {
226 log.error("exception while building transport object to resolve URL: %s", ex.what());
227 throw IOException("Unable to resolve entityID with a known transport protocol.");
229 auto_ptr<SOAPTransport> transportwrapper(transport);
231 // Apply properties as directed.
232 transport->setVerifyHost(m_verifyHost);
233 DummyCredentialResolver dcr;
234 if (m_trust && !transport->setTrustEngine(m_trust, &dcr))
235 throw IOException("Unable to install X509TrustEngine into metadata resolver.");
237 Locker credlocker(NULL, false);
238 CredentialResolver* credResolver = NULL;
239 pair<bool,const char*> authType=relyingParty->getString("authType");
240 if (!authType.first || !strcmp(authType.second,"TLS")) {
241 credResolver = mpc->application.getCredentialResolver();
243 credlocker.assign(credResolver);
245 CredentialCriteria cc;
246 cc.setUsage(Credential::TLS_CREDENTIAL);
247 authType = relyingParty->getString("keyName");
249 cc.getKeyNames().insert(authType.second);
250 const Credential* cred = credResolver->resolve(&cc);
251 cc.getKeyNames().clear();
253 if (!transport->setCredential(cred))
254 log.error("failed to load Credential into metadata resolver");
257 log.error("no TLS credential supplied");
261 log.error("no CredentialResolver available for TLS");
265 SOAPTransport::transport_auth_t type=SOAPTransport::transport_auth_none;
266 pair<bool,const char*> username=relyingParty->getString("authUsername");
267 pair<bool,const char*> password=relyingParty->getString("authPassword");
268 if (!username.first || !password.first)
269 log.error("transport authType (%s) specified but authUsername or authPassword was missing", authType.second);
270 else if (!strcmp(authType.second,"basic"))
271 type = SOAPTransport::transport_auth_basic;
272 else if (!strcmp(authType.second,"digest"))
273 type = SOAPTransport::transport_auth_digest;
274 else if (!strcmp(authType.second,"ntlm"))
275 type = SOAPTransport::transport_auth_ntlm;
276 else if (!strcmp(authType.second,"gss"))
277 type = SOAPTransport::transport_auth_gss;
278 else if (strcmp(authType.second,"none"))
279 log.error("unknown authType (%s) specified for RelyingParty", authType.second);
280 if (type > SOAPTransport::transport_auth_none) {
281 if (transport->setAuth(type,username.second,password.second))
282 log.debug("configured for transport authentication (method=%s, username=%s)", authType.second, username.second);
284 log.error("failed to configure transport authentication (method=%s)", authType.second);
288 pair<bool,unsigned int> timeout = relyingParty->getUnsignedInt("connectTimeout");
289 transport->setConnectTimeout(timeout.first ? timeout.second : 10);
290 timeout = relyingParty->getUnsignedInt("timeout");
291 transport->setTimeout(timeout.first ? timeout.second : 20);
292 mpc->application.getServiceProvider().setTransportOptions(*transport);
294 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(transport);
296 pair<bool,bool> flag = relyingParty->getBool("chunkedEncoding");
297 http->useChunkedEncoding(flag.first && flag.second);
298 http->setRequestHeader("Xerces-C", XERCES_FULLVERSIONDOT);
299 http->setRequestHeader("XML-Security-C", XSEC_FULLVERSIONDOT);
300 http->setRequestHeader("OpenSAML-C", OPENSAML_FULLVERSIONDOT);
301 http->setRequestHeader("User-Agent", PACKAGE_NAME);
302 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
306 // Use a NULL stream to trigger a body-less "GET" operation.
308 istream& msg = transport->receive();
310 DOMDocument* doc=NULL;
311 StreamInputSource src(msg, "DynamicMetadataProvider");
312 Wrapper4InputSource dsrc(&src,false);
314 doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
316 doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
318 // Wrap the document for now.
319 XercesJanitor<DOMDocument> docjanitor(doc);
321 // Unmarshall objects, binding the document.
322 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
323 docjanitor.release();
325 // Make sure it's metadata.
326 saml2md::EntityDescriptor* entity = dynamic_cast<saml2md::EntityDescriptor*>(xmlObject.get());
328 throw saml2md::MetadataException(
329 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
335 catch (XMLException& e) {
336 auto_ptr_char msg(e.getMessage());
337 log.error("Xerces error while resolving location (%s): %s", name.c_str(), msg.get());
338 throw saml2md::MetadataException(msg.get());