2 * Copyright 2001-2009 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 * XMLAttributeFilter.cpp
20 * AttributeFilter based on an XML policy language.
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"
34 #include <xmltooling/util/NDC.h>
35 #include <xmltooling/util/ReloadableXMLFile.h>
36 #include <xmltooling/util/XMLHelper.h>
37 #include <xercesc/util/XMLUniDefs.hpp>
39 using shibspconstants::SHIB2ATTRIBUTEFILTER_NS;
40 using namespace shibsp;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
43 using namespace xmltooling;
48 #if defined (_MSC_VER)
49 #pragma warning( push )
50 #pragma warning( disable : 4250 )
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
57 Policy() : m_applies(NULL) {}
58 const MatchFunctor* m_applies;
59 typedef multimap< string,pair<const MatchFunctor*,const MatchFunctor*> > rules_t;
63 class SHIBSP_DLLLOCAL XMLFilterImpl
66 XMLFilterImpl(const DOMElement* e, Category& log);
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>());
75 void setDocument(DOMDocument* doc) {
79 void filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const;
82 MatchFunctor* buildFunctor(
83 const DOMElement* e, const FilterPolicyContext& functorMap, const char* logname, bool standalone
85 pair< string,pair<const MatchFunctor*,const MatchFunctor*> > buildAttributeRule(
86 const DOMElement* e, const FilterPolicyContext& permMap, const FilterPolicyContext& denyMap, bool standalone
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;
98 class SHIBSP_DLLLOCAL XMLFilter : public AttributeFilter, public ReloadableXMLFile
101 XMLFilter(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeFilter")), m_impl(NULL) {
108 void filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const {
109 m_impl->filterAttributes(context, attributes);
113 pair<bool,DOMElement*> load();
116 XMLFilterImpl* m_impl;
119 #if defined (_MSC_VER)
120 #pragma warning( pop )
123 AttributeFilter* SHIBSP_DLLLOCAL XMLAttributeFilterFactory(const DOMElement* const & e)
125 return new XMLFilter(e);
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);
143 XMLFilterImpl::XMLFilterImpl(const DOMElement* e, Category& log) : m_log(log), m_document(NULL)
146 xmltooling::NDC ndc("XMLFilterImpl");
149 if (!XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, AttributeFilterPolicyGroup))
150 throw ConfigurationException("XML AttributeFilter requires afp:AttributeFilterPolicyGroup at root of configuration.");
152 FilterPolicyContext reqFunctors(m_policyReqRules);
153 FilterPolicyContext permFunctors(m_permitValRules);
154 FilterPolicyContext denyFunctors(m_denyValRules);
156 DOMElement* child = XMLHelper::getFirstChildElement(e);
158 if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRule)) {
159 buildFunctor(child, reqFunctors, "PolicyRequirementRule", true);
161 else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, PermitValueRule)) {
162 buildFunctor(child, permFunctors, "PermitValueRule", true);
164 else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, DenyValueRule)) {
165 buildFunctor(child, denyFunctors, "DenyValueRule", true);
167 else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, AttributeRule)) {
168 buildAttributeRule(child, permFunctors, denyFunctors, true);
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);
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;
184 m_policies.push_back(Policy());
185 m_policies.back().m_applies = func;
186 e = XMLHelper::getNextSiblingElement(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));
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));
200 m_log.warn("skipping invalid AttributeRuleReference (%s)", ref.get());
203 e = XMLHelper::getNextSiblingElement(e);
207 m_log.warn("skipping AttributeFilterPolicy, PolicyRequirementRule invalid or missing");
210 child = XMLHelper::getNextSiblingElement(child);
214 MatchFunctor* XMLFilterImpl::buildFunctor(
215 const DOMElement* e, const FilterPolicyContext& functorMap, const char* logname, bool standalone
218 auto_ptr_char temp(e->getAttributeNS(NULL,_id));
219 const char* id = (temp.get() && *temp.get()) ? temp.get() : "";
221 if (standalone && !*id) {
222 m_log.warn("skipping stand-alone %s with no id", logname);
225 else if (*id && functorMap.getMatchFunctors().count(id)) {
227 m_log.warn("skipping duplicate stand-alone %s with id (%s)", logname, id);
234 auto_ptr<xmltooling::QName> type(XMLHelper::getXSIType(e));
237 MatchFunctor* func = SPConfig::getConfig().MatchFunctorManager.newPlugin(*type.get(), make_pair(&functorMap,e));
238 functorMap.getMatchFunctors().insert(multimap<string,MatchFunctor*>::value_type(id, func));
241 catch (exception& ex) {
242 m_log.error("error building %s with type (%s): %s", logname, type->toString().c_str(), ex.what());
246 m_log.warn("skipping stand-alone %s with no xsi:type", logname);
248 m_log.error("%s with no xsi:type", logname);
253 pair< string,pair<const MatchFunctor*,const MatchFunctor*> > XMLFilterImpl::buildAttributeRule(
254 const DOMElement* e, const FilterPolicyContext& permMap, const FilterPolicyContext& denyMap, bool standalone
257 auto_ptr_char temp(e->getAttributeNS(NULL,_id));
258 const char* id = (temp.get() && *temp.get()) ? temp.get() : "";
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));
264 else if (*id && m_attrRules.count(id)) {
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));
273 auto_ptr_char attrID(e->getAttributeNS(NULL,attributeID));
274 if (!attrID.get() || !*attrID.get())
275 m_log.warn("skipping AttributeRule with no attributeID");
277 MatchFunctor* perm=NULL;
278 MatchFunctor* deny=NULL;
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);
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;
291 e = XMLHelper::getNextSiblingElement(e);
294 if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, DenyValueRule)) {
295 deny = buildFunctor(e, denyMap, "DenyValueRule", false);
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;
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];
311 return pair< string,pair<const MatchFunctor*,const MatchFunctor*> >(attrID.get(), pair<const MatchFunctor*,const MatchFunctor*>(perm,deny));
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));
319 void XMLFilterImpl::filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const
321 auto_ptr_char issuer(context.getAttributeIssuer());
323 m_log.debug("filtering %lu attribute(s) from (%s)", attributes.size(), issuer.get() ? issuer.get() : "unknown source");
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>());
332 // We have to evaluate every policy that applies against each attribute before deciding what to keep.
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));
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;
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);
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;
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];
362 // Clear the rule store.
363 applicableRules.clear();
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);
372 // If no rules found, apply wildcards.
373 const vector< pair<const MatchFunctor*,const MatchFunctor*> >& rulesToRun = applicableRules.empty() ? wildcardRules : applicableRules;
375 // If no rules apply, remove the attribute entirely.
376 if (rulesToRun.empty()) {
378 "no rule found, removing attribute (%s) from (%s)",
379 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
381 deletedAttributes[a] = true;
385 // Run each permit/deny rule.
387 "applying filtering rule(s) for attribute (%s) from (%s)",
388 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
393 // Examine each value.
394 for (size_t count = attr->valueCount(), index = 0; index < count; ++index) {
396 // Assume we're kicking it out.
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))
403 if (!kickit && r->second && r->second->evaluatePermitValue(context, *attr, index))
407 // If we're kicking it, record that in the tracker.
410 "removed value at position (%lu) of attribute (%s) from (%s)",
411 index, attr->getId(), issuer.get() ? issuer.get() : "unknown source"
413 deletedPositions[attr].resize(index+1);
414 deletedPositions[attr][index] = true;
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];
424 if (deletedAttributes[a]) {
426 deletedAttributes.erase(deletedAttributes.begin() + a);
427 attributes.erase(attributes.begin() + a);
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) {
437 attr->removeValue(index-1);
441 // Check for no values.
442 if (attr->valueCount() == 0) {
444 "no values left, removing attribute (%s) from (%s)",
445 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
448 attributes.erase(attributes.begin() + a);
456 pair<bool,DOMElement*> XMLFilter::load()
458 // Load from source using base class.
459 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
461 // If we own it, wrap it.
462 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
464 XMLFilterImpl* impl = new XMLFilterImpl(raw.second, m_log);
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());
472 return make_pair(false,(DOMElement*)NULL);