First set of logout base classes and non-building draft of SP-initiated logout.
[shibboleth/cpp-sp.git] / shibsp / attribute / resolver / impl / QueryAttributeResolver.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * QueryAttributeResolver.cpp
19  * 
20  * AttributeResolver based on SAML queries.
21  */
22
23 #include "internal.h"
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"
35
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>
51
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;
61 using namespace std;
62
63 namespace shibsp {
64
65     class SHIBSP_DLLLOCAL QueryContext : public ResolutionContext
66     {
67     public:
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());
73         }
74         
75         QueryContext(
76             const Application& application,
77             const EntityDescriptor* issuer,
78             const XMLCh* protocol,
79             const NameID* nameid,
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) {
86
87             if (tokens) {
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()) {
91                         m_query = false;
92                     }
93                     else {
94                         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(*t);
95                         if (token1 && !token1->getAttributeStatements().empty()) {
96                             m_query = false;
97                         }
98                     }
99                 }
100             }
101         }
102         
103         ~QueryContext() {
104             if (m_session) {
105                 XMLString::release((XMLCh**)&m_protocol);
106                 XMLString::release((XMLCh**)&m_class);
107                 XMLString::release((XMLCh**)&m_decl);
108             }
109             if (m_metadata)
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>());
113         }
114     
115         bool doQuery() const {
116             return m_query;
117         }
118
119         const Application& getApplication() const {
120             return m_app;
121         }
122         const EntityDescriptor* getEntityDescriptor() const {
123             if (m_entity)
124                 return m_entity;
125             if (m_session && m_session->getEntityID()) {
126                 m_metadata = m_app.getMetadataProvider();
127                 if (m_metadata) {
128                     m_metadata->lock();
129                     return m_entity = m_metadata->getEntityDescriptor(m_session->getEntityID());
130                 }
131             }
132             return NULL;
133         }
134         const XMLCh* getProtocol() const {
135             return m_protocol;
136         }
137         const NameID* getNameID() const {
138             return m_session ? m_session->getNameID() : m_nameid;
139         }
140         const XMLCh* getClassRef() const {
141             return m_class;
142         }
143         const XMLCh* getDeclRef() const {
144             return m_decl;
145         }
146         const Session* getSession() const {
147             return m_session;
148         }
149         multimap<string,shibsp::Attribute*>& getResolvedAttributes() {
150             return m_attributes;
151         }
152         vector<opensaml::Assertion*>& getResolvedAssertions() {
153             return m_assertions;
154         }
155
156     private:
157         bool m_query;
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;
165         const XMLCh* m_decl;
166         multimap<string,shibsp::Attribute*> m_attributes;
167         vector<opensaml::Assertion*> m_assertions;
168     };
169     
170     class SHIBSP_DLLLOCAL QueryResolver : public AttributeResolver
171     {
172     public:
173         QueryResolver(const DOMElement* e);
174         ~QueryResolver() {
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>());
177         }
178
179         Lockable* lock() {return this;}
180         void unlock() {}
181         
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
191             ) const {
192             return new QueryContext(application,issuer,protocol,nameid,authncontext_class,authncontext_decl,tokens,attributes);
193         }
194
195         ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
196             return new QueryContext(application,session);
197         }
198
199         void resolveAttributes(ResolutionContext& ctx) const;
200
201         void getAttributeIds(vector<string>& attributes) const {
202             // Nothing to do, only the extractor would actually generate them.
203         }
204
205     private:
206         bool SAML1Query(QueryContext& ctx) const;
207         bool SAML2Query(QueryContext& ctx) const;
208
209         Category& m_log;
210         vector<AttributeDesignator*> m_SAML1Designators;
211         vector<saml2::Attribute*> m_SAML2Designators;
212     };
213
214     AttributeResolver* SHIBSP_DLLLOCAL QueryResolverFactory(const DOMElement* const & e)
215     {
216         return new QueryResolver(e);
217     }
218     
219 };
220
221 void SHIBSP_API shibsp::registerAttributeResolvers()
222 {
223     SPConfig::getConfig().AttributeResolverManager.registerFactory(QUERY_ATTRIBUTE_RESOLVER, QueryResolverFactory);
224 }
225
226 QueryResolver::QueryResolver(const DOMElement* e) : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver"))
227 {
228 #ifdef _DEBUG
229     xmltooling::NDC ndc("QueryResolver");
230 #endif
231     
232     DOMElement* child = XMLHelper::getFirstChildElement(e);
233     while (child) {
234         try {
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());
238                 if (down) {
239                     m_SAML2Designators.push_back(down);
240                     obj.release();
241                 }
242             }
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());
246                 if (down) {
247                     m_SAML1Designators.push_back(down);
248                     obj.release();
249                 }
250             }
251         }
252         catch (exception& ex) {
253             m_log.error("exception loading attribute designator: %s", ex.what());
254         }
255         child = XMLHelper::getNextSiblingElement(child);
256     }
257 }
258
259 bool QueryResolver::SAML1Query(QueryContext& ctx) const
260 {
261 #ifdef _DEBUG
262     xmltooling::NDC ndc("query");
263 #endif
264
265     int version = 1;
266     const AttributeAuthorityDescriptor* AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(samlconstants::SAML11_PROTOCOL_ENUM);
267     if (!AA) {
268         AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(samlconstants::SAML10_PROTOCOL_ENUM);
269         version = 0;
270     }
271     if (!AA) {
272         m_log.debug("no SAML 1.x AttributeAuthority role found in metadata");
273         return false;
274     }
275
276     shibsp::SecurityPolicy policy(ctx.getApplication());
277     MetadataCredentialCriteria mcc(*AA);
278     shibsp::SOAPClient soaper(policy);
279     const PropertySet* policySettings =
280         ctx.getApplication().getServiceProvider().getPolicySettings(ctx.getApplication().getString("policyId").second);
281     pair<bool,bool> signedAssertions = policySettings->getBool("signedAssertions");
282
283     auto_ptr_XMLCh binding(samlconstants::SAML1_BINDING_SOAP);
284     saml1p::Response* response=NULL;
285     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
286     for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
287         try {
288             if (!XMLString::equals((*ep)->getBinding(),binding.get()))
289                 continue;
290             auto_ptr_char loc((*ep)->getLocation());
291             auto_ptr_XMLCh issuer(ctx.getApplication().getString("entityID").second);
292             NameIdentifier* nameid = NameIdentifierBuilder::buildNameIdentifier();
293             nameid->setName(ctx.getNameID()->getName());
294             nameid->setFormat(ctx.getNameID()->getFormat());
295             nameid->setNameQualifier(ctx.getNameID()->getNameQualifier());
296             saml1::Subject* subject = saml1::SubjectBuilder::buildSubject();
297             subject->setNameIdentifier(nameid);
298             saml1p::AttributeQuery* query = saml1p::AttributeQueryBuilder::buildAttributeQuery();
299             query->setSubject(subject);
300             query->setResource(issuer.get());
301             for (vector<AttributeDesignator*>::const_iterator ad = m_SAML1Designators.begin(); ad!=m_SAML1Designators.end(); ++ad)
302                 query->getAttributeDesignators().push_back((*ad)->cloneAttributeDesignator());
303             Request* request = RequestBuilder::buildRequest();
304             request->setAttributeQuery(query);
305             request->setMinorVersion(version);
306
307             SAML1SOAPClient client(soaper, false);
308             client.sendSAML(request, mcc, loc.get());
309             response = client.receiveSAML();
310         }
311         catch (exception& ex) {
312             m_log.error("exception making SAML query: %s", ex.what());
313             soaper.reset();
314         }
315     }
316
317     if (!response) {
318         m_log.error("unable to obtain a SAML response from attribute authority");
319         return false;
320     }
321     else if (!response->getStatus() || !response->getStatus()->getStatusCode() || response->getStatus()->getStatusCode()->getValue()==NULL ||\r
322             *(response->getStatus()->getStatusCode()->getValue()) != saml1p::StatusCode::SUCCESS) {\r
323         delete response;\r
324         m_log.error("attribute authority returned a SAML error");\r
325         return true;\r
326     }\r
327
328     const vector<saml1::Assertion*>& assertions = const_cast<const saml1p::Response*>(response)->getAssertions();
329     if (assertions.size()>1)
330         m_log.warn("simple resolver only supports one assertion in the query response");
331
332     auto_ptr<saml1p::Response> wrapper(response);
333     saml1::Assertion* newtoken = assertions.front();
334
335     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
336         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
337         return true;
338     }
339
340     try {
341         policy.evaluate(*newtoken);
342         if (!policy.isSecure())
343             throw SecurityPolicyException("Security of SAML 1.x query result not established.");
344         saml1::AssertionValidator tokval(ctx.getApplication().getAudiences(), time(NULL));
345         tokval.validateAssertion(*newtoken);
346     }
347     catch (exception& ex) {
348         m_log.error("assertion failed policy/validation: %s", ex.what());
349         return true;
350     }
351
352     newtoken->detach();
353     wrapper.release();
354     ctx.getResolvedAssertions().push_back(newtoken);
355
356     // Finally, extract and filter the result.
357     try {
358         AttributeExtractor* extractor = ctx.getApplication().getAttributeExtractor();
359         if (extractor) {
360             Locker extlocker(extractor);
361             extractor->extractAttributes(ctx.getApplication(), AA, *newtoken, ctx.getResolvedAttributes());
362         }
363
364         AttributeFilter* filter = ctx.getApplication().getAttributeFilter();
365         if (filter) {
366             BasicFilteringContext fc(ctx.getApplication(), ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
367             Locker filtlocker(filter);
368             filter->filterAttributes(fc, ctx.getResolvedAttributes());
369         }
370     }
371     catch (exception& ex) {
372         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
373         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), cleanup_pair<string,shibsp::Attribute>());
374         ctx.getResolvedAttributes().clear();
375     }
376
377     return true;
378 }
379
380 bool QueryResolver::SAML2Query(QueryContext& ctx) const
381 {
382 #ifdef _DEBUG
383     xmltooling::NDC ndc("query");
384 #endif
385
386     const AttributeAuthorityDescriptor* AA = ctx.getEntityDescriptor()->getAttributeAuthorityDescriptor(samlconstants::SAML20P_NS);
387     if (!AA) {
388         m_log.debug("no SAML 2 AttributeAuthority role found in metadata");
389         return false;
390     }
391
392     shibsp::SecurityPolicy policy(ctx.getApplication());
393     MetadataCredentialCriteria mcc(*AA);
394     shibsp::SOAPClient soaper(policy);
395     const PropertySet* policySettings =
396         ctx.getApplication().getServiceProvider().getPolicySettings(ctx.getApplication().getString("policyId").second);
397     pair<bool,bool> signedAssertions = policySettings->getBool("signedAssertions");
398
399     auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
400     saml2p::StatusResponseType* srt=NULL;
401     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
402     for (vector<AttributeService*>::const_iterator ep=endpoints.begin(); !srt && ep!=endpoints.end(); ++ep) {
403         try {
404             if (!XMLString::equals((*ep)->getBinding(),binding.get()))
405                 continue;
406             auto_ptr_char loc((*ep)->getLocation());
407             auto_ptr_XMLCh issuer(ctx.getApplication().getString("entityID").second);
408             saml2::Subject* subject = saml2::SubjectBuilder::buildSubject();
409             subject->setNameID(ctx.getNameID()->cloneNameID());
410             saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
411             query->setSubject(subject);
412             Issuer* iss = IssuerBuilder::buildIssuer();
413             iss->setName(issuer.get());
414             query->setIssuer(iss);
415             for (vector<saml2::Attribute*>::const_iterator ad = m_SAML2Designators.begin(); ad!=m_SAML2Designators.end(); ++ad)
416                 query->getAttributes().push_back((*ad)->cloneAttribute());
417
418             SAML2SOAPClient client(soaper, false);
419             client.sendSAML(query, mcc, loc.get());
420             srt = client.receiveSAML();
421         }
422         catch (exception& ex) {
423             m_log.error("exception making SAML query: %s", ex.what());
424             soaper.reset();
425         }
426     }
427
428     if (!srt) {
429         m_log.error("unable to obtain a SAML response from attribute authority");
430         return false;
431     }
432     saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt);
433     if (!response) {
434         delete srt;
435         m_log.error("message was not a samlp:Response");
436         return true;
437     }
438     else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
439             !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
440         delete srt;
441         m_log.error("attribute authority returned a SAML error");
442         return true;
443     }
444
445     const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
446     if (assertions.size()>1)
447         m_log.warn("simple resolver only supports one assertion in the query response");
448
449     auto_ptr<saml2p::Response> wrapper(response);
450     saml2::Assertion* newtoken = assertions.front();
451
452     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
453         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
454         return true;
455     }
456
457     try {
458         policy.evaluate(*newtoken);
459         if (!policy.isSecure())
460             throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
461         saml2::AssertionValidator tokval(ctx.getApplication().getAudiences(), time(NULL));
462         tokval.validateAssertion(*newtoken);
463     }
464     catch (exception& ex) {
465         m_log.error("assertion failed policy/validation: %s", ex.what());
466         return true;
467     }
468
469     newtoken->detach();
470     wrapper.release();
471     ctx.getResolvedAssertions().push_back(newtoken);
472
473     // Finally, extract and filter the result.
474     try {
475         AttributeExtractor* extractor = ctx.getApplication().getAttributeExtractor();
476         if (extractor) {
477             Locker extlocker(extractor);
478             extractor->extractAttributes(ctx.getApplication(), AA, *newtoken, ctx.getResolvedAttributes());
479         }
480
481         AttributeFilter* filter = ctx.getApplication().getAttributeFilter();
482         if (filter) {
483             BasicFilteringContext fc(ctx.getApplication(), ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
484             Locker filtlocker(filter);
485             filter->filterAttributes(fc, ctx.getResolvedAttributes());
486         }
487     }
488     catch (exception& ex) {
489         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
490         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), cleanup_pair<string,shibsp::Attribute>());
491         ctx.getResolvedAttributes().clear();
492     }
493
494     return true;
495 }
496
497 void QueryResolver::resolveAttributes(ResolutionContext& ctx) const
498 {
499 #ifdef _DEBUG
500     xmltooling::NDC ndc("resolveAttributes");
501 #endif
502
503     QueryContext& qctx = dynamic_cast<QueryContext&>(ctx);
504     if (!qctx.doQuery()) {
505         m_log.debug("found AttributeStatement in input to new session, skipping query");
506         return;
507     }
508
509     if (qctx.getNameID() && qctx.getEntityDescriptor()) {
510         m_log.debug("attempting SAML 2.0 attribute query");
511         if (SAML2Query(qctx))
512             return;
513         m_log.debug("attempting SAML 1.x attribute query");
514         SAML1Query(qctx);
515         return;
516     }
517     m_log.warn("can't attempt attribute query, either no NameID or no metadata to use");
518 }