Shell of new SP object interface to replace old IConfig layer.
[shibboleth/cpp-sp.git] / shibsp / impl / XMLAccessControl.cpp
1 /*\r
2  *  Copyright 2001-2005 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 \r
28 #include <xmltooling/util/ReloadableXMLFile.h>\r
29 #include <xmltooling/util/XMLHelper.h>\r
30 #include <xercesc/util/XMLUniDefs.hpp>\r
31 \r
32 #ifndef HAVE_STRCASECMP\r
33 # define strcasecmp _stricmp\r
34 #endif\r
35 \r
36 using namespace shibsp;\r
37 using namespace xmltooling;\r
38 using namespace std;\r
39 \r
40 namespace {\r
41     \r
42     class Rule : public AccessControl\r
43     {\r
44     public:\r
45         Rule(const DOMElement* e);\r
46         ~Rule() {}\r
47 \r
48         Lockable* lock() {return this;}\r
49         void unlock() {}\r
50 \r
51         bool authorized(SPRequest& request, Session* session) const;\r
52     \r
53     private:\r
54         string m_alias;\r
55         vector <string> m_vals;\r
56     };\r
57     \r
58     class Operator : public AccessControl\r
59     {\r
60     public:\r
61         Operator(const DOMElement* e);\r
62         ~Operator();\r
63 \r
64         Lockable* lock() {return this;}\r
65         void unlock() {}\r
66 \r
67         bool authorized(SPRequest& request, Session* session) const;\r
68         \r
69     private:\r
70         enum operator_t { OP_NOT, OP_AND, OP_OR } m_op;\r
71         vector<AccessControl*> m_operands;\r
72     };\r
73 \r
74 #if defined (_MSC_VER)\r
75     #pragma warning( push )\r
76     #pragma warning( disable : 4250 )\r
77 #endif\r
78 \r
79     class XMLAccessControl : public AccessControl, public ReloadableXMLFile\r
80     {\r
81     public:\r
82         XMLAccessControl(const DOMElement* e) : ReloadableXMLFile(e), m_rootAuthz(NULL) {\r
83             load(); // guarantees an exception or the policy is loaded\r
84         }\r
85         \r
86         ~XMLAccessControl() {\r
87             delete m_rootAuthz;\r
88         }\r
89 \r
90         bool authorized(SPRequest& request, Session* session) const;\r
91 \r
92     protected:\r
93         pair<bool,DOMElement*> load();\r
94 \r
95     private:\r
96         AccessControl* m_rootAuthz;\r
97     };\r
98 \r
99 #if defined (_MSC_VER)\r
100     #pragma warning( pop )\r
101 #endif\r
102 \r
103     AccessControl* SHIBSP_DLLLOCAL XMLAccessControlFactory(const DOMElement* const & e)\r
104     {\r
105         return new XMLAccessControl(e);\r
106     }\r
107 \r
108     static const XMLCh _AccessControl[] =    UNICODE_LITERAL_13(A,c,c,e,s,s,C,o,n,t,r,o,l);\r
109     static const XMLCh require[] =          UNICODE_LITERAL_7(r,e,q,u,i,r,e);\r
110     static const XMLCh NOT[] =              UNICODE_LITERAL_3(N,O,T);\r
111     static const XMLCh AND[] =              UNICODE_LITERAL_3(A,N,D);\r
112     static const XMLCh OR[] =               UNICODE_LITERAL_2(O,R);\r
113     static const XMLCh _Rule[] =            UNICODE_LITERAL_4(R,u,l,e);\r
114 }\r
115 \r
116 void SHIBSP_API shibsp::registerAccessControls()\r
117 {\r
118     SPConfig::getConfig().AccessControlManager.registerFactory(XML_ACCESS_CONTROL, XMLAccessControlFactory);\r
119 }\r
120 \r
121 Rule::Rule(const DOMElement* e)\r
122 {\r
123     xmltooling::auto_ptr_char req(e->getAttributeNS(NULL,require));\r
124     if (!req.get() || !*req.get())\r
125         throw ConfigurationException("Access control rule missing require attribute");\r
126     m_alias=req.get();\r
127     \r
128     xmltooling::auto_ptr_char vals(e->hasChildNodes() ? e->getFirstChild()->getNodeValue() : NULL);\r
129 #ifdef HAVE_STRTOK_R\r
130     char* pos=NULL;\r
131     const char* token=strtok_r(const_cast<char*>(vals.get()),"/",&pos);\r
132 #else\r
133     const char* token=strtok(const_cast<char*>(vals.get()),"/");\r
134 #endif\r
135     while (token) {\r
136         m_vals.push_back(token);\r
137 #ifdef HAVE_STRTOK_R\r
138         token=strtok_r(NULL,"/",&pos);\r
139 #else\r
140         token=strtok(NULL,"/");\r
141 #endif\r
142     }\r
143 }\r
144 \r
145 bool Rule::authorized(SPRequest& request, Session* session) const\r
146 {\r
147     /*\r
148     TODO: port...\r
149     // Map alias in rule to the attribute.\r
150     Iterator<IAAP*> provs=st->getApplication()->getAAPProviders();\r
151     AAP wrapper(provs,m_alias.c_str());\r
152     if (wrapper.fail()) {\r
153         st->log(ShibTarget::LogLevelWarn, string("AccessControl plugin didn't recognize rule (") + m_alias + "), check AAP for corresponding Alias");\r
154         return false;\r
155     }\r
156     else if (!entry) {\r
157         st->log(ShibTarget::LogLevelWarn, "AccessControl plugin not given a valid session to evaluate, are you using lazy sessions?");\r
158         return false;\r
159     }\r
160     \r
161     // Find the corresponding attribute. This isn't very efficient...\r
162     pair<const char*,const SAMLResponse*> filtered=entry->getFilteredTokens(false,true);\r
163     Iterator<SAMLAssertion*> a_iter(filtered.second ? filtered.second->getAssertions() : EMPTY(SAMLAssertion*));\r
164     while (a_iter.hasNext()) {\r
165         SAMLAssertion* assert=a_iter.next();\r
166         Iterator<SAMLStatement*> statements=assert->getStatements();\r
167         while (statements.hasNext()) {\r
168             SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());\r
169             if (!astate)\r
170                 continue;\r
171             Iterator<SAMLAttribute*> attrs=astate->getAttributes();\r
172             while (attrs.hasNext()) {\r
173                 SAMLAttribute* attr=attrs.next();\r
174                 if (!XMLString::compareString(attr->getName(),wrapper->getName()) &&\r
175                     !XMLString::compareString(attr->getNamespace(),wrapper->getNamespace())) {\r
176                     // Now we have to intersect the attribute's values against the rule's list.\r
177                     Iterator<string> vals=attr->getSingleByteValues();\r
178                     if (!vals.hasNext())\r
179                         return false;\r
180                     for (vector<string>::const_iterator ival=m_vals.begin(); ival!=m_vals.end(); ival++) {\r
181                         vals.reset();\r
182                         while (vals.hasNext()) {\r
183                             const string& v=vals.next();\r
184                             if ((wrapper->getCaseSensitive() && v == *ival) || (!wrapper->getCaseSensitive() && !strcasecmp(v.c_str(),ival->c_str()))) {\r
185                                 st->log(ShibTarget::LogLevelDebug, string("XMLAccessControl plugin expecting " + *ival + ", authz granted"));\r
186                                 return true;\r
187                             }\r
188                         }\r
189                     }\r
190                 }\r
191             }\r
192         }\r
193     }\r
194     */\r
195     return true;\r
196 }\r
197 \r
198 Operator::Operator(const DOMElement* e)\r
199 {\r
200     if (XMLString::equals(e->getLocalName(),NOT))\r
201         m_op=OP_NOT;\r
202     else if (XMLString::equals(e->getLocalName(),AND))\r
203         m_op=OP_AND;\r
204     else if (XMLString::equals(e->getLocalName(),OR))\r
205         m_op=OP_OR;\r
206     else\r
207         throw ConfigurationException("Unrecognized operator in access control rule");\r
208     \r
209     try {\r
210         e=XMLHelper::getFirstChildElement(e);\r
211         if (XMLString::equals(e->getLocalName(),_Rule))\r
212             m_operands.push_back(new Rule(e));\r
213         else\r
214             m_operands.push_back(new Operator(e));\r
215         \r
216         if (m_op==OP_NOT)\r
217             return;\r
218         \r
219         e=XMLHelper::getNextSiblingElement(e);\r
220         while (e) {\r
221             if (XMLString::equals(e->getLocalName(),_Rule))\r
222                 m_operands.push_back(new Rule(e));\r
223             else\r
224                 m_operands.push_back(new Operator(e));\r
225             e=XMLHelper::getNextSiblingElement(e);\r
226         }\r
227     }\r
228     catch (exception&) {\r
229         for_each(m_operands.begin(),m_operands.end(),xmltooling::cleanup<AccessControl>());\r
230         throw;\r
231     }\r
232 }\r
233 \r
234 Operator::~Operator()\r
235 {\r
236     for_each(m_operands.begin(),m_operands.end(),xmltooling::cleanup<AccessControl>());\r
237 }\r
238 \r
239 bool Operator::authorized(SPRequest& request, Session* session) const\r
240 {\r
241     switch (m_op) {\r
242         case OP_NOT:\r
243             return !m_operands[0]->authorized(request,session);\r
244         \r
245         case OP_AND:\r
246         {\r
247             for (vector<AccessControl*>::const_iterator i=m_operands.begin(); i!=m_operands.end(); i++) {\r
248                 if (!(*i)->authorized(request,session))\r
249                     return false;\r
250             }\r
251             return true;\r
252         }\r
253         \r
254         case OP_OR:\r
255         {\r
256             for (vector<AccessControl*>::const_iterator i=m_operands.begin(); i!=m_operands.end(); i++) {\r
257                 if ((*i)->authorized(request,session))\r
258                     return true;\r
259             }\r
260             return false;\r
261         }\r
262     }\r
263     //st->log(ShibTarget::LogLevelWarn,"Unknown operation in access control policy, denying access");\r
264     return false;\r
265 }\r
266 \r
267 pair<bool,DOMElement*> XMLAccessControl::load()\r
268 {\r
269     // Load from source using base class.\r
270     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();\r
271     \r
272     // If we own it, wrap it.\r
273     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);\r
274 \r
275     // Check for AccessControl wrapper and drop a level.\r
276     if (XMLString::equals(raw.second->getLocalName(),_AccessControl))\r
277         raw.second = XMLHelper::getFirstChildElement(raw.second);\r
278     \r
279     AccessControl* authz;\r
280     if (XMLString::equals(raw.second->getLocalName(),_Rule))\r
281         authz=new Rule(raw.second);\r
282     else\r
283         authz=new Operator(raw.second);\r
284 \r
285     delete m_rootAuthz;\r
286     m_rootAuthz = authz;\r
287     return make_pair(false,(DOMElement*)NULL);\r
288 }\r
289 \r
290 bool XMLAccessControl::authorized(SPRequest& request, Session* session) const\r
291 {\r
292     return m_rootAuthz ? m_rootAuthz->authorized(request,session) : false;\r
293 }\r