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