Metadata revisions, fixed lack of per-thread binding config.
[shibboleth/sp.git] / xmlproviders / XMLMetadata.cpp
1 /* 
2  * The Shibboleth License, Version 1. 
3  * Copyright (c) 2002 
4  * University Corporation for Advanced Internet Development, Inc. 
5  * All rights reserved
6  * 
7  * 
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  * Redistributions of source code must retain the above copyright notice, this 
12  * list of conditions and the following disclaimer.
13  * 
14  * Redistributions in binary form must reproduce the above copyright notice, 
15  * this list of conditions and the following disclaimer in the documentation 
16  * and/or other materials provided with the distribution, if any, must include 
17  * the following acknowledgment: "This product includes software developed by 
18  * the University Corporation for Advanced Internet Development 
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement 
20  * may appear in the software itself, if and wherever such third-party 
21  * acknowledgments normally appear.
22  * 
23  * Neither the name of Shibboleth nor the names of its contributors, nor 
24  * Internet2, nor the University Corporation for Advanced Internet Development, 
25  * Inc., nor UCAID may be used to endorse or promote products derived from this 
26  * software without specific prior written permission. For written permission, 
27  * please contact shibboleth@shibboleth.org
28  * 
29  * Products derived from this software may not be called Shibboleth, Internet2, 
30  * UCAID, or the University Corporation for Advanced Internet Development, nor 
31  * may Shibboleth appear in their name, without prior written permission of the 
32  * University Corporation for Advanced Internet Development.
33  * 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK 
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. 
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY 
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, 
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /* XMLMetadata.cpp - a metadata implementation that uses an XML-based registry
51
52    Scott Cantor
53    9/27/02
54
55    $History:$
56 */
57
58 #include "internal.h"
59
60 #include <sys/types.h>
61 #include <sys/stat.h>
62
63 #include <log4cpp/Category.hh>
64 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
65
66 using namespace shibboleth;
67 using namespace saml;
68 using namespace log4cpp;
69 using namespace std;
70
71 namespace {
72
73     class XMLMetadataImpl : public ReloadableXMLFileImpl
74     {
75     public:
76         XMLMetadataImpl(const char* pathname) : ReloadableXMLFileImpl(pathname) { init(); }
77         XMLMetadataImpl(const DOMElement* e) : ReloadableXMLFileImpl(e) { init(); }
78         void init();
79         ~XMLMetadataImpl();
80     
81         class ContactPerson : public IContactPerson
82         {
83         public:
84             ContactPerson(const DOMElement* e);
85             ~ContactPerson() {}
86         
87             ContactType getType() const { return m_type; }
88             const char* getCompany() const { return NULL; }
89             const char* getName() const { return m_name.get(); }
90             Iterator<string> getEmails() const { return m_emails; }
91             Iterator<string> getTelephones() const { return EMPTY(string); }
92             const DOMElement* getElement() const { return m_root; }
93         
94         private:
95             const DOMElement* m_root;
96             ContactType m_type;
97             auto_ptr_char m_name;
98             vector<string> m_emails;
99         };
100
101         class Provider;
102         
103         class KeyDescriptor : public IKeyDescriptor
104         {
105         public:
106             KeyDescriptor() : m_klist(NULL) {}
107             ~KeyDescriptor() {}
108             
109             KeyUse getUse() const { return signing; }
110             const XMLCh* getEncryptionMethod() const { return NULL; }
111             int getKeySize() const { return 0; }
112             DSIGKeyInfoList* getKeyInfo() const { return &m_klist; }
113             const DOMElement* getElement() const { return NULL; }
114         
115         private:
116             mutable DSIGKeyInfoList m_klist;
117             friend class Provider;
118         };
119         
120         class Role : public virtual IProviderRole
121         {
122         public:
123             Role(const Provider* provider, const DOMElement* e) : m_provider(provider), m_root(e) { }
124             ~Role();
125             
126             // External contract
127             const IProvider* getProvider() const {return m_provider;}
128             Iterator<const XMLCh*> getProtocolSupportEnumeration() const {return m_protocolEnum;}
129             Iterator<const IKeyDescriptor*> getKeyDescriptors() const {return m_keys;}
130             const IOrganization* getOrganization() const {return NULL;}
131             Iterator<const IContactPerson*> getContacts() const {return m_provider->getContacts();}
132             Iterator<const IEndpoint*> getDefaultEndpoints() const {return EMPTY(const IEndpoint*);}
133             const char* getErrorURL() const {return m_provider->getErrorURL();}
134             const DOMElement* getElement() const {return m_root;}
135         
136         protected:
137             vector<const XMLCh*> m_protocolEnum;
138
139         private:
140             const Provider* m_provider;
141             const DOMElement* m_root;
142             vector<const IKeyDescriptor*> m_keys;
143             friend class Provider;
144         };
145         
146         class Endpoint : public IEndpoint
147         {
148         public:
149             Endpoint(const XMLCh* binding, const XMLCh* loc) : m_binding(binding), m_location(loc) {}
150             ~Endpoint() {}
151             
152             const XMLCh* getBinding() const { return m_binding; }
153             const XMLCh* getVersion() const { return NULL; }
154             const XMLCh* getLocation() const { return m_location; }
155             const XMLCh* getResponseLocation() const { return NULL; }
156             const DOMElement* getElement() const { return NULL; }
157         
158         private:
159             const XMLCh* m_binding;
160             const XMLCh* m_location;
161         };
162         
163         class SSORole : public Role, public virtual ISSOProviderRole
164         {
165         public:
166             SSORole(const Provider* provider, const DOMElement* e) : Role(provider,e) {}
167             ~SSORole() {}
168             Iterator<const IEndpoint*> getSingleLogoutServices() const {return EMPTY(const IEndpoint*);}
169             Iterator<const IEndpoint*> getFederationTerminationServices() const {return EMPTY(const IEndpoint*);}
170             Iterator<const IEndpoint*> getRegisterNameIdentifierServices() const {return EMPTY(const IEndpoint*);}
171         };
172         
173         class IDPRole : public SSORole, public virtual IIDPProviderRole
174         {
175         public:
176             IDPRole(const Provider* provider, const DOMElement* e) : SSORole(provider,e) {m_protocolEnum.push_back(::XML::SHIB_NS);}
177             ~IDPRole() {}
178             Iterator<const IEndpoint*> getSingleSignOnServices() const {return m_pepv;}
179         
180         private:
181             vector<Endpoint> m_epv;
182             vector<const IEndpoint*> m_pepv;
183             friend class Provider;
184         };
185
186         class AARole : public Role, public virtual IAttributeAuthorityRole
187         {
188         public:
189             AARole(const Provider* provider, const DOMElement* e) : Role(provider,e) {m_protocolEnum.push_back(saml::XML::SAMLP_NS);}
190             ~AARole() {}
191             Iterator<const IEndpoint*> getAttributeServices() const {return m_pepv;}
192         
193         private:
194             vector<Endpoint> m_epv;
195             vector<const IEndpoint*> m_pepv;
196             friend class Provider;
197         };
198     
199         class Provider : public IProvider
200         {
201         public:
202             Provider(const DOMElement* e);
203             ~Provider();
204         
205             // External contract
206             const XMLCh* getId() const {return m_id;}
207             Iterator<const XMLCh*> getGroups() const {return m_groups;}
208             const IOrganization* getOrganization() const {return NULL;}
209             Iterator<const IContactPerson*> getContacts() const {return m_contacts;}
210             Iterator<const IProviderRole*> getRoles() const {return m_roles;}
211             const DOMElement* getElement() const {return m_root;}
212             Iterator<std::pair<const XMLCh*,bool> > getSecurityDomains() const {return m_domains;}
213
214             // Used internally
215             const char* getErrorURL() const {return m_errorURL.get();}
216         private:
217             friend class XMLMetadataImpl;
218             const XMLCh* m_id;
219             const DOMElement* m_root;
220             auto_ptr_char m_errorURL;
221             vector<const IContactPerson*> m_contacts;
222             vector<const IProviderRole*> m_roles;
223             IDPRole* m_IDP;
224             AARole* m_AA;
225             vector<pair<const XMLCh*,bool> > m_domains;
226             vector<const XMLCh*> m_groups;
227         };
228
229     #ifdef HAVE_GOOD_STL
230         typedef map<xstring,Provider*> sitemap_t;
231     #else
232         typedef map<string,Provider*> sitemap_t;
233     #endif
234         sitemap_t m_sites;
235     };
236
237     class XMLMetadata : public IMetadata, public ReloadableXMLFile
238     {
239     public:
240         XMLMetadata(const DOMElement* e) : ReloadableXMLFile(e) {}
241         ~XMLMetadata() {}
242
243         const IProvider* lookup(const XMLCh* providerId) const;
244         
245     protected:
246         virtual ReloadableXMLFileImpl* newImplementation(const char* pathname) const;
247         virtual ReloadableXMLFileImpl* newImplementation(const DOMElement* e) const;
248     };
249 }
250
251 extern "C" IMetadata* XMLMetadataFactory(const DOMElement* e)
252 {
253     XMLMetadata* m=new XMLMetadata(e);
254     try {
255         m->getImplementation();
256     }
257     catch (...) {
258         delete m;
259         throw;
260     }
261     return m;    
262 }
263
264 ReloadableXMLFileImpl* XMLMetadata::newImplementation(const DOMElement* e) const
265 {
266     return new XMLMetadataImpl(e);
267 }
268
269 ReloadableXMLFileImpl* XMLMetadata::newImplementation(const char* pathname) const
270 {
271     return new XMLMetadataImpl(pathname);
272 }
273
274 XMLMetadataImpl::Role::~Role()
275 {
276     for (vector<const IKeyDescriptor*>::iterator i=m_keys.begin(); i!=m_keys.end(); i++)
277         delete const_cast<IKeyDescriptor*>(*i);
278 }
279
280 XMLMetadataImpl::ContactPerson::ContactPerson(const DOMElement* e) : m_root(e), m_name(e->getAttributeNS(NULL,SHIB_L(Name)))
281 {
282     ContactPerson::ContactType type;
283     if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(Type)),SHIB_L(technical)))
284         m_type=IContactPerson::technical;
285     else if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(Type)),SHIB_L(support)))
286         type=IContactPerson::support;
287     else if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(Type)),SHIB_L(administrative)))
288         type=IContactPerson::administrative;
289     else if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(Type)),SHIB_L(billing)))
290         type=IContactPerson::billing;
291     else if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(Type)),SHIB_L(other)))
292         type=IContactPerson::other;
293     
294     auto_ptr_char temp(e->getAttributeNS(NULL,SHIB_L(Email)));
295     if (temp.get())
296         m_emails.push_back(temp.get());
297 }
298
299 XMLMetadataImpl::Provider::Provider(const DOMElement* e) : m_root(e), m_IDP(NULL), m_AA(NULL),
300     m_id(e->getAttributeNS(NULL,SHIB_L(Name))), m_errorURL(e->getAttributeNS(NULL,SHIB_L(ErrorURL)))
301 {
302     // Record all the SiteGroups containing this site.
303     DOMNode* group=e->getParentNode();
304     while (group && group->getNodeType()==DOMNode::ELEMENT_NODE) {
305         m_groups.push_back(static_cast<DOMElement*>(group)->getAttributeNS(NULL,SHIB_L(Name)));
306         group=group->getParentNode();
307     }
308
309     DOMElement* child=saml::XML::getFirstChildElement(e);
310     while (child) {
311         // Process the various kinds of OriginSite children that we care about...
312         if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(Contact))) {
313             m_contacts.push_back(new ContactPerson(child));
314         }
315         else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(HandleService))) {
316             // Create the IDP role if needed.
317             if (!m_IDP) {
318                 m_IDP=new IDPRole(this, child);
319                 m_IDP->m_keys.push_back(new KeyDescriptor());
320             }
321             m_roles.push_back(m_IDP);
322             
323             // Manufacture an endpoint for this role.
324             m_IDP->m_epv.push_back(Endpoint(::XML::SHIB_NS,child->getAttributeNS(NULL,SHIB_L(Location))));
325             m_IDP->m_pepv.push_back(&(m_IDP->m_epv.back()));
326
327             // We're going to "mock up" a KeyInfo that contains the specified Name as KeyName.
328             DOMElement* kne=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,SHIB_L(KeyName));
329             kne->appendChild(e->getOwnerDocument()->createTextNode(child->getAttributeNS(NULL,SHIB_L(Name))));
330             KeyDescriptor* kd=const_cast<KeyDescriptor*>(static_cast<const KeyDescriptor*>(m_IDP->m_keys.back()));
331             if (!kd->m_klist.addXMLKeyInfo(kne))
332                 throw MetadataException("Provider::Provider() unable to mock up ds:KeyName");
333         }
334         else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(AttributeAuthority))) {
335             // Create the AA role if needed.
336             if (!m_AA) {
337                 m_AA=new AARole(this, child);
338                 m_AA->m_keys.push_back(new KeyDescriptor());
339             }
340             m_roles.push_back(m_AA);
341             
342             // Manufacture an endpoint for this role.
343             m_AA->m_epv.push_back(Endpoint(SAMLBinding::SAML_SOAP_HTTPS,child->getAttributeNS(NULL,SHIB_L(Location))));
344             m_AA->m_pepv.push_back(&(m_AA->m_epv.back()));
345
346             // We're going to "mock up" a KeyInfo that contains the specified Name as KeyName.
347             DOMElement* kne=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,SHIB_L(KeyName));
348             kne->appendChild(e->getOwnerDocument()->createTextNode(child->getAttributeNS(NULL,SHIB_L(Name))));
349             KeyDescriptor* kd=const_cast<KeyDescriptor*>(static_cast<const KeyDescriptor*>(m_AA->m_keys.back()));
350             if (!kd->m_klist.addXMLKeyInfo(kne))
351                 throw MetadataException("Provider::Provider() unable to mock up ds:KeyName");
352         }
353         else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(Domain))) {
354             const XMLCh* dom=child->getFirstChild()->getNodeValue();
355             if (dom && *dom) {
356                 static const XMLCh one[]={ chDigit_1, chNull };
357                 static const XMLCh tru[]={ chLatin_t, chLatin_r, chLatin_u, chLatin_e, chNull };
358                 const XMLCh* regexp=child->getAttributeNS(NULL,SHIB_L(regexp));
359                 bool flag=(!XMLString::compareString(regexp,one) || !XMLString::compareString(regexp,tru));
360                 m_domains.push_back(pair<const XMLCh*,bool>(dom,flag));
361             }
362         }
363         child = saml::XML::getNextSiblingElement(child);
364     }
365 }
366
367 XMLMetadataImpl::Provider::~Provider()
368 {
369     for (vector<const IContactPerson*>::iterator i=m_contacts.begin(); i!=m_contacts.end(); i++)
370         delete const_cast<IContactPerson*>(*i);
371     delete m_IDP;
372     delete m_AA;
373 }
374
375 void XMLMetadataImpl::init()
376 {
377     NDC ndc("XMLMetadataImpl");
378     Category& log=Category::getInstance(XMLPROVIDERS_LOGCAT".XMLMetadataImpl");
379
380     try
381     {
382         if (!saml::XML::isElementNamed(m_root,::XML::SHIB_NS,SHIB_L(SiteGroup))) {
383             log.error("Construction requires a valid site file: (shib:SiteGroup as root element)");
384             throw MetadataException("Construction requires a valid site file: (shib:SiteGroup as root element)");
385         }
386
387         // Loop over the OriginSite elements.
388         DOMNodeList* nlist = m_root->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(OriginSite));
389         for (int i=0; nlist && i<nlist->getLength(); i++) {
390             const XMLCh* os_name=static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Name));
391             if (!os_name || !*os_name)
392                 continue;
393
394             Provider* p = new Provider(static_cast<DOMElement*>(nlist->item(i)));
395 #ifdef HAVE_GOOD_STL
396             m_sites[os_name]=p;
397 #else
398             auto_ptr_char os_name2(os_name);
399             m_sites[os_name2.get()]=p;
400 #endif
401         }
402     }
403     catch (SAMLException& e)
404     {
405         log.errorStream() << "Error while parsing site configuration: " << e.what() << CategoryStream::ENDLINE;
406         for (sitemap_t::iterator i=m_sites.begin(); i!=m_sites.end(); i++)
407             delete i->second;
408         throw;
409     }
410     catch (...)
411     {
412         log.error("Unexpected error while parsing site configuration");
413         for (sitemap_t::iterator i=m_sites.begin(); i!=m_sites.end(); i++)
414             delete i->second;
415         throw;
416     }
417 }
418
419 XMLMetadataImpl::~XMLMetadataImpl()
420 {
421     for (sitemap_t::iterator i=m_sites.begin(); i!=m_sites.end(); i++)
422         delete i->second;
423 }
424
425 const IProvider* XMLMetadata::lookup(const XMLCh* providerId) const
426 {
427     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
428 #ifdef HAVE_GOOD_STL
429     XMLMetadataImpl::sitemap_t::const_iterator i=impl->m_sites.find(providerId);
430 #else
431     auto_ptr_char temp(providerId);
432     XMLMetadataImpl::sitemap_t::const_iterator i=impl->m_sites.find(temp.get());
433 #endif
434     return (i==impl->m_sites.end()) ? NULL : i->second;
435 }