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