dc9622562710a3d41b54f96f3db4d6fe32f2d7ba
[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     split(m_vals, temp, boost::is_space(), algorithm::token_compress_on);
172     if (m_vals.empty())
173         throw ConfigurationException("Rule did not contain any usable values.");
174 }
175
176 AccessControl::aclresult_t Rule::authorized(const SPRequest& request, const Session* session) const
177 {
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.
180
181     // Map alias in rule to the attribute.
182     if (!session) {
183         request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
184         return shib_acl_false;
185     }
186
187     if (m_alias == "valid-user") {
188         if (session) {
189             request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
190             return shib_acl_true;
191         }
192         return shib_acl_false;
193     }
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;
198         }
199         return shib_acl_false;
200     }
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;
206         }
207         return shib_acl_false;
208     }
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;
214         }
215         return shib_acl_false;
216     }
217
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;
224     }
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;
228     }
229
230     for (; attrs.first != attrs.second; ++attrs.first) {
231         bool caseSensitive = attrs.first->second->isCaseSensitive();
232
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;
240                 }
241             }
242         }
243     }
244
245     return shib_acl_false;
246 }
247
248 RuleRegex::RuleRegex(const DOMElement* e)
249     : m_alias(XMLHelper::getAttrString(e, nullptr, require)),
250         m_exp(toUTF8(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : nullptr))
251 {
252     if (m_alias.empty() || !m_exp.get() || !*m_exp.get())
253         throw ConfigurationException("Access control rule missing require attribute or element content.");
254
255     bool ignore = XMLHelper::getAttrBool(e, false, ignoreCase);
256     try {
257         m_re.reset(new RegularExpression(e->getFirstChild()->getNodeValue(), (ignore ? ignoreOption : &chNull)));
258     }
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()));
262     }
263 }
264
265 AccessControl::aclresult_t RuleRegex::authorized(const SPRequest& request, const Session* session) const
266 {
267     // Map alias in rule to the attribute.
268     if (!session) {
269         request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
270         return shib_acl_false;
271     }
272
273     if (m_alias == "valid-user") {
274         if (session) {
275             request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
276             return shib_acl_true;
277         }
278         return shib_acl_false;
279     }
280
281     try {
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;
286             }
287             return shib_acl_false;
288         }
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;
293             }
294             return shib_acl_false;
295         }
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;
300             }
301             return shib_acl_false;
302         }
303
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;
310         }
311
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;
319                 }
320             }
321         }
322     }
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());
326     }
327
328     return shib_acl_false;
329 }
330
331 Operator::Operator(const DOMElement* e)
332 {
333     if (XMLString::equals(e->getLocalName(),NOT))
334         m_op=OP_NOT;
335     else if (XMLString::equals(e->getLocalName(),AND))
336         m_op=OP_AND;
337     else if (XMLString::equals(e->getLocalName(),OR))
338         m_op=OP_OR;
339     else
340         throw ConfigurationException("Unrecognized operator in access control rule");
341
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));
347     else
348         m_operands.push_back(new Operator(e));
349
350     if (m_op==OP_NOT)
351         return;
352
353     e=XMLHelper::getNextSiblingElement(e);
354     while (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));
359         else
360             m_operands.push_back(new Operator(e));
361         e=XMLHelper::getNextSiblingElement(e);
362     }
363 }
364
365 AccessControl::aclresult_t Operator::authorized(const SPRequest& request, const Session* session) const
366 {
367     switch (m_op) {
368         case OP_NOT:
369             switch (m_operands.front().authorized(request,session)) {
370                 case shib_acl_true:
371                     return shib_acl_false;
372                 case shib_acl_false:
373                     return shib_acl_true;
374                 default:
375                     return shib_acl_indeterminate;
376             }
377
378         case OP_AND:
379         {
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;
384             }
385             return shib_acl_true;
386
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
390                 );
391             return (i != m_operands.end()) ? shib_acl_false : shib_acl_true;
392         }
393
394         case OP_OR:
395         {
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
400                 );
401             return (i != m_operands.end()) ? shib_acl_true : shib_acl_false;
402         }
403     }
404     request.log(SPRequest::SPWarn,"unknown operation in access control policy, denying access");
405     return shib_acl_false;
406 }
407
408 pair<bool,DOMElement*> XMLAccessControl::background_load()
409 {
410     // Load from source using base class.
411     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
412
413     // If we own it, wrap it.
414     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
415
416     // Check for AccessControl wrapper and drop a level.
417     if (XMLString::equals(raw.second->getLocalName(),_AccessControl)) {
418         raw.second = XMLHelper::getFirstChildElement(raw.second);
419         if (!raw.second)
420             throw ConfigurationException("No child element found in AccessControl parent element.");
421     }
422     else if (XMLString::equals(raw.second->getLocalName(),_Handler)) {
423         raw.second = XMLHelper::getFirstChildElement(raw.second);
424         if (!raw.second)
425             throw ConfigurationException("No child element found in Handler parent element.");
426     }
427
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));
433     else
434         authz.reset(new Operator(raw.second));
435
436     // Perform the swap inside a lock.
437     if (m_lock)
438         m_lock->wrlock();
439     SharedLock locker(m_lock, false);
440     m_rootAuthz.swap(authz);
441
442     return make_pair(false,(DOMElement*)nullptr);
443 }
444
445 AccessControl::aclresult_t XMLAccessControl::authorized(const SPRequest& request, const Session* session) const
446 {
447     return m_rootAuthz ? m_rootAuthz->authorized(request,session) : shib_acl_false;
448 }