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());
172 split(m_vals, temp, boost::is_space(), algorithm::token_compress_on);
174 throw ConfigurationException("Rule did not contain any usable values.");
177 AccessControl::aclresult_t Rule::authorized(const SPRequest& request, const Session* session) const
179 // We can make this more complex later using pluggable comparison functions,
180 // but for now, just a straight port to the new Attribute API.
182 // Map alias in rule to the attribute.
184 request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
185 return shib_acl_false;
188 if (m_alias == "valid-user") {
190 request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
191 return shib_acl_true;
193 return shib_acl_false;
195 if (m_alias == "user") {
196 if (m_vals.find(request.getRemoteUser()) != m_vals.end()) {
197 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting REMOTE_USER (") + request.getRemoteUser() + "), authz granted");
198 return shib_acl_true;
200 return shib_acl_false;
202 else if (m_alias == "authnContextClassRef") {
203 const char* ref = session->getAuthnContextClassRef();
204 if (ref && m_vals.find(ref) != m_vals.end()) {
205 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextClassRef (") + ref + "), authz granted");
206 return shib_acl_true;
208 return shib_acl_false;
210 else if (m_alias == "authnContextDeclRef") {
211 const char* ref = session->getAuthnContextDeclRef();
212 if (ref && m_vals.find(ref) != m_vals.end()) {
213 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextDeclRef (") + ref + "), authz granted");
214 return shib_acl_true;
216 return shib_acl_false;
219 // Find the attribute(s) matching the require rule.
220 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> attrs =
221 session->getIndexedAttributes().equal_range(m_alias);
222 if (attrs.first == attrs.second) {
223 request.log(SPRequest::SPWarn, string("rule requires attribute (") + m_alias + "), not found in session");
224 return shib_acl_false;
226 else if (m_vals.empty()) {
227 request.log(SPRequest::SPDebug, string("AccessControl plugin requires presence of attribute (") + m_alias + "), authz granted");
228 return shib_acl_true;
231 for (; attrs.first != attrs.second; ++attrs.first) {
232 bool caseSensitive = attrs.first->second->isCaseSensitive();
234 // Now we have to intersect the attribute's values against the rule's list.
235 const vector<string>& vals = attrs.first->second->getSerializedValues();
236 for (set<string>::const_iterator i = m_vals.begin(); i != m_vals.end(); ++i) {
237 for (vector<string>::const_iterator j = vals.begin(); j != vals.end(); ++j) {
238 if ((caseSensitive && *i == *j) || (!caseSensitive && !strcasecmp(i->c_str(),j->c_str()))) {
239 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting (") + *j + "), authz granted");
240 return shib_acl_true;
246 return shib_acl_false;
249 RuleRegex::RuleRegex(const DOMElement* e)
250 : m_alias(XMLHelper::getAttrString(e, nullptr, require)),
251 m_exp(toUTF8(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : nullptr))
253 if (m_alias.empty() || !m_exp.get() || !*m_exp.get())
254 throw ConfigurationException("Access control rule missing require attribute or element content.");
256 bool ignore = XMLHelper::getAttrBool(e, false, ignoreCase);
258 m_re.reset(new RegularExpression(e->getFirstChild()->getNodeValue(), (ignore ? ignoreOption : &chNull)));
260 catch (XMLException& ex) {
261 auto_ptr_char tmp(ex.getMessage());
262 throw ConfigurationException("Caught exception while parsing RuleRegex regular expression: $1", params(1,tmp.get()));
266 AccessControl::aclresult_t RuleRegex::authorized(const SPRequest& request, const Session* session) const
268 // Map alias in rule to the attribute.
270 request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
271 return shib_acl_false;
274 if (m_alias == "valid-user") {
276 request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
277 return shib_acl_true;
279 return shib_acl_false;
283 if (m_alias == "user") {
284 if (m_re->matches(request.getRemoteUser().c_str())) {
285 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting REMOTE_USER (") + m_exp.get() + "), authz granted");
286 return shib_acl_true;
288 return shib_acl_false;
290 else if (m_alias == "authnContextClassRef") {
291 if (session->getAuthnContextClassRef() && m_re->matches(session->getAuthnContextClassRef())) {
292 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextClassRef (") + m_exp.get() + "), authz granted");
293 return shib_acl_true;
295 return shib_acl_false;
297 else if (m_alias == "authnContextDeclRef") {
298 if (session->getAuthnContextDeclRef() && m_re->matches(session->getAuthnContextDeclRef())) {
299 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextDeclRef (") + m_exp.get() + "), authz granted");
300 return shib_acl_true;
302 return shib_acl_false;
305 // Find the attribute(s) matching the require rule.
306 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> attrs =
307 session->getIndexedAttributes().equal_range(m_alias);
308 if (attrs.first == attrs.second) {
309 request.log(SPRequest::SPWarn, string("rule requires attribute (") + m_alias + "), not found in session");
310 return shib_acl_false;
313 for (; attrs.first != attrs.second; ++attrs.first) {
314 // Now we have to intersect the attribute's values against the regular expression.
315 const vector<string>& vals = attrs.first->second->getSerializedValues();
316 for (vector<string>::const_iterator j = vals.begin(); j != vals.end(); ++j) {
317 if (m_re->matches(j->c_str())) {
318 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting (") + m_exp.get() + "), authz granted");
319 return shib_acl_true;
324 catch (XMLException& ex) {
325 auto_ptr_char tmp(ex.getMessage());
326 request.log(SPRequest::SPError, string("caught exception while parsing RuleRegex regular expression: ") + tmp.get());
329 return shib_acl_false;
332 Operator::Operator(const DOMElement* e)
334 if (XMLString::equals(e->getLocalName(),NOT))
336 else if (XMLString::equals(e->getLocalName(),AND))
338 else if (XMLString::equals(e->getLocalName(),OR))
341 throw ConfigurationException("Unrecognized operator in access control rule");
343 e=XMLHelper::getFirstChildElement(e);
344 if (XMLString::equals(e->getLocalName(),_Rule))
345 m_operands.push_back(new Rule(e));
346 else if (XMLString::equals(e->getLocalName(),_RuleRegex))
347 m_operands.push_back(new RuleRegex(e));
349 m_operands.push_back(new Operator(e));
354 e=XMLHelper::getNextSiblingElement(e);
356 if (XMLString::equals(e->getLocalName(),_Rule))
357 m_operands.push_back(new Rule(e));
358 else if (XMLString::equals(e->getLocalName(),_RuleRegex))
359 m_operands.push_back(new RuleRegex(e));
361 m_operands.push_back(new Operator(e));
362 e=XMLHelper::getNextSiblingElement(e);
366 AccessControl::aclresult_t Operator::authorized(const SPRequest& request, const Session* session) const
370 switch (m_operands.front().authorized(request,session)) {
372 return shib_acl_false;
374 return shib_acl_true;
376 return shib_acl_indeterminate;
381 // Look for a rule that returns non-true.
382 for (ptr_vector<AccessControl>::const_iterator i = m_operands.begin(); i != m_operands.end(); ++i) {
383 if (i->authorized(request,session) != shib_acl_true)
384 return shib_acl_false;
386 return shib_acl_true;
388 ptr_vector<AccessControl>::const_iterator i = find_if(
389 m_operands.begin(), m_operands.end(),
390 boost::bind(&AccessControl::authorized, _1, boost::cref(request), session) != shib_acl_true
392 return (i != m_operands.end()) ? shib_acl_false : shib_acl_true;
397 // Look for a rule that returns true.
398 ptr_vector<AccessControl>::const_iterator i = find_if(
399 m_operands.begin(), m_operands.end(),
400 boost::bind(&AccessControl::authorized, _1, boost::cref(request), session) == shib_acl_true
402 return (i != m_operands.end()) ? shib_acl_true : shib_acl_false;
405 request.log(SPRequest::SPWarn,"unknown operation in access control policy, denying access");
406 return shib_acl_false;
409 pair<bool,DOMElement*> XMLAccessControl::background_load()
411 // Load from source using base class.
412 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
414 // If we own it, wrap it.
415 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
417 // Check for AccessControl wrapper and drop a level.
418 if (XMLString::equals(raw.second->getLocalName(),_AccessControl)) {
419 raw.second = XMLHelper::getFirstChildElement(raw.second);
421 throw ConfigurationException("No child element found in AccessControl parent element.");
423 else if (XMLString::equals(raw.second->getLocalName(),_Handler)) {
424 raw.second = XMLHelper::getFirstChildElement(raw.second);
426 throw ConfigurationException("No child element found in Handler parent element.");
429 scoped_ptr<AccessControl> authz;
430 if (XMLString::equals(raw.second->getLocalName(),_Rule))
431 authz.reset(new Rule(raw.second));
432 else if (XMLString::equals(raw.second->getLocalName(),_RuleRegex))
433 authz.reset(new RuleRegex(raw.second));
435 authz.reset(new Operator(raw.second));
437 // Perform the swap inside a lock.
440 SharedLock locker(m_lock, false);
441 m_rootAuthz.swap(authz);
443 return make_pair(false,(DOMElement*)nullptr);
446 AccessControl::aclresult_t XMLAccessControl::authorized(const SPRequest& request, const Session* session) const
448 return m_rootAuthz ? m_rootAuthz->authorized(request,session) : shib_acl_false;