059ab09e2d787ef380b83f39862637cc15da3a43
[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/scoped_ptr.hpp>
36 #include <boost/bind.hpp>
37 #include <boost/algorithm/string.hpp>
38 #include <boost/ptr_container/ptr_vector.hpp>
39 #include <xmltooling/unicode.h>
40 #include <xmltooling/util/ReloadableXMLFile.h>
41 #include <xmltooling/util/Threads.h>
42 #include <xmltooling/util/XMLHelper.h>
43 #include <xercesc/util/XMLUniDefs.hpp>
44 #include <xercesc/util/regx/RegularExpression.hpp>
45
46 #ifndef HAVE_STRCASECMP
47 # define strcasecmp _stricmp
48 #endif
49
50 using namespace shibsp;
51 using namespace xmltooling;
52 using namespace boost;
53 using namespace std;
54
55 namespace shibsp {
56
57     class Rule : public AccessControl
58     {
59     public:
60         Rule(const DOMElement* e);
61         ~Rule() {}
62
63         Lockable* lock() {return this;}
64         void unlock() {}
65
66         aclresult_t authorized(const SPRequest& request, const Session* session) const;
67
68     private:
69         string m_alias;
70         set <string> m_vals;
71     };
72
73     class RuleRegex : public AccessControl
74     {
75     public:
76         RuleRegex(const DOMElement* e);
77         ~RuleRegex() {}
78
79         Lockable* lock() {return this;}
80         void unlock() {}
81
82         aclresult_t authorized(const SPRequest& request, const Session* session) const;
83
84     private:
85         string m_alias;
86         auto_arrayptr<char> m_exp;
87         scoped_ptr<RegularExpression> m_re;
88     };
89
90     class Operator : public AccessControl
91     {
92     public:
93         Operator(const DOMElement* e);
94         ~Operator() {}
95
96         Lockable* lock() {return this;}
97         void unlock() {}
98
99         aclresult_t authorized(const SPRequest& request, const Session* session) const;
100
101     private:
102         enum operator_t { OP_NOT, OP_AND, OP_OR } m_op;
103         ptr_vector<AccessControl> m_operands;
104     };
105
106 #if defined (_MSC_VER)
107     #pragma warning( push )
108     #pragma warning( disable : 4250 )
109 #endif
110
111     class XMLAccessControl : public AccessControl, public ReloadableXMLFile
112     {
113     public:
114         XMLAccessControl(const DOMElement* e)
115                 : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AccessControl.XML")) {
116             background_load(); // guarantees an exception or the policy is loaded
117         }
118
119         ~XMLAccessControl() {
120             shutdown();
121         }
122
123         aclresult_t authorized(const SPRequest& request, const Session* session) const;
124
125     protected:
126         pair<bool,DOMElement*> background_load();
127
128     private:
129         scoped_ptr<AccessControl> m_rootAuthz;
130     };
131
132 #if defined (_MSC_VER)
133     #pragma warning( pop )
134 #endif
135
136     AccessControl* SHIBSP_DLLLOCAL XMLAccessControlFactory(const DOMElement* const & e)
137     {
138         return new XMLAccessControl(e);
139     }
140
141     static const XMLCh _AccessControl[] =   UNICODE_LITERAL_13(A,c,c,e,s,s,C,o,n,t,r,o,l);
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
158     auto_arrayptr<char> vals(toUTF8(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : nullptr));
159     if (!vals.get())
160         return;
161
162     bool listflag = XMLHelper::getAttrBool(e, true, _list);
163     if (!listflag) {
164         if (*vals.get())
165             m_vals.insert(vals.get());
166         return;
167     }
168
169     string temp(vals.get());
170     split(m_vals, temp, boost::is_space(), algorithm::token_compress_on);
171 }
172
173 AccessControl::aclresult_t Rule::authorized(const SPRequest& request, const Session* session) const
174 {
175     // We can make this more complex later using pluggable comparison functions,
176     // but for now, just a straight port to the new Attribute API.
177
178     // Map alias in rule to the attribute.
179     if (!session) {
180         request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
181         return shib_acl_false;
182     }
183
184     if (m_alias == "valid-user") {
185         if (session) {
186             request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
187             return shib_acl_true;
188         }
189         return shib_acl_false;
190     }
191     if (m_alias == "user") {
192         if (m_vals.find(request.getRemoteUser()) != m_vals.end()) {
193             request.log(SPRequest::SPDebug, string("AccessControl plugin expecting REMOTE_USER (") + request.getRemoteUser() + "), authz granted");
194             return shib_acl_true;
195         }
196         return shib_acl_false;
197     }
198     else if (m_alias == "authnContextClassRef") {
199         const char* ref = session->getAuthnContextClassRef();
200         if (ref && m_vals.find(ref) != m_vals.end()) {
201             request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextClassRef (") + ref + "), authz granted");
202             return shib_acl_true;
203         }
204         return shib_acl_false;
205     }
206     else if (m_alias == "authnContextDeclRef") {
207         const char* ref = session->getAuthnContextDeclRef();
208         if (ref && m_vals.find(ref) != m_vals.end()) {
209             request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextDeclRef (") + ref + "), authz granted");
210             return shib_acl_true;
211         }
212         return shib_acl_false;
213     }
214
215     // Find the attribute(s) matching the require rule.
216     pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> attrs =
217         session->getIndexedAttributes().equal_range(m_alias);
218     if (attrs.first == attrs.second) {
219         request.log(SPRequest::SPWarn, string("rule requires attribute (") + m_alias + "), not found in session");
220         return shib_acl_false;
221     }
222
223     for (; attrs.first != attrs.second; ++attrs.first) {
224         bool caseSensitive = attrs.first->second->isCaseSensitive();
225
226         // Now we have to intersect the attribute's values against the rule's list.
227         const vector<string>& vals = attrs.first->second->getSerializedValues();
228         for (set<string>::const_iterator i = m_vals.begin(); i != m_vals.end(); ++i) {
229             for (vector<string>::const_iterator j = vals.begin(); j != vals.end(); ++j) {
230                 if ((caseSensitive && *i == *j) || (!caseSensitive && !strcasecmp(i->c_str(),j->c_str()))) {
231                     request.log(SPRequest::SPDebug, string("AccessControl plugin expecting (") + *j + "), authz granted");
232                     return shib_acl_true;
233                 }
234             }
235         }
236     }
237
238     return shib_acl_false;
239 }
240
241 RuleRegex::RuleRegex(const DOMElement* e)
242     : m_alias(XMLHelper::getAttrString(e, nullptr, require)),
243         m_exp(toUTF8(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : nullptr))
244 {
245     if (m_alias.empty() || !m_exp.get() || !*m_exp.get())
246         throw ConfigurationException("Access control rule missing require attribute or element content.");
247
248     bool ignore = XMLHelper::getAttrBool(e, false, ignoreCase);
249     try {
250         m_re.reset(new RegularExpression(e->getFirstChild()->getNodeValue(), (ignore ? ignoreOption : &chNull)));
251     }
252     catch (XMLException& ex) {
253         auto_ptr_char tmp(ex.getMessage());
254         throw ConfigurationException("Caught exception while parsing RuleRegex regular expression: $1", params(1,tmp.get()));
255     }
256 }
257
258 AccessControl::aclresult_t RuleRegex::authorized(const SPRequest& request, const Session* session) const
259 {
260     // Map alias in rule to the attribute.
261     if (!session) {
262         request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");
263         return shib_acl_false;
264     }
265
266     if (m_alias == "valid-user") {
267         if (session) {
268             request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");
269             return shib_acl_true;
270         }
271         return shib_acl_false;
272     }
273
274     try {
275         if (m_alias == "user") {
276             if (m_re->matches(request.getRemoteUser().c_str())) {
277                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting REMOTE_USER (") + m_exp.get() + "), authz granted");
278                 return shib_acl_true;
279             }
280             return shib_acl_false;
281         }
282         else if (m_alias == "authnContextClassRef") {
283             if (session->getAuthnContextClassRef() && m_re->matches(session->getAuthnContextClassRef())) {
284                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextClassRef (") + m_exp.get() + "), authz granted");
285                 return shib_acl_true;
286             }
287             return shib_acl_false;
288         }
289         else if (m_alias == "authnContextDeclRef") {
290             if (session->getAuthnContextDeclRef() && m_re->matches(session->getAuthnContextDeclRef())) {
291                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextDeclRef (") + m_exp.get() + "), authz granted");
292                 return shib_acl_true;
293             }
294             return shib_acl_false;
295         }
296
297         // Find the attribute(s) matching the require rule.
298         pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> attrs =
299             session->getIndexedAttributes().equal_range(m_alias);
300         if (attrs.first == attrs.second) {
301             request.log(SPRequest::SPWarn, string("rule requires attribute (") + m_alias + "), not found in session");
302             return shib_acl_false;
303         }
304
305         for (; attrs.first != attrs.second; ++attrs.first) {
306             // Now we have to intersect the attribute's values against the regular expression.
307             const vector<string>& vals = attrs.first->second->getSerializedValues();
308             for (vector<string>::const_iterator j = vals.begin(); j != vals.end(); ++j) {
309                 if (m_re->matches(j->c_str())) {
310                     request.log(SPRequest::SPDebug, string("AccessControl plugin expecting (") + m_exp.get() + "), authz granted");
311                     return shib_acl_true;
312                 }
313             }
314         }
315     }
316     catch (XMLException& ex) {
317         auto_ptr_char tmp(ex.getMessage());
318         request.log(SPRequest::SPError, string("caught exception while parsing RuleRegex regular expression: ") + tmp.get());
319     }
320
321     return shib_acl_false;
322 }
323
324 Operator::Operator(const DOMElement* e)
325 {
326     if (XMLString::equals(e->getLocalName(),NOT))
327         m_op=OP_NOT;
328     else if (XMLString::equals(e->getLocalName(),AND))
329         m_op=OP_AND;
330     else if (XMLString::equals(e->getLocalName(),OR))
331         m_op=OP_OR;
332     else
333         throw ConfigurationException("Unrecognized operator in access control rule");
334
335     e=XMLHelper::getFirstChildElement(e);
336     if (XMLString::equals(e->getLocalName(),_Rule))
337         m_operands.push_back(new Rule(e));
338     else if (XMLString::equals(e->getLocalName(),_RuleRegex))
339         m_operands.push_back(new RuleRegex(e));
340     else
341         m_operands.push_back(new Operator(e));
342
343     if (m_op==OP_NOT)
344         return;
345
346     e=XMLHelper::getNextSiblingElement(e);
347     while (e) {
348         if (XMLString::equals(e->getLocalName(),_Rule))
349             m_operands.push_back(new Rule(e));
350         else if (XMLString::equals(e->getLocalName(),_RuleRegex))
351             m_operands.push_back(new RuleRegex(e));
352         else
353             m_operands.push_back(new Operator(e));
354         e=XMLHelper::getNextSiblingElement(e);
355     }
356 }
357
358 AccessControl::aclresult_t Operator::authorized(const SPRequest& request, const Session* session) const
359 {
360     switch (m_op) {
361         case OP_NOT:
362             switch (m_operands.front().authorized(request,session)) {
363                 case shib_acl_true:
364                     return shib_acl_false;
365                 case shib_acl_false:
366                     return shib_acl_true;
367                 default:
368                     return shib_acl_indeterminate;
369             }
370
371         case OP_AND:
372         {
373             // Look for a rule that returns non-true.
374             for (ptr_vector<AccessControl>::const_iterator i = m_operands.begin(); i != m_operands.end(); ++i) {
375                 if (i->authorized(request,session) != shib_acl_true)
376                     return shib_acl_false;
377             }
378             return shib_acl_true;
379
380             ptr_vector<AccessControl>::const_iterator i = find_if(
381                 m_operands.begin(), m_operands.end(),
382                 boost::bind(&AccessControl::authorized, _1, boost::cref(request), session) != shib_acl_true
383                 );
384             return (i != m_operands.end()) ? shib_acl_false : shib_acl_true;
385         }
386
387         case OP_OR:
388         {
389             // Look for a rule that returns true.
390             ptr_vector<AccessControl>::const_iterator i = find_if(
391                 m_operands.begin(), m_operands.end(),
392                 boost::bind(&AccessControl::authorized, _1, boost::cref(request), session) == shib_acl_true
393                 );
394             return (i != m_operands.end()) ? shib_acl_true : shib_acl_false;
395         }
396     }
397     request.log(SPRequest::SPWarn,"unknown operation in access control policy, denying access");
398     return shib_acl_false;
399 }
400
401 pair<bool,DOMElement*> XMLAccessControl::background_load()
402 {
403     // Load from source using base class.
404     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
405
406     // If we own it, wrap it.
407     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
408
409     // Check for AccessControl wrapper and drop a level.
410     if (XMLString::equals(raw.second->getLocalName(),_AccessControl))
411         raw.second = XMLHelper::getFirstChildElement(raw.second);
412
413     scoped_ptr<AccessControl> authz;
414     if (XMLString::equals(raw.second->getLocalName(),_Rule))
415         authz.reset(new Rule(raw.second));
416     else if (XMLString::equals(raw.second->getLocalName(),_RuleRegex))
417         authz.reset(new RuleRegex(raw.second));
418     else
419         authz.reset(new Operator(raw.second));
420
421     // Perform the swap inside a lock.
422     if (m_lock)
423         m_lock->wrlock();
424     SharedLock locker(m_lock, false);
425     m_rootAuthz.swap(authz);
426
427     return make_pair(false,(DOMElement*)nullptr);
428 }
429
430 AccessControl::aclresult_t XMLAccessControl::authorized(const SPRequest& request, const Session* session) const
431 {
432     return m_rootAuthz ? m_rootAuthz->authorized(request,session) : shib_acl_false;
433 }