Cleanup log message.
[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     if (*id)
316         m_log.warn("skipping AttributeRule (%s), permit and denial rule(s) invalid or missing", id);
317     else
318         m_log.warn("skipping AttributeRule, permit and denial rule(s) invalid or missing");
319     return pair< string,pair<const MatchFunctor*,const MatchFunctor*> >(string(),pair<const MatchFunctor*,const MatchFunctor*>(NULL,NULL));
320 }
321
322 void XMLFilterImpl::filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const
323 {
324     auto_ptr_char issuer(context.getAttributeIssuer());
325
326     m_log.debug("filtering %lu attribute(s) from (%s)", attributes.size(), issuer.get() ? issuer.get() : "unknown source");
327
328     if (m_policies.empty()) {
329         m_log.warn("no filter policies were loaded, filtering out all attributes from (%s)", issuer.get() ? issuer.get() : "unknown source");
330         for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
331         attributes.clear();
332         return;
333     }
334
335     // We have to evaluate every policy that applies against each attribute before deciding what to keep.
336
337     // For efficiency, we build an array of the policies that apply in advance.
338     vector<const Policy*> applicablePolicies;
339     for (vector<Policy>::const_iterator p=m_policies.begin(); p!=m_policies.end(); ++p) {
340         if (p->m_applies->evaluatePolicyRequirement(context))
341             applicablePolicies.push_back(&(*p));
342     }
343
344     // For further efficiency, we declare arrays to store the applicable rules for an Attribute.
345     vector< pair<const MatchFunctor*,const MatchFunctor*> > applicableRules;
346     vector< pair<const MatchFunctor*,const MatchFunctor*> > wildcardRules;
347
348     // Store off the wildcards ahead of time.
349     for (vector<const Policy*>::const_iterator pol=applicablePolicies.begin(); pol!=applicablePolicies.end(); ++pol) {
350         pair<Policy::rules_t::const_iterator,Policy::rules_t::const_iterator> rules = (*pol)->m_rules.equal_range("*");
351         for (; rules.first!=rules.second; ++rules.first)
352             wildcardRules.push_back(rules.first->second);
353     }
354
355     // To track what to keep without removing anything from the original set until the end, we maintain
356     // a map of each Attribute object to a boolean array with true flags indicating what to delete.
357     // A single dimension array tracks attributes being removed entirely.
358     vector<bool> deletedAttributes(attributes.size(), false);
359     map< Attribute*, vector<bool> > deletedPositions;
360
361     // Loop over each attribute to filter them.
362     for (vector<Attribute*>::size_type a=0; a<attributes.size(); ++a) {
363         Attribute* attr = attributes[a];
364
365         // Clear the rule store.
366         applicableRules.clear();
367
368         // Look for rules to run in each policy.
369         for (vector<const Policy*>::const_iterator pol=applicablePolicies.begin(); pol!=applicablePolicies.end(); ++pol) {
370             pair<Policy::rules_t::const_iterator,Policy::rules_t::const_iterator> rules = (*pol)->m_rules.equal_range(attr->getId());
371             for (; rules.first!=rules.second; ++rules.first)
372                 applicableRules.push_back(rules.first->second);
373         }
374
375         // If no rules found, apply wildcards.
376         const vector< pair<const MatchFunctor*,const MatchFunctor*> >& rulesToRun = applicableRules.empty() ? wildcardRules : applicableRules;
377
378         // If no rules apply, remove the attribute entirely.
379         if (rulesToRun.empty()) {
380             m_log.warn(
381                 "no rule found, removing attribute (%s) from (%s)",
382                 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
383                 );
384             deletedAttributes[a] = true;
385             continue;
386         }
387
388         // Run each permit/deny rule.
389         m_log.debug(
390             "applying filtering rule(s) for attribute (%s) from (%s)",
391             attr->getId(), issuer.get() ? issuer.get() : "unknown source"
392             );
393
394         bool kickit;
395
396         // Examine each value.
397         for (size_t count = attr->valueCount(), index = 0; index < count; ++index) {
398
399             // Assume we're kicking it out.
400             kickit=true;
401
402             for (vector< pair<const MatchFunctor*,const MatchFunctor*> >::const_iterator r=rulesToRun.begin(); r!=rulesToRun.end(); ++r) {
403                 // If there's a permit rule that passes, don't kick it.
404                 if (r->first && r->first->evaluatePermitValue(context, *attr, index))
405                     kickit = false;
406                 if (!kickit && r->second && r->second->evaluatePermitValue(context, *attr, index))
407                     kickit = true;
408             }
409
410             // If we're kicking it, record that in the tracker.
411             if (kickit) {
412                 m_log.warn(
413                     "removed value at position (%lu) of attribute (%s) from (%s)",
414                     index, attr->getId(), issuer.get() ? issuer.get() : "unknown source"
415                     );
416                 deletedPositions[attr].resize(index+1);
417                 deletedPositions[attr][index] = true;
418             }
419         }
420     }
421
422     // Final step: go over the deletedPositions matrix and apply the actual changes. In order to delete
423     // any attributes that end up with no values, we have to do it by looping over the originals.
424     for (vector<Attribute*>::size_type a=0; a<attributes.size();) {
425         Attribute* attr = attributes[a];
426
427         if (deletedAttributes[a]) {
428             delete attr;
429             deletedAttributes.erase(deletedAttributes.begin() + a);
430             attributes.erase(attributes.begin() + a);
431             continue;
432         }
433         else if (deletedPositions.count(attr) > 0) {
434             // To do the removal, we loop over the bits backwards so that the
435             // underlying value sequence doesn't get distorted by any removals.
436             // Index has to be offset by one because size_type is unsigned.
437             const vector<bool>& row = deletedPositions[attr];
438             for (vector<bool>::size_type index = row.size(); index > 0; --index) {
439                 if (row[index-1])
440                     attr->removeValue(index-1);
441             }
442         }
443
444         // Check for no values.
445         if (attr->valueCount() == 0) {
446             m_log.warn(
447                 "no values left, removing attribute (%s) from (%s)",
448                 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
449                 );
450             delete attr;
451             attributes.erase(attributes.begin() + a);
452             continue;
453         }
454
455         ++a;
456     }
457 }
458
459 pair<bool,DOMElement*> XMLFilter::load()
460 {
461     // Load from source using base class.
462     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
463
464     // If we own it, wrap it.
465     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
466
467     XMLFilterImpl* impl = new XMLFilterImpl(raw.second, m_log);
468
469     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
470     impl->setDocument(docjanitor.release());
471
472     delete m_impl;
473     m_impl = impl;
474
475     return make_pair(false,(DOMElement*)NULL);
476 }