2 * Copyright 2001-2009 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 "metadata/MetadataProviderCriteria.h"
35 #include "util/SPConstants.h"
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/saml2/binding/SAML2SOAPClient.h>
43 #include <saml/saml2/core/Protocols.h>
44 #include <saml/saml2/metadata/Metadata.h>
45 #include <saml/saml2/metadata/MetadataProvider.h>
46 #include <xmltooling/util/NDC.h>
47 #include <xmltooling/util/XMLHelper.h>
48 #include <xercesc/util/XMLUniDefs.hpp>
50 using namespace shibsp;
51 using namespace opensaml::saml1;
52 using namespace opensaml::saml1p;
53 using namespace opensaml::saml2;
54 using namespace opensaml::saml2p;
55 using namespace opensaml::saml2md;
56 using namespace opensaml;
57 using namespace xmltooling;
62 class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
65 QueryContext(const Application& application, const Session& session)
66 : m_query(true), m_app(application), m_session(&session), m_metadata(NULL), m_entity(NULL), m_nameid(NULL) {
67 m_protocol = XMLString::transcode(session.getProtocol());
68 m_class = XMLString::transcode(session.getAuthnContextClassRef());
69 m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
73 const Application& application,
74 const EntityDescriptor* issuer,
75 const XMLCh* protocol,
76 const NameID* nameid=NULL,
77 const XMLCh* authncontext_class=NULL,
78 const XMLCh* authncontext_decl=NULL,
79 const vector<const opensaml::Assertion*>* tokens=NULL
80 ) : m_query(true), m_app(application), m_session(NULL), m_metadata(NULL), m_entity(issuer),
81 m_protocol(protocol), 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 XMLString::release((XMLCh**)&m_protocol);
102 XMLString::release((XMLCh**)&m_class);
103 XMLString::release((XMLCh**)&m_decl);
106 m_metadata->unlock();
107 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
108 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
111 bool doQuery() const {
115 const Application& getApplication() const {
118 const EntityDescriptor* getEntityDescriptor() const {
121 if (m_session && m_session->getEntityID()) {
122 m_metadata = m_app.getMetadataProvider(false);
125 return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
130 const XMLCh* getProtocol() const {
133 const NameID* getNameID() const {
134 return m_session ? m_session->getNameID() : m_nameid;
136 const XMLCh* getClassRef() const {
139 const XMLCh* getDeclRef() const {
142 const Session* getSession() const {
145 vector<shibsp::Attribute*>& getResolvedAttributes() {
148 vector<opensaml::Assertion*>& getResolvedAssertions() {
154 const Application& m_app;
155 const Session* m_session;
156 mutable MetadataProvider* m_metadata;
157 mutable const EntityDescriptor* m_entity;
158 const XMLCh* m_protocol;
159 const NameID* m_nameid;
160 const XMLCh* m_class;
162 vector<shibsp::Attribute*> m_attributes;
163 vector<opensaml::Assertion*> m_assertions;
166 class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
169 QueryResolver(const DOMElement* e);
171 for_each(m_SAML1Designators.begin(), m_SAML1Designators.end(), xmltooling::cleanup<AttributeDesignator>());
172 for_each(m_SAML2Designators.begin(), m_SAML2Designators.end(), xmltooling::cleanup<saml2::Attribute>());
175 Lockable* lock() {return this;}
178 ResolutionContext* createResolutionContext(
179 const Application& application,
180 const EntityDescriptor* issuer,
181 const XMLCh* protocol,
182 const NameID* nameid=NULL,
183 const XMLCh* authncontext_class=NULL,
184 const XMLCh* authncontext_decl=NULL,
185 const vector<const opensaml::Assertion*>* tokens=NULL,
186 const vector<shibsp::Attribute*>* attributes=NULL
188 return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens);
191 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
192 return new QueryContext(application,session);
195 void resolveAttributes(ResolutionContext& ctx) const;
197 void getAttributeIds(vector<string>& attributes) const {
198 // Nothing to do, only the extractor would actually generate them.
202 bool SAML1Query(QueryContext& ctx) const;
203 bool SAML2Query(QueryContext& ctx) const;
207 vector<AttributeDesignator*> m_SAML1Designators;
208 vector<saml2::Attribute*> m_SAML2Designators;
211 AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
213 return new QueryResolver(e);
216 static const XMLCh _policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
219 QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.Query"))
222 xmltooling::NDC ndc("QueryResolver");
225 const XMLCh* pid = e ? e->getAttributeNS(NULL, _policyId) : NULL;
227 auto_ptr_char temp(pid);
228 m_policyId = temp.get();
231 DOMElement* child = XMLHelper::getFirstChildElement(e);
234 if (XMLHelper::isNodeNamed(e, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
235 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
236 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
238 m_SAML2Designators.push_back(down);
242 else if (XMLHelper::isNodeNamed(e, samlconstants::SAML1P_NS, AttributeDesignator::LOCAL_NAME)) {
243 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
244 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
246 m_SAML1Designators.push_back(down);
251 catch (exception& ex) {
252 m_log.error("exception loading attribute designator: %s", ex.what());
254 child = XMLHelper::getNextSiblingElement(child);
258 bool QueryResolver::SAML1Query(QueryContext& ctx) const
261 xmltooling::NDC ndc("query");
264 int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
265 const AttributeAuthorityDescriptor* AA =
266 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
268 m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
272 const Application& application = ctx.getApplication();
273 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
275 // Locate policy key.
276 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
278 // Access policy properties.
279 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
280 pair<bool,bool> validate = settings->getBool("validate");
282 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
283 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
284 MetadataCredentialCriteria mcc(*AA);
285 shibsp::SOAPClient soaper(policy);
287 auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
288 saml1p::Response* response=NULL;
289 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
290 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
291 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
293 auto_ptr_char loc((*ep)->getLocation());
295 NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
296 nameid->setName(ctx.getNameID()->getName());
297 nameid->setFormat(ctx.getNameID()->getFormat());
298 nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
299 saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
300 subject->setNameIdentifier(nameid);
301 saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
302 query->setSubject(subject);
303 query->setResource(relyingParty->getXMLString("entityID").second);
304 for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
305 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
306 Request* request = RequestBuilder::buildRequest();
307 request->setAttributeQuery(query);
308 request->setMinorVersion(version);
310 SAML1SOAPClient client(soaper, false);
311 client.sendSAML(request, application.getId(), mcc, loc.get());
312 response = client.receiveSAML();
314 catch (exception& ex) {
315 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
321 m_log.error("unable to obtain a SAML response from attribute authority");
324 else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==NULL ||
325 *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
327 m_log.error("attribute authority returned a SAML error");
331 const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
332 if (assertions.empty()) {
334 m_log.warn("response from attribute authority was empty");
337 else if (assertions.size()>1)
338 m_log.warn("simple resolver only supports one assertion in the query response");
340 auto_ptr<saml1p::Response> wrapper(response);
341 saml1::Assertion* newtoken = assertions.front();
343 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
344 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
345 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
350 // We're going to insist that the assertion issuer is the same as the peer.
351 // Reset the policy's message bits and extract them from the assertion.
353 policy.setMessageID(newtoken->getAssertionID());
354 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
355 policy.setIssuer(newtoken->getIssuer());
356 policy.evaluate(*newtoken);
358 // Now we can check the security status of the policy.
359 if (!policy.isAuthenticated())
360 throw SecurityPolicyException("Security of SAML 1.x query result not established.");
362 catch (exception& ex) {
363 m_log.error("assertion failed policy validation: %s", ex.what());
369 ctx.getResolvedAssertions().push_back(newtoken);
371 // Finally, extract and filter the result.
373 AttributeExtractor* extractor = application.getAttributeExtractor();
375 Locker extlocker(extractor);
376 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
379 AttributeFilter* filter = application.getAttributeFilter();
381 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
382 Locker filtlocker(filter);
383 filter->filterAttributes(fc, ctx.getResolvedAttributes());
386 catch (exception& ex) {
387 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
388 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
389 ctx.getResolvedAttributes().clear();
395 bool QueryResolver::SAML2Query(QueryContext& ctx) const
398 xmltooling::NDC ndc("query");
401 const AttributeAuthorityDescriptor* AA =
402 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
404 m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
408 const Application& application = ctx.getApplication();
409 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
411 // Locate policy key.
412 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
414 // Access policy properties.
415 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
416 pair<bool,bool> validate = settings->getBool("validate");
418 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
419 pair<bool,const char*> encryption = relyingParty->getString("encryption");
421 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
422 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
423 MetadataCredentialCriteria mcc(*AA);
424 shibsp::SOAPClient soaper(policy);
426 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
427 saml2p::StatusResponseType* srt=NULL;
428 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
429 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
430 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
432 auto_ptr_char loc((*ep)->getLocation());
434 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
436 // Encrypt the NameID?
437 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
438 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
439 MetadataCredentialCriteria mcc(*AA);
442 *(application.getMetadataProvider()),
445 relyingParty->getXMLString("encryptionAlg").second
447 subject->setEncryptedID(encrypted.release());
450 subject->setNameID(ctx.getNameID()->cloneNameID());
453 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
454 query->setSubject(subject.release());
455 Issuer* iss = IssuerBuilder::buildIssuer();
456 iss->setName(relyingParty->getXMLString("entityID").second);
457 query->setIssuer(iss);
458 for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
459 query->getAttributes().push_back((*ad)->cloneAttribute());
461 SAML2SOAPClient client(soaper, false);
462 client.sendSAML(query, application.getId(), mcc, loc.get());
463 srt = client.receiveSAML();
465 catch (exception& ex) {
466 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
472 m_log.error("unable to obtain a SAML response from attribute authority");
475 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
478 m_log.error("message was not a samlp:Response");
481 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
482 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
484 m_log.error("attribute authority returned a SAML error");
488 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
489 if (assertions.empty()) {
491 m_log.warn("response from attribute authority was empty");
494 else if (assertions.size()>1)
495 m_log.warn("simple resolver only supports one assertion in the query response");
497 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
498 saml2::Assertion* newtoken = assertions.front();
500 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
501 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
506 // We're going to insist that the assertion issuer is the same as the peer.
507 // Reset the policy's message bits and extract them from the assertion.
509 policy.setMessageID(newtoken->getID());
510 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
511 policy.setIssuer(newtoken->getIssuer());
512 policy.evaluate(*newtoken);
514 // Now we can check the security status of the policy.
515 if (!policy.isAuthenticated())
516 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
518 catch (exception& ex) {
519 m_log.error("assertion failed policy validation: %s", ex.what());
525 ctx.getResolvedAssertions().push_back(newtoken);
527 // Finally, extract and filter the result.
529 AttributeExtractor* extractor = application.getAttributeExtractor();
531 Locker extlocker(extractor);
532 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
535 AttributeFilter* filter = application.getAttributeFilter();
537 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
538 Locker filtlocker(filter);
539 filter->filterAttributes(fc, ctx.getResolvedAttributes());
542 catch (exception& ex) {
543 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
544 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
545 ctx.getResolvedAttributes().clear();
551 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
554 xmltooling::NDC ndc("resolveAttributes");
557 QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
558 if (!qctx.doQuery()) {
559 m_log.debug("found AttributeStatement in input to new session, skipping query");
563 if (qctx.getNameID() && qctx.getEntityDescriptor()) {
564 if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
565 m_log.debug("attempting SAML 2.0 attribute query");
568 else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
569 XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
570 m_log.debug("attempting SAML 1.x attribute query");
574 m_log.warn("SSO protocol does not allow for attribute query");
577 m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");