2 * Copyright 2001-2007 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 * QueryAttributeResolver.cpp
20 * AttributeResolver based on SAML queries.
24 #include "Application.h"
25 #include "ServiceProvider.h"
26 #include "SessionCache.h"
27 #include "attribute/Attribute.h"
28 #include "attribute/filtering/AttributeFilter.h"
29 #include "attribute/filtering/BasicFilteringContext.h"
30 #include "attribute/resolver/AttributeExtractor.h"
31 #include "attribute/resolver/AttributeResolver.h"
32 #include "attribute/resolver/ResolutionContext.h"
33 #include "binding/SOAPClient.h"
34 #include "util/SPConstants.h"
36 #include <log4cpp/Category.hh>
37 #include <saml/exceptions.h>
38 #include <saml/binding/SecurityPolicy.h>
39 #include <saml/saml1/binding/SAML1SOAPClient.h>
40 #include <saml/saml1/core/Assertions.h>
41 #include <saml/saml1/core/Protocols.h>
42 #include <saml/saml1/profile/AssertionValidator.h>
43 #include <saml/saml2/binding/SAML2SOAPClient.h>
44 #include <saml/saml2/core/Protocols.h>
45 #include <saml/saml2/metadata/Metadata.h>
46 #include <saml/saml2/metadata/MetadataProvider.h>
47 #include <saml/saml2/profile/AssertionValidator.h>
48 #include <xmltooling/util/NDC.h>
49 #include <xmltooling/util/XMLHelper.h>
50 #include <xercesc/util/XMLUniDefs.hpp>
52 using namespace shibsp;
53 using namespace opensaml::saml1;
54 using namespace opensaml::saml1p;
55 using namespace opensaml::saml2;
56 using namespace opensaml::saml2p;
57 using namespace opensaml::saml2md;
58 using namespace opensaml;
59 using namespace xmltooling;
60 using namespace log4cpp;
65 class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
68 QueryContext(const Application& application, const Session& session)
69 : m_query(true), m_app(application), m_session(&session), m_metadata(NULL), m_entity(NULL), m_nameid(NULL) {
73 const Application& application,
74 const EntityDescriptor* issuer,
76 const char* authncontext_class=NULL,
77 const char* authncontext_decl=NULL,
78 const vector<const opensaml::Assertion*>* tokens=NULL,
79 const multimap<string,Attribute*>* attributes=NULL
80 ) : m_query(true), m_app(application), m_session(NULL), m_metadata(NULL), m_entity(issuer),
81 m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
84 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
85 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
86 if (token2 && !token2->getAttributeStatements().empty()) {
90 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
91 if (token1 && !token1->getAttributeStatements().empty()) {
101 m_metadata->unlock();
102 for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,shibsp::Attribute>());
103 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
106 bool doQuery() const {
110 const Application& getApplication() const {
113 const EntityDescriptor* getEntityDescriptor() const {
116 if (m_session && m_session->getEntityID()) {
117 m_metadata = m_app.getMetadataProvider();
120 return m_entity = m_metadata->getEntityDescriptor(m_session->getEntityID());
125 const NameID* getNameID() const {
126 return m_session ? m_session->getNameID() : m_nameid;
128 const char* getClassRef() const {
129 return m_session ? m_session->getAuthnContextClassRef() : m_class;
131 const char* getDeclRef() const {
132 return m_session ? m_session->getAuthnContextDeclRef() : m_decl;
134 const Session* getSession() const {
137 multimap<string,shibsp::Attribute*>& getResolvedAttributes() {
140 vector<opensaml::Assertion*>& getResolvedAssertions() {
146 const Application& m_app;
147 const Session* m_session;
148 mutable MetadataProvider* m_metadata;
149 mutable const EntityDescriptor* m_entity;
150 const NameID* m_nameid;
153 multimap<string,shibsp::Attribute*> m_attributes;
154 vector<opensaml::Assertion*> m_assertions;
157 class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
160 QueryResolver(const DOMElement* e);
162 for_each(m_SAML1Designators.begin(), m_SAML1Designators.end(), xmltooling::cleanup<AttributeDesignator>());
163 for_each(m_SAML2Designators.begin(), m_SAML2Designators.end(), xmltooling::cleanup<saml2::Attribute>());
166 Lockable* lock() {return this;}
169 ResolutionContext* createResolutionContext(
170 const Application& application,
171 const EntityDescriptor* issuer,
172 const NameID* nameid,
173 const char* authncontext_class=NULL,
174 const char* authncontext_decl=NULL,
175 const vector<const opensaml::Assertion*>* tokens=NULL,
176 const multimap<string,shibsp::Attribute*>* attributes=NULL
178 return new QueryContext(application,issuer,nameid,authncontext_class,authncontext_decl,tokens,attributes);
181 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
182 return new QueryContext(application,session);
185 void resolveAttributes(ResolutionContext& ctx) const;
188 bool SAML1Query(QueryContext& ctx) const;
189 bool SAML2Query(QueryContext& ctx) const;
192 vector<AttributeDesignator*> m_SAML1Designators;
193 vector<saml2::Attribute*> m_SAML2Designators;
196 AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
198 return new QueryResolver(e);
203 void SHIBSP_API shibsp::registerAttributeResolvers()
205 SPConfig::getConfig().AttributeResolverManager.registerFactory(QUERY_ATTRIBUTE_RESOLVER, QueryResolverFactory);
208 QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver"))
211 xmltooling::NDC ndc("QueryResolver");
214 DOMElement* child = XMLHelper::getFirstChildElement(e);
217 if (XMLHelper::isNodeNamed(e, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
218 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
219 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
221 m_SAML2Designators.push_back(down);
225 else if (XMLHelper::isNodeNamed(e, samlconstants::SAML1P_NS, AttributeDesignator::LOCAL_NAME)) {
226 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
227 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
229 m_SAML1Designators.push_back(down);
234 catch (exception& ex) {
235 m_log.error("exception loading attribute designator: %s", ex.what());
237 child = XMLHelper::getNextSiblingElement(child);
241 bool QueryResolver::SAML1Query(QueryContext& ctx) const
244 xmltooling::NDC ndc("query");
248 const AttributeAuthorityDescriptor* AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(samlconstants::SAML11_PROTOCOL_ENUM);
250 AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(samlconstants::SAML10_PROTOCOL_ENUM);
254 m_log.info("no SAML 1.x AttributeAuthority role found in metadata");
258 shibsp::SecurityPolicy policy(ctx.getApplication());
259 MetadataCredentialCriteria mcc(*AA);
260 shibsp::SOAPClient soaper(policy);
261 const PropertySet* policySettings =
262 ctx.getApplication().getServiceProvider().getPolicySettings(ctx.getApplication().getString("policyId").second);
263 pair<bool,bool> signedAssertions = policySettings->getBool("signedAssertions");
265 auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
266 saml1p::Response* response=NULL;
267 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
268 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
270 if (!XMLString::equals((*ep)->getBinding(),binding.get()))
272 auto_ptr_char loc((*ep)->getLocation());
273 auto_ptr_XMLCh issuer(ctx.getApplication().getString("entityID").second);
274 NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
275 nameid->setName(ctx.getNameID()->getName());
276 nameid->setFormat(ctx.getNameID()->getFormat());
277 nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
278 saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
279 subject->setNameIdentifier(nameid);
280 saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
281 query->setSubject(subject);
282 query->setResource(issuer.get());
283 for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
284 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
285 Request* request = RequestBuilder::buildRequest();
286 request->setAttributeQuery(query);
287 request->setMinorVersion(version);
289 SAML1SOAPClient client(soaper);
290 client.sendSAML(request, mcc, loc.get());
291 response = client.receiveSAML();
293 catch (exception& ex) {
294 m_log.error("exception making SAML query: %s", ex.what());
300 m_log.error("unable to successfully query for attributes");
304 const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
305 if (assertions.size()>1)
306 m_log.warn("simple resolver only supports one assertion in the query response");
308 auto_ptr<saml1p::Response> wrapper(response);
309 saml1::Assertion* newtoken = assertions.front();
311 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
312 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
317 policy.evaluate(*newtoken);
318 if (!policy.isSecure())
319 throw SecurityPolicyException("Security of SAML 1.x query result not established.");
320 saml1::AssertionValidator tokval(ctx.getApplication().getAudiences(), time(NULL));
321 tokval.validateAssertion(*newtoken);
323 catch (exception& ex) {
324 m_log.error("assertion failed policy/validation: %s", ex.what());
330 ctx.getResolvedAssertions().push_back(newtoken);
332 // Finally, extract and filter the result.
334 AttributeExtractor* extractor = ctx.getApplication().getAttributeExtractor();
336 Locker extlocker(extractor);
337 extractor->extractAttributes(ctx.getApplication(), AA, *newtoken, ctx.getResolvedAttributes());
340 AttributeFilter* filter = ctx.getApplication().getAttributeFilter();
342 BasicFilteringContext fc(ctx.getApplication(), ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
343 Locker filtlocker(filter);
344 filter->filterAttributes(fc, ctx.getResolvedAttributes());
347 catch (exception& ex) {
348 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
349 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), cleanup_pair<string,shibsp::Attribute>());
350 ctx.getResolvedAttributes().clear();
356 bool QueryResolver::SAML2Query(QueryContext& ctx) const
359 xmltooling::NDC ndc("query");
362 const AttributeAuthorityDescriptor* AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(samlconstants::SAML20P_NS);
364 m_log.info("no SAML 2 AttributeAuthority role found in metadata");
368 shibsp::SecurityPolicy policy(ctx.getApplication());
369 MetadataCredentialCriteria mcc(*AA);
370 shibsp::SOAPClient soaper(policy);
371 const PropertySet* policySettings =
372 ctx.getApplication().getServiceProvider().getPolicySettings(ctx.getApplication().getString("policyId").second);
373 pair<bool,bool> signedAssertions = policySettings->getBool("signedAssertions");
375 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
376 saml2p::StatusResponseType* srt=NULL;
377 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
378 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
380 if (!XMLString::equals((*ep)->getBinding(),binding.get()))
382 auto_ptr_char loc((*ep)->getLocation());
383 auto_ptr_XMLCh issuer(ctx.getApplication().getString("entityID").second);
384 saml2::Subject* subject = saml2::SubjectBuilder::buildSubject();
385 subject->setNameID(ctx.getNameID()->cloneNameID());
386 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
387 query->setSubject(subject);
388 Issuer* iss = IssuerBuilder::buildIssuer();
389 iss->setName(issuer.get());
390 query->setIssuer(iss);
391 for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
392 query->getAttributes().push_back((*ad)->cloneAttribute());
394 SAML2SOAPClient client(soaper);
395 client.sendSAML(query, mcc, loc.get());
396 srt = client.receiveSAML();
398 catch (exception& ex) {
399 m_log.error("exception making SAML query: %s", ex.what());
405 m_log.error("unable to successfully query for attributes");
408 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
411 m_log.error("message was not a samlp:Response");
415 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
416 if (assertions.size()>1)
417 m_log.warn("simple resolver only supports one assertion in the query response");
419 auto_ptr<saml2p::Response> wrapper(response);
420 saml2::Assertion* newtoken = assertions.front();
422 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
423 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
428 policy.evaluate(*newtoken);
429 if (!policy.isSecure())
430 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
431 saml2::AssertionValidator tokval(ctx.getApplication().getAudiences(), time(NULL));
432 tokval.validateAssertion(*newtoken);
434 catch (exception& ex) {
435 m_log.error("assertion failed policy/validation: %s", ex.what());
441 ctx.getResolvedAssertions().push_back(newtoken);
443 // Finally, extract and filter the result.
445 AttributeExtractor* extractor = ctx.getApplication().getAttributeExtractor();
447 Locker extlocker(extractor);
448 extractor->extractAttributes(ctx.getApplication(), AA, *newtoken, ctx.getResolvedAttributes());
451 AttributeFilter* filter = ctx.getApplication().getAttributeFilter();
453 BasicFilteringContext fc(ctx.getApplication(), ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
454 Locker filtlocker(filter);
455 filter->filterAttributes(fc, ctx.getResolvedAttributes());
458 catch (exception& ex) {
459 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
460 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), cleanup_pair<string,shibsp::Attribute>());
461 ctx.getResolvedAttributes().clear();
467 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
470 xmltooling::NDC ndc("resolveAttributes");
473 QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
474 if (!qctx.doQuery()) {
475 m_log.debug("found AttributeStatement in input to new session, skipping query");
479 if (qctx.getNameID() && qctx.getEntityDescriptor()) {
480 m_log.debug("attempting SAML 2.0 attribute query");
481 if (!SAML2Query(qctx)) {
482 m_log.debug("attempting SAML 1.x attribute query");
486 m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");