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 * XMLAccessControl.cpp
24 * XML-based access control syntax.
28 #include "exceptions.h"
29 #include "AccessControl.h"
30 #include "SessionCache.h"
31 #include "SPRequest.h"
32 #include "attribute/Attribute.h"
35 #include <boost/bind.hpp>
36 #include <boost/algorithm/string.hpp>
37 #include <boost/ptr_container/ptr_vector.hpp>
38 #include <xmltooling/unicode.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>
43 #include <xercesc/util/regx/RegularExpression.hpp>
45 #ifndef HAVE_STRCASECMP
46 # define strcasecmp _stricmp
49 using namespace shibsp;
50 using namespace xmltooling;
51 using namespace boost;
56 class Rule : public AccessControl
59 Rule(const DOMElement* e);
62 Lockable* lock() {return this;}
65 aclresult_t authorized(const SPRequest& request, const Session* session) const;
72 class RuleRegex : public AccessControl
75 RuleRegex(const DOMElement* e);
78 Lockable* lock() {return this;}
81 aclresult_t authorized(const SPRequest& request, const Session* session) const;
85 auto_arrayptr<char> m_exp;
86 scoped_ptr<RegularExpression> m_re;
89 class Operator : public AccessControl
92 Operator(const DOMElement* e);
95 Lockable* lock() {return this;}
98 aclresult_t authorized(const SPRequest& request, const Session* session) const;
101 enum operator_t { OP_NOT, OP_AND, OP_OR } m_op;
102 ptr_vector<AccessControl> m_operands;
105 #if defined (_MSC_VER)
106 #pragma warning( push )
107 #pragma warning( disable : 4250 )
110 class XMLAccessControl : public AccessControl, public ReloadableXMLFile
113 XMLAccessControl(const DOMElement* e)
114 : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AccessControl.XML")) {
115 background_load(); // guarantees an exception or the policy is loaded
118 ~XMLAccessControl() {
122 aclresult_t authorized(const SPRequest& request, const Session* session) const;
125 pair<bool,DOMElement*> background_load();
128 scoped_ptr<AccessControl> m_rootAuthz;
131 #if defined (_MSC_VER)
132 #pragma warning( pop )
135 AccessControl* SHIBSP_DLLLOCAL XMLAccessControlFactory(const DOMElement* const & e)
137 return new XMLAccessControl(e);
140 static const XMLCh _AccessControl[] = UNICODE_LITERAL_13(A,c,c,e,s,s,C,o,n,t,r,o,l);
141 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
142 static const XMLCh ignoreCase[] = UNICODE_LITERAL_10(i,g,n,o,r,e,C,a,s,e);
143 static const XMLCh ignoreOption[] = UNICODE_LITERAL_1(i);
144 static const XMLCh _list[] = UNICODE_LITERAL_4(l,i,s,t);
145 static const XMLCh require[] = UNICODE_LITERAL_7(r,e,q,u,i,r,e);
146 static const XMLCh NOT[] = UNICODE_LITERAL_3(N,O,T);
147 static const XMLCh AND[] = UNICODE_LITERAL_3(A,N,D);
148 static const XMLCh OR[] = UNICODE_LITERAL_2(O,R);
149 static const XMLCh _Rule[] = UNICODE_LITERAL_4(R,u,l,e);
150 static const XMLCh _RuleRegex[] = UNICODE_LITERAL_9(R,u,l,e,R,e,g,e,x);
153 Rule::Rule(const DOMElement* e) : m_alias(XMLHelper::getAttrString(e, nullptr, require))
156 throw ConfigurationException("Access control rule missing require attribute");
157 if (!e->hasChildNodes())
158 return; // empty rule
160 auto_arrayptr<char> vals(toUTF8(e->getTextContent()));
161 if (!vals.get() || !*vals.get())
162 throw ConfigurationException("Unable to convert Rule content into UTF-8.");
164 bool listflag = XMLHelper::getAttrBool(e, true, _list);
166 m_vals.insert(vals.get());
170 string temp(vals.get());
171 split(m_vals, temp, boost::is_space(), algorithm::token_compress_on);
173 throw ConfigurationException("Rule did not contain any usable values.");
176 AccessControl::aclresult_t Rule::authorized(const SPRequest& request, const Session* session) const
178 // We can make this more complex later using pluggable comparison functions,
179 // but for now, just a straight port to the new Attribute API.
181 // Map alias in rule to the attribute.
183 request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
184 return shib_acl_false;
187 if (m_alias == "valid-user") {
189 request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
190 return shib_acl_true;
192 return shib_acl_false;
194 if (m_alias == "user") {
195 if (m_vals.find(request.getRemoteUser()) != m_vals.end()) {
196 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting REMOTE_USER (") + request.getRemoteUser() + "), authz granted");
197 return shib_acl_true;
199 return shib_acl_false;
201 else if (m_alias == "authnContextClassRef") {
202 const char* ref = session->getAuthnContextClassRef();
203 if (ref && m_vals.find(ref) != m_vals.end()) {
204 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextClassRef (") + ref + "), authz granted");
205 return shib_acl_true;
207 return shib_acl_false;
209 else if (m_alias == "authnContextDeclRef") {
210 const char* ref = session->getAuthnContextDeclRef();
211 if (ref && m_vals.find(ref) != m_vals.end()) {
212 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextDeclRef (") + ref + "), authz granted");
213 return shib_acl_true;
215 return shib_acl_false;
218 // Find the attribute(s) matching the require rule.
219 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> attrs =
220 session->getIndexedAttributes().equal_range(m_alias);
221 if (attrs.first == attrs.second) {
222 request.log(SPRequest::SPWarn, string("rule requires attribute (") + m_alias + "), not found in session");
223 return shib_acl_false;
225 else if (m_vals.empty()) {
226 request.log(SPRequest::SPDebug, string("AccessControl plugin requires presence of attribute (") + m_alias + "), authz granted");
227 return shib_acl_true;
230 for (; attrs.first != attrs.second; ++attrs.first) {
231 bool caseSensitive = attrs.first->second->isCaseSensitive();
233 // Now we have to intersect the attribute's values against the rule's list.
234 const vector<string>& vals = attrs.first->second->getSerializedValues();
235 for (set<string>::const_iterator i = m_vals.begin(); i != m_vals.end(); ++i) {
236 for (vector<string>::const_iterator j = vals.begin(); j != vals.end(); ++j) {
237 if ((caseSensitive && *i == *j) || (!caseSensitive && !strcasecmp(i->c_str(),j->c_str()))) {
238 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting (") + *j + "), authz granted");
239 return shib_acl_true;
245 return shib_acl_false;
248 RuleRegex::RuleRegex(const DOMElement* e)
249 : m_alias(XMLHelper::getAttrString(e, nullptr, require)),
250 m_exp(toUTF8(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : nullptr))
252 if (m_alias.empty() || !m_exp.get() || !*m_exp.get())
253 throw ConfigurationException("Access control rule missing require attribute or element content.");
255 bool ignore = XMLHelper::getAttrBool(e, false, ignoreCase);
257 m_re.reset(new RegularExpression(e->getFirstChild()->getNodeValue(), (ignore ? ignoreOption : &chNull)));
259 catch (XMLException& ex) {
260 auto_ptr_char tmp(ex.getMessage());
261 throw ConfigurationException("Caught exception while parsing RuleRegex regular expression: $1", params(1,tmp.get()));
265 AccessControl::aclresult_t RuleRegex::authorized(const SPRequest& request, const Session* session) const
267 // Map alias in rule to the attribute.
269 request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
270 return shib_acl_false;
273 if (m_alias == "valid-user") {
275 request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
276 return shib_acl_true;
278 return shib_acl_false;
282 if (m_alias == "user") {
283 if (m_re->matches(request.getRemoteUser().c_str())) {
284 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting REMOTE_USER (") + m_exp.get() + "), authz granted");
285 return shib_acl_true;
287 return shib_acl_false;
289 else if (m_alias == "authnContextClassRef") {
290 if (session->getAuthnContextClassRef() && m_re->matches(session->getAuthnContextClassRef())) {
291 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextClassRef (") + m_exp.get() + "), authz granted");
292 return shib_acl_true;
294 return shib_acl_false;
296 else if (m_alias == "authnContextDeclRef") {
297 if (session->getAuthnContextDeclRef() && m_re->matches(session->getAuthnContextDeclRef())) {
298 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextDeclRef (") + m_exp.get() + "), authz granted");
299 return shib_acl_true;
301 return shib_acl_false;
304 // Find the attribute(s) matching the require rule.
305 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> attrs =
306 session->getIndexedAttributes().equal_range(m_alias);
307 if (attrs.first == attrs.second) {
308 request.log(SPRequest::SPWarn, string("rule requires attribute (") + m_alias + "), not found in session");
309 return shib_acl_false;
312 for (; attrs.first != attrs.second; ++attrs.first) {
313 // Now we have to intersect the attribute's values against the regular expression.
314 const vector<string>& vals = attrs.first->second->getSerializedValues();
315 for (vector<string>::const_iterator j = vals.begin(); j != vals.end(); ++j) {
316 if (m_re->matches(j->c_str())) {
317 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting (") + m_exp.get() + "), authz granted");
318 return shib_acl_true;
323 catch (XMLException& ex) {
324 auto_ptr_char tmp(ex.getMessage());
325 request.log(SPRequest::SPError, string("caught exception while parsing RuleRegex regular expression: ") + tmp.get());
328 return shib_acl_false;
331 Operator::Operator(const DOMElement* e)
333 if (XMLString::equals(e->getLocalName(),NOT))
335 else if (XMLString::equals(e->getLocalName(),AND))
337 else if (XMLString::equals(e->getLocalName(),OR))
340 throw ConfigurationException("Unrecognized operator in access control rule");
342 e=XMLHelper::getFirstChildElement(e);
343 if (XMLString::equals(e->getLocalName(),_Rule))
344 m_operands.push_back(new Rule(e));
345 else if (XMLString::equals(e->getLocalName(),_RuleRegex))
346 m_operands.push_back(new RuleRegex(e));
348 m_operands.push_back(new Operator(e));
353 e=XMLHelper::getNextSiblingElement(e);
355 if (XMLString::equals(e->getLocalName(),_Rule))
356 m_operands.push_back(new Rule(e));
357 else if (XMLString::equals(e->getLocalName(),_RuleRegex))
358 m_operands.push_back(new RuleRegex(e));
360 m_operands.push_back(new Operator(e));
361 e=XMLHelper::getNextSiblingElement(e);
365 AccessControl::aclresult_t Operator::authorized(const SPRequest& request, const Session* session) const
369 switch (m_operands.front().authorized(request,session)) {
371 return shib_acl_false;
373 return shib_acl_true;
375 return shib_acl_indeterminate;
380 // Look for a rule that returns non-true.
381 for (ptr_vector<AccessControl>::const_iterator i = m_operands.begin(); i != m_operands.end(); ++i) {
382 if (i->authorized(request,session) != shib_acl_true)
383 return shib_acl_false;
385 return shib_acl_true;
387 ptr_vector<AccessControl>::const_iterator i = find_if(
388 m_operands.begin(), m_operands.end(),
389 boost::bind(&AccessControl::authorized, _1, boost::cref(request), session) != shib_acl_true
391 return (i != m_operands.end()) ? shib_acl_false : shib_acl_true;
396 // Look for a rule that returns true.
397 ptr_vector<AccessControl>::const_iterator i = find_if(
398 m_operands.begin(), m_operands.end(),
399 boost::bind(&AccessControl::authorized, _1, boost::cref(request), session) == shib_acl_true
401 return (i != m_operands.end()) ? shib_acl_true : shib_acl_false;
404 request.log(SPRequest::SPWarn,"unknown operation in access control policy, denying access");
405 return shib_acl_false;
408 pair<bool,DOMElement*> XMLAccessControl::background_load()
410 // Load from source using base class.
411 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
413 // If we own it, wrap it.
414 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
416 // Check for AccessControl wrapper and drop a level.
417 if (XMLString::equals(raw.second->getLocalName(),_AccessControl)) {
418 raw.second = XMLHelper::getFirstChildElement(raw.second);
420 throw ConfigurationException("No child element found in AccessControl parent element.");
422 else if (XMLString::equals(raw.second->getLocalName(),_Handler)) {
423 raw.second = XMLHelper::getFirstChildElement(raw.second);
425 throw ConfigurationException("No child element found in Handler parent element.");
428 scoped_ptr<AccessControl> authz;
429 if (XMLString::equals(raw.second->getLocalName(),_Rule))
430 authz.reset(new Rule(raw.second));
431 else if (XMLString::equals(raw.second->getLocalName(),_RuleRegex))
432 authz.reset(new RuleRegex(raw.second));
434 authz.reset(new Operator(raw.second));
436 // Perform the swap inside a lock.
439 SharedLock locker(m_lock, false);
440 m_rootAuthz.swap(authz);
442 return make_pair(false,(DOMElement*)nullptr);
445 AccessControl::aclresult_t XMLAccessControl::authorized(const SPRequest& request, const Session* session) const
447 return m_rootAuthz ? m_rootAuthz->authorized(request,session) : shib_acl_false;