2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * XMLAttributeFilter.cpp
24 * AttributeFilter based on an XML policy language.
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "attribute/Attribute.h"
32 #include "attribute/filtering/AttributeFilter.h"
33 #include "attribute/filtering/FilteringContext.h"
34 #include "attribute/filtering/FilterPolicyContext.h"
35 #include "attribute/filtering/MatchFunctor.h"
36 #include "util/SPConstants.h"
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/ReloadableXMLFile.h>
40 #include <xmltooling/util/Threads.h>
41 #include <xmltooling/util/XMLHelper.h>
42 #include <xercesc/util/XMLUniDefs.hpp>
44 using shibspconstants::SHIB2ATTRIBUTEFILTER_NS;
45 using namespace shibsp;
46 using namespace opensaml::saml2md;
47 using namespace opensaml;
48 using namespace xmltooling;
53 #if defined (_MSC_VER)
54 #pragma warning( push )
55 #pragma warning( disable : 4250 )
58 // Each Policy has a functor for determining applicability and a map of
59 // attribute IDs to Accept/Deny functor pairs (which can include nullptrs).
60 struct SHIBSP_DLLLOCAL Policy
62 Policy() : m_applies(nullptr) {}
63 const MatchFunctor* m_applies;
64 typedef multimap< string,pair<const MatchFunctor*,const MatchFunctor*> > rules_t;
68 class SHIBSP_DLLLOCAL XMLFilterImpl
71 XMLFilterImpl(const DOMElement* e, Category& log);
74 m_document->release();
75 for_each(m_policyReqRules.begin(), m_policyReqRules.end(), cleanup_pair<string,MatchFunctor>());
76 for_each(m_permitValRules.begin(), m_permitValRules.end(), cleanup_pair<string,MatchFunctor>());
77 for_each(m_denyValRules.begin(), m_denyValRules.end(), cleanup_pair<string,MatchFunctor>());
80 void setDocument(DOMDocument* doc) {
84 void filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const;
87 MatchFunctor* buildFunctor(
88 const DOMElement* e, const FilterPolicyContext& functorMap, const char* logname, bool standalone
90 pair< string,pair<const MatchFunctor*,const MatchFunctor*> > buildAttributeRule(
91 const DOMElement* e, const FilterPolicyContext& permMap, const FilterPolicyContext& denyMap, bool standalone
95 DOMDocument* m_document;
96 vector<Policy> m_policies;
97 map< string,pair<string,pair<const MatchFunctor*,const MatchFunctor*> > > m_attrRules;
98 multimap<string,MatchFunctor*> m_policyReqRules;
99 multimap<string,MatchFunctor*> m_permitValRules;
100 multimap<string,MatchFunctor*> m_denyValRules;
103 class SHIBSP_DLLLOCAL XMLFilter : public AttributeFilter, public ReloadableXMLFile
106 XMLFilter(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeFilter")), m_impl(nullptr) {
114 void filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const {
115 m_impl->filterAttributes(context, attributes);
119 pair<bool,DOMElement*> background_load();
122 XMLFilterImpl* m_impl;
125 #if defined (_MSC_VER)
126 #pragma warning( pop )
129 AttributeFilter* SHIBSP_DLLLOCAL XMLAttributeFilterFactory(const DOMElement* const & e)
131 return new XMLFilter(e);
134 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);
135 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);
136 static const XMLCh AttributeRule[] = UNICODE_LITERAL_13(A,t,t,r,i,b,u,t,e,R,u,l,e);
137 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);
138 static const XMLCh DenyValueRule[] = UNICODE_LITERAL_13(D,e,n,y,V,a,l,u,e,R,u,l,e);
139 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);
140 static const XMLCh PermitValueRule[] = UNICODE_LITERAL_15(P,e,r,m,i,t,V,a,l,u,e,R,u,l,e);
141 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);
142 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);
143 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);
144 static const XMLCh attributeID[] = UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,D);
145 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
146 static const XMLCh _ref[] = UNICODE_LITERAL_3(r,e,f);
149 XMLFilterImpl::XMLFilterImpl(const DOMElement* e, Category& log) : m_log(log), m_document(nullptr)
152 xmltooling::NDC ndc("XMLFilterImpl");
155 if (!XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, AttributeFilterPolicyGroup))
156 throw ConfigurationException("XML AttributeFilter requires afp:AttributeFilterPolicyGroup at root of configuration.");
158 FilterPolicyContext reqFunctors(m_policyReqRules);
159 FilterPolicyContext permFunctors(m_permitValRules);
160 FilterPolicyContext denyFunctors(m_denyValRules);
162 DOMElement* child = XMLHelper::getFirstChildElement(e);
164 if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRule)) {
165 buildFunctor(child, reqFunctors, "PolicyRequirementRule", true);
167 else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, PermitValueRule)) {
168 buildFunctor(child, permFunctors, "PermitValueRule", true);
170 else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, DenyValueRule)) {
171 buildFunctor(child, denyFunctors, "DenyValueRule", true);
173 else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, AttributeRule)) {
174 buildAttributeRule(child, permFunctors, denyFunctors, true);
176 else if (XMLHelper::isNodeNamed(child, SHIB2ATTRIBUTEFILTER_NS, AttributeFilterPolicy)) {
177 e = XMLHelper::getFirstChildElement(child);
178 MatchFunctor* func = nullptr;
179 if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRule)) {
180 func = buildFunctor(e, reqFunctors, "PolicyRequirementRule", false);
182 else if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, PolicyRequirementRuleReference)) {
183 string ref(XMLHelper::getAttrString(e, nullptr, _ref));
185 multimap<string,MatchFunctor*>::const_iterator prr = m_policyReqRules.find(ref);
186 func = (prr!=m_policyReqRules.end()) ? prr->second : nullptr;
190 m_policies.push_back(Policy());
191 m_policies.back().m_applies = func;
192 e = XMLHelper::getNextSiblingElement(e);
194 if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, AttributeRule)) {
195 pair< string,pair<const MatchFunctor*,const MatchFunctor*> > rule = buildAttributeRule(e, permFunctors, denyFunctors, false);
196 if (rule.second.first || rule.second.second)
197 m_policies.back().m_rules.insert(Policy::rules_t::value_type(rule.first, rule.second));
199 else if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, AttributeRuleReference)) {
200 string ref(XMLHelper::getAttrString(e, nullptr, _ref));
202 map< string,pair< string,pair< const MatchFunctor*,const MatchFunctor*> > >::const_iterator ar = m_attrRules.find(ref);
203 if (ar != m_attrRules.end())
204 m_policies.back().m_rules.insert(Policy::rules_t::value_type(ar->second.first, ar->second.second));
206 m_log.warn("skipping invalid AttributeRuleReference (%s)", ref.c_str());
209 e = XMLHelper::getNextSiblingElement(e);
213 m_log.warn("skipping AttributeFilterPolicy, PolicyRequirementRule invalid or missing");
216 child = XMLHelper::getNextSiblingElement(child);
220 MatchFunctor* XMLFilterImpl::buildFunctor(
221 const DOMElement* e, const FilterPolicyContext& functorMap, const char* logname, bool standalone
224 string id(XMLHelper::getAttrString(e, nullptr, _id));
226 if (standalone && id.empty()) {
227 m_log.warn("skipping stand-alone %s with no id", logname);
230 else if (!id.empty() && functorMap.getMatchFunctors().count(id)) {
232 m_log.warn("skipping duplicate stand-alone %s with id (%s)", logname, id.c_str());
239 auto_ptr<xmltooling::QName> type(XMLHelper::getXSIType(e));
242 MatchFunctor* func = SPConfig::getConfig().MatchFunctorManager.newPlugin(*type.get(), make_pair(&functorMap,e));
243 functorMap.getMatchFunctors().insert(multimap<string,MatchFunctor*>::value_type(id, func));
246 catch (exception& ex) {
247 m_log.error("error building %s with type (%s): %s", logname, type->toString().c_str(), ex.what());
251 m_log.warn("skipping stand-alone %s with no xsi:type", logname);
253 m_log.error("%s with no xsi:type", logname);
258 pair< string,pair<const MatchFunctor*,const MatchFunctor*> > XMLFilterImpl::buildAttributeRule(
259 const DOMElement* e, const FilterPolicyContext& permMap, const FilterPolicyContext& denyMap, bool standalone
262 string id(XMLHelper::getAttrString(e, nullptr, _id));
264 if (standalone && id.empty()) {
265 m_log.warn("skipping stand-alone AttributeRule with no id");
266 return make_pair(string(),pair<const MatchFunctor*,const MatchFunctor*>(nullptr,nullptr));
268 else if (!id.empty() && m_attrRules.count(id)) {
270 m_log.warn("skipping duplicate stand-alone AttributeRule with id (%s)", id.c_str());
271 return make_pair(string(),pair<const MatchFunctor*,const MatchFunctor*>(nullptr,nullptr));
277 string attrID(XMLHelper::getAttrString(e, nullptr, attributeID));
279 m_log.warn("skipping AttributeRule with no attributeID");
281 MatchFunctor* perm=nullptr;
282 MatchFunctor* deny=nullptr;
284 e = XMLHelper::getFirstChildElement(e);
285 if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, PermitValueRule)) {
286 perm = buildFunctor(e, permMap, "PermitValueRule", false);
287 e = XMLHelper::getNextSiblingElement(e);
289 else if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, PermitValueRuleReference)) {
290 string ref(XMLHelper::getAttrString(e, nullptr, _ref));
292 multimap<string,MatchFunctor*>::const_iterator pvr = m_permitValRules.find(ref);
293 perm = (pvr!=m_permitValRules.end()) ? pvr->second : nullptr;
295 e = XMLHelper::getNextSiblingElement(e);
298 if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, DenyValueRule)) {
299 deny = buildFunctor(e, denyMap, "DenyValueRule", false);
301 else if (e && XMLHelper::isNodeNamed(e, SHIB2ATTRIBUTEFILTER_NS, DenyValueRuleReference)) {
302 string ref(XMLHelper::getAttrString(e, nullptr, _ref));
304 multimap<string,MatchFunctor*>::const_iterator pvr = m_denyValRules.find(ref);
305 deny = (pvr!=m_denyValRules.end()) ? pvr->second : nullptr;
312 pair< string,pair<const MatchFunctor*,const MatchFunctor*> >(attrID, pair<const MatchFunctor*,const MatchFunctor*>(perm,deny));
313 return m_attrRules[id];
316 return pair< string,pair<const MatchFunctor*,const MatchFunctor*> >(attrID, pair<const MatchFunctor*,const MatchFunctor*>(perm,deny));
321 m_log.warn("skipping AttributeRule (%s), permit and denial rule(s) invalid or missing", id.c_str());
323 m_log.warn("skipping AttributeRule, permit and denial rule(s) invalid or missing");
324 return pair< string,pair<const MatchFunctor*,const MatchFunctor*> >(string(),pair<const MatchFunctor*,const MatchFunctor*>(nullptr,nullptr));
327 void XMLFilterImpl::filterAttributes(const FilteringContext& context, vector<Attribute*>& attributes) const
329 auto_ptr_char issuer(context.getAttributeIssuer());
331 m_log.debug("filtering %lu attribute(s) from (%s)", attributes.size(), issuer.get() ? issuer.get() : "unknown source");
333 if (m_policies.empty()) {
334 m_log.warn("no filter policies were loaded, filtering out all attributes from (%s)", issuer.get() ? issuer.get() : "unknown source");
335 for_each(attributes.begin(), attributes.end(), xmltooling::cleanup<Attribute>());
340 // We have to evaluate every policy that applies against each attribute before deciding what to keep.
342 // For efficiency, we build an array of the policies that apply in advance.
343 vector<const Policy*> applicablePolicies;
344 for (vector<Policy>::const_iterator p=m_policies.begin(); p!=m_policies.end(); ++p) {
345 if (p->m_applies->evaluatePolicyRequirement(context))
346 applicablePolicies.push_back(&(*p));
349 // For further efficiency, we declare arrays to store the applicable rules for an Attribute.
350 vector< pair<const MatchFunctor*,const MatchFunctor*> > applicableRules;
351 vector< pair<const MatchFunctor*,const MatchFunctor*> > wildcardRules;
353 // Store off the wildcards ahead of time.
354 for (vector<const Policy*>::const_iterator pol=applicablePolicies.begin(); pol!=applicablePolicies.end(); ++pol) {
355 pair<Policy::rules_t::const_iterator,Policy::rules_t::const_iterator> rules = (*pol)->m_rules.equal_range("*");
356 for (; rules.first!=rules.second; ++rules.first)
357 wildcardRules.push_back(rules.first->second);
360 // To track what to keep without removing anything from the original set until the end, we maintain
361 // a map of each Attribute object to a boolean array with true flags indicating what to delete.
362 // A single dimension array tracks attributes being removed entirely.
363 vector<bool> deletedAttributes(attributes.size(), false);
364 map< Attribute*, vector<bool> > deletedPositions;
366 // Loop over each attribute to filter them.
367 for (vector<Attribute*>::size_type a=0; a<attributes.size(); ++a) {
368 Attribute* attr = attributes[a];
370 // Clear the rule store.
371 applicableRules.clear();
373 // Look for rules to run in each policy.
374 for (vector<const Policy*>::const_iterator pol=applicablePolicies.begin(); pol!=applicablePolicies.end(); ++pol) {
375 pair<Policy::rules_t::const_iterator,Policy::rules_t::const_iterator> rules = (*pol)->m_rules.equal_range(attr->getId());
376 for (; rules.first!=rules.second; ++rules.first)
377 applicableRules.push_back(rules.first->second);
380 // If no rules found, apply wildcards.
381 const vector< pair<const MatchFunctor*,const MatchFunctor*> >& rulesToRun = applicableRules.empty() ? wildcardRules : applicableRules;
383 // If no rules apply, remove the attribute entirely.
384 if (rulesToRun.empty()) {
386 "no rule found, will remove attribute (%s) from (%s)",
387 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
389 deletedAttributes[a] = true;
393 // Run each permit/deny rule.
395 "applying filtering rule(s) for attribute (%s) from (%s)",
396 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
401 // Examine each value.
402 for (size_t count = attr->valueCount(), index = 0; index < count; ++index) {
404 // Assume we're kicking it out.
407 for (vector< pair<const MatchFunctor*,const MatchFunctor*> >::const_iterator r=rulesToRun.begin(); r!=rulesToRun.end(); ++r) {
408 // If there's a permit rule that passes, don't kick it.
409 if (r->first && r->first->evaluatePermitValue(context, *attr, index))
411 if (!kickit && r->second && r->second->evaluatePermitValue(context, *attr, index))
415 // If we're kicking it, record that in the tracker.
418 "removed value at position (%lu) of attribute (%s) from (%s)",
419 index, attr->getId(), issuer.get() ? issuer.get() : "unknown source"
421 deletedPositions[attr].resize(index+1);
422 deletedPositions[attr][index] = true;
427 // Final step: go over the deletedPositions matrix and apply the actual changes. In order to delete
428 // any attributes that end up with no values, we have to do it by looping over the originals.
429 for (vector<Attribute*>::size_type a=0; a<attributes.size();) {
430 Attribute* attr = attributes[a];
432 if (deletedAttributes[a]) {
434 "removing filtered attribute (%s) from (%s)",
435 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
438 deletedAttributes.erase(deletedAttributes.begin() + a);
439 attributes.erase(attributes.begin() + a);
442 else if (deletedPositions.count(attr) > 0) {
443 // To do the removal, we loop over the bits backwards so that the
444 // underlying value sequence doesn't get distorted by any removals.
445 // Index has to be offset by one because size_type is unsigned.
446 const vector<bool>& row = deletedPositions[attr];
447 for (vector<bool>::size_type index = row.size(); index > 0; --index) {
449 attr->removeValue(index-1);
453 // Check for no values.
454 if (attr->valueCount() == 0) {
456 "no values left, removing attribute (%s) from (%s)",
457 attr->getId(), issuer.get() ? issuer.get() : "unknown source"
460 deletedAttributes.erase(deletedAttributes.begin() + a);
461 attributes.erase(attributes.begin() + a);
469 pair<bool,DOMElement*> XMLFilter::background_load()
471 // Load from source using base class.
472 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
474 // If we own it, wrap it.
475 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
477 XMLFilterImpl* impl = new XMLFilterImpl(raw.second, m_log);
479 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
480 impl->setDocument(docjanitor.release());
482 // Perform the swap inside a lock.
485 SharedLock locker(m_lock, false);
489 return make_pair(false,(DOMElement*)nullptr);