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 "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/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;
64 class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
67 QueryContext(const Application& application, const Session& session)
68 : m_query(true), m_app(application), m_session(&session), m_metadata(NULL), m_entity(NULL), m_nameid(NULL) {
69 m_protocol = XMLString::transcode(session.getProtocol());
70 m_class = XMLString::transcode(session.getAuthnContextClassRef());
71 m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
75 const Application& application,
76 const EntityDescriptor* issuer,
77 const XMLCh* protocol,
78 const NameID* nameid=NULL,
79 const XMLCh* authncontext_class=NULL,
80 const XMLCh* authncontext_decl=NULL,
81 const vector<const opensaml::Assertion*>* tokens=NULL,
82 const vector<Attribute*>* attributes=NULL
83 ) : m_query(true), m_app(application), m_session(NULL), m_metadata(NULL), m_entity(issuer),
84 m_protocol(protocol), m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
87 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
88 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
89 if (token2 && !token2->getAttributeStatements().empty()) {
93 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
94 if (token1 && !token1->getAttributeStatements().empty()) {
104 XMLString::release((XMLCh**)&m_protocol);
105 XMLString::release((XMLCh**)&m_class);
106 XMLString::release((XMLCh**)&m_decl);
109 m_metadata->unlock();
110 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
111 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
114 bool doQuery() const {
118 const Application& getApplication() const {
121 const EntityDescriptor* getEntityDescriptor() const {
124 if (m_session && m_session->getEntityID()) {
125 m_metadata = m_app.getMetadataProvider(false);
128 return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
133 const XMLCh* getProtocol() const {
136 const NameID* getNameID() const {
137 return m_session ? m_session->getNameID() : m_nameid;
139 const XMLCh* getClassRef() const {
142 const XMLCh* getDeclRef() const {
145 const Session* getSession() const {
148 vector<shibsp::Attribute*>& getResolvedAttributes() {
151 vector<opensaml::Assertion*>& getResolvedAssertions() {
157 const Application& m_app;
158 const Session* m_session;
159 mutable MetadataProvider* m_metadata;
160 mutable const EntityDescriptor* m_entity;
161 const XMLCh* m_protocol;
162 const NameID* m_nameid;
163 const XMLCh* m_class;
165 vector<shibsp::Attribute*> m_attributes;
166 vector<opensaml::Assertion*> m_assertions;
169 class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
172 QueryResolver(const DOMElement* e);
174 for_each(m_SAML1Designators.begin(), m_SAML1Designators.end(), xmltooling::cleanup<AttributeDesignator>());
175 for_each(m_SAML2Designators.begin(), m_SAML2Designators.end(), xmltooling::cleanup<saml2::Attribute>());
178 Lockable* lock() {return this;}
181 ResolutionContext* createResolutionContext(
182 const Application& application,
183 const EntityDescriptor* issuer,
184 const XMLCh* protocol,
185 const NameID* nameid=NULL,
186 const XMLCh* authncontext_class=NULL,
187 const XMLCh* authncontext_decl=NULL,
188 const vector<const opensaml::Assertion*>* tokens=NULL,
189 const vector<shibsp::Attribute*>* attributes=NULL
191 return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens,attributes);
194 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
195 return new QueryContext(application,session);
198 void resolveAttributes(ResolutionContext& ctx) const;
200 void getAttributeIds(vector<string>& attributes) const {
201 // Nothing to do, only the extractor would actually generate them.
205 bool SAML1Query(QueryContext& ctx) const;
206 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);
219 static const XMLCh _policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
222 QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.Query"))
225 xmltooling::NDC ndc("QueryResolver");
228 const XMLCh* pid = e ? e->getAttributeNS(NULL, _policyId) : NULL;
230 auto_ptr_char temp(pid);
231 m_policyId = temp.get();
234 DOMElement* child = XMLHelper::getFirstChildElement(e);
237 if (XMLHelper::isNodeNamed(e, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
238 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
239 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
241 m_SAML2Designators.push_back(down);
245 else if (XMLHelper::isNodeNamed(e, samlconstants::SAML1P_NS, AttributeDesignator::LOCAL_NAME)) {
246 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
247 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
249 m_SAML1Designators.push_back(down);
254 catch (exception& ex) {
255 m_log.error("exception loading attribute designator: %s", ex.what());
257 child = XMLHelper::getNextSiblingElement(child);
261 bool QueryResolver::SAML1Query(QueryContext& ctx) const
264 xmltooling::NDC ndc("query");
267 int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
268 const AttributeAuthorityDescriptor* AA =
269 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
271 m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
275 const Application& application = ctx.getApplication();
276 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
278 // Locate policy key.
279 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
281 // Access policy properties.
282 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
283 pair<bool,bool> validate = settings->getBool("validate");
285 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
286 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
287 MetadataCredentialCriteria mcc(*AA);
288 shibsp::SOAPClient soaper(policy);
290 auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
291 saml1p::Response* response=NULL;
292 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
293 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
294 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
296 auto_ptr_char loc((*ep)->getLocation());
298 NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
299 nameid->setName(ctx.getNameID()->getName());
300 nameid->setFormat(ctx.getNameID()->getFormat());
301 nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
302 saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
303 subject->setNameIdentifier(nameid);
304 saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
305 query->setSubject(subject);
306 query->setResource(relyingParty->getXMLString("entityID").second);
307 for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
308 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
309 Request* request = RequestBuilder::buildRequest();
310 request->setAttributeQuery(query);
311 request->setMinorVersion(version);
313 SAML1SOAPClient client(soaper, false);
314 client.sendSAML(request, application.getId(), mcc, loc.get());
315 response = client.receiveSAML();
317 catch (exception& ex) {
318 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
324 m_log.error("unable to obtain a SAML response from attribute authority");
327 else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==NULL ||
328 *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
330 m_log.error("attribute authority returned a SAML error");
334 const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
335 if (assertions.empty()) {
337 m_log.warn("response from attribute authority was empty");
340 else if (assertions.size()>1)
341 m_log.warn("simple resolver only supports one assertion in the query response");
343 auto_ptr<saml1p::Response> wrapper(response);
344 saml1::Assertion* newtoken = assertions.front();
346 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
347 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
348 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
353 // We're going to insist that the assertion issuer is the same as the peer.
354 // Reset the policy's message bits and extract them from the assertion.
356 policy.setMessageID(newtoken->getAssertionID());
357 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
358 policy.setIssuer(newtoken->getIssuer());
359 policy.evaluate(*newtoken);
361 // Now we can check the security status of the policy.
362 if (!policy.isAuthenticated())
363 throw SecurityPolicyException("Security of SAML 1.x query result not established.");
365 // Lastly, check it over.
366 saml1::AssertionValidator tokval(relyingParty->getXMLString("entityID").second, application.getAudiences(), time(NULL));
367 tokval.validateAssertion(*newtoken);
369 catch (exception& ex) {
370 m_log.error("assertion failed policy/validation: %s", ex.what());
376 ctx.getResolvedAssertions().push_back(newtoken);
378 // Finally, extract and filter the result.
380 AttributeExtractor* extractor = application.getAttributeExtractor();
382 Locker extlocker(extractor);
383 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
386 AttributeFilter* filter = application.getAttributeFilter();
388 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
389 Locker filtlocker(filter);
390 filter->filterAttributes(fc, ctx.getResolvedAttributes());
393 catch (exception& ex) {
394 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
395 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
396 ctx.getResolvedAttributes().clear();
402 bool QueryResolver::SAML2Query(QueryContext& ctx) const
405 xmltooling::NDC ndc("query");
408 const AttributeAuthorityDescriptor* AA =
409 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
411 m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
415 const Application& application = ctx.getApplication();
416 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
418 // Locate policy key.
419 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
421 // Access policy properties.
422 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
423 pair<bool,bool> validate = settings->getBool("validate");
425 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
426 pair<bool,const char*> encryption = relyingParty->getString("encryption");
428 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
429 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
430 MetadataCredentialCriteria mcc(*AA);
431 shibsp::SOAPClient soaper(policy);
433 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
434 saml2p::StatusResponseType* srt=NULL;
435 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
436 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
437 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
439 auto_ptr_char loc((*ep)->getLocation());
441 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
443 // Encrypt the NameID?
444 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
445 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
446 MetadataCredentialCriteria mcc(*AA);
449 *(application.getMetadataProvider()),
452 relyingParty->getXMLString("encryptionAlg").second
454 subject->setEncryptedID(encrypted.release());
457 subject->setNameID(ctx.getNameID()->cloneNameID());
460 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
461 query->setSubject(subject.release());
462 Issuer* iss = IssuerBuilder::buildIssuer();
463 iss->setName(relyingParty->getXMLString("entityID").second);
464 query->setIssuer(iss);
465 for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
466 query->getAttributes().push_back((*ad)->cloneAttribute());
468 SAML2SOAPClient client(soaper, false);
469 client.sendSAML(query, application.getId(), mcc, loc.get());
470 srt = client.receiveSAML();
472 catch (exception& ex) {
473 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
479 m_log.error("unable to obtain a SAML response from attribute authority");
482 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
485 m_log.error("message was not a samlp:Response");
488 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
489 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
491 m_log.error("attribute authority returned a SAML error");
495 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
496 if (assertions.empty()) {
498 m_log.warn("response from attribute authority was empty");
501 else if (assertions.size()>1)
502 m_log.warn("simple resolver only supports one assertion in the query response");
504 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
505 saml2::Assertion* newtoken = assertions.front();
507 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
508 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
513 // We're going to insist that the assertion issuer is the same as the peer.
514 // Reset the policy's message bits and extract them from the assertion.
516 policy.setMessageID(newtoken->getID());
517 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
518 policy.setIssuer(newtoken->getIssuer());
519 policy.evaluate(*newtoken);
521 // Now we can check the security status of the policy.
522 if (!policy.isAuthenticated())
523 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
525 // Lastly, check it over.
526 saml2::AssertionValidator tokval(relyingParty->getXMLString("entityID").second, application.getAudiences(), time(NULL));
527 tokval.validateAssertion(*newtoken);
529 catch (exception& ex) {
530 m_log.error("assertion failed policy/validation: %s", ex.what());
536 ctx.getResolvedAssertions().push_back(newtoken);
538 // Finally, extract and filter the result.
540 AttributeExtractor* extractor = application.getAttributeExtractor();
542 Locker extlocker(extractor);
543 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
546 AttributeFilter* filter = application.getAttributeFilter();
548 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
549 Locker filtlocker(filter);
550 filter->filterAttributes(fc, ctx.getResolvedAttributes());
553 catch (exception& ex) {
554 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
555 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
556 ctx.getResolvedAttributes().clear();
562 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
565 xmltooling::NDC ndc("resolveAttributes");
568 QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
569 if (!qctx.doQuery()) {
570 m_log.debug("found AttributeStatement in input to new session, skipping query");
574 if (qctx.getNameID() && qctx.getEntityDescriptor()) {
575 if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
576 m_log.debug("attempting SAML 2.0 attribute query");
579 else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
580 XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
581 m_log.debug("attempting SAML 1.x attribute query");
585 m_log.warn("SSO protocol does not allow for attribute query");
588 m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");