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 <saml/exceptions.h>
37 #include <saml/binding/SecurityPolicy.h>
38 #include <saml/saml1/binding/SAML1SOAPClient.h>
39 #include <saml/saml1/core/Assertions.h>
40 #include <saml/saml1/core/Protocols.h>
41 #include <saml/saml1/profile/AssertionValidator.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 <saml/saml2/profile/AssertionValidator.h>
47 #include <xmltooling/util/NDC.h>
48 #include <xmltooling/util/XMLHelper.h>
49 #include <xercesc/util/XMLUniDefs.hpp>
51 using namespace shibsp;
52 using namespace opensaml::saml1;
53 using namespace opensaml::saml1p;
54 using namespace opensaml::saml2;
55 using namespace opensaml::saml2p;
56 using namespace opensaml::saml2md;
57 using namespace opensaml;
58 using namespace xmltooling;
63 class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
66 QueryContext(const Application& application, const Session& session)
67 : m_query(true), m_app(application), m_session(&session), m_metadata(NULL), m_entity(NULL), m_nameid(NULL) {
68 m_protocol = XMLString::transcode(session.getProtocol());
69 m_class = XMLString::transcode(session.getAuthnContextClassRef());
70 m_decl = XMLString::transcode(session.getAuthnContextDeclRef());
74 const Application& application,
75 const EntityDescriptor* issuer,
76 const XMLCh* protocol,
78 const XMLCh* authncontext_class=NULL,
79 const XMLCh* authncontext_decl=NULL,
80 const vector<const opensaml::Assertion*>* tokens=NULL,
81 const vector<Attribute*>* attributes=NULL
82 ) : m_query(true), m_app(application), m_session(NULL), m_metadata(NULL), m_entity(issuer),
83 m_protocol(protocol), m_nameid(nameid), m_class(authncontext_class), m_decl(authncontext_decl) {
86 for (vector<const opensaml::Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
87 const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(*t);
88 if (token2 && !token2->getAttributeStatements().empty()) {
92 const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
93 if (token1 && !token1->getAttributeStatements().empty()) {
103 XMLString::release((XMLCh**)&m_protocol);
104 XMLString::release((XMLCh**)&m_class);
105 XMLString::release((XMLCh**)&m_decl);
108 m_metadata->unlock();
109 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
110 for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
113 bool doQuery() const {
117 const Application& getApplication() const {
120 const EntityDescriptor* getEntityDescriptor() const {
123 if (m_session && m_session->getEntityID()) {
124 m_metadata = m_app.getMetadataProvider(false);
127 return m_entity = m_metadata->getEntityDescriptor(MetadataProvider::Criteria(m_session->getEntityID())).first;
132 const XMLCh* getProtocol() const {
135 const NameID* getNameID() const {
136 return m_session ? m_session->getNameID() : m_nameid;
138 const XMLCh* getClassRef() const {
141 const XMLCh* getDeclRef() const {
144 const Session* getSession() const {
147 vector<shibsp::Attribute*>& getResolvedAttributes() {
150 vector<opensaml::Assertion*>& getResolvedAssertions() {
156 const Application& m_app;
157 const Session* m_session;
158 mutable MetadataProvider* m_metadata;
159 mutable const EntityDescriptor* m_entity;
160 const XMLCh* m_protocol;
161 const NameID* m_nameid;
162 const XMLCh* m_class;
164 vector<shibsp::Attribute*> m_attributes;
165 vector<opensaml::Assertion*> m_assertions;
168 class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
171 QueryResolver(const DOMElement* e);
173 for_each(m_SAML1Designators.begin(), m_SAML1Designators.end(), xmltooling::cleanup<AttributeDesignator>());
174 for_each(m_SAML2Designators.begin(), m_SAML2Designators.end(), xmltooling::cleanup<saml2::Attribute>());
177 Lockable* lock() {return this;}
180 ResolutionContext* createResolutionContext(
181 const Application& application,
182 const EntityDescriptor* issuer,
183 const XMLCh* protocol,
184 const NameID* nameid,
185 const XMLCh* authncontext_class=NULL,
186 const XMLCh* authncontext_decl=NULL,
187 const vector<const opensaml::Assertion*>* tokens=NULL,
188 const vector<shibsp::Attribute*>* attributes=NULL
190 return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens,attributes);
193 ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
194 return new QueryContext(application,session);
197 void resolveAttributes(ResolutionContext& ctx) const;
199 void getAttributeIds(vector<string>& attributes) const {
200 // Nothing to do, only the extractor would actually generate them.
204 bool SAML1Query(QueryContext& ctx) const;
205 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);
219 QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver"))
222 xmltooling::NDC ndc("QueryResolver");
225 DOMElement* child = XMLHelper::getFirstChildElement(e);
228 if (XMLHelper::isNodeNamed(e, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
229 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
230 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
232 m_SAML2Designators.push_back(down);
236 else if (XMLHelper::isNodeNamed(e, samlconstants::SAML1P_NS, AttributeDesignator::LOCAL_NAME)) {
237 auto_ptr<XMLObject> obj(AttributeDesignatorBuilder::buildOneFromElement(child));
238 AttributeDesignator* down = dynamic_cast<AttributeDesignator*>(obj.get());
240 m_SAML1Designators.push_back(down);
245 catch (exception& ex) {
246 m_log.error("exception loading attribute designator: %s", ex.what());
248 child = XMLHelper::getNextSiblingElement(child);
252 bool QueryResolver::SAML1Query(QueryContext& ctx) const
255 xmltooling::NDC ndc("query");
258 int version = XMLString::equals(ctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ? 1 : 0;
259 const AttributeAuthorityDescriptor* AA =
260 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(ctx.getProtocol()));
262 m_log.warn("no SAML 1.%d AttributeAuthority role found in metadata", version);
266 const Application& application = ctx.getApplication();
267 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
268 shibsp::SecurityPolicy policy(application);
269 MetadataCredentialCriteria mcc(*AA);
270 shibsp::SOAPClient soaper(policy);
272 auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
273 saml1p::Response* response=NULL;
274 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
275 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
277 if (!XMLString::equals((*ep)->getBinding(),binding.get()))
279 auto_ptr_char loc((*ep)->getLocation());
280 NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
281 nameid->setName(ctx.getNameID()->getName());
282 nameid->setFormat(ctx.getNameID()->getFormat());
283 nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
284 saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
285 subject->setNameIdentifier(nameid);
286 saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
287 query->setSubject(subject);
288 query->setResource(relyingParty->getXMLString("entityID").second);
289 for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
290 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
291 Request* request = RequestBuilder::buildRequest();
292 request->setAttributeQuery(query);
293 request->setMinorVersion(version);
295 SAML1SOAPClient client(soaper, false);
296 client.sendSAML(request, application.getId(), mcc, loc.get());
297 response = client.receiveSAML();
299 catch (exception& ex) {
300 m_log.error("exception making SAML query: %s", ex.what());
306 m_log.error("unable to obtain a SAML response from attribute authority");
309 else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==NULL ||
310 *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {
312 m_log.error("attribute authority returned a SAML error");
316 const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
317 if (assertions.empty()) {
319 m_log.warn("response from attribute authority was empty");
322 else if (assertions.size()>1)
323 m_log.warn("simple resolver only supports one assertion in the query response");
325 auto_ptr<saml1p::Response> wrapper(response);
326 saml1::Assertion* newtoken = assertions.front();
328 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
329 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
330 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
335 // We're going to insist that the assertion issuer is the same as the peer.
336 // Reset the policy's message bits and extract them from the assertion.
338 policy.setMessageID(newtoken->getAssertionID());
339 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
340 policy.setIssuer(newtoken->getIssuer());
341 policy.evaluate(*newtoken);
343 // Now we can check the security status of the policy.
344 if (!policy.isAuthenticated())
345 throw SecurityPolicyException("Security of SAML 1.x query result not established.");
347 // Lastly, check it over.
348 saml1::AssertionValidator tokval(relyingParty->getXMLString("entityID").second, application.getAudiences(), time(NULL));
349 tokval.validateAssertion(*newtoken);
351 catch (exception& ex) {
352 m_log.error("assertion failed policy/validation: %s", ex.what());
358 ctx.getResolvedAssertions().push_back(newtoken);
360 // Finally, extract and filter the result.
362 AttributeExtractor* extractor = application.getAttributeExtractor();
364 Locker extlocker(extractor);
365 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
368 AttributeFilter* filter = application.getAttributeFilter();
370 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
371 Locker filtlocker(filter);
372 filter->filterAttributes(fc, ctx.getResolvedAttributes());
375 catch (exception& ex) {
376 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
377 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
378 ctx.getResolvedAttributes().clear();
384 bool QueryResolver::SAML2Query(QueryContext& ctx) const
387 xmltooling::NDC ndc("query");
390 const AttributeAuthorityDescriptor* AA =
391 find_if(ctx.getEntityDescriptor()->getAttributeAuthorityDescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
393 m_log.warn("no SAML 2 AttributeAuthority role found in metadata");
397 const Application& application = ctx.getApplication();
398 shibsp::SecurityPolicy policy(application);
399 MetadataCredentialCriteria mcc(*AA);
400 shibsp::SOAPClient soaper(policy);
402 const PropertySet* relyingParty = application.getRelyingParty(ctx.getEntityDescriptor());
403 pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
404 pair<bool,const char*> encryption = relyingParty->getString("encryption");
406 auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
407 saml2p::StatusResponseType* srt=NULL;
408 const vector<AttributeService*>& endpoints=AA->getAttributeServices();
409 for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
411 if (!XMLString::equals((*ep)->getBinding(),binding.get()))
413 auto_ptr_char loc((*ep)->getLocation());
414 auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
416 // Encrypt the NameID?
417 if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
418 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
419 MetadataCredentialCriteria mcc(*AA);
422 *(application.getMetadataProvider()),
425 relyingParty->getXMLString("encryptionAlg").second
427 subject->setEncryptedID(encrypted.release());
430 subject->setNameID(ctx.getNameID()->cloneNameID());
433 saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
434 query->setSubject(subject.release());
435 Issuer* iss = IssuerBuilder::buildIssuer();
436 iss->setName(relyingParty->getXMLString("entityID").second);
437 query->setIssuer(iss);
438 for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
439 query->getAttributes().push_back((*ad)->cloneAttribute());
441 SAML2SOAPClient client(soaper, false);
442 client.sendSAML(query, application.getId(), mcc, loc.get());
443 srt = client.receiveSAML();
445 catch (exception& ex) {
446 m_log.error("exception making SAML query: %s", ex.what());
452 m_log.error("unable to obtain a SAML response from attribute authority");
455 saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
458 m_log.error("message was not a samlp:Response");
461 else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
462 !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
464 m_log.error("attribute authority returned a SAML error");
468 const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
469 if (assertions.empty()) {
471 m_log.warn("response from attribute authority was empty");
474 else if (assertions.size()>1)
475 m_log.warn("simple resolver only supports one assertion in the query response");
477 auto_ptr<saml2p::StatusResponseType> wrapper(srt);
478 saml2::Assertion* newtoken = assertions.front();
480 if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
481 m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
486 // We're going to insist that the assertion issuer is the same as the peer.
487 // Reset the policy's message bits and extract them from the assertion.
489 policy.setMessageID(newtoken->getID());
490 policy.setIssueInstant(newtoken->getIssueInstantEpoch());
491 policy.setIssuer(newtoken->getIssuer());
492 policy.evaluate(*newtoken);
494 // Now we can check the security status of the policy.
495 if (!policy.isAuthenticated())
496 throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
498 // Lastly, check it over.
499 saml2::AssertionValidator tokval(relyingParty->getXMLString("entityID").second, application.getAudiences(), time(NULL));
500 tokval.validateAssertion(*newtoken);
502 catch (exception& ex) {
503 m_log.error("assertion failed policy/validation: %s", ex.what());
509 ctx.getResolvedAssertions().push_back(newtoken);
511 // Finally, extract and filter the result.
513 AttributeExtractor* extractor = application.getAttributeExtractor();
515 Locker extlocker(extractor);
516 extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
519 AttributeFilter* filter = application.getAttributeFilter();
521 BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
522 Locker filtlocker(filter);
523 filter->filterAttributes(fc, ctx.getResolvedAttributes());
526 catch (exception& ex) {
527 m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
528 for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
529 ctx.getResolvedAttributes().clear();
535 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
538 xmltooling::NDC ndc("resolveAttributes");
541 QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
542 if (!qctx.doQuery()) {
543 m_log.debug("found AttributeStatement in input to new session, skipping query");
547 if (qctx.getNameID() && qctx.getEntityDescriptor()) {
548 if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML20P_NS)) {
549 m_log.debug("attempting SAML 2.0 attribute query");
552 else if (XMLString::equals(qctx.getProtocol(), samlconstants::SAML11_PROTOCOL_ENUM) ||
553 XMLString::equals(qctx.getProtocol(), samlconstants::SAML10_PROTOCOL_ENUM)) {
554 m_log.debug("attempting SAML 1.x attribute query");
558 m_log.warn("SSO protocol does not allow for attribute query");
561 m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");