Attribute filtering code.
[shibboleth/sp.git] / shibsp / attribute / filtering / impl / XMLAttributeFilter.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  * XMLAttributeFilter.cpp
19  * 
20  * AttributeFilter based on an XML policy language.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "ServiceProvider.h"
26 #include "attribute/Attribute.h"
27 #include "attribute/filtering/AttributeFilter.h"
28 #include "attribute/filtering/MatchFunctor.h"
29 #include "util/SPConstants.h"
30
31 #include <xmltooling/util/NDC.h>
32 #include <xmltooling/util/ReloadableXMLFile.h>
33 #include <xmltooling/util/XMLHelper.h>
34 #include <xercesc/util/XMLUniDefs.hpp>
35
36 using namespace shibsp;
37 using namespace opensaml::saml2md;
38 using namespace opensaml;
39 using namespace xmltooling;
40 using namespace log4cpp;
41 using namespace std;
42
43 namespace shibsp {
44
45 #if defined (_MSC_VER)
46     #pragma warning( push )
47     #pragma warning( disable : 4250 )
48 #endif
49
50     struct SHIBSP_DLLLOCAL Policy
51     {
52         Policy() : m_applies(NULL) {}
53         const MatchFunctor* m_applies;
54         typedef multimap<string,const MatchFunctor*> rules_t;
55         rules_t m_rules;
56     };
57
58     class SHIBSP_DLLLOCAL XMLFilterImpl
59     {
60     public:
61         XMLFilterImpl(const DOMElement* e, Category& log);
62         ~XMLFilterImpl() {
63             if (m_document)
64                 m_document->release();
65             for_each(m_policyReqRules.begin(), m_policyReqRules.end(), cleanup_pair<string,MatchFunctor>());
66             for_each(m_permitValRules.begin(), m_permitValRules.end(), cleanup_pair<string,MatchFunctor>());
67         }
68
69         void setDocument(DOMDocument* doc) {
70             m_document = doc;
71         }
72
73         void filterAttributes(const FilteringContext& context, multimap<string,Attribute*>& attributes) const;
74
75     private:
76         MatchFunctor* buildFunctor(
77             const DOMElement* e, multimap<string,MatchFunctor*>& functorMap, const char* logname, bool standalone
78             );
79         pair<string,const MatchFunctor*> buildAttributeRule(const DOMElement* e, bool standalone);
80
81         Category& m_log;
82         DOMDocument* m_document;
83         vector<Policy> m_policies;
84         map< string,pair<string,const MatchFunctor*> > m_attrRules;
85         multimap<string,MatchFunctor*> m_policyReqRules;
86         multimap<string,MatchFunctor*> m_permitValRules;
87     };
88     
89     class SHIBSP_DLLLOCAL XMLFilter : public AttributeFilter, public ReloadableXMLFile
90     {
91     public:
92         XMLFilter(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeFilter")), m_impl(NULL) {
93             load();
94         }
95         ~XMLFilter() {
96             delete m_impl;
97         }
98         
99         void filterAttributes(const FilteringContext& context, multimap<string,Attribute*>& attributes) const {
100             m_impl->filterAttributes(context, attributes);
101         }
102
103     protected:
104         pair<bool,DOMElement*> load();
105
106     private:
107         XMLFilterImpl* m_impl;
108     };
109
110 #if defined (_MSC_VER)
111     #pragma warning( pop )
112 #endif
113
114     AttributeFilter* SHIBSP_DLLLOCAL XMLAttributeFilterFactory(const DOMElement* const & e)
115     {
116         return new XMLFilter(e);
117     }
118     
119     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);
120     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);
121     static const XMLCh AttributeRule[] =                UNICODE_LITERAL_13(A,t,t,r,i,b,u,t,e,R,u,l,e);
122     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);
123     static const XMLCh PermitValueRule[] =              UNICODE_LITERAL_15(P,e,r,m,i,t,V,a,l,u,e,R,u,l,e);
124     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);
125     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);
126     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);
127     static const XMLCh attributeId[] =                  UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,d);
128     static const XMLCh _id[] =                          UNICODE_LITERAL_2(i,d);
129     static const XMLCh _ref[] =                         UNICODE_LITERAL_3(r,e,f);
130 };
131
132 XMLFilterImpl::XMLFilterImpl(const DOMElement* e, Category& log) : m_log(log), m_document(NULL)
133 {
134 #ifdef _DEBUG
135     xmltooling::NDC ndc("XMLFilterImpl");
136 #endif
137     
138     if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, AttributeFilterPolicyGroup))
139         throw ConfigurationException("XML AttributeFilter requires afp:AttributeFilterPolicyGroup at root of configuration.");
140
141     DOMElement* child = XMLHelper::getFirstChildElement(e);
142     while (child) {
143         if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRule)) {
144             buildFunctor(child, m_policyReqRules, "PolicyRequirementRule", true);
145         }
146         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, PermitValueRule)) {
147             buildFunctor(child, m_permitValRules, "PermitValueRule", true);
148         }
149         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, AttributeRule)) {
150             buildAttributeRule(child, true);
151         }
152         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, AttributeFilterPolicy)) {
153             e = XMLHelper::getFirstChildElement(child);
154             MatchFunctor* func;
155             if (e && XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRule)) {
156                 func = buildFunctor(e, m_policyReqRules, "PolicyRequirementRule", false);
157             }
158             else if (e && XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRuleReference)) {
159                 auto_ptr_char ref(e->getAttributeNS(NULL, _ref));
160                 if (ref.get() && *ref.get()) {
161                     multimap<string,MatchFunctor*>::const_iterator prr = m_policyReqRules.find(ref.get());
162                     func = (prr!=m_policyReqRules.end()) ? prr->second : NULL;
163                 }
164             }
165             if (func) {
166                 m_policies.push_back(Policy());
167                 m_policies.back().m_applies = func;
168                 e = XMLHelper::getNextSiblingElement(e);
169                 while (e) {
170                     if (e && XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, AttributeRule)) {
171                         pair<string,const MatchFunctor*> rule = buildAttributeRule(e, false);
172                         if (rule.second)
173                             m_policies.back().m_rules.insert(rule);
174                     }
175                     else if (e && XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, AttributeRuleReference)) {
176                         auto_ptr_char ref(e->getAttributeNS(NULL, _ref));
177                         if (ref.get() && *ref.get()) {
178                             map< string,pair<string,const MatchFunctor*> >::const_iterator ar = m_attrRules.find(ref.get());
179                             if (ar != m_attrRules.end())
180                                 m_policies.back().m_rules.insert(ar->second);
181                             else
182                                 m_log.warn("skipping invalid AttributeRuleReference (%s)", ref.get());
183                         }
184                     }
185                     e = XMLHelper::getNextSiblingElement(e);
186                 }
187             }
188             else {
189                 m_log.warn("skipping AttributeFilterPolicy, PolicyRequirementRule invalid or missing");
190             }
191         }
192         child = XMLHelper::getNextSiblingElement(child);
193     }
194 }
195
196 MatchFunctor* XMLFilterImpl::buildFunctor(
197     const DOMElement* e, multimap<string,MatchFunctor*>& functorMap, const char* logname, bool standalone
198     )
199 {
200     auto_ptr_char temp(e->getAttributeNS(NULL,_id));
201     const char* id = (temp.get() && *temp.get()) ? temp.get() : "";
202
203     if (standalone && !*id) {
204         m_log.warn("skipping stand-alone %s with no id", logname);
205         return NULL;
206     }
207     else if (*id && functorMap.count(id)) {
208         if (standalone) {
209             m_log.warn("skipping duplicate stand-alone %s with id (%s)", logname, id);
210             return NULL;
211         }
212         else
213             id = "";
214     }
215
216     auto_ptr<QName> type(XMLHelper::getXSIType(e));
217     if (type.get()) {
218         try {
219             MatchFunctor* func = SPConfig::getConfig().MatchFunctorManager.newPlugin(*type.get(), e);
220             functorMap.insert(make_pair(id, func));
221             return func;
222         }
223         catch (exception& ex) {
224             m_log.error("error building %s with type (%s): %s", logname, type->toString().c_str(), ex.what());
225         }
226     }
227     else if (standalone)
228         m_log.warn("skipping stand-alone %s with no xsi:type", logname);
229     else
230         m_log.error("%s with no xsi:type", logname);
231
232     return NULL;
233 }
234
235 pair<string,const MatchFunctor*> XMLFilterImpl::buildAttributeRule(const DOMElement* e, bool standalone)
236 {
237     auto_ptr_char temp(e->getAttributeNS(NULL,_id));
238     const char* id = (temp.get() && *temp.get()) ? temp.get() : "";
239
240     if (standalone && !*id) {
241         m_log.warn("skipping stand-alone AttributeRule with no id");
242         return make_pair(string(),(MatchFunctor*)NULL);
243     }
244     else if (*id && m_attrRules.count(id)) {
245         if (standalone) {
246             m_log.warn("skipping duplicate stand-alone AttributeRule with id (%s)", id);
247             return make_pair(string(),(MatchFunctor*)NULL);
248         }
249         else
250             id = "";
251     }
252
253     auto_ptr_char attrId(e->getAttributeNS(NULL,attributeId));
254     if (!attrId.get() || !*attrId.get())
255         m_log.warn("skipping AttributeRule with no attributeId");
256
257     e = XMLHelper::getFirstChildElement(e);
258     MatchFunctor* func=NULL;
259     if (e && XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, PermitValueRule)) {
260         func = buildFunctor(e, m_permitValRules, "PermitValueRule", false);
261     }
262     else if (e && XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEFILTER_NS, PermitValueRuleReference)) {
263         auto_ptr_char ref(e->getAttributeNS(NULL, _ref));
264         if (ref.get() && *ref.get()) {
265             multimap<string,MatchFunctor*>::const_iterator pvr = m_permitValRules.find(ref.get());
266             func = (pvr!=m_permitValRules.end()) ? pvr->second : NULL;
267         }
268     }
269
270     if (func) {
271         if (*id)
272             return m_attrRules[id] = make_pair(attrId.get(), func);
273         else
274             return make_pair(attrId.get(), func);
275     }
276
277     m_log.warn("skipping AttributeRule (%s), PermitValueRule invalid or missing", id);
278     return make_pair(string(),(MatchFunctor*)NULL);
279 }
280
281 void XMLFilterImpl::filterAttributes(const FilteringContext& context, multimap<string,Attribute*>& attributes) const
282 {
283     auto_ptr_char issuer(context.getAttributeIssuer());\r
284 \r
285     m_log.debug("filtering %lu attribute(s) from (%s)", attributes.size(), issuer.get() ? issuer.get() : "unknown source");\r
286 \r
287     if (m_policies.empty()) {\r
288         m_log.warn("no filter policies were loaded, filtering out all attributes from (%s)", issuer.get() ? issuer.get() : "unknown source");\r
289         for_each(attributes.begin(), attributes.end(), cleanup_pair<string,Attribute>());\r
290         attributes.clear();\r
291         return;\r
292     }\r
293
294     size_t count,index;
295
296     // Test each Policy.
297     for (vector<Policy>::const_iterator p=m_policies.begin(); p!=m_policies.end(); ++p) {
298         if (p->m_applies->evaluatePolicyRequirement(context)) {
299             // Loop over the attributes and look for possible rules to run.
300             for (multimap<string,Attribute*>::iterator a=attributes.begin(); a!=attributes.end();) {
301                 pair<Policy::rules_t::const_iterator,Policy::rules_t::const_iterator> rules = p->m_rules.equal_range(a->second->getId());
302                 if (rules.first == rules.second) {
303                     // No rule found, so we're filtering it out.
304                     m_log.warn(\r
305                         "no rule found, filtering out values of attribute (%s) from (%s)", a->second->getId(), issuer.get() ? issuer.get() : "unknown source"\r
306                         );\r
307                     multimap<string,Attribute*>::iterator dead = a++;\r
308                     delete dead->second;\r
309                     attributes.erase(dead);\r
310                 }
311                 else {
312                     // Run each rule in sequence.
313                     m_log.debug("filtering values of attribute (%s) from (%s)", a->second->getId(), issuer.get() ? issuer.get() : "unknown source");\r
314                     for (; rules.first!=rules.second; ++rules.first) {
315                         count = a->second->valueCount();
316                         for (index=0; index < count;) {
317                             // The return value tells us whether to index past the accepted value, or stay put and decrement the count.
318                             if (rules.first->second->evaluatePermitValue(context, *(a->second), index))
319                                 index++;
320                             else
321                                 count--;
322                         }
323                     }
324                     // See if any values are left, delete if not.
325                     if (count>0) {
326                         ++a;
327                     }
328                     else {
329                         multimap<string,Attribute*>::iterator dead = a++;\r
330                         delete dead->second;\r
331                         attributes.erase(dead);\r
332                     }
333                 }
334             }
335         }
336     }
337 }
338
339 pair<bool,DOMElement*> XMLFilter::load()
340 {
341     // Load from source using base class.
342     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
343     
344     // If we own it, wrap it.
345     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
346
347     XMLFilterImpl* impl = new XMLFilterImpl(raw.second, m_log);
348     
349     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
350     impl->setDocument(docjanitor.release());
351
352     delete m_impl;
353     m_impl = impl;
354
355     return make_pair(false,(DOMElement*)NULL);
356 }