e14a6644c3305b0301ca9aadf753bf7b8f1e48e8
[shibboleth/cpp-sp.git] / shibsp / impl / XMLAccessControl.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  * XMLAccessControl.cpp
23  *
24  * XML-based access control syntax.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "AccessControl.h"
30 #include "SessionCache.h"
31 #include "SPRequest.h"
32 #include "attribute/Attribute.h"
33
34 #include <algorithm>
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>
44
45 #ifndef HAVE_STRCASECMP
46 # define strcasecmp _stricmp
47 #endif
48
49 using namespace shibsp;
50 using namespace xmltooling;
51 using namespace boost;
52 using namespace std;
53
54 namespace shibsp {
55
56     class Rule : public AccessControl
57     {
58     public:
59         Rule(const DOMElement* e);
60         ~Rule() {}
61
62         Lockable* lock() {return this;}
63         void unlock() {}
64
65         aclresult_t authorized(const SPRequest& request, const Session* session) const;
66
67     private:
68         string m_alias;
69         set <string> m_vals;
70     };
71
72     class RuleRegex : public AccessControl
73     {
74     public:
75         RuleRegex(const DOMElement* e);
76         ~RuleRegex() {}
77
78         Lockable* lock() {return this;}
79         void unlock() {}
80
81         aclresult_t authorized(const SPRequest& request, const Session* session) const;
82
83     private:
84         string m_alias;
85         auto_arrayptr<char> m_exp;
86         scoped_ptr<RegularExpression> m_re;
87     };
88
89     class Operator : public AccessControl
90     {
91     public:
92         Operator(const DOMElement* e);
93         ~Operator() {}
94
95         Lockable* lock() {return this;}
96         void unlock() {}
97
98         aclresult_t authorized(const SPRequest& request, const Session* session) const;
99
100     private:
101         enum operator_t { OP_NOT, OP_AND, OP_OR } m_op;
102         ptr_vector<AccessControl> m_operands;
103     };
104
105 #if defined (_MSC_VER)
106     #pragma warning( push )
107     #pragma warning( disable : 4250 )
108 #endif
109
110     class XMLAccessControl : public AccessControl, public ReloadableXMLFile
111     {
112     public:
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
116         }
117
118         ~XMLAccessControl() {
119             shutdown();
120         }
121
122         aclresult_t authorized(const SPRequest& request, const Session* session) const;
123
124     protected:
125         pair<bool,DOMElement*> background_load();
126
127     private:
128         scoped_ptr<AccessControl> m_rootAuthz;
129     };
130
131 #if defined (_MSC_VER)
132     #pragma warning( pop )
133 #endif
134
135     AccessControl* SHIBSP_DLLLOCAL XMLAccessControlFactory(const DOMElement* const & e)
136     {
137         return new XMLAccessControl(e);
138     }
139
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);
151 }
152
153 Rule::Rule(const DOMElement* e) : m_alias(XMLHelper::getAttrString(e, nullptr, require))
154 {
155     if (m_alias.empty())
156         throw ConfigurationException("Access control rule missing require attribute");
157     if (!e->hasChildNodes())
158         return; // empty rule
159
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.");
163
164     bool listflag = XMLHelper::getAttrBool(e, true, _list);
165     if (!listflag) {
166         m_vals.insert(vals.get());
167         return;
168     }
169
170     string temp(vals.get());
171     trim(temp);
172     split(m_vals, temp, boost::is_space(), algorithm::token_compress_on);
173     if (m_vals.empty())
174         throw ConfigurationException("Rule did not contain any usable values.");
175 }
176
177 AccessControl::aclresult_t Rule::authorized(const SPRequest& request, const Session* session) const
178 {
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.
181
182     // Map alias in rule to the attribute.
183     if (!session) {
184         request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
185         return shib_acl_false;
186     }
187
188     if (m_alias == "valid-user") {
189         if (session) {
190             request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
191             return shib_acl_true;
192         }
193         return shib_acl_false;
194     }
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;
199         }
200         return shib_acl_false;
201     }
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;
207         }
208         return shib_acl_false;
209     }
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;
215         }
216         return shib_acl_false;
217     }
218
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;
225     }
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;
229     }
230
231     for (; attrs.first != attrs.second; ++attrs.first) {
232         bool caseSensitive = attrs.first->second->isCaseSensitive();
233
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;
241                 }
242             }
243         }
244     }
245
246     return shib_acl_false;
247 }
248
249 RuleRegex::RuleRegex(const DOMElement* e)
250     : m_alias(XMLHelper::getAttrString(e, nullptr, require)),
251         m_exp(toUTF8(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : nullptr))
252 {
253     if (m_alias.empty() || !m_exp.get() || !*m_exp.get())
254         throw ConfigurationException("Access control rule missing require attribute or element content.");
255
256     bool ignore = XMLHelper::getAttrBool(e, false, ignoreCase);
257     try {
258         m_re.reset(new RegularExpression(e->getFirstChild()->getNodeValue(), (ignore ? ignoreOption : &chNull)));
259     }
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()));
263     }
264 }
265
266 AccessControl::aclresult_t RuleRegex::authorized(const SPRequest& request, const Session* session) const
267 {
268     // Map alias in rule to the attribute.
269     if (!session) {
270         request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
271         return shib_acl_false;
272     }
273
274     if (m_alias == "valid-user") {
275         if (session) {
276             request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
277             return shib_acl_true;
278         }
279         return shib_acl_false;
280     }
281
282     try {
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;
287             }
288             return shib_acl_false;
289         }
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;
294             }
295             return shib_acl_false;
296         }
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;
301             }
302             return shib_acl_false;
303         }
304
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;
311         }
312
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;
320                 }
321             }
322         }
323     }
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());
327     }
328
329     return shib_acl_false;
330 }
331
332 Operator::Operator(const DOMElement* e)
333 {
334     if (XMLString::equals(e->getLocalName(),NOT))
335         m_op=OP_NOT;
336     else if (XMLString::equals(e->getLocalName(),AND))
337         m_op=OP_AND;
338     else if (XMLString::equals(e->getLocalName(),OR))
339         m_op=OP_OR;
340     else
341         throw ConfigurationException("Unrecognized operator in access control rule");
342
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));
348     else
349         m_operands.push_back(new Operator(e));
350
351     if (m_op==OP_NOT)
352         return;
353
354     e=XMLHelper::getNextSiblingElement(e);
355     while (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));
360         else
361             m_operands.push_back(new Operator(e));
362         e=XMLHelper::getNextSiblingElement(e);
363     }
364 }
365
366 AccessControl::aclresult_t Operator::authorized(const SPRequest& request, const Session* session) const
367 {
368     switch (m_op) {
369         case OP_NOT:
370             switch (m_operands.front().authorized(request,session)) {
371                 case shib_acl_true:
372                     return shib_acl_false;
373                 case shib_acl_false:
374                     return shib_acl_true;
375                 default:
376                     return shib_acl_indeterminate;
377             }
378
379         case OP_AND:
380         {
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;
385             }
386             return shib_acl_true;
387
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
391                 );
392             return (i != m_operands.end()) ? shib_acl_false : shib_acl_true;
393         }
394
395         case OP_OR:
396         {
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
401                 );
402             return (i != m_operands.end()) ? shib_acl_true : shib_acl_false;
403         }
404     }
405     request.log(SPRequest::SPWarn,"unknown operation in access control policy, denying access");
406     return shib_acl_false;
407 }
408
409 pair<bool,DOMElement*> XMLAccessControl::background_load()
410 {
411     // Load from source using base class.
412     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
413
414     // If we own it, wrap it.
415     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
416
417     // Check for AccessControl wrapper and drop a level.
418     if (XMLString::equals(raw.second->getLocalName(),_AccessControl)) {
419         raw.second = XMLHelper::getFirstChildElement(raw.second);
420         if (!raw.second)
421             throw ConfigurationException("No child element found in AccessControl parent element.");
422     }
423     else if (XMLString::equals(raw.second->getLocalName(),_Handler)) {
424         raw.second = XMLHelper::getFirstChildElement(raw.second);
425         if (!raw.second)
426             throw ConfigurationException("No child element found in Handler parent element.");
427     }
428
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));
434     else
435         authz.reset(new Operator(raw.second));
436
437     // Perform the swap inside a lock.
438     if (m_lock)
439         m_lock->wrlock();
440     SharedLock locker(m_lock, false);
441     m_rootAuthz.swap(authz);
442
443     return make_pair(false,(DOMElement*)nullptr);
444 }
445
446 AccessControl::aclresult_t XMLAccessControl::authorized(const SPRequest& request, const Session* session) const
447 {
448     return m_rootAuthz ? m_rootAuthz->authorized(request,session) : shib_acl_false;
449 }