9c2e4ca07143d1928d861811a49f1889d53a0970
[shibboleth/cpp-sp.git] / shibsp / impl / XMLAccessControl.cpp
1 /*\r
2  *  Copyright 2001-2009 Internet2\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * XMLAccessControl.cpp\r
19  *\r
20  * XML-based access control syntax\r
21  */\r
22 \r
23 #include "internal.h"\r
24 #include "exceptions.h"\r
25 #include "AccessControl.h"\r
26 #include "SessionCache.h"\r
27 #include "SPRequest.h"\r
28 #include "attribute/Attribute.h"\r
29 \r
30 #include <algorithm>\r
31 #include <xmltooling/unicode.h>\r
32 #include <xmltooling/util/ReloadableXMLFile.h>\r
33 #include <xmltooling/util/XMLHelper.h>\r
34 #include <xercesc/util/XMLUniDefs.hpp>\r
35 #include <xercesc/util/regx/RegularExpression.hpp>\r
36 \r
37 #ifndef HAVE_STRCASECMP\r
38 # define strcasecmp _stricmp\r
39 #endif\r
40 \r
41 using namespace shibsp;\r
42 using namespace xmltooling;\r
43 using namespace std;\r
44 \r
45 namespace shibsp {\r
46 \r
47     class Rule : public AccessControl\r
48     {\r
49     public:\r
50         Rule(const DOMElement* e);\r
51         ~Rule() {}\r
52 \r
53         Lockable* lock() {return this;}\r
54         void unlock() {}\r
55 \r
56         aclresult_t authorized(const SPRequest& request, const Session* session) const;\r
57 \r
58     private:\r
59         string m_alias;\r
60         vector <string> m_vals;\r
61     };\r
62 \r
63     class RuleRegex : public AccessControl\r
64     {\r
65     public:\r
66         RuleRegex(const DOMElement* e);\r
67         ~RuleRegex() {\r
68             delete m_re;\r
69         }\r
70 \r
71         Lockable* lock() {return this;}\r
72         void unlock() {}\r
73 \r
74         aclresult_t authorized(const SPRequest& request, const Session* session) const;\r
75 \r
76     private:\r
77         string m_alias;\r
78         auto_arrayptr<char> m_exp;\r
79         RegularExpression* m_re;\r
80     };\r
81 \r
82     class Operator : public AccessControl\r
83     {\r
84     public:\r
85         Operator(const DOMElement* e);\r
86         ~Operator();\r
87 \r
88         Lockable* lock() {return this;}\r
89         void unlock() {}\r
90 \r
91         aclresult_t authorized(const SPRequest& request, const Session* session) const;\r
92 \r
93     private:\r
94         enum operator_t { OP_NOT, OP_AND, OP_OR } m_op;\r
95         vector<AccessControl*> m_operands;\r
96     };\r
97 \r
98 #if defined (_MSC_VER)\r
99     #pragma warning( push )\r
100     #pragma warning( disable : 4250 )\r
101 #endif\r
102 \r
103     class XMLAccessControl : public AccessControl, public ReloadableXMLFile\r
104     {\r
105     public:\r
106         XMLAccessControl(const DOMElement* e)\r
107                 : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AccessControl.XML")), m_rootAuthz(NULL) {\r
108             load(); // guarantees an exception or the policy is loaded\r
109         }\r
110 \r
111         ~XMLAccessControl() {\r
112             delete m_rootAuthz;\r
113         }\r
114 \r
115         aclresult_t authorized(const SPRequest& request, const Session* session) const;\r
116 \r
117     protected:\r
118         pair<bool,DOMElement*> load();\r
119 \r
120     private:\r
121         AccessControl* m_rootAuthz;\r
122     };\r
123 \r
124 #if defined (_MSC_VER)\r
125     #pragma warning( pop )\r
126 #endif\r
127 \r
128     AccessControl* SHIBSP_DLLLOCAL XMLAccessControlFactory(const DOMElement* const & e)\r
129     {\r
130         return new XMLAccessControl(e);\r
131     }\r
132 \r
133     static const XMLCh _AccessControl[] =   UNICODE_LITERAL_13(A,c,c,e,s,s,C,o,n,t,r,o,l);\r
134     static const XMLCh ignoreCase[] =       UNICODE_LITERAL_10(i,g,n,o,r,e,C,a,s,e);\r
135     static const XMLCh ignoreOption[] =     UNICODE_LITERAL_1(i);\r
136     static const XMLCh _list[] =            UNICODE_LITERAL_4(l,i,s,t);\r
137     static const XMLCh require[] =          UNICODE_LITERAL_7(r,e,q,u,i,r,e);\r
138     static const XMLCh NOT[] =              UNICODE_LITERAL_3(N,O,T);\r
139     static const XMLCh AND[] =              UNICODE_LITERAL_3(A,N,D);\r
140     static const XMLCh OR[] =               UNICODE_LITERAL_2(O,R);\r
141     static const XMLCh _Rule[] =            UNICODE_LITERAL_4(R,u,l,e);\r
142     static const XMLCh _RuleRegex[] =       UNICODE_LITERAL_9(R,u,l,e,R,e,g,e,x);\r
143 }\r
144 \r
145 Rule::Rule(const DOMElement* e)\r
146 {\r
147     auto_ptr_char req(e->getAttributeNS(NULL,require));\r
148     if (!req.get() || !*req.get())\r
149         throw ConfigurationException("Access control rule missing require attribute");\r
150     m_alias=req.get();\r
151 \r
152     auto_arrayptr<char> vals(toUTF8(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : NULL));\r
153     if (!vals.get())\r
154         return;\r
155 \r
156     const XMLCh* flag = e->getAttributeNS(NULL,_list);\r
157     if (flag && (*flag == chLatin_f || *flag == chDigit_0)) {\r
158         if (*vals.get())\r
159             m_vals.push_back(vals.get());\r
160         return;\r
161     }\r
162 \r
163 #ifdef HAVE_STRTOK_R\r
164     char* pos=NULL;\r
165     const char* token=strtok_r(const_cast<char*>(vals.get())," ",&pos);\r
166 #else\r
167     const char* token=strtok(const_cast<char*>(vals.get())," ");\r
168 #endif\r
169     while (token) {\r
170         m_vals.push_back(token);\r
171 #ifdef HAVE_STRTOK_R\r
172         token=strtok_r(NULL," ",&pos);\r
173 #else\r
174         token=strtok(NULL," ");\r
175 #endif\r
176     }\r
177 }\r
178 \r
179 AccessControl::aclresult_t Rule::authorized(const SPRequest& request, const Session* session) const\r
180 {\r
181     // We can make this more complex later using pluggable comparison functions,\r
182     // but for now, just a straight port to the new Attribute API.\r
183 \r
184     // Map alias in rule to the attribute.\r
185     if (!session) {\r
186         request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");\r
187         return shib_acl_false;\r
188     }\r
189 \r
190     if (m_alias == "valid-user") {\r
191         if (session) {\r
192             request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");\r
193             return shib_acl_true;\r
194         }\r
195         return shib_acl_false;\r
196     }\r
197     if (m_alias == "user") {\r
198         for (vector<string>::const_iterator i=m_vals.begin(); i!=m_vals.end(); ++i) {\r
199             if (*i == request.getRemoteUser()) {\r
200                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting REMOTE_USER (") + *i + "), authz granted");\r
201                 return shib_acl_true;\r
202             }\r
203         }\r
204         return shib_acl_false;\r
205     }\r
206     else if (m_alias == "authnContextClassRef") {\r
207         const char* ref = session->getAuthnContextClassRef();\r
208         for (vector<string>::const_iterator i=m_vals.begin(); ref && i!=m_vals.end(); ++i) {\r
209             if (!strcmp(i->c_str(),ref)) {\r
210                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextClassRef (") + *i + "), authz granted");\r
211                 return shib_acl_true;\r
212             }\r
213         }\r
214         return shib_acl_false;\r
215     }\r
216     else if (m_alias == "authnContextDeclRef") {\r
217         const char* ref = session->getAuthnContextDeclRef();\r
218         for (vector<string>::const_iterator i=m_vals.begin(); ref && i!=m_vals.end(); ++i) {\r
219             if (!strcmp(i->c_str(),ref)) {\r
220                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextDeclRef (") + *i + "), authz granted");\r
221                 return shib_acl_true;\r
222             }\r
223         }\r
224         return shib_acl_false;\r
225     }\r
226 \r
227     // Find the attribute(s) matching the require rule.\r
228     pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> attrs =\r
229         session->getIndexedAttributes().equal_range(m_alias);\r
230     if (attrs.first == attrs.second) {\r
231         request.log(SPRequest::SPWarn, string("rule requires attribute (") + m_alias + "), not found in session");\r
232         return shib_acl_false;\r
233     }\r
234 \r
235     for (; attrs.first != attrs.second; ++attrs.first) {\r
236         bool caseSensitive = attrs.first->second->isCaseSensitive();\r
237 \r
238         // Now we have to intersect the attribute's values against the rule's list.\r
239         const vector<string>& vals = attrs.first->second->getSerializedValues();\r
240         for (vector<string>::const_iterator i=m_vals.begin(); i!=m_vals.end(); ++i) {\r
241             for (vector<string>::const_iterator j=vals.begin(); j!=vals.end(); ++j) {\r
242                 if ((caseSensitive && *i == *j) || (!caseSensitive && !strcasecmp(i->c_str(),j->c_str()))) {\r
243                     request.log(SPRequest::SPDebug, string("AccessControl plugin expecting (") + *j + "), authz granted");\r
244                     return shib_acl_true;\r
245                 }\r
246             }\r
247         }\r
248     }\r
249 \r
250     return shib_acl_false;\r
251 }\r
252 \r
253 RuleRegex::RuleRegex(const DOMElement* e) : m_exp(toUTF8(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : NULL))\r
254 {\r
255     auto_ptr_char req(e->getAttributeNS(NULL,require));\r
256     if (!req.get() || !*req.get() || !m_exp.get() || !*m_exp.get())\r
257         throw ConfigurationException("Access control rule missing require attribute or element content.");\r
258     m_alias=req.get();\r
259 \r
260     const XMLCh* flag = e->getAttributeNS(NULL,ignoreCase);\r
261     bool ignore = (flag && (*flag == chLatin_t || *flag == chDigit_1));\r
262     try {\r
263         m_re = new RegularExpression(e->getFirstChild()->getNodeValue(), (ignore ? ignoreOption : &chNull));\r
264     }\r
265     catch (XMLException& ex) {\r
266         auto_ptr_char tmp(ex.getMessage());\r
267         throw ConfigurationException("Caught exception while parsing RuleRegex regular expression: $1", params(1,tmp.get()));\r
268     }\r
269 }\r
270 \r
271 AccessControl::aclresult_t RuleRegex::authorized(const SPRequest& request, const Session* session) const\r
272 {\r
273     // Map alias in rule to the attribute.\r
274     if (!session) {\r
275         request.log(SPRequest::SPWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");\r
276         return shib_acl_false;\r
277     }\r
278 \r
279     if (m_alias == "valid-user") {\r
280         if (session) {\r
281             request.log(SPRequest::SPDebug,"AccessControl plugin accepting valid-user based on active session");\r
282             return shib_acl_true;\r
283         }\r
284         return shib_acl_false;\r
285     }\r
286 \r
287     try {\r
288         if (m_alias == "user") {\r
289             if (m_re->matches(request.getRemoteUser().c_str())) {\r
290                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting REMOTE_USER (") + m_exp.get() + "), authz granted");\r
291                 return shib_acl_true;\r
292             }\r
293             return shib_acl_false;\r
294         }\r
295         else if (m_alias == "authnContextClassRef") {\r
296             if (session->getAuthnContextClassRef() && m_re->matches(session->getAuthnContextClassRef())) {\r
297                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextClassRef (") + m_exp.get() + "), authz granted");\r
298                 return shib_acl_true;\r
299             }\r
300             return shib_acl_false;\r
301         }\r
302         else if (m_alias == "authnContextDeclRef") {\r
303             if (session->getAuthnContextDeclRef() && m_re->matches(session->getAuthnContextDeclRef())) {\r
304                 request.log(SPRequest::SPDebug, string("AccessControl plugin expecting authnContextDeclRef (") + m_exp.get() + "), authz granted");\r
305                 return shib_acl_true;\r
306             }\r
307             return shib_acl_false;\r
308         }\r
309 \r
310         // Find the attribute(s) matching the require rule.\r
311         pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> attrs =\r
312             session->getIndexedAttributes().equal_range(m_alias);\r
313         if (attrs.first == attrs.second) {\r
314             request.log(SPRequest::SPWarn, string("rule requires attribute (") + m_alias + "), not found in session");\r
315             return shib_acl_false;\r
316         }\r
317 \r
318         for (; attrs.first != attrs.second; ++attrs.first) {\r
319             // Now we have to intersect the attribute's values against the regular expression.\r
320             const vector<string>& vals = attrs.first->second->getSerializedValues();\r
321             for (vector<string>::const_iterator j=vals.begin(); j!=vals.end(); ++j) {\r
322                 if (m_re->matches(j->c_str())) {\r
323                     request.log(SPRequest::SPDebug, string("AccessControl plugin expecting (") + m_exp.get() + "), authz granted");\r
324                     return shib_acl_true;\r
325                 }\r
326             }\r
327         }\r
328     }\r
329     catch (XMLException& ex) {\r
330         auto_ptr_char tmp(ex.getMessage());\r
331         request.log(SPRequest::SPError, string("caught exception while parsing RuleRegex regular expression: ") + tmp.get());\r
332     }\r
333 \r
334     return shib_acl_false;\r
335 }\r
336 \r
337 Operator::Operator(const DOMElement* e)\r
338 {\r
339     if (XMLString::equals(e->getLocalName(),NOT))\r
340         m_op=OP_NOT;\r
341     else if (XMLString::equals(e->getLocalName(),AND))\r
342         m_op=OP_AND;\r
343     else if (XMLString::equals(e->getLocalName(),OR))\r
344         m_op=OP_OR;\r
345     else\r
346         throw ConfigurationException("Unrecognized operator in access control rule");\r
347 \r
348     try {\r
349         e=XMLHelper::getFirstChildElement(e);\r
350         if (XMLString::equals(e->getLocalName(),_Rule))\r
351             m_operands.push_back(new Rule(e));\r
352         else if (XMLString::equals(e->getLocalName(),_RuleRegex))\r
353             m_operands.push_back(new RuleRegex(e));\r
354         else\r
355             m_operands.push_back(new Operator(e));\r
356 \r
357         if (m_op==OP_NOT)\r
358             return;\r
359 \r
360         e=XMLHelper::getNextSiblingElement(e);\r
361         while (e) {\r
362             if (XMLString::equals(e->getLocalName(),_Rule))\r
363                 m_operands.push_back(new Rule(e));\r
364             else if (XMLString::equals(e->getLocalName(),_RuleRegex))\r
365                 m_operands.push_back(new RuleRegex(e));\r
366             else\r
367                 m_operands.push_back(new Operator(e));\r
368             e=XMLHelper::getNextSiblingElement(e);\r
369         }\r
370     }\r
371     catch (exception&) {\r
372         for_each(m_operands.begin(),m_operands.end(),xmltooling::cleanup<AccessControl>());\r
373         throw;\r
374     }\r
375 }\r
376 \r
377 Operator::~Operator()\r
378 {\r
379     for_each(m_operands.begin(),m_operands.end(),xmltooling::cleanup<AccessControl>());\r
380 }\r
381 \r
382 AccessControl::aclresult_t Operator::authorized(const SPRequest& request, const Session* session) const\r
383 {\r
384     switch (m_op) {\r
385         case OP_NOT:\r
386             switch (m_operands.front()->authorized(request,session)) {\r
387                 case shib_acl_true:\r
388                     return shib_acl_false;\r
389                 case shib_acl_false:\r
390                     return shib_acl_true;\r
391                 default:\r
392                     return shib_acl_indeterminate;\r
393             }\r
394 \r
395         case OP_AND:\r
396         {\r
397             for (vector<AccessControl*>::const_iterator i=m_operands.begin(); i!=m_operands.end(); i++) {\r
398                 if ((*i)->authorized(request,session) != shib_acl_true)\r
399                     return shib_acl_false;\r
400             }\r
401             return shib_acl_true;\r
402         }\r
403 \r
404         case OP_OR:\r
405         {\r
406             for (vector<AccessControl*>::const_iterator i=m_operands.begin(); i!=m_operands.end(); i++) {\r
407                 if ((*i)->authorized(request,session) == shib_acl_true)\r
408                     return shib_acl_true;\r
409             }\r
410             return shib_acl_false;\r
411         }\r
412     }\r
413     request.log(SPRequest::SPWarn,"unknown operation in access control policy, denying access");\r
414     return shib_acl_false;\r
415 }\r
416 \r
417 pair<bool,DOMElement*> XMLAccessControl::load()\r
418 {\r
419     // Load from source using base class.\r
420     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();\r
421 \r
422     // If we own it, wrap it.\r
423     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);\r
424 \r
425     // Check for AccessControl wrapper and drop a level.\r
426     if (XMLString::equals(raw.second->getLocalName(),_AccessControl))\r
427         raw.second = XMLHelper::getFirstChildElement(raw.second);\r
428 \r
429     AccessControl* authz;\r
430     if (XMLString::equals(raw.second->getLocalName(),_Rule))\r
431         authz=new Rule(raw.second);\r
432     else if (XMLString::equals(raw.second->getLocalName(),_RuleRegex))\r
433         authz=new RuleRegex(raw.second);\r
434     else\r
435         authz=new Operator(raw.second);\r
436 \r
437     delete m_rootAuthz;\r
438     m_rootAuthz = authz;\r
439     return make_pair(false,(DOMElement*)NULL);\r
440 }\r
441 \r
442 AccessControl::aclresult_t XMLAccessControl::authorized(const SPRequest& request, const Session* session) const\r
443 {\r
444     return m_rootAuthz ? m_rootAuthz->authorized(request,session) : shib_acl_false;\r
445 }\r