Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-sp.git] / shibsp / attribute / filtering / impl / XMLAttributeFilter.cpp
1 /*
2  *  Copyright 2001-2009 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  * XMLAttributeFilter.cpp
19  *
20  * AttributeFilter based on an XML policy language.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "attribute/Attribute.h"
28 #include "attribute/filtering/AttributeFilter.h"
29 #include "attribute/filtering/FilteringContext.h"
30 #include "attribute/filtering/FilterPolicyContext.h"
31 #include "attribute/filtering/MatchFunctor.h"
32 #include "util/SPConstants.h"
33
34 #include <xmltooling/util/NDC.h>
35 #include <xmltooling/util/ReloadableXMLFile.h>
36 #include <xmltooling/util/XMLHelper.h>
37 #include <xercesc/util/XMLUniDefs.hpp>
38
39 using shibspconstants::SHIB2ATTRIBUTEFILTER_NS;
40 using namespace shibsp;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
43 using namespace xmltooling;
44 using namespace std;
45
46 namespace shibsp {
47
48 #if defined (_MSC_VER)
49     #pragma warning( push )
50     #pragma warning( disable : 4250 )
51 #endif
52
53     // Each Policy has a functor for determining applicability and a map of
54     // attribute IDs to Accept/Deny functor pairs (which can include NULLs).
55     struct SHIBSP_DLLLOCAL Policy
56     {
57         Policy() : m_applies(NULL) {}
58         const MatchFunctor* m_applies;
59         typedef multimap< string,pair<const MatchFunctor*,const MatchFunctor*> > rules_t;
60         rules_t m_rules;
61     };
62
63     class SHIBSP_DLLLOCAL XMLFilterImpl
64     {
65     public:
66         XMLFilterImpl(const DOMElement* e, Category& log);
67         ~XMLFilterImpl() {
68             if (m_document)
69                 m_document->release();
70             for_each(m_policyReqRules.begin(), m_policyReqRules.end(), cleanup_pair<string,MatchFunctor>());
71             for_each(m_permitValRules.begin(), m_permitValRules.end(), cleanup_pair<string,MatchFunctor>());
72             for_each(m_denyValRules.begin(), m_denyValRules.end(), cleanup_pair<string,MatchFunctor>());
73         }
74
75         void setDocument(DOMDocument* doc) {
76             m_document = doc;
77         }
78
79         void filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const;
80
81     private:
82         MatchFunctor* buildFunctor(
83             const DOMElement* e, const FilterPolicyContext& functorMap, const char* logname, bool standalone
84             );
85         pair< string,pair<const MatchFunctor*,const MatchFunctor*> > buildAttributeRule(
86             const DOMElement* e, const FilterPolicyContext& permMap, const FilterPolicyContext& denyMap, bool standalone
87             );
88
89         Category& m_log;
90         DOMDocument* m_document;
91         vector<Policy> m_policies;
92         map< string,pair<string,pair<const MatchFunctor*,const MatchFunctor*> > > m_attrRules;
93         multimap<string,MatchFunctor*> m_policyReqRules;
94         multimap<string,MatchFunctor*> m_permitValRules;
95         multimap<string,MatchFunctor*> m_denyValRules;
96     };
97
98     class SHIBSP_DLLLOCAL XMLFilter : public AttributeFilter, public ReloadableXMLFile
99     {
100     public:
101         XMLFilter(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeFilter")), m_impl(NULL) {
102             load();
103         }
104         ~XMLFilter() {
105             delete m_impl;
106         }
107
108         void filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const {
109             m_impl->filterAttributes(context, attributes);
110         }
111
112     protected:
113         pair<bool,DOMElement*> load();
114
115     private:
116         XMLFilterImpl* m_impl;
117     };
118
119 #if defined (_MSC_VER)
120     #pragma warning( pop )
121 #endif
122
123     AttributeFilter* SHIBSP_DLLLOCAL XMLAttributeFilterFactory(const DOMElement* const & e)
124     {
125         return new XMLFilter(e);
126     }
127
128     static const XMLCh AttributeFilterPolicyGroup[] =   UNICODE_LITERAL_26(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r,P,o,l,i,c,y,G,r,o,u,p);
129     static const XMLCh AttributeFilterPolicy[] =        UNICODE_LITERAL_21(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r,P,o,l,i,c,y);
130     static const XMLCh AttributeRule[] =                UNICODE_LITERAL_13(A,t,t,r,i,b,u,t,e,R,u,l,e);
131     static const XMLCh AttributeRuleReference[] =       UNICODE_LITERAL_22(A,t,t,r,i,b,u,t,e,R,u,l,e,R,e,f,e,r,e,n,c,e);
132     static const XMLCh DenyValueRule[] =                UNICODE_LITERAL_13(D,e,n,y,V,a,l,u,e,R,u,l,e);
133     static const XMLCh DenyValueRuleReference[] =       UNICODE_LITERAL_22(D,e,n,y,V,a,l,u,e,R,u,l,e,R,e,f,e,r,e,n,c,e);
134     static const XMLCh PermitValueRule[] =              UNICODE_LITERAL_15(P,e,r,m,i,t,V,a,l,u,e,R,u,l,e);
135     static const XMLCh PermitValueRuleReference[] =     UNICODE_LITERAL_24(P,e,r,m,i,t,V,a,l,u,e,R,u,l,e,R,e,f,e,r,e,n,c,e);
136     static const XMLCh PolicyRequirementRule[] =        UNICODE_LITERAL_21(P,o,l,i,c,y,R,e,q,u,i,r,e,m,e,n,t,R,u,l,e);
137     static const XMLCh PolicyRequirementRuleReference[]=UNICODE_LITERAL_30(P,o,l,i,c,y,R,e,q,u,i,r,e,m,e,n,t,R,u,l,e,R,e,f,e,r,e,n,c,e);
138     static const XMLCh attributeID[] =                  UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,D);
139     static const XMLCh _id[] =                          UNICODE_LITERAL_2(i,d);
140     static const XMLCh _ref[] =                         UNICODE_LITERAL_3(r,e,f);
141 };
142
143 XMLFilterImpl::XMLFilterImpl(const DOMElement* e, Category& log) : m_log(log), m_document(NULL)
144 {
145 #ifdef _DEBUG
146     xmltooling::NDC ndc("XMLFilterImpl");
147 #endif
148
149     if (!XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, AttributeFilterPolicyGroup))
150         throw ConfigurationException("XML AttributeFilter requires afp:AttributeFilterPolicyGroup at root of configuration.");
151
152     FilterPolicyContext reqFunctors(m_policyReqRules);
153     FilterPolicyContext permFunctors(m_permitValRules);
154     FilterPolicyContext denyFunctors(m_denyValRules);
155
156     DOMElement* child = XMLHelper::getFirstChildElement(e);
157     while (child) {
158         if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRule)) {
159             buildFunctor(child, reqFunctors, "PolicyRequirementRule", true);
160         }
161         else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, PermitValueRule)) {
162             buildFunctor(child, permFunctors, "PermitValueRule", true);
163         }
164         else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, DenyValueRule)) {
165             buildFunctor(child, denyFunctors, "DenyValueRule", true);
166         }
167         else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, AttributeRule)) {
168             buildAttributeRule(child, permFunctors, denyFunctors, true);
169         }
170         else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, AttributeFilterPolicy)) {
171             e = XMLHelper::getFirstChildElement(child);
172             MatchFunctor* func = NULL;
173             if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRule)) {
174                 func = buildFunctor(e, reqFunctors, "PolicyRequirementRule", false);
175             }
176             else if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRuleReference)) {
177                 auto_ptr_char ref(e->getAttributeNS(NULL, _ref));
178                 if (ref.get() && *ref.get()) {
179                     multimap<string,MatchFunctor*>::const_iterator prr = m_policyReqRules.find(ref.get());
180                     func = (prr!=m_policyReqRules.end()) ? prr->second : NULL;
181                 }
182             }
183             if (func) {
184                 m_policies.push_back(Policy());
185                 m_policies.back().m_applies = func;
186                 e = XMLHelper::getNextSiblingElement(e);
187                 while (e) {
188                     if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, AttributeRule)) {
189                         pair< string,pair<const MatchFunctor*,const MatchFunctor*> > rule = buildAttributeRule(e, permFunctors, denyFunctors, false);
190                         if (rule.second.first || rule.second.second)
191                             m_policies.back().m_rules.insert(Policy::rules_t::value_type(rule.first, rule.second));
192                     }
193                     else if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, AttributeRuleReference)) {
194                         auto_ptr_char ref(e->getAttributeNS(NULL, _ref));
195                         if (ref.get() && *ref.get()) {
196                             map< string,pair< string,pair< const MatchFunctor*,const MatchFunctor*> > >::const_iterator ar = m_attrRules.find(ref.get());
197                             if (ar != m_attrRules.end())
198                                 m_policies.back().m_rules.insert(Policy::rules_t::value_type(ar->second.first, ar->second.second));
199                             else
200                                 m_log.warn("skipping invalid AttributeRuleReference (%s)", ref.get());
201                         }
202                     }
203                     e = XMLHelper::getNextSiblingElement(e);
204                 }
205             }
206             else {
207                 m_log.warn("skipping AttributeFilterPolicy, PolicyRequirementRule invalid or missing");
208             }
209         }
210         child = XMLHelper::getNextSiblingElement(child);
211     }
212 }
213
214 MatchFunctor* XMLFilterImpl::buildFunctor(
215     const DOMElement* e, const FilterPolicyContext& functorMap, const char* logname, bool standalone
216     )
217 {
218     auto_ptr_char temp(e->getAttributeNS(NULL,_id));
219     const char* id = (temp.get() && *temp.get()) ? temp.get() : "";
220
221     if (standalone && !*id) {
222         m_log.warn("skipping stand-alone %s with no id", logname);
223         return NULL;
224     }
225     else if (*id && functorMap.getMatchFunctors().count(id)) {
226         if (standalone) {
227             m_log.warn("skipping duplicate stand-alone %s with id (%s)", logname, id);
228             return NULL;
229         }
230         else
231             id = "";
232     }
233
234     auto_ptr<xmltooling::QName> type(XMLHelper::getXSIType(e));
235     if (type.get()) {
236         try {
237             MatchFunctor* func = SPConfig::getConfig().MatchFunctorManager.newPlugin(*type.get(), make_pair(&functorMap,e));
238             functorMap.getMatchFunctors().insert(multimap<string,MatchFunctor*>::value_type(id, func));
239             return func;
240         }
241         catch (exception& ex) {
242             m_log.error("error building %s with type (%s): %s", logname, type->toString().c_str(), ex.what());
243         }
244     }
245     else if (standalone)
246         m_log.warn("skipping stand-alone %s with no xsi:type", logname);
247     else
248         m_log.error("%s with no xsi:type", logname);
249
250     return NULL;
251 }
252
253 pair< string,pair<const MatchFunctor*,const MatchFunctor*> > XMLFilterImpl::buildAttributeRule(
254     const DOMElement* e, const FilterPolicyContext& permMap, const FilterPolicyContext& denyMap, bool standalone
255     )
256 {
257     auto_ptr_char temp(e->getAttributeNS(NULL,_id));
258     const char* id = (temp.get() && *temp.get()) ? temp.get() : "";
259
260     if (standalone && !*id) {
261         m_log.warn("skipping stand-alone AttributeRule with no id");
262         return make_pair(string(),pair<const MatchFunctor*,const MatchFunctor*>(NULL,NULL));
263     }
264     else if (*id && m_attrRules.count(id)) {
265         if (standalone) {
266             m_log.warn("skipping duplicate stand-alone AttributeRule with id (%s)", id);
267             return make_pair(string(),pair<const MatchFunctor*,const MatchFunctor*>(NULL,NULL));
268         }
269         else
270             id = "";
271     }
272
273     auto_ptr_char attrID(e->getAttributeNS(NULL,attributeID));
274     if (!attrID.get() || !*attrID.get())
275         m_log.warn("skipping AttributeRule with no attributeID");
276
277     MatchFunctor* perm=NULL;
278     MatchFunctor* deny=NULL;
279
280     e = XMLHelper::getFirstChildElement(e);
281     if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, PermitValueRule)) {
282         perm = buildFunctor(e, permMap, "PermitValueRule", false);
283         e = XMLHelper::getNextSiblingElement(e);
284     }
285     else if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, PermitValueRuleReference)) {
286         auto_ptr_char ref(e->getAttributeNS(NULL, _ref));
287         if (ref.get() && *ref.get()) {
288             multimap<string,MatchFunctor*>::const_iterator pvr = m_permitValRules.find(ref.get());
289             perm = (pvr!=m_permitValRules.end()) ? pvr->second : NULL;
290         }
291         e = XMLHelper::getNextSiblingElement(e);
292     }
293
294     if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, DenyValueRule)) {
295         deny = buildFunctor(e, denyMap, "DenyValueRule", false);
296     }
297     else if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, DenyValueRuleReference)) {
298         auto_ptr_char ref(e->getAttributeNS(NULL, _ref));
299         if (ref.get() && *ref.get()) {
300             multimap<string,MatchFunctor*>::const_iterator pvr = m_denyValRules.find(ref.get());
301             deny = (pvr!=m_denyValRules.end()) ? pvr->second : NULL;
302         }
303     }
304
305     if (perm || deny) {
306         if (*id) {
307             m_attrRules[id] = pair< string,pair<const MatchFunctor*,const MatchFunctor*> >(attrID.get(), pair<const MatchFunctor*,const MatchFunctor*>(perm,deny));
308             return m_attrRules[id];
309         }
310         else {
311             return pair< string,pair<const MatchFunctor*,const MatchFunctor*> >(attrID.get(), pair<const MatchFunctor*,const MatchFunctor*>(perm,deny));
312         }
313     }
314
315     m_log.warn("skipping AttributeRule (%s), permit and denial rule(s) invalid or missing", id);
316     return pair< string,pair<const MatchFunctor*,const MatchFunctor*> >(string(),pair<const MatchFunctor*,const MatchFunctor*>(NULL,NULL));
317 }
318
319 void XMLFilterImpl::filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const
320 {
321     auto_ptr_char issuer(context.getAttributeIssuer());
322
323     m_log.debug("filtering %lu attribute(s) from (%s)", attributes.size(), issuer.get() ? issuer.get() : "unknown source");
324
325     if (m_policies.empty()) {
326         m_log.warn("no filter policies were loaded, filtering out all attributes from (%s)", issuer.get() ? issuer.get() : "unknown source");
327         for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
328         attributes.clear();
329         return;
330     }
331
332     // We have to evaluate every policy that applies against each attribute before deciding what to keep.
333
334     // For efficiency, we build an array of the policies that apply in advance.
335     vector<const Policy*> applicablePolicies;
336     for (vector<Policy>::const_iterator p=m_policies.begin(); p!=m_policies.end(); ++p) {
337         if (p->m_applies->evaluatePolicyRequirement(context))
338             applicablePolicies.push_back(&(*p));
339     }
340
341     // For further efficiency, we declare arrays to store the applicable rules for an Attribute.
342     vector< pair<const MatchFunctor*,const MatchFunctor*> > applicableRules;
343     vector< pair<const MatchFunctor*,const MatchFunctor*> > wildcardRules;
344
345     // Store off the wildcards ahead of time.
346     for (vector<const Policy*>::const_iterator pol=applicablePolicies.begin(); pol!=applicablePolicies.end(); ++pol) {
347         pair<Policy::rules_t::const_iterator,Policy::rules_t::const_iterator> rules = (*pol)->m_rules.equal_range("*");
348         for (; rules.first!=rules.second; ++rules.first)
349             wildcardRules.push_back(rules.first->second);
350     }
351
352     // To track what to keep without removing anything from the original set until the end, we maintain
353     // a map of each Attribute object to a boolean array with true flags indicating what to delete.
354     // A single dimension array tracks attributes being removed entirely.
355     vector<bool> deletedAttributes(attributes.size(), false);
356     map< Attribute*, vector<bool> > deletedPositions;
357
358     // Loop over each attribute to filter them.
359     for (vector<Attribute*>::size_type a=0; a<attributes.size(); ++a) {
360         Attribute* attr = attributes[a];
361
362         // Clear the rule store.
363         applicableRules.clear();
364
365         // Look for rules to run in each policy.
366         for (vector<const Policy*>::const_iterator pol=applicablePolicies.begin(); pol!=applicablePolicies.end(); ++pol) {
367             pair<Policy::rules_t::const_iterator,Policy::rules_t::const_iterator> rules = (*pol)->m_rules.equal_range(attr->getId());
368             for (; rules.first!=rules.second; ++rules.first)
369                 applicableRules.push_back(rules.first->second);
370         }
371
372         // If no rules found, apply wildcards.
373         const vector< pair<const MatchFunctor*,const MatchFunctor*> >& rulesToRun = applicableRules.empty() ? wildcardRules : applicableRules;
374
375         // If no rules apply, remove the attribute entirely.
376         if (rulesToRun.empty()) {
377             m_log.warn(
378                 "no rule found, removing attribute (%s) from (%s)",
379                 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
380                 );
381             deletedAttributes[a] = true;
382             continue;
383         }
384
385         // Run each permit/deny rule.
386         m_log.debug(
387             "applying filtering rule(s) for attribute (%s) from (%s)",
388             attr->getId(), issuer.get() ? issuer.get() : "unknown source"
389             );
390
391         bool kickit;
392
393         // Examine each value.
394         for (size_t count = attr->valueCount(), index = 0; index < count; ++index) {
395
396             // Assume we're kicking it out.
397             kickit=true;
398
399             for (vector< pair<const MatchFunctor*,const MatchFunctor*> >::const_iterator r=rulesToRun.begin(); r!=rulesToRun.end(); ++r) {
400                 // If there's a permit rule that passes, don't kick it.
401                 if (r->first && r->first->evaluatePermitValue(context, *attr, index))
402                     kickit = false;
403                 if (!kickit && r->second && r->second->evaluatePermitValue(context, *attr, index))
404                     kickit = true;
405             }
406
407             // If we're kicking it, record that in the tracker.
408             if (kickit) {
409                 m_log.warn(
410                     "removed value at position (%lu) of attribute (%s) from (%s)",
411                     index, attr->getId(), issuer.get() ? issuer.get() : "unknown source"
412                     );
413                 deletedPositions[attr].resize(index+1);
414                 deletedPositions[attr][index] = true;
415             }
416         }
417     }
418
419     // Final step: go over the deletedPositions matrix and apply the actual changes. In order to delete
420     // any attributes that end up with no values, we have to do it by looping over the originals.
421     for (vector<Attribute*>::size_type a=0; a<attributes.size();) {
422         Attribute* attr = attributes[a];
423
424         if (deletedAttributes[a]) {
425             delete attr;
426             deletedAttributes.erase(deletedAttributes.begin() + a);
427             attributes.erase(attributes.begin() + a);
428             continue;
429         }
430         else if (deletedPositions.count(attr) > 0) {
431             // To do the removal, we loop over the bits backwards so that the
432             // underlying value sequence doesn't get distorted by any removals.
433             // Index has to be offset by one because size_type is unsigned.
434             const vector<bool>& row = deletedPositions[attr];
435             for (vector<bool>::size_type index = row.size(); index > 0; --index) {
436                 if (row[index-1])
437                     attr->removeValue(index-1);
438             }
439         }
440
441         // Check for no values.
442         if (attr->valueCount() == 0) {
443             m_log.warn(
444                 "no values left, removing attribute (%s) from (%s)",
445                 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
446                 );
447             delete attr;
448             attributes.erase(attributes.begin() + a);
449             continue;
450         }
451
452         ++a;
453     }
454 }
455
456 pair<bool,DOMElement*> XMLFilter::load()
457 {
458     // Load from source using base class.
459     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
460
461     // If we own it, wrap it.
462     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
463
464     XMLFilterImpl* impl = new XMLFilterImpl(raw.second, m_log);
465
466     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
467     impl->setDocument(docjanitor.release());
468
469     delete m_impl;
470     m_impl = impl;
471
472     return make_pair(false,(DOMElement*)NULL);
473 }