76aa5135faadb84ef03a0346fc0aedf81cd651f4
[shibboleth/cpp-sp.git] / shibsp / impl / XMLSecurityPolicyProvider.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  * XMLSecurityPolicyProvider.cpp
23  *
24  * XML-based security policy provider.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "security/SecurityPolicy.h"
31 #include "security/SecurityPolicyProvider.h"
32 #include "util/DOMPropertySet.h"
33 #include "util/SPConstants.h"
34
35 #include <map>
36 #include <boost/scoped_ptr.hpp>
37 #include <boost/shared_ptr.hpp>
38 #include <saml/SAMLConfig.h>
39 #include <saml/binding/SecurityPolicyRule.h>
40 #include <xmltooling/io/HTTPResponse.h>
41 #include <xmltooling/util/NDC.h>
42 #include <xmltooling/util/ReloadableXMLFile.h>
43 #include <xmltooling/util/Threads.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xercesc/util/XMLStringTokenizer.hpp>
46 #include <xercesc/util/XMLUniDefs.hpp>
47
48 using shibspconstants::SHIB2SPCONFIG_NS;
49 using opensaml::SAMLConfig;
50 using opensaml::SecurityPolicyRule;
51 using namespace shibsp;
52 using namespace xmltooling;
53 using namespace boost;
54 using namespace std;
55
56 namespace shibsp {
57
58 #if defined (_MSC_VER)
59     #pragma warning( push )
60     #pragma warning( disable : 4250 )
61 #endif
62
63     class SHIBSP_DLLLOCAL XMLSecurityPolicyProviderImpl
64     {
65     public:
66         XMLSecurityPolicyProviderImpl(const DOMElement* e, Category& log);
67         ~XMLSecurityPolicyProviderImpl() {
68             if (m_document)
69                 m_document->release();
70         }
71
72         void setDocument(DOMDocument* doc) {
73             m_document = doc;
74         }
75
76     private:
77         DOMDocument* m_document;
78         vector<xstring> m_whitelist,m_blacklist;
79         vector< boost::shared_ptr<SecurityPolicyRule> > m_ruleJanitor;   // need this to maintain vector type in API
80         typedef map< string,pair< boost::shared_ptr<PropertySet>,vector<const SecurityPolicyRule*> > > policymap_t;
81         policymap_t m_policyMap;
82         policymap_t::const_iterator m_defaultPolicy;
83
84         friend class SHIBSP_DLLLOCAL XMLSecurityPolicyProvider;
85     };
86
87     class XMLSecurityPolicyProvider : public SecurityPolicyProvider, public ReloadableXMLFile
88     {
89     public:
90         XMLSecurityPolicyProvider(const DOMElement* e)
91                 : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".SecurityPolicyProvider.XML")) {
92             background_load(); // guarantees an exception or the policy is loaded
93         }
94
95         ~XMLSecurityPolicyProvider() {
96             shutdown();
97         }
98
99         const PropertySet* getPolicySettings(const char* id=nullptr) const {
100             if (!id || !*id)
101                 return m_impl->m_defaultPolicy->second.first.get();
102             XMLSecurityPolicyProviderImpl::policymap_t::const_iterator i = m_impl->m_policyMap.find(id);
103             if (i != m_impl->m_policyMap.end())
104                 return i->second.first.get();
105             throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
106         }
107
108         const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id=nullptr) const {
109             if (!id || !*id)
110                 return m_impl->m_defaultPolicy->second.second;
111             XMLSecurityPolicyProviderImpl::policymap_t::const_iterator i = m_impl->m_policyMap.find(id);
112             if (i != m_impl->m_policyMap.end())
113                 return i->second.second;
114             throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
115         }
116         const vector<xstring>& getAlgorithmBlacklist() const {
117             return m_impl->m_blacklist;
118         }
119         const vector<xstring>& getAlgorithmWhitelist() const {
120             return m_impl->m_whitelist;
121         }
122         
123     protected:
124         pair<bool,DOMElement*> load(bool backup);
125         pair<bool,DOMElement*> background_load();
126
127     private:
128         scoped_ptr<XMLSecurityPolicyProviderImpl> m_impl;
129     };
130
131 #if defined (_MSC_VER)
132     #pragma warning( pop )
133 #endif
134
135     SecurityPolicyProvider* SHIBSP_DLLLOCAL XMLSecurityPolicyProviderFactory(const DOMElement* const & e)
136     {
137         return new XMLSecurityPolicyProvider(e);
138     }
139
140     class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
141     {
142     public:
143 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
144         short
145 #else
146         FilterAction
147 #endif
148         acceptNode(const DOMNode* node) const {
149             return FILTER_REJECT;
150         }
151     };
152
153     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
154     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
155     static const XMLCh AlgorithmBlacklist[] =   UNICODE_LITERAL_18(A,l,g,o,r,i,t,h,m,B,l,a,c,k,l,i,s,t);
156     static const XMLCh AlgorithmWhitelist[] =   UNICODE_LITERAL_18(A,l,g,o,r,i,t,h,m,W,h,i,t,e,l,i,s,t);
157     static const XMLCh Policy[] =               UNICODE_LITERAL_6(P,o,l,i,c,y);
158     static const XMLCh PolicyRule[] =           UNICODE_LITERAL_10(P,o,l,i,c,y,R,u,l,e);
159     static const XMLCh Rule[] =                 UNICODE_LITERAL_4(R,u,l,e);
160     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
161 }
162
163 void SHIBSP_API shibsp::registerSecurityPolicyProviders()
164 {
165     SPConfig::getConfig().SecurityPolicyProviderManager.registerFactory(XML_SECURITYPOLICY_PROVIDER, XMLSecurityPolicyProviderFactory);
166 }
167
168 SecurityPolicyProvider::SecurityPolicyProvider()
169 {
170 }
171
172 SecurityPolicyProvider::~SecurityPolicyProvider()
173 {
174 }
175
176 SecurityPolicy* SecurityPolicyProvider::createSecurityPolicy(
177     const Application& application, const xmltooling::QName* role, const char* policyId
178     ) const
179 {
180     pair<bool,bool> validate = getPolicySettings(policyId ? policyId : application.getString("policyId").second)->getBool("validate");
181     return new SecurityPolicy(application, role, (validate.first && validate.second), policyId);
182 }
183
184 XMLSecurityPolicyProviderImpl::XMLSecurityPolicyProviderImpl(const DOMElement* e, Category& log)
185     : m_document(nullptr), m_defaultPolicy(m_policyMap.end())
186 {
187 #ifdef _DEBUG
188     xmltooling::NDC ndc("XMLSecurityPolicyProviderImpl");
189 #endif
190
191     if (!XMLHelper::isNodeNamed(e, SHIB2SPCONFIG_NS, SecurityPolicies))
192         throw ConfigurationException("XML SecurityPolicyProvider requires conf:SecurityPolicies at root of configuration.");
193
194     const XMLCh* algs = nullptr;
195     const DOMElement* alglist = XMLHelper::getLastChildElement(e, AlgorithmBlacklist);
196     if (alglist && alglist->hasChildNodes()) {
197         algs = alglist->getFirstChild()->getNodeValue();
198     }
199     else if ((alglist = XMLHelper::getLastChildElement(e, AlgorithmWhitelist)) && alglist->hasChildNodes()) {
200         algs = alglist->getFirstChild()->getNodeValue();
201     }
202     if (algs) {
203         const XMLCh* token;
204         XMLStringTokenizer tokenizer(algs);
205         while (tokenizer.hasMoreTokens()) {
206             token = tokenizer.nextToken();
207             if (token) {
208                 if (XMLString::equals(alglist->getLocalName(), AlgorithmBlacklist))
209                     m_blacklist.push_back(token);
210                 else
211                     m_whitelist.push_back(token);
212             }
213         }
214     }
215
216     PolicyNodeFilter filter;
217     SAMLConfig& samlConf = SAMLConfig::getConfig();
218     e = XMLHelper::getFirstChildElement(e, Policy);
219     while (e) {
220         string id(XMLHelper::getAttrString(e, nullptr, _id));
221         policymap_t::mapped_type& rules = m_policyMap[id];
222         boost::shared_ptr<DOMPropertySet> settings(new DOMPropertySet());
223         settings->load(e, nullptr, &filter);
224         rules.first = settings;
225
226         // Set default policy if not set, or id is "default".
227         if (m_defaultPolicy == m_policyMap.end() || id == "default")
228             m_defaultPolicy = m_policyMap.find(id);
229
230         // Process PolicyRule elements.
231         const DOMElement* rule = XMLHelper::getFirstChildElement(e, PolicyRule);
232         while (rule) {
233             string t(XMLHelper::getAttrString(rule, nullptr, _type));
234             if (!t.empty()) {
235                 try {
236                     boost::shared_ptr<SecurityPolicyRule> ptr(samlConf.SecurityPolicyRuleManager.newPlugin(t.c_str(), rule));
237                     m_ruleJanitor.push_back(ptr);
238                     rules.second.push_back(ptr.get());
239                 }
240                 catch (std::exception& ex) {
241                     log.crit("error instantiating policy rule (%s) in policy (%s): %s", t.c_str(), id.c_str(), ex.what());
242                 }
243             }
244             rule = XMLHelper::getNextSiblingElement(rule, PolicyRule);
245         }
246
247         if (rules.second.size() == 0) {
248             // Process Rule elements.
249             log.warn("detected deprecated Policy configuration, consider converting to new PolicyRule syntax");
250             rule = XMLHelper::getFirstChildElement(e, Rule);
251             while (rule) {
252                 string t(XMLHelper::getAttrString(rule, nullptr, _type));
253                 if (!t.empty()) {
254                     try {
255                         boost::shared_ptr<SecurityPolicyRule> ptr(samlConf.SecurityPolicyRuleManager.newPlugin(t.c_str(), rule));
256                         m_ruleJanitor.push_back(ptr);
257                         rules.second.push_back(ptr.get());
258                     }
259                     catch (std::exception& ex) {
260                         log.crit("error instantiating policy rule (%s) in policy (%s): %s", t.c_str(), id.c_str(), ex.what());
261                     }
262                 }
263                 rule = XMLHelper::getNextSiblingElement(rule, Rule);
264             }
265
266             // Manually add a basic Conditions rule.
267             log.info("installing a default Conditions rule in policy (%s) for compatibility with legacy configuration", id.c_str());
268             boost::shared_ptr<SecurityPolicyRule> cptr(samlConf.SecurityPolicyRuleManager.newPlugin(CONDITIONS_POLICY_RULE, nullptr));
269             m_ruleJanitor.push_back(cptr);
270             rules.second.push_back(cptr.get());
271         }
272
273         e = XMLHelper::getNextSiblingElement(e, Policy);
274     }
275
276     if (m_defaultPolicy == m_policyMap.end())
277         throw ConfigurationException("XML SecurityPolicyProvider requires at least one Policy.");
278 }
279
280 pair<bool,DOMElement*> XMLSecurityPolicyProvider::load(bool backup)
281 {
282     // Load from source using base class.
283     pair<bool,DOMElement*> raw = ReloadableXMLFile::load(backup);
284
285     // If we own it, wrap it.
286     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
287
288     scoped_ptr<XMLSecurityPolicyProviderImpl> impl(new XMLSecurityPolicyProviderImpl(raw.second, m_log));
289
290     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
291     impl->setDocument(docjanitor.release());
292
293     // Perform the swap inside a lock.
294     if (m_lock)
295         m_lock->wrlock();
296     SharedLock locker(m_lock, false);
297     m_impl.swap(impl);
298
299     return make_pair(false,(DOMElement*)nullptr);
300 }
301
302 pair<bool,DOMElement*> XMLSecurityPolicyProvider::background_load()
303 {
304     try {
305         return load(false);
306     }
307     catch (long& ex) {
308         if (ex == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED)
309             m_log.info("remote resource (%s) unchanged", m_source.c_str());
310         if (!m_loaded && !m_backing.empty())
311             return load(true);
312         throw;
313     }
314     catch (std::exception&) {
315         if (!m_loaded && !m_backing.empty())
316             return load(true);
317         throw;
318     }
319 }