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) {
70 m_protocol = XMLString::transcode(session.getProtocol());
71 m_class = XMLString::transcode(session.getAuthnContextClassRef());
72 m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
76 const Application& application,
77 const EntityDescriptor* issuer,
78 const XMLCh* protocol,
80 const XMLCh* authncontext_class=NULL,
81 const XMLCh* authncontext_decl=NULL,
82 const vector<const opensaml::Assertion*>* tokens=NULL,
83 const multimap<string,Attribute*>* attributes=NULL
84 ) : m_query(true), m_app(application), m_session(NULL), m_metadata(NULL), m_entity(issuer),
85 m_protocol(protocol), m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
88 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
89 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
90 if (token2 && !token2->getAttributeStatements().empty()) {
94 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
95 if (token1 && !token1->getAttributeStatements().empty()) {
105 XMLString::release((XMLCh**)&m_protocol);
106 XMLString::release((XMLCh**)&m_class);
107 XMLString::release((XMLCh**)&m_decl);
110 m_metadata->unlock();
111 for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,shibsp::Attribute>());
112 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
115 bool doQuery() const {
119 const Application& getApplication() const {
122 const EntityDescriptor* getEntityDescriptor() const {
125 if (m_session && m_session->getEntityID()) {
126 m_metadata = m_app.getMetadataProvider();
129 return m_entity = m_metadata->getEntityDescriptor(m_session->getEntityID());
134 const XMLCh* getProtocol() const {
137 const NameID* getNameID() const {
138 return m_session ? m_session->getNameID() : m_nameid;
140 const XMLCh* getClassRef() const {
143 const XMLCh* getDeclRef() const {
146 const Session* getSession() const {
149 multimap<string,shibsp::Attribute*>& getResolvedAttributes() {
152 vector<opensaml::Assertion*>& getResolvedAssertions() {
158 const Application& m_app;
159 const Session* m_session;
160 mutable MetadataProvider* m_metadata;
161 mutable const EntityDescriptor* m_entity;
162 const XMLCh* m_protocol;
163 const NameID* m_nameid;
164 const XMLCh* m_class;
166 multimap<string,shibsp::Attribute*> m_attributes;
167 vector<opensaml::Assertion*> m_assertions;
170 class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
173 QueryResolver(const DOMElement* e);
175 for_each(m_SAML1Designators.begin(), m_SAML1Designators.end(), xmltooling::cleanup<AttributeDesignator>());
176 for_each(m_SAML2Designators.begin(), m_SAML2Designators.end(), xmltooling::cleanup<saml2::Attribute>());
179 Lockable* lock() {return this;}
182 ResolutionContext* createResolutionContext(
183 const Application& application,
184 const EntityDescriptor* issuer,
185 const XMLCh* protocol,
186 const NameID* nameid,
187 const XMLCh* authncontext_class=NULL,
188 const XMLCh* authncontext_decl=NULL,
189 const vector<const opensaml::Assertion*>* tokens=NULL,
190 const multimap<string,shibsp::Attribute*>* attributes=NULL
192 return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens,attributes);
195 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
196 return new QueryContext(application,session);
199 void resolveAttributes(ResolutionContext& ctx) const;
201 void getAttributeIds(vector<string>& attributes) const {
202 // Nothing to do, only the extractor would actually generate them.
206 bool SAML1Query(QueryContext& ctx) const;
207 bool SAML2Query(QueryContext& ctx) const;
210 vector<AttributeDesignator*> m_SAML1Designators;
211 vector<saml2::Attribute*> m_SAML2Designators;
214 AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
216 return new QueryResolver(e);
221 void SHIBSP_API shibsp::registerAttributeResolvers()
223 SPConfig::getConfig().AttributeResolverManager.registerFactory(QUERY_ATTRIBUTE_RESOLVER, QueryResolverFactory);
226 QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver"))
229 xmltooling::NDC ndc("QueryResolver");
232 DOMElement* child = XMLHelper::getFirstChildElement(e);
235 if (XMLHelper::isNodeNamed(e, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
236 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
237 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
239 m_SAML2Designators.push_back(down);
243 else if (XMLHelper::isNodeNamed(e, samlconstants::SAML1P_NS, AttributeDesignator::LOCAL_NAME)) {
244 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
245 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
247 m_SAML1Designators.push_back(down);
252 catch (exception& ex) {
253 m_log.error("exception loading attribute designator: %s", ex.what());
255 child = XMLHelper::getNextSiblingElement(child);
259 bool QueryResolver::SAML1Query(QueryContext& ctx) const
262 xmltooling::NDC ndc("query");
265 int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
266 const AttributeAuthorityDescriptor* AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(ctx.getProtocol());
268 m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
272 shibsp::SecurityPolicy policy(ctx.getApplication());
273 MetadataCredentialCriteria mcc(*AA);
274 shibsp::SOAPClient soaper(policy);
275 const PropertySet* policySettings =
276 ctx.getApplication().getServiceProvider().getPolicySettings(ctx.getApplication().getString("policyId").second);
277 pair<bool,bool> signedAssertions = policySettings->getBool("signedAssertions");
279 auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
280 saml1p::Response* response=NULL;
281 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
282 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
284 if (!XMLString::equals((*ep)->getBinding(),binding.get()))
286 auto_ptr_char loc((*ep)->getLocation());
287 auto_ptr_XMLCh issuer(ctx.getApplication().getString("entityID").second);
288 NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
289 nameid->setName(ctx.getNameID()->getName());
290 nameid->setFormat(ctx.getNameID()->getFormat());
291 nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
292 saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
293 subject->setNameIdentifier(nameid);
294 saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
295 query->setSubject(subject);
296 query->setResource(issuer.get());
297 for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
298 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
299 Request* request = RequestBuilder::buildRequest();
300 request->setAttributeQuery(query);
301 request->setMinorVersion(version);
303 SAML1SOAPClient client(soaper, false);
304 client.sendSAML(request, mcc, loc.get());
305 response = client.receiveSAML();
307 catch (exception& ex) {
308 m_log.error("exception making SAML query: %s", ex.what());
314 m_log.error("unable to obtain a SAML response from attribute authority");
317 else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==NULL ||
318 *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
320 m_log.error("attribute authority returned a SAML error");
324 const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
325 if (assertions.size()>1)
326 m_log.warn("simple resolver only supports one assertion in the query response");
328 auto_ptr<saml1p::Response> wrapper(response);
329 saml1::Assertion* newtoken = assertions.front();
331 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
332 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
337 policy.evaluate(*newtoken);
338 if (!policy.isSecure())
339 throw SecurityPolicyException("Security of SAML 1.x query result not established.");
340 saml1::AssertionValidator tokval(ctx.getApplication().getAudiences(), time(NULL));
341 tokval.validateAssertion(*newtoken);
343 catch (exception& ex) {
344 m_log.error("assertion failed policy/validation: %s", ex.what());
350 ctx.getResolvedAssertions().push_back(newtoken);
352 // Finally, extract and filter the result.
354 AttributeExtractor* extractor = ctx.getApplication().getAttributeExtractor();
356 Locker extlocker(extractor);
357 extractor->extractAttributes(ctx.getApplication(), AA, *newtoken, ctx.getResolvedAttributes());
360 AttributeFilter* filter = ctx.getApplication().getAttributeFilter();
362 BasicFilteringContext fc(ctx.getApplication(), ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
363 Locker filtlocker(filter);
364 filter->filterAttributes(fc, ctx.getResolvedAttributes());
367 catch (exception& ex) {
368 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
369 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), cleanup_pair<string,shibsp::Attribute>());
370 ctx.getResolvedAttributes().clear();
376 bool QueryResolver::SAML2Query(QueryContext& ctx) const
379 xmltooling::NDC ndc("query");
382 const AttributeAuthorityDescriptor* AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(samlconstants::SAML20P_NS);
384 m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
388 shibsp::SecurityPolicy policy(ctx.getApplication());
389 MetadataCredentialCriteria mcc(*AA);
390 shibsp::SOAPClient soaper(policy);
391 const PropertySet* policySettings =
392 ctx.getApplication().getServiceProvider().getPolicySettings(ctx.getApplication().getString("policyId").second);
393 pair<bool,bool> signedAssertions = policySettings->getBool("signedAssertions");
395 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
396 saml2p::StatusResponseType* srt=NULL;
397 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
398 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
400 if (!XMLString::equals((*ep)->getBinding(),binding.get()))
402 auto_ptr_char loc((*ep)->getLocation());
403 auto_ptr_XMLCh issuer(ctx.getApplication().getString("entityID").second);
404 saml2::Subject* subject = saml2::SubjectBuilder::buildSubject();
405 subject->setNameID(ctx.getNameID()->cloneNameID());
406 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
407 query->setSubject(subject);
408 Issuer* iss = IssuerBuilder::buildIssuer();
409 iss->setName(issuer.get());
410 query->setIssuer(iss);
411 for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
412 query->getAttributes().push_back((*ad)->cloneAttribute());
414 SAML2SOAPClient client(soaper, false);
415 client.sendSAML(query, mcc, loc.get());
416 srt = client.receiveSAML();
418 catch (exception& ex) {
419 m_log.error("exception making SAML query: %s", ex.what());
425 m_log.error("unable to obtain a SAML response from attribute authority");
428 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
431 m_log.error("message was not a samlp:Response");
434 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
435 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
437 m_log.error("attribute authority returned a SAML error");
441 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
442 if (assertions.size()>1)
443 m_log.warn("simple resolver only supports one assertion in the query response");
445 auto_ptr<saml2p::Response> wrapper(response);
446 saml2::Assertion* newtoken = assertions.front();
448 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
449 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
454 policy.evaluate(*newtoken);
455 if (!policy.isSecure())
456 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
457 saml2::AssertionValidator tokval(ctx.getApplication().getAudiences(), time(NULL));
458 tokval.validateAssertion(*newtoken);
460 catch (exception& ex) {
461 m_log.error("assertion failed policy/validation: %s", ex.what());
467 ctx.getResolvedAssertions().push_back(newtoken);
469 // Finally, extract and filter the result.
471 AttributeExtractor* extractor = ctx.getApplication().getAttributeExtractor();
473 Locker extlocker(extractor);
474 extractor->extractAttributes(ctx.getApplication(), AA, *newtoken, ctx.getResolvedAttributes());
477 AttributeFilter* filter = ctx.getApplication().getAttributeFilter();
479 BasicFilteringContext fc(ctx.getApplication(), ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
480 Locker filtlocker(filter);
481 filter->filterAttributes(fc, ctx.getResolvedAttributes());
484 catch (exception& ex) {
485 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
486 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), cleanup_pair<string,shibsp::Attribute>());
487 ctx.getResolvedAttributes().clear();
493 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
496 xmltooling::NDC ndc("resolveAttributes");
499 QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
500 if (!qctx.doQuery()) {
501 m_log.debug("found AttributeStatement in input to new session, skipping query");
505 if (qctx.getNameID() && qctx.getEntityDescriptor()) {
506 if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
507 m_log.debug("attempting SAML 2.0 attribute query");
510 else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
511 XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
512 m_log.debug("attempting SAML 1.x attribute query");
516 m_log.warn("SSO protocol does not allow for attribute query");
519 m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");