5c38639f86bee172c9b05da7cf7e5b6ec814e6cc
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / WhitelistMetadataFilter.cpp
1 /**
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.
6  *
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
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20
21 /**
22  * WhitelistMetadataFilter.cpp
23  *
24  * Removes non-whitelisted entities from a metadata instance
25  */
26
27 #include "internal.h"
28 #include "saml2/metadata/Metadata.h"
29 #include "saml2/metadata/MetadataFilter.h"
30
31 #include <boost/lambda/bind.hpp>
32 #include <boost/lambda/casts.hpp>
33 #include <boost/lambda/lambda.hpp>
34 #include <boost/shared_ptr.hpp>
35 #include <boost/iterator/indirect_iterator.hpp>
36 #include <xmltooling/logging.h>
37
38 using namespace opensaml::saml2;
39 using namespace opensaml::saml2md;
40 using namespace xmltooling::logging;
41 using namespace xmltooling;
42 using namespace boost::lambda;
43 using namespace boost;
44 using namespace std;
45
46 namespace opensaml {
47     namespace saml2md {
48         class SAML_DLLLOCAL WhitelistMetadataFilter : public MetadataFilter
49         {
50         public:
51             WhitelistMetadataFilter(const DOMElement* e);
52             ~WhitelistMetadataFilter() {}
53
54             const char* getId() const { return WHITELIST_METADATA_FILTER; }
55             void doFilter(XMLObject& xmlObject) const;
56
57         private:
58             void filterGroup(EntitiesDescriptor&) const;
59             bool included(const EntityDescriptor&) const;
60             bool matches(const EntityAttributes*, const Attribute*) const;
61
62             set<xstring> m_entities;
63             bool m_trimTags;
64             vector< boost::shared_ptr<Attribute> > m_tags;
65         };
66
67         MetadataFilter* SAML_DLLLOCAL WhitelistMetadataFilterFactory(const DOMElement* const & e)
68         {
69             return new WhitelistMetadataFilter(e);
70         }
71
72         static const XMLCh Include[] =  UNICODE_LITERAL_7(I,n,c,l,u,d,e);
73         static const XMLCh trimTags[] = UNICODE_LITERAL_8(t,r,i,m,T,a,g,s);
74     };
75 };
76
77
78 WhitelistMetadataFilter::WhitelistMetadataFilter(const DOMElement* e)
79     : m_trimTags(XMLHelper::getAttrBool(e, false, trimTags))
80 {
81     DOMElement* child = XMLHelper::getFirstChildElement(e);
82     while (child) {
83         if (XMLString::equals(child->getLocalName(), Include) && child->hasChildNodes()) {
84             m_entities.insert(child->getFirstChild()->getTextContent());
85         }
86         else if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, Attribute::LOCAL_NAME)) {
87             boost::shared_ptr<XMLObject> obj(AttributeBuilder::buildOneFromElement(child));
88             m_tags.push_back(boost::shared_dynamic_cast<Attribute>(obj));
89         }
90         child = XMLHelper::getNextSiblingElement(child);
91     }
92 }
93
94 void WhitelistMetadataFilter::doFilter(XMLObject& xmlObject) const
95 {
96     EntitiesDescriptor* group = dynamic_cast<EntitiesDescriptor*>(&xmlObject);
97     if (group) {
98         filterGroup(*group);
99     }
100     else {
101         EntityDescriptor* entity = dynamic_cast<EntityDescriptor*>(&xmlObject);
102         if (entity) {
103             if (!included(*entity))
104                 throw MetadataFilterException(WHITELIST_METADATA_FILTER" MetadataFilter instructed to filter the root/only entity in the metadata.");
105         }
106         else {
107             throw MetadataFilterException(WHITELIST_METADATA_FILTER" MetadataFilter was given an improper metadata instance to filter.");
108         }
109     }
110 }
111
112 void WhitelistMetadataFilter::filterGroup(EntitiesDescriptor& entities) const
113 {
114     Category& log=Category::getInstance(SAML_LOGCAT".MetadataFilter."WHITELIST_METADATA_FILTER);
115
116     VectorOf(EntityDescriptor) v = entities.getEntityDescriptors();
117     for (VectorOf(EntityDescriptor)::size_type i = 0; i < v.size(); ) {
118         if (!included(*v[i])) {
119             auto_ptr_char id(v[i]->getEntityID());
120             log.info("filtering out non-whitelisted entity (%s)", id.get());
121             v.erase(v.begin() + i);
122         }
123         else {
124             i++;
125         }
126     }
127
128     const vector<EntitiesDescriptor*>& groups = const_cast<const EntitiesDescriptor&>(entities).getEntitiesDescriptors();
129     for_each(
130         make_indirect_iterator(groups.begin()), make_indirect_iterator(groups.end()),
131         lambda::bind(&WhitelistMetadataFilter::filterGroup, this, _1)
132         );
133 }
134
135 bool WhitelistMetadataFilter::included(const EntityDescriptor& entity) const
136 {
137     // Check for entityID.
138     if (entity.getEntityID() && !m_entities.empty() && m_entities.count(entity.getEntityID()) == 1)
139         return true;
140
141     // Check for a tag match in the EntityAttributes extension of the entity and its parent(s).
142     if (!m_tags.empty()) {
143         const Extensions* exts = entity.getExtensions();
144         if (exts) {
145             const vector<XMLObject*>& children = exts->getUnknownXMLObjects();
146             const XMLObject* xo = find_if(children, ll_dynamic_cast<EntityAttributes*>(_1) != ((EntityAttributes*)nullptr));
147             if (xo) {
148                 // If we find a matching tag, we win. Each tag is treated in OR fashion.
149                 if (find_if(m_tags.begin(), m_tags.end(),
150                     lambda::bind(&WhitelistMetadataFilter::matches, this, dynamic_cast<const EntityAttributes*>(xo),
151                         lambda::bind(&boost::shared_ptr<Attribute>::get, _1))) != m_tags.end()) {
152                     return true;
153                 }
154             }
155         }
156
157         const EntitiesDescriptor* group = dynamic_cast<EntitiesDescriptor*>(entity.getParent());
158         while (group) {
159             exts = group->getExtensions();
160             if (exts) {
161                 const vector<XMLObject*>& children = exts->getUnknownXMLObjects();
162                 const XMLObject* xo = find_if(children, ll_dynamic_cast<EntityAttributes*>(_1) != ((EntityAttributes*)nullptr));
163                 if (xo) {
164                     // If we find a matching tag, we win. Each tag is treated in OR fashion.
165                     if (find_if(m_tags.begin(), m_tags.end(),
166                         lambda::bind(&WhitelistMetadataFilter::matches, this, dynamic_cast<const EntityAttributes*>(xo),
167                             lambda::bind(&boost::shared_ptr<Attribute>::get, _1))) != m_tags.end()) {
168                         return true;
169                     }
170                 }
171             }
172             group = dynamic_cast<EntitiesDescriptor*>(group->getParent());
173         }
174     }
175     return false;
176 }
177
178 bool WhitelistMetadataFilter::matches(const EntityAttributes* ea, const Attribute* tag) const
179 {
180     const vector<Attribute*>& attrs = ea->getAttributes();
181     const vector<XMLObject*>& tagvals = tag->getAttributeValues();
182     if (!attrs.empty() && !tagvals.empty()) {
183         // Track whether we've found every tag value.
184         vector<bool> flags(tagvals.size());
185
186         // Check each attribute/tag in the candidate.
187         for (indirect_iterator<vector<Attribute*>::const_iterator> a = make_indirect_iterator(attrs.begin());
188                 a != make_indirect_iterator(attrs.end()); ++a) {
189             // Compare Name and NameFormat for a matching tag.
190             if (XMLString::equals(a->getName(), tag->getName()) &&
191                 (!tag->getNameFormat() || XMLString::equals(tag->getNameFormat(), Attribute::UNSPECIFIED) ||
192                     XMLString::equals(tag->getNameFormat(), a->getNameFormat()))) {
193                 // Check each tag value's simple content for a match.
194                 for (vector<XMLObject*>::size_type tagindex = 0; tagindex < tagvals.size(); ++tagindex) {
195                     const XMLObject* tagval = tagvals[tagindex];
196                     const XMLCh* tagvalstr = (tagval->getDOM()) ? tagval->getDOM()->getTextContent() : tagval->getTextContent();
197                     const vector<XMLObject*>& cvals = const_cast<const Attribute&>(*a).getAttributeValues();
198                     for (indirect_iterator<vector<XMLObject*>::const_iterator> cval = make_indirect_iterator(cvals.begin());
199                             cval != make_indirect_iterator(cvals.end()); ++cval) {
200                         const XMLCh* cvalstr = cval->getDOM() ? cval->getDOM()->getTextContent() : cval->getTextContent();
201                         if (tagvalstr && cvalstr) {
202                             if (XMLString::equals(tagvalstr, cvalstr)) {
203                                 flags[tagindex] = true;
204                                 break;
205                             }
206                             else if (m_trimTags) {
207                                 XMLCh* dup = XMLString::replicate(cvalstr);
208                                 XMLString::trim(dup);
209                                 if (XMLString::equals(tagvalstr, dup)) {
210                                     XMLString::release(&dup);
211                                     flags[tagindex] = true;
212                                     break;
213                                 }
214                                 XMLString::release(&dup);
215                             }
216                         }
217                     }
218                 }
219             }
220         }
221
222         if (find(flags.begin(), flags.end(), false) == flags.end())
223             return true;
224     }
225     return false;
226 }