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 const vector<Attribute*>* attributes=NULL
81 ) : m_query(true), m_app(application), m_session(NULL), m_metadata(NULL), m_entity(issuer),
82 m_protocol(protocol), m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
85 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
86 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
87 if (token2 && !token2->getAttributeStatements().empty()) {
91 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
92 if (token1 && !token1->getAttributeStatements().empty()) {
102 XMLString::release((XMLCh**)&m_protocol);
103 XMLString::release((XMLCh**)&m_class);
104 XMLString::release((XMLCh**)&m_decl);
107 m_metadata->unlock();
108 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
109 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
112 bool doQuery() const {
116 const Application& getApplication() const {
119 const EntityDescriptor* getEntityDescriptor() const {
122 if (m_session && m_session->getEntityID()) {
123 m_metadata = m_app.getMetadataProvider(false);
126 return m_entity = m_metadata->getEntityDescriptor(MetadataProviderCriteria(m_app, m_session->getEntityID())).first;
131 const XMLCh* getProtocol() const {
134 const NameID* getNameID() const {
135 return m_session ? m_session->getNameID() : m_nameid;
137 const XMLCh* getClassRef() const {
140 const XMLCh* getDeclRef() const {
143 const Session* getSession() const {
146 vector<shibsp::Attribute*>& getResolvedAttributes() {
149 vector<opensaml::Assertion*>& getResolvedAssertions() {
155 const Application& m_app;
156 const Session* m_session;
157 mutable MetadataProvider* m_metadata;
158 mutable const EntityDescriptor* m_entity;
159 const XMLCh* m_protocol;
160 const NameID* m_nameid;
161 const XMLCh* m_class;
163 vector<shibsp::Attribute*> m_attributes;
164 vector<opensaml::Assertion*> m_assertions;
167 class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
170 QueryResolver(const DOMElement* e);
172 for_each(m_SAML1Designators.begin(), m_SAML1Designators.end(), xmltooling::cleanup<AttributeDesignator>());
173 for_each(m_SAML2Designators.begin(), m_SAML2Designators.end(), xmltooling::cleanup<saml2::Attribute>());
176 Lockable* lock() {return this;}
179 ResolutionContext* createResolutionContext(
180 const Application& application,
181 const EntityDescriptor* issuer,
182 const XMLCh* protocol,
183 const NameID* nameid=NULL,
184 const XMLCh* authncontext_class=NULL,
185 const XMLCh* authncontext_decl=NULL,
186 const vector<const opensaml::Assertion*>* tokens=NULL,
187 const vector<shibsp::Attribute*>* attributes=NULL
189 return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens,attributes);
192 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
193 return new QueryContext(application,session);
196 void resolveAttributes(ResolutionContext& ctx) const;
198 void getAttributeIds(vector<string>& attributes) const {
199 // Nothing to do, only the extractor would actually generate them.
203 bool SAML1Query(QueryContext& ctx) const;
204 bool SAML2Query(QueryContext& ctx) const;
208 vector<AttributeDesignator*> m_SAML1Designators;
209 vector<saml2::Attribute*> m_SAML2Designators;
212 AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
214 return new QueryResolver(e);
217 static const XMLCh _policyId[] = UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
220 QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.Query"))
223 xmltooling::NDC ndc("QueryResolver");
226 const XMLCh* pid = e ? e->getAttributeNS(NULL, _policyId) : NULL;
228 auto_ptr_char temp(pid);
229 m_policyId = temp.get();
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 =
267 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
269 m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
273 const Application& application = ctx.getApplication();
274 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
276 // Locate policy key.
277 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
279 // Access policy properties.
280 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
281 pair<bool,bool> validate = settings->getBool("validate");
283 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
284 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
285 MetadataCredentialCriteria mcc(*AA);
286 shibsp::SOAPClient soaper(policy);
288 auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
289 saml1p::Response* response=NULL;
290 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
291 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
292 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
294 auto_ptr_char loc((*ep)->getLocation());
296 NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
297 nameid->setName(ctx.getNameID()->getName());
298 nameid->setFormat(ctx.getNameID()->getFormat());
299 nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
300 saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
301 subject->setNameIdentifier(nameid);
302 saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
303 query->setSubject(subject);
304 query->setResource(relyingParty->getXMLString("entityID").second);
305 for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
306 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
307 Request* request = RequestBuilder::buildRequest();
308 request->setAttributeQuery(query);
309 request->setMinorVersion(version);
311 SAML1SOAPClient client(soaper, false);
312 client.sendSAML(request, application.getId(), mcc, loc.get());
313 response = client.receiveSAML();
315 catch (exception& ex) {
316 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
322 m_log.error("unable to obtain a SAML response from attribute authority");
325 else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==NULL ||
326 *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
328 m_log.error("attribute authority returned a SAML error");
332 const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
333 if (assertions.empty()) {
335 m_log.warn("response from attribute authority was empty");
338 else if (assertions.size()>1)
339 m_log.warn("simple resolver only supports one assertion in the query response");
341 auto_ptr<saml1p::Response> wrapper(response);
342 saml1::Assertion* newtoken = assertions.front();
344 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
345 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
346 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
351 // We're going to insist that the assertion issuer is the same as the peer.
352 // Reset the policy's message bits and extract them from the assertion.
354 policy.setMessageID(newtoken->getAssertionID());
355 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
356 policy.setIssuer(newtoken->getIssuer());
357 policy.evaluate(*newtoken);
359 // Now we can check the security status of the policy.
360 if (!policy.isAuthenticated())
361 throw SecurityPolicyException("Security of SAML 1.x query result not established.");
363 catch (exception& ex) {
364 m_log.error("assertion failed policy validation: %s", ex.what());
370 ctx.getResolvedAssertions().push_back(newtoken);
372 // Finally, extract and filter the result.
374 AttributeExtractor* extractor = application.getAttributeExtractor();
376 Locker extlocker(extractor);
377 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
380 AttributeFilter* filter = application.getAttributeFilter();
382 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
383 Locker filtlocker(filter);
384 filter->filterAttributes(fc, ctx.getResolvedAttributes());
387 catch (exception& ex) {
388 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
389 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
390 ctx.getResolvedAttributes().clear();
396 bool QueryResolver::SAML2Query(QueryContext& ctx) const
399 xmltooling::NDC ndc("query");
402 const AttributeAuthorityDescriptor* AA =
403 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
405 m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
409 const Application& application = ctx.getApplication();
410 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
412 // Locate policy key.
413 const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
415 // Access policy properties.
416 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId);
417 pair<bool,bool> validate = settings->getBool("validate");
419 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
420 pair<bool,const char*> encryption = relyingParty->getString("encryption");
422 shibsp::SecurityPolicy policy(application, NULL, validate.first && validate.second, policyId);
423 policy.getAudiences().push_back(relyingParty->getXMLString("entityID").second);
424 MetadataCredentialCriteria mcc(*AA);
425 shibsp::SOAPClient soaper(policy);
427 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
428 saml2p::StatusResponseType* srt=NULL;
429 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
430 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
431 if (!XMLString::equals((*ep)->getBinding(),binding.get()) || !(*ep)->getLocation())
433 auto_ptr_char loc((*ep)->getLocation());
435 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
437 // Encrypt the NameID?
438 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
439 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
440 MetadataCredentialCriteria mcc(*AA);
443 *(application.getMetadataProvider()),
446 relyingParty->getXMLString("encryptionAlg").second
448 subject->setEncryptedID(encrypted.release());
451 subject->setNameID(ctx.getNameID()->cloneNameID());
454 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
455 query->setSubject(subject.release());
456 Issuer* iss = IssuerBuilder::buildIssuer();
457 iss->setName(relyingParty->getXMLString("entityID").second);
458 query->setIssuer(iss);
459 for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
460 query->getAttributes().push_back((*ad)->cloneAttribute());
462 SAML2SOAPClient client(soaper, false);
463 client.sendSAML(query, application.getId(), mcc, loc.get());
464 srt = client.receiveSAML();
466 catch (exception& ex) {
467 m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
473 m_log.error("unable to obtain a SAML response from attribute authority");
476 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
479 m_log.error("message was not a samlp:Response");
482 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
483 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
485 m_log.error("attribute authority returned a SAML error");
489 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
490 if (assertions.empty()) {
492 m_log.warn("response from attribute authority was empty");
495 else if (assertions.size()>1)
496 m_log.warn("simple resolver only supports one assertion in the query response");
498 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
499 saml2::Assertion* newtoken = assertions.front();
501 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
502 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
507 // We're going to insist that the assertion issuer is the same as the peer.
508 // Reset the policy's message bits and extract them from the assertion.
510 policy.setMessageID(newtoken->getID());
511 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
512 policy.setIssuer(newtoken->getIssuer());
513 policy.evaluate(*newtoken);
515 // Now we can check the security status of the policy.
516 if (!policy.isAuthenticated())
517 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
519 catch (exception& ex) {
520 m_log.error("assertion failed policy validation: %s", ex.what());
526 ctx.getResolvedAssertions().push_back(newtoken);
528 // Finally, extract and filter the result.
530 AttributeExtractor* extractor = application.getAttributeExtractor();
532 Locker extlocker(extractor);
533 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
536 AttributeFilter* filter = application.getAttributeFilter();
538 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
539 Locker filtlocker(filter);
540 filter->filterAttributes(fc, ctx.getResolvedAttributes());
543 catch (exception& ex) {
544 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
545 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
546 ctx.getResolvedAttributes().clear();
552 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
555 xmltooling::NDC ndc("resolveAttributes");
558 QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
559 if (!qctx.doQuery()) {
560 m_log.debug("found AttributeStatement in input to new session, skipping query");
564 if (qctx.getNameID() && qctx.getEntityDescriptor()) {
565 if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
566 m_log.debug("attempting SAML 2.0 attribute query");
569 else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
570 XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
571 m_log.debug("attempting SAML 1.x attribute query");
575 m_log.warn("SSO protocol does not allow for attribute query");
578 m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");