Fix improper uses of delete and free.
[shibboleth/cpp-sp.git] / xmlproviders / XMLMetadata.cpp
1 /*
2  *  Copyright 2001-2005 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17
18 /* XMLMetadata.cpp - a metadata implementation that uses an XML-based registry
19
20    Scott Cantor
21    9/27/02
22
23    $History:$
24 */
25
26 #include "internal.h"
27
28 #include <sys/types.h>
29 #include <sys/stat.h>
30
31 #include <xercesc/util/XMLChar.hpp>
32 #include <xsec/dsig/DSIGTransformC14n.hpp>
33 #include <xsec/dsig/DSIGReference.hpp>
34 #include <xsec/dsig/DSIGTransformList.hpp>
35 #include <xsec/enc/XSECCryptoException.hpp>
36 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
37 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
38 #include <xsec/framework/XSECException.hpp>
39 #include <xsec/framework/XSECProvider.hpp>
40
41 using namespace xmlproviders::logging;
42 using namespace shibboleth;
43 using namespace saml;
44 using namespace std;
45
46 namespace {
47
48     class XMLMetadata;
49     class XMLMetadataImpl : public ReloadableXMLFileImpl
50     {
51     public:
52         class ContactPerson : public IContactPerson
53         {
54         public:
55             ContactPerson(const DOMElement* e);
56             ~ContactPerson() {
57                 delete[] m_givenName;
58                 delete[] m_surName;
59                 delete[] m_company;
60             }
61         
62             ContactType getType() const { return m_type; }
63             const char* getCompany() const { return m_company; }
64             const char* getGivenName() const { return m_givenName; }
65             const char* getSurName() const { return m_surName; }
66             Iterator<string> getEmailAddresses() const { return m_emails; }
67             Iterator<string> getTelephoneNumbers() const { return m_phones; }
68             const DOMElement* getElement() const { return m_root; }
69         
70         private:
71             const DOMElement* m_root;
72             ContactType m_type;
73             char* m_givenName;
74             char* m_surName;
75             char* m_company;
76             vector<string> m_emails,m_phones;
77         };
78         
79         class Organization : public IOrganization
80         {
81         public:
82             Organization(const DOMElement* e);
83             ~Organization() {}
84             
85             const char* getName(const char* lang="en") const { return forLang(m_names,lang); }
86             const char* getDisplayName(const char* lang="en") const { return forLang(m_displays,lang); }
87             const char* getURL(const char* lang="en") const { return forLang(m_urls,lang); }
88             const DOMElement* getElement() const { return m_root; }
89         
90         private:
91             const char* forLang(const map<string,string>& m, const char* lang) const {
92                 map<string,string>::const_iterator i=m.find(lang);
93                 return (i==m.end()) ? NULL : i->second.c_str();
94             }
95             const DOMElement* m_root;
96             map<string,string> m_names,m_displays,m_urls;
97         };
98
99         class EntityDescriptor;
100         
101         class EncryptionMethod : public XENCEncryptionMethod
102         {
103         public:
104             EncryptionMethod(const DOMElement* e);
105             ~EncryptionMethod() {}
106             
107             const XMLCh * getAlgorithm(void) const { return m_alg; }
108             const XMLCh * getDigestMethod(void) const { return m_digest; }
109             const XMLCh * getOAEPparams(void) const { return m_params; }
110             int getKeySize(void) const { return m_size; }
111             DOMElement* getElement(void) const { return const_cast<DOMElement*>(m_root); }
112             void setDigestMethod(const XMLCh * method) {throw exception();}
113             void setOAEPparams(const XMLCh * params) {throw exception();}
114             void setKeySize(int size) {throw exception();}
115         
116         private:
117             const DOMElement* m_root;
118             const XMLCh* m_alg;
119             const XMLCh* m_digest;
120             const XMLCh* m_params;
121             int m_size;
122         };
123         
124         class KeyDescriptor : public IKeyDescriptor
125         {
126         public:
127             KeyDescriptor(const DOMElement* e);
128             ~KeyDescriptor();
129             
130             KeyUse getUse() const { return m_use; }
131             DSIGKeyInfoList* getKeyInfo() const { return m_klist; }
132             saml::Iterator<const XENCEncryptionMethod*> getEncryptionMethods() const { return m_methods; }
133             const DOMElement* getElement() const { return m_root; }
134         
135         private:
136             const DOMElement* m_root;
137             KeyUse m_use;
138             mutable DSIGKeyInfoList* m_klist;
139             vector<const XENCEncryptionMethod*> m_methods;
140         };
141         
142         class KeyAuthority : public IKeyAuthority
143         {
144         public:
145             KeyAuthority(const DOMElement* e);
146             ~KeyAuthority();
147             
148             int getVerifyDepth() const { return m_depth; }
149             Iterator<DSIGKeyInfoList*> getKeyInfos() const { return m_klists; }
150         
151         private:
152             int m_depth;
153             vector<DSIGKeyInfoList*> m_klists;
154         };
155         
156         class Role : public virtual IRoleDescriptor
157         {
158         public:
159             Role(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e);
160             ~Role();
161             
162             // External contract
163             const IEntityDescriptor* getEntityDescriptor() const {return m_provider;}
164             Iterator<const XMLCh*> getProtocolSupportEnumeration() const {return m_protocolEnum;}
165             bool hasSupport(const XMLCh* protocol) const;
166             const char* getErrorURL() const {return (m_errorURL ? m_errorURL : m_provider->getErrorURL());}
167             bool isValid() const {return time(NULL) < m_validUntil;}
168             Iterator<const IKeyDescriptor*> getKeyDescriptors() const {return m_keys;}
169             const IOrganization* getOrganization() const {return m_org ? m_org : m_provider->getOrganization();}
170             Iterator<const IContactPerson*> getContactPersons() const
171                 {return (m_contacts.empty() ? m_provider->getContactPersons() : m_contacts);}
172             const DOMElement* getElement() const {return m_root;}
173         
174         protected:
175             vector<const XMLCh*> m_protocolEnum;
176             vector<const IKeyDescriptor*> m_keys;
177
178         private:
179             const EntityDescriptor* m_provider;
180             const DOMElement* m_root;
181             XMLCh* m_protocolEnumCopy;
182             char* m_errorURL;
183             Organization* m_org;
184             vector<const IContactPerson*> m_contacts;
185             time_t m_validUntil;
186         };
187         
188         class Endpoint : public virtual IEndpoint
189         {
190         public:
191             Endpoint(const DOMElement* e) : m_root(e),
192                 m_binding(e->getAttributeNS(NULL,L(Binding))),
193                 m_location(e->getAttributeNS(NULL,L(Location))),
194                 m_resploc(e->getAttributeNS(NULL,SHIB_L(ResponseLocation))) {}
195             Endpoint(const XMLCh* binding, const XMLCh* loc)
196                 : m_root(NULL), m_binding(binding), m_location(loc), m_resploc(NULL) {}
197             ~Endpoint() {}
198             
199             const XMLCh* getBinding() const { return m_binding; }
200             const XMLCh* getLocation() const { return m_location; }
201             const XMLCh* getResponseLocation() const { return m_resploc; }
202             const DOMElement* getElement() const { return m_root; }
203         
204         private:
205             const DOMElement* m_root;
206             const XMLCh* m_binding;
207             const XMLCh* m_location;
208             const XMLCh* m_resploc;
209         };
210         
211         class IndexedEndpoint : public Endpoint, public virtual IIndexedEndpoint
212         {
213         public:
214             IndexedEndpoint(const DOMElement* e) : Endpoint(e), m_index(XMLString::parseInt(e->getAttributeNS(NULL,SHIB_L(index)))) {}
215             unsigned short getIndex() const {return m_index;}
216             
217         private:
218             unsigned short m_index;
219         };
220         
221         class EndpointManager : public IEndpointManager
222         {
223         public:
224             EndpointManager() : m_soft(NULL), m_hard(NULL) {}
225             ~EndpointManager() {
226                 for (vector<const IEndpoint*>::iterator i=m_endpoints.begin(); i!=m_endpoints.end(); i++)
227                     delete const_cast<IEndpoint*>(*i);
228             }
229             saml::Iterator<const IEndpoint*> getEndpoints() const {return m_endpoints;}
230             const IEndpoint* getDefaultEndpoint() const {
231                 if (m_hard) return m_hard;
232                 if (m_soft) return m_soft;
233                 if (!m_endpoints.empty()) return *(m_endpoints.begin());
234                 return NULL;
235             }
236             const IEndpoint* getEndpointByIndex(unsigned short index) const {
237                 for (vector<const IEndpoint*>::const_iterator i=m_endpoints.begin(); i!=m_endpoints.end(); i++) {
238                     const IIndexedEndpoint* temp=dynamic_cast<const IIndexedEndpoint*>(*i);
239                     if (temp && index==temp->getIndex())
240                         return temp;
241                 }
242                 return NULL;
243             }
244             const IEndpoint* getEndpointByBinding(const XMLCh* binding) const {
245                 for (vector<const IEndpoint*>::const_iterator i=m_endpoints.begin(); i!=m_endpoints.end(); i++)
246                     if (!XMLString::compareString(binding,(*i)->getBinding()))
247                         return *i;
248                 return NULL;
249             }
250             void add(IEndpoint* e) {
251                 m_endpoints.push_back(e);
252                 if (!m_hard && e->getElement()) {
253                     const XMLCh* v=e->getElement()->getAttributeNS(NULL,SHIB_L(isDefault));
254                     if (v && (*v==chDigit_1 || *v==chLatin_t))  // explicit default
255                         m_hard=e;
256                     else if ((!v || !*v) && !m_soft)            // implicit default
257                         m_soft=e;
258                 }
259                 else if (!m_hard && !m_soft) {
260                     // No default yet, so this one qualifies as an implicit.
261                     m_soft=e;
262                 }
263             }
264             
265         private:
266             vector<const IEndpoint*> m_endpoints;
267             const IEndpoint* m_soft;    // Soft default (not explicit)
268             const IEndpoint* m_hard;    // Hard default (explicit)
269         };
270         
271         class SSORole : public Role, public virtual ISSODescriptor
272         {
273         public:
274             SSORole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e);
275             ~SSORole() {}
276             const IEndpointManager* getArtifactResolutionServiceManager() const {return &m_artifact;}
277             const IEndpointManager* getSingleLogoutServiceManager() const {return &m_logout;}
278             const IEndpointManager* getManageNameIDServiceManager() const {return &m_nameid;}
279             saml::Iterator<const XMLCh*> getNameIDFormats() const {return m_formats;}
280             
281         private:
282             EndpointManager m_artifact,m_logout,m_nameid;
283             vector<const XMLCh*> m_formats;
284         };
285
286         class ScopedRole : public virtual IScopedRoleDescriptor
287         {
288         public:
289             ScopedRole(const DOMElement* e);
290             saml::Iterator<std::pair<const XMLCh*,bool> > getScopes() const {return m_scopes;}
291
292         private:
293             vector<pair<const XMLCh*,bool> > m_scopes;
294         };
295         
296         class IDPRole : public SSORole, public ScopedRole, public virtual IIDPSSODescriptor
297         {
298         public:
299             IDPRole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e);
300             ~IDPRole();
301             bool getWantAuthnRequestsSigned() const {return m_wantAuthnRequestsSigned;}
302             const IEndpointManager* getSingleSignOnServiceManager() const {return &m_sso;}
303             const IEndpointManager* getNameIDMappingServiceManager() const {return &m_mapping;}
304             const IEndpointManager* getAssertionIDRequestServiceManager() const {return &m_idreq;}
305             saml::Iterator<const XMLCh*> getAttributeProfiles() const {return m_attrprofs;}
306             saml::Iterator<const saml::SAMLAttribute*> getAttributes() const {return m_attrs;}
307         
308         private:
309             EndpointManager m_sso,m_mapping,m_idreq;
310             vector<const XMLCh*> m_attrprofs;
311             vector<const SAMLAttribute*> m_attrs;
312             bool m_wantAuthnRequestsSigned;
313             const XMLCh* m_sourceId;
314             friend class EntityDescriptor;
315         };
316
317         class AARole : public Role, public ScopedRole, public virtual IAttributeAuthorityDescriptor
318         {
319         public:
320             AARole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e);
321             ~AARole();
322             const IEndpointManager* getAttributeServiceManager() const {return &m_query;}
323             const IEndpointManager* getAssertionIDRequestServiceManager() const {return &m_idreq;}
324             saml::Iterator<const XMLCh*> getNameIDFormats() const {return m_formats;}
325             saml::Iterator<const XMLCh*> getAttributeProfiles() const {return m_attrprofs;}
326             saml::Iterator<const saml::SAMLAttribute*> getAttributes() const {return m_attrs;}
327         
328         private:
329             EndpointManager m_query,m_idreq;
330             vector<const XMLCh*> m_formats,m_attrprofs;
331             vector<const SAMLAttribute*> m_attrs;
332         };
333     
334         class EntityDescriptor : public IExtendedEntityDescriptor
335         {
336         public:
337             EntityDescriptor(
338                 const DOMElement* e,
339                 XMLMetadataImpl* wrapper,
340                 time_t validUntil=LONG_MAX,
341                 const IEntitiesDescriptor* parent=NULL
342                 );
343             ~EntityDescriptor();
344         
345             // External contract
346             const XMLCh* getId() const {return m_id;}
347             bool isValid() const {return time(NULL) < m_validUntil;}
348             Iterator<const IRoleDescriptor*> getRoleDescriptors() const {return m_roles;}
349             const IIDPSSODescriptor* getIDPSSODescriptor(const XMLCh* protocol) const;
350             const ISPSSODescriptor* getSPSSODescriptor(const XMLCh* protocol) const {return NULL;}
351             const IAuthnAuthorityDescriptor* getAuthnAuthorityDescriptor(const XMLCh* protocol) const {return NULL;}
352             const IAttributeAuthorityDescriptor* getAttributeAuthorityDescriptor(const XMLCh* protocol) const;
353             const IPDPDescriptor* getPDPDescriptor(const XMLCh* protocol) const {return NULL;}
354             const IAffiliationDescriptor* getAffiliationDescriptor() const {return NULL;}
355             const IOrganization* getOrganization() const {return m_org;}
356             Iterator<const IContactPerson*> getContactPersons() const {return m_contacts;}
357             Iterator<pair<const XMLCh*,const XMLCh*> > getAdditionalMetadataLocations() const {return m_locs;}
358             const IEntitiesDescriptor* getEntitiesDescriptor() const {return m_parent;}
359             Iterator<const IKeyAuthority*> getKeyAuthorities() const {return m_keyauths;}
360             const DOMElement* getElement() const {return m_root;}
361
362             // Used internally
363             const char* getErrorURL() const {return m_errorURL;}
364             time_t getValidUntil() const {return m_validUntil;}
365         private:
366             const DOMElement* m_root;
367             const IEntitiesDescriptor* m_parent;
368             const XMLCh* m_id;
369             char* m_errorURL;
370             IOrganization* m_org;
371             vector<const IContactPerson*> m_contacts;
372             vector<const IRoleDescriptor*> m_roles;
373             vector<pair<const XMLCh*,const XMLCh*> > m_locs;
374             vector<const IKeyAuthority*> m_keyauths;
375             time_t m_validUntil;
376         };
377
378         class EntitiesDescriptor : public IExtendedEntitiesDescriptor
379         {
380         public:
381             EntitiesDescriptor(
382                 const DOMElement* e,
383                 XMLMetadataImpl* wrapper,
384                 time_t validUntil=LONG_MAX,
385                 const IEntitiesDescriptor* parent=NULL
386                 );
387             ~EntitiesDescriptor();
388             
389             const XMLCh* getName() const {return m_name;}
390             bool isValid() const {return time(NULL) < m_validUntil;}
391             const IEntitiesDescriptor* getEntitiesDescriptor() const {return m_parent;}
392             Iterator<const IEntitiesDescriptor*> getEntitiesDescriptors() const {return m_groups;}
393             Iterator<const IEntityDescriptor*> getEntityDescriptors() const {return m_providers;}
394             Iterator<const IKeyAuthority*> getKeyAuthorities() const {return m_keyauths;}
395             const DOMElement* getElement() const {return m_root;}
396         
397             // Used internally
398             time_t getValidUntil() const {return m_validUntil;}
399         private:
400             const DOMElement* m_root;
401             const IEntitiesDescriptor* m_parent;
402             const XMLCh* m_name;
403             vector<const IEntitiesDescriptor*> m_groups;
404             vector<const IEntityDescriptor*> m_providers;
405             vector<const IKeyAuthority*> m_keyauths;
406             time_t m_validUntil;
407         };
408
409         XMLMetadataImpl(const char* pathname, const XMLMetadata* wrapper)
410             : ReloadableXMLFileImpl(pathname), m_rootProvider(NULL), m_rootGroup(NULL), m_outer(wrapper) { init(); }
411         XMLMetadataImpl(const DOMElement* e, const XMLMetadata* wrapper)
412             : ReloadableXMLFileImpl(e), m_rootProvider(NULL), m_rootGroup(NULL), m_outer(wrapper) { init(); }
413         void init();
414         ~XMLMetadataImpl();
415
416         typedef multimap<string,const EntityDescriptor*> sitemap_t;
417         typedef multimap<string,const EntitiesDescriptor*> groupmap_t;
418         sitemap_t m_sites;
419         sitemap_t m_sources;
420         groupmap_t m_groups;
421         EntityDescriptor* m_rootProvider;
422         EntitiesDescriptor* m_rootGroup;
423         const XMLMetadata* m_outer;
424     };
425
426     class XMLMetadata : public IMetadata, public ReloadableXMLFile
427     {
428     public:
429         XMLMetadata(const DOMElement* e);
430         ~XMLMetadata() {delete m_credResolver;}
431
432         const IEntityDescriptor* lookup(const char* providerId, bool strict=true) const;
433         const IEntityDescriptor* lookup(const XMLCh* providerId, bool strict=true) const;
434         const IEntityDescriptor* lookup(const saml::SAMLArtifact* artifact) const;
435         const IEntitiesDescriptor* lookupGroup(const char* name, bool strict=true) const;
436         const IEntitiesDescriptor* lookupGroup(const XMLCh* name, bool strict=true) const;
437         pair<const IEntitiesDescriptor*,const IEntityDescriptor*> getRoot() const;
438         
439         bool verifySignature(DOMDocument* doc, const DOMElement* parent, bool failUnsigned) const;
440         
441     protected:
442         virtual ReloadableXMLFileImpl* newImplementation(const char* pathname, bool first=true) const;
443         virtual ReloadableXMLFileImpl* newImplementation(const DOMElement* e, bool first=true) const;
444         
445     private:
446         bool m_exclusions,m_verify;
447         set<string> m_set;
448         ICredResolver* m_credResolver;
449     };
450 }
451
452 IPlugIn* XMLMetadataFactory(const DOMElement* e)
453 {
454     auto_ptr<XMLMetadata> m(new XMLMetadata(e));
455     m->getImplementation();
456     return m.release();
457 }
458
459 ReloadableXMLFileImpl* XMLMetadata::newImplementation(const DOMElement* e, bool first) const
460 {
461     return new XMLMetadataImpl(e,this);
462 }
463
464 ReloadableXMLFileImpl* XMLMetadata::newImplementation(const char* pathname, bool first) const
465 {
466     return new XMLMetadataImpl(pathname,this);
467 }
468
469 XMLMetadataImpl::ContactPerson::ContactPerson(const DOMElement* e) : m_root(e), m_type(IContactPerson::other)
470 {
471     const XMLCh* type=NULL;
472     
473     // Old metadata or new?
474     if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(Contact))) {
475         type=e->getAttributeNS(NULL,SHIB_L(Type));
476         m_surName=toUTF8(e->getAttributeNS(NULL,SHIB_L(Name)));
477         if (e->hasAttributeNS(NULL,SHIB_L(Email))) {
478             char* temp = toUTF8(e->getAttributeNS(NULL,SHIB_L(Email)));
479             if (temp)
480                 m_emails.push_back(temp);
481             delete[] temp;
482         }
483     }
484     else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(ContactPerson))) {
485         type=e->getAttributeNS(NULL,SHIB_L(contactType));
486         DOMNode* n=NULL;
487         e=saml::XML::getFirstChildElement(e);
488         while (e) {
489             if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(Company))) {
490                 n=e->getFirstChild();
491                 if (n) m_company=toUTF8(n->getNodeValue());
492             }
493             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(GivenName))) {
494                 n=e->getFirstChild();
495                 if (n) m_givenName=toUTF8(n->getNodeValue());
496             }
497             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(SurName))) {
498                 n=e->getFirstChild();
499                 if (n) m_surName=toUTF8(n->getNodeValue());
500             }
501             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EmailAddress))) {
502                 n=e->getFirstChild();
503                 if (n) {
504                     char* temp = toUTF8(n->getNodeValue());
505                     if (temp) m_emails.push_back(temp);
506                     delete[] temp;
507                 }
508             }
509             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(TelephoneNumber))) {
510                 n=e->getFirstChild();
511                 if (n) {
512                     char* temp = toUTF8(n->getNodeValue());
513                     if (temp) m_phones.push_back(temp);
514                     delete[] temp;
515                 }
516             }
517             e=saml::XML::getNextSiblingElement(e);
518         }
519     }
520     
521     if (!XMLString::compareString(type,SHIB_L(technical)))
522         m_type=IContactPerson::technical;
523     else if (!XMLString::compareString(type,SHIB_L(support)))
524         m_type=IContactPerson::support;
525     else if (!XMLString::compareString(type,SHIB_L(administrative)))
526         m_type=IContactPerson::administrative;
527     else if (!XMLString::compareString(type,SHIB_L(billing)))
528         m_type=IContactPerson::billing;
529 }
530
531 XMLMetadataImpl::Organization::Organization(const DOMElement* e) : m_root(e)
532 {
533     DOMNode* n=NULL;
534     e=saml::XML::getFirstChildElement(e);
535     while (e) {
536         if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationName))) {
537             n=e->getFirstChild();
538             if (n) {
539                 char* name = toUTF8(n->getNodeValue());
540                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
541                 m_names[lang.get()]=name;
542                 delete[] name;
543             }
544         }
545         else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationDisplayName))) {
546             n=e->getFirstChild();
547             if (n) {
548                 char* display = toUTF8(n->getNodeValue());
549                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
550                 m_displays[lang.get()]=display;
551                 delete[] display;
552             }
553         }
554         else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationURL))) {
555             n=e->getFirstChild();
556             if (n) {
557                 char* url = toUTF8(n->getNodeValue());
558                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
559                 m_urls[lang.get()]=url;
560                 delete[] url;
561             }
562         }
563         e=saml::XML::getNextSiblingElement(e);
564     }
565 }
566
567 XMLMetadataImpl::EncryptionMethod::EncryptionMethod(const DOMElement* e) : m_root(e)
568 {
569     m_alg=e->getAttributeNS(NULL,SHIB_L(Algorithm));
570     e=saml::XML::getFirstChildElement(e);
571     while (e) {
572         if (saml::XML::isElementNamed(e,::XML::XMLENC_NS,SHIB_L(KeySize))) {
573             DOMNode* n=e->getFirstChild();
574             if (n) m_size=XMLString::parseInt(n->getNodeValue());
575         }
576         else if (saml::XML::isElementNamed(e,saml::XML::XMLSIG_NS,SHIB_L(DigestMethod))) {
577             DOMNode* n=e->getFirstChild();
578             if (n) m_digest=n->getNodeValue();
579         }
580         else if (saml::XML::isElementNamed(e,::XML::XMLENC_NS,SHIB_L(OAEParams))) {
581             DOMNode* n=e->getFirstChild();
582             if (n) m_params=n->getNodeValue();
583         }
584         e=saml::XML::getNextSiblingElement(e);
585     }
586 }
587
588 XMLMetadataImpl::KeyDescriptor::KeyDescriptor(const DOMElement* e) : m_root(e), m_use(unspecified), m_klist(NULL)
589 {
590 #ifdef _DEBUG
591     saml::NDC ndc("KeyDescriptor");
592 #endif
593     if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(use)),SHIB_L(encryption)))
594         m_use=encryption;
595     else if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(use)),SHIB_L(signing)))
596         m_use=signing;
597     
598     m_klist = new DSIGKeyInfoList(NULL);
599
600     // Process ds:KeyInfo
601     e=saml::XML::getFirstChildElement(e);
602
603     // We let XMLSec hack through anything it can. This should evolve over time, or we can
604     // plug in our own KeyResolver later...
605     try {
606         if (!m_klist->loadListFromXML(const_cast<DOMElement*>(e)))
607             Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
608                 "skipping ds:KeyInfo element containing unsupported children"
609                 );
610     }
611     catch (XSECCryptoException& xe) {
612         Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error("unable to process ds:KeyInfo element: %s",xe.getMsg());
613     }
614     
615     // Check for encryption methods.
616     e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(EncryptionMethod));
617     while (e) {
618         m_methods.push_back(new EncryptionMethod(e));
619         e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(EncryptionMethod));
620     }
621 }
622
623 XMLMetadataImpl::KeyDescriptor::~KeyDescriptor()
624 {
625     for (vector<const XENCEncryptionMethod*>::iterator i=m_methods.begin(); i!=m_methods.end(); i++)
626         delete const_cast<XENCEncryptionMethod*>(*i);
627     delete m_klist;
628 }
629
630 XMLMetadataImpl::KeyAuthority::KeyAuthority(const DOMElement* e) : m_depth(1)
631 {
632 #ifdef _DEBUG
633     saml::NDC ndc("KeyAuthority");
634 #endif
635     if (e->hasAttributeNS(NULL,SHIB_L(VerifyDepth)))
636         m_depth=XMLString::parseInt(e->getAttributeNS(NULL,SHIB_L(VerifyDepth)));
637     
638     // Process ds:KeyInfo children
639     e=saml::XML::getFirstChildElement(e,saml::XML::XMLSIG_NS,L(KeyInfo));
640     while (e) {
641         auto_ptr<DSIGKeyInfoList> klist(new DSIGKeyInfoList(NULL));
642
643         // We let XMLSec hack through anything it can. This should evolve over time, or we can
644         // plug in our own KeyResolver later...
645         DOMElement* child=saml::XML::getFirstChildElement(e);
646         while (child) {
647             try {
648                 if (!klist->addXMLKeyInfo(child)) {
649                     Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
650                         "skipped unresolvable ds:KeyInfo child element");
651                 }
652             }
653             catch (XSECCryptoException& xe) {
654                 Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error(
655                     "unable to process ds:KeyInfo child element: %s",xe.getMsg());
656             }
657             child=saml::XML::getNextSiblingElement(child);
658         }
659         
660         if (klist->getSize()>0)
661             m_klists.push_back(klist.release());
662         else
663             Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
664                 "skipping ds:KeyInfo with no resolvable child elements");
665         e=saml::XML::getNextSiblingElement(e,saml::XML::XMLSIG_NS,L(KeyInfo));
666     }
667 }
668
669 XMLMetadataImpl::KeyAuthority::~KeyAuthority()
670 {
671     for (vector<DSIGKeyInfoList*>::iterator i=m_klists.begin(); i!=m_klists.end(); i++)
672         delete (*i);
673 }
674
675 XMLMetadataImpl::Role::Role(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
676     : m_provider(provider), m_root(e), m_protocolEnumCopy(NULL), m_errorURL(NULL), m_org(NULL), m_validUntil(validUntil)
677 {
678     // Check the root element namespace. If SAML2, assume it's the std schema.
679     if (e && !XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
680        
681         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
682             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
683             exp.parseDateTime();
684             m_validUntil=min(m_validUntil,exp.getEpoch());
685         }
686         
687         if (e->hasAttributeNS(NULL,SHIB_L(errorURL)))
688             m_errorURL=toUTF8(e->getAttributeNS(NULL,SHIB_L(errorURL)));
689         
690         // Chop the protocol list into pieces...assume any whitespace can appear in between.
691         m_protocolEnumCopy=XMLString::replicate(e->getAttributeNS(NULL,SHIB_L(protocolSupportEnumeration)));
692         XMLCh* temp=m_protocolEnumCopy;
693         while (temp && *temp) {
694             XMLCh* start=temp++;
695             while (*temp && !XMLChar1_1::isWhitespace(*temp)) temp++;
696             if (*temp)
697                 *temp++=chNull;
698             m_protocolEnum.push_back(start);
699             while (*temp && XMLChar1_1::isWhitespace(*temp)) temp++;
700         }
701         
702         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
703         while (e) {
704             m_keys.push_back(new KeyDescriptor(e));
705             e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
706         }
707
708         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(Organization));
709         if (e)
710             m_org=new Organization(e);
711
712         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(ContactPerson));
713         while (e) {
714             m_contacts.push_back(new ContactPerson(e));
715             e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(ContactPerson));
716         }
717     }
718 }
719
720 XMLMetadataImpl::Role::~Role()
721 {
722     delete m_org;
723     delete m_errorURL;
724     if (m_protocolEnumCopy) XMLString::release(&m_protocolEnumCopy);
725     for (vector<const IKeyDescriptor*>::iterator i=m_keys.begin(); i!=m_keys.end(); i++)
726         delete const_cast<IKeyDescriptor*>(*i);
727     for (vector<const IContactPerson*>::iterator j=m_contacts.begin(); j!=m_contacts.end(); j++)
728         delete const_cast<IContactPerson*>(*j);
729 }
730
731 bool XMLMetadataImpl::Role::hasSupport(const XMLCh* protocol) const
732 {
733     Iterator<const XMLCh*> i(m_protocolEnum);
734     while (i.hasNext()) {
735         if (!XMLString::compareString(protocol,i.next()))
736             return true;
737     }
738     return false;
739 }
740
741 XMLMetadataImpl::SSORole::SSORole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
742     : Role(provider,validUntil,e)
743 {
744     // Check the root element namespace. If SAML2, assume it's the std schema.
745     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
746         XMLSize_t i;
747         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(ArtifactResolutionService));
748         for (i=0; nlist && i<nlist->getLength(); i++)
749             m_artifact.add(new IndexedEndpoint(static_cast<DOMElement*>(nlist->item(i))));
750
751         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(SingleLogoutService));
752         for (i=0; nlist && i<nlist->getLength(); i++)
753             m_logout.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
754
755         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(ManageNameIDService));
756         for (i=0; nlist && i<nlist->getLength(); i++)
757             m_nameid.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
758
759         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDFormat));
760         for (i=0; nlist && i<nlist->getLength(); i++) {
761             DOMNode* n=nlist->item(i)->getFirstChild();
762             if (n) m_formats.push_back(n->getNodeValue());
763         }
764     }
765     else {
766         // For old style, we just do SAML 1.1 compatibility with Shib handles.
767         m_protocolEnum.push_back(saml::XML::SAML11_PROTOCOL_ENUM);
768         m_formats.push_back(shibboleth::Constants::SHIB_NAMEID_FORMAT_URI);
769     }
770 }
771
772 XMLMetadataImpl::ScopedRole::ScopedRole(const DOMElement* e)
773 {
774     // Check the root element namespace. If SAML2, assume it's the std schema.
775     DOMNodeList* nlist=NULL;
776     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
777         e=saml::XML::getFirstChildElement(e,::XML::SAML2META_NS,SHIB_L(Extensions));
778         if (e) nlist=e->getElementsByTagNameNS(::XML::SHIBMETA_NS,SHIB_L(Scope));
779     }
780     else {
781         nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(Domain));
782     }
783     
784     for (XMLSize_t i=0; nlist && i < nlist->getLength(); i++) {
785         const XMLCh* dom=(nlist->item(i)->hasChildNodes()) ? nlist->item(i)->getFirstChild()->getNodeValue() : NULL;
786         if (dom && *dom) {
787             const XMLCh* regexp=static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(regexp));
788             m_scopes.push_back(
789                 pair<const XMLCh*,bool>(dom,(regexp && (*regexp==chLatin_t || *regexp==chDigit_1)))
790                 );
791         }
792     }
793 }
794
795 XMLMetadataImpl::IDPRole::IDPRole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
796     : SSORole(provider,validUntil,e), ScopedRole(e), m_wantAuthnRequestsSigned(false), m_sourceId(NULL)
797 {
798     // Check the root element namespace. If SAML2, assume it's the std schema.
799     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
800         const XMLCh* flag=e->getAttributeNS(NULL,SHIB_L(WantAuthnRequestsSigned));
801         m_wantAuthnRequestsSigned=(flag && (*flag==chDigit_1 || *flag==chLatin_t));
802         
803         // Check for SourceID extension.
804         DOMElement* ext=saml::XML::getFirstChildElement(e,::XML::SAML2META_NS,SHIB_L(Extensions));
805         if (ext) {
806             ext=saml::XML::getFirstChildElement(ext,saml::XML::SAML_ARTIFACT_SOURCEID,SHIB_L(SourceID));
807             if (ext && ext->hasChildNodes())
808                 m_sourceId=ext->getFirstChild()->getNodeValue();
809         }
810         
811         XMLSize_t i;
812         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(SingleSignOnService));
813         for (i=0; nlist && i<nlist->getLength(); i++)
814             m_sso.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
815
816         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDMappingService));
817         for (i=0; nlist && i<nlist->getLength(); i++)
818             m_mapping.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
819
820         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AssertionIDRequestService));
821         for (i=0; nlist && i<nlist->getLength(); i++)
822             m_idreq.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
823
824         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeProfile));
825         for (i=0; nlist && i<nlist->getLength(); i++) {
826             DOMNode* n=nlist->item(i)->getFirstChild();
827             if (n) m_attrprofs.push_back(n->getNodeValue());
828         }
829
830         nlist=e->getElementsByTagNameNS(::XML::SAML2ASSERT_NS,L(Attribute));
831         for (i=0; nlist && i<nlist->getLength(); i++) {
832             // For now, we need to convert these to plain SAML 1.1 attributes.
833             DOMElement* src=static_cast<DOMElement*>(nlist->item(i));
834             DOMElement* copy=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(Attribute));
835             copy->setAttributeNS(NULL,L(AttributeName),src->getAttributeNS(NULL,SHIB_L(Name)));
836             copy->setAttributeNS(NULL,L(AttributeNamespace),src->getAttributeNS(NULL,SHIB_L(NameFormat)));
837             src=saml::XML::getFirstChildElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
838             while (src) {
839                 src=saml::XML::getNextSiblingElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
840                 DOMElement* val=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(AttributeValue));
841                 DOMNamedNodeMap* attrs = src->getAttributes();
842                 for (XMLSize_t j=0; j<attrs->getLength(); j++)
843                     val->setAttributeNodeNS(static_cast<DOMAttr*>(e->getOwnerDocument()->importNode(attrs->item(j),true)));
844                 while (src->hasChildNodes())
845                     val->appendChild(src->getFirstChild());
846                 copy->appendChild(val);
847             }
848             m_attrs.push_back(SAMLAttribute::getInstance(copy));
849         }
850     }
851     else {
852         m_protocolEnum.push_back(Constants::SHIB_NS);
853         m_attrprofs.push_back(Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
854         XMLSize_t i;
855         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(HandleService));
856         for (i=0; nlist && i<nlist->getLength(); i++) {
857             // Manufacture an endpoint for the "Shib" binding.
858             m_sso.add(
859                 new Endpoint(Constants::SHIB_AUTHNREQUEST_PROFILE_URI,static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,L(Location)))
860                 );
861
862             // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
863             DOMElement* kd=e->getOwnerDocument()->createElementNS(::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
864             DOMElement* ki=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,L(KeyInfo));
865             DOMElement* kn=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,SHIB_L(KeyName));
866             kn->appendChild(
867                 e->getOwnerDocument()->createTextNode(
868                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Name))
869                     )
870                 );
871             ki->appendChild(kn);
872             kd->appendChild(ki);
873             kd->setAttributeNS(NULL,SHIB_L(use),SHIB_L(signing));
874             m_keys.push_back(new KeyDescriptor(kd));
875         }
876     }
877 }
878
879 XMLMetadataImpl::IDPRole::~IDPRole()
880 {
881     for (vector<const SAMLAttribute*>::iterator i=m_attrs.begin(); i!=m_attrs.end(); i++)
882         delete const_cast<SAMLAttribute*>(*i);
883 }
884
885 XMLMetadataImpl::AARole::AARole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
886     : Role(provider,validUntil,e), ScopedRole(e)
887 {
888     // Check the root element namespace. If SAML2, assume it's the std schema.
889     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
890         XMLSize_t i;
891         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeService));
892         for (i=0; nlist && i<nlist->getLength(); i++)
893             m_query.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
894
895         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AssertionIDRequestService));
896         for (i=0; nlist && i<nlist->getLength(); i++)
897             m_idreq.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
898
899         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDFormat));
900         for (i=0; nlist && i<nlist->getLength(); i++) {
901             DOMNode* n=nlist->item(i)->getFirstChild();
902             if (n) m_formats.push_back(n->getNodeValue());
903         }
904
905         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeProfile));
906         for (i=0; nlist && i<nlist->getLength(); i++) {
907             DOMNode* n=nlist->item(i)->getFirstChild();
908             if (n) m_attrprofs.push_back(n->getNodeValue());
909         }
910
911         nlist=e->getElementsByTagNameNS(::XML::SAML2ASSERT_NS,L(Attribute));
912         for (i=0; nlist && i<nlist->getLength(); i++) {
913             // For now, we need to convert these to plain SAML 1.1 attributes.
914             DOMElement* src=static_cast<DOMElement*>(nlist->item(i));
915             DOMElement* copy=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(Attribute));
916             copy->setAttributeNS(NULL,L(AttributeName),src->getAttributeNS(NULL,SHIB_L(Name)));
917             copy->setAttributeNS(NULL,L(AttributeNamespace),src->getAttributeNS(NULL,SHIB_L(NameFormat)));
918             src=saml::XML::getFirstChildElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
919             while (src) {
920                 src=saml::XML::getNextSiblingElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
921                 DOMElement* val=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(AttributeValue));
922                 DOMNamedNodeMap* attrs = src->getAttributes();
923                 for (XMLSize_t j=0; j<attrs->getLength(); j++)
924                     val->setAttributeNodeNS(static_cast<DOMAttr*>(e->getOwnerDocument()->importNode(attrs->item(j),true)));
925                 while (src->hasChildNodes())
926                     val->appendChild(src->getFirstChild());
927                 copy->appendChild(val);
928             }
929             m_attrs.push_back(SAMLAttribute::getInstance(copy));
930         }
931     }
932     else {
933         // For old style, we just do SAML 1.1 compatibility with Shib handles.
934         m_protocolEnum.push_back(saml::XML::SAML11_PROTOCOL_ENUM);
935         m_formats.push_back(Constants::SHIB_NAMEID_FORMAT_URI);
936         m_attrprofs.push_back(Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
937         XMLSize_t i;
938         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(AttributeAuthority));
939         for (i=0; nlist && i<nlist->getLength(); i++) {
940             // Manufacture an endpoint for the SOAP binding.
941             m_query.add(
942                 new Endpoint(
943                     SAMLBinding::SOAP,
944                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,L(Location))
945                     )
946                 );
947
948             // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
949             DOMElement* kd=e->getOwnerDocument()->createElementNS(::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
950             DOMElement* ki=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,L(KeyInfo));
951             DOMElement* kn=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,SHIB_L(KeyName));
952             kn->appendChild(
953                 e->getOwnerDocument()->createTextNode(
954                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Name))
955                     )
956                 );
957             ki->appendChild(kn);
958             kd->appendChild(ki);
959             m_keys.push_back(new KeyDescriptor(kd));
960         }
961     }
962 }
963
964 XMLMetadataImpl::AARole::~AARole()
965 {
966     for (vector<const SAMLAttribute*>::iterator i=m_attrs.begin(); i!=m_attrs.end(); i++)
967         delete const_cast<SAMLAttribute*>(*i);
968 }
969
970 XMLMetadataImpl::EntityDescriptor::EntityDescriptor(
971     const DOMElement* e, XMLMetadataImpl* wrapper, time_t validUntil, const IEntitiesDescriptor* parent
972     ) : m_root(e), m_parent(parent), m_org(NULL), m_validUntil(validUntil)
973 {
974     // Check the root element namespace. If SAML2, assume it's the std schema.
975     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
976         m_id=e->getAttributeNS(NULL,SHIB_L(entityID));
977
978         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
979             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
980             exp.parseDateTime();
981             m_validUntil=min(validUntil,exp.getEpoch());
982         }
983
984         DOMElement* child=saml::XML::getFirstChildElement(e);
985         while (child) {
986             // Process the various kinds of children that we care about...
987             if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(Extensions))) {
988                 DOMElement* ext = saml::XML::getFirstChildElement(child,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
989                 while (ext) {
990                     m_keyauths.push_back(new KeyAuthority(ext));
991                     ext = saml::XML::getNextSiblingElement(ext,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
992                 }
993             }
994             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(ContactPerson))) {
995                 m_contacts.push_back(new ContactPerson(child));
996             }
997             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(Organization))) {
998                 m_org=new Organization(child);
999             }
1000             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(AdditionalMetadataLocation))) {
1001                 DOMNode* loc=child->getFirstChild();
1002                 if (loc)
1003                     m_locs.push_back(
1004                     pair<const XMLCh*,const XMLCh*>(child->getAttributeNS(NULL,::XML::Literals::_namespace),loc->getNodeValue())
1005                         );
1006             }
1007             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(IDPSSODescriptor))) {
1008                 if (wrapper->m_outer->verifySignature(child->getOwnerDocument(),child,false))
1009                     m_roles.push_back(new IDPRole(this,m_validUntil,child));
1010             }
1011             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(AttributeAuthorityDescriptor))) {
1012                 if (wrapper->m_outer->verifySignature(child->getOwnerDocument(),child,false))
1013                     m_roles.push_back(new AARole(this,m_validUntil,child));
1014             }
1015             child = saml::XML::getNextSiblingElement(child);
1016         }
1017     }
1018     else {
1019         m_id=e->getAttributeNS(NULL,SHIB_L(Name));
1020         m_errorURL=toUTF8(e->getAttributeNS(NULL,SHIB_L(ErrorURL)));
1021         
1022         bool idp=false,aa=false;    // only want to build a role once
1023         DOMElement* child=saml::XML::getFirstChildElement(e);
1024         while (child) {
1025             // Process the various kinds of OriginSite children that we care about...
1026             if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(Contact))) {
1027                 m_contacts.push_back(new ContactPerson(child));
1028             }
1029             else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(HandleService)) && !idp) {
1030                 // Create the IDP role if needed.
1031                 m_roles.push_back(new IDPRole(this, m_validUntil, e));
1032                 idp=true;
1033             }
1034             else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(AttributeAuthority)) && !aa) {
1035                 // Create the AA role if needed.
1036                 m_roles.push_back(new AARole(this, m_validUntil, e));
1037                 aa=true;
1038             }
1039             child = saml::XML::getNextSiblingElement(child);
1040         }
1041     }
1042
1043     if (m_id && *m_id) {
1044         auto_ptr_char id(m_id);
1045         wrapper->m_sites.insert(pair<const string,const EntityDescriptor*>(id.get(),this));
1046         
1047         // Look for an IdP role, and register the artifact source ID and endpoints.
1048         const IDPRole* idp=NULL;
1049         for (vector<const IRoleDescriptor*>::const_iterator r=m_roles.begin(); r!=m_roles.end(); r++) {
1050             if (idp=dynamic_cast<const IDPRole*>(*r)) {
1051                 if (idp->m_sourceId) {
1052                     auto_ptr_char sourceid(idp->m_sourceId);
1053                     wrapper->m_sources.insert(pair<const string,const EntityDescriptor*>(sourceid.get(),this));
1054                 }
1055                 else {
1056                     string sourceid=SAMLArtifact::toHex(SAMLArtifactType0001::generateSourceId(id.get()));
1057                     wrapper->m_sources.insert(pair<const string,const EntityDescriptor*>(sourceid,this));
1058                 }
1059                 Iterator<const IEndpoint*> locs=idp->getArtifactResolutionServiceManager()->getEndpoints();
1060                 while (locs.hasNext()) {
1061                     auto_ptr_char loc(locs.next()->getLocation());
1062                     wrapper->m_sources.insert(pair<const string,const EntityDescriptor*>(loc.get(),this));
1063                 }
1064             }
1065         }
1066     }
1067 }
1068
1069 const IIDPSSODescriptor* XMLMetadataImpl::EntityDescriptor::getIDPSSODescriptor(const XMLCh* protocol) const
1070 {
1071     const IIDPSSODescriptor* ret=NULL;
1072     for (vector<const IRoleDescriptor*>::const_iterator i=m_roles.begin(); i!=m_roles.end(); i++) {
1073         if ((*i)->hasSupport(protocol) && (*i)->isValid() && (ret=dynamic_cast<const IIDPSSODescriptor*>(*i)))
1074             return ret;
1075     }
1076     return NULL;
1077 }
1078
1079 const IAttributeAuthorityDescriptor* XMLMetadataImpl::EntityDescriptor::getAttributeAuthorityDescriptor(const XMLCh* protocol) const
1080 {
1081     const IAttributeAuthorityDescriptor* ret=NULL;
1082     for (vector<const IRoleDescriptor*>::const_iterator i=m_roles.begin(); i!=m_roles.end(); i++) {
1083         if ((*i)->hasSupport(protocol) && (*i)->isValid() && (ret=dynamic_cast<const IAttributeAuthorityDescriptor*>(*i)))
1084             return ret;
1085     }
1086     return NULL;
1087 }
1088
1089 XMLMetadataImpl::EntityDescriptor::~EntityDescriptor()
1090 {
1091     delete[] m_errorURL;
1092     delete m_org;
1093     for (vector<const IContactPerson*>::iterator i=m_contacts.begin(); i!=m_contacts.end(); i++)
1094         delete const_cast<IContactPerson*>(*i);
1095     for (vector<const IRoleDescriptor*>::iterator j=m_roles.begin(); j!=m_roles.end(); j++)
1096         delete const_cast<IRoleDescriptor*>(*j);
1097     for (vector<const IKeyAuthority*>::iterator k=m_keyauths.begin(); k!=m_keyauths.end(); k++)
1098         delete const_cast<IKeyAuthority*>(*k);
1099 }
1100
1101 XMLMetadataImpl::EntitiesDescriptor::EntitiesDescriptor(
1102     const DOMElement* e, XMLMetadataImpl* wrapper, time_t validUntil, const IEntitiesDescriptor* parent
1103     ) : m_root(e),  m_parent(parent), m_name(e->getAttributeNS(NULL,SHIB_L(Name))), m_validUntil(validUntil)
1104 {
1105     // Check the root element namespace. If SAML2, assume it's the std schema.
1106     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
1107
1108         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
1109             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
1110             exp.parseDateTime();
1111             m_validUntil=min(validUntil,exp.getEpoch());
1112         }
1113
1114         e=saml::XML::getFirstChildElement(e);
1115         while (e) {
1116             if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(Extensions))) {
1117                 DOMElement* ext = saml::XML::getFirstChildElement(e,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
1118                 while (ext) {
1119                     m_keyauths.push_back(new KeyAuthority(ext));
1120                     ext = saml::XML::getNextSiblingElement(ext,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
1121                 }
1122             }
1123             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EntitiesDescriptor))) {
1124                 if (wrapper->m_outer->verifySignature(e->getOwnerDocument(),e,false))
1125                     m_groups.push_back(new EntitiesDescriptor(e,wrapper,m_validUntil,this));
1126             }
1127             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EntityDescriptor))) {
1128                 if (wrapper->m_outer->verifySignature(e->getOwnerDocument(),e,false))
1129                     m_providers.push_back(new EntityDescriptor(e,wrapper,m_validUntil,this));
1130             }
1131             e=saml::XML::getNextSiblingElement(e);
1132         }
1133     }
1134     else {
1135         e=saml::XML::getFirstChildElement(e);
1136         while (e) {
1137             if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(SiteGroup))) {
1138                 if (wrapper->m_outer->verifySignature(e->getOwnerDocument(),e,false))
1139                     m_groups.push_back(new EntitiesDescriptor(e,wrapper,m_validUntil,this));
1140             }
1141             else if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(OriginSite)))
1142                 m_providers.push_back(new EntityDescriptor(e,wrapper,m_validUntil,this));
1143             e=saml::XML::getNextSiblingElement(e);
1144         }
1145     }
1146
1147     if (!saml::XML::isEmpty(m_name)) {
1148         auto_ptr_char n(m_name);
1149         wrapper->m_groups.insert(pair<const string,const EntitiesDescriptor*>(n.get(),this));
1150     }
1151     else
1152         m_name=NULL;
1153 }
1154
1155 XMLMetadataImpl::EntitiesDescriptor::~EntitiesDescriptor()
1156 {
1157     for (vector<const IEntityDescriptor*>::iterator i=m_providers.begin(); i!=m_providers.end(); i++)
1158         delete const_cast<IEntityDescriptor*>(*i);
1159     for (vector<const IEntitiesDescriptor*>::iterator j=m_groups.begin(); j!=m_groups.end(); j++)
1160         delete const_cast<IEntitiesDescriptor*>(*j);
1161     for (vector<const IKeyAuthority*>::iterator k=m_keyauths.begin(); k!=m_keyauths.end(); k++)
1162         delete const_cast<IKeyAuthority*>(*k);
1163 }
1164
1165 void XMLMetadataImpl::init()
1166 {
1167 #ifdef _DEBUG
1168     NDC ndc("init");
1169 #endif
1170     Category& log=Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata");
1171
1172     try
1173     {
1174         if (saml::XML::isElementNamed(m_root,::XML::SAML2META_NS,SHIB_L(EntitiesDescriptor))) {
1175             if (m_outer->verifySignature(m_root->getOwnerDocument(),m_root,true))
1176                 m_rootGroup=new EntitiesDescriptor(m_root,this);
1177         }
1178         else if (saml::XML::isElementNamed(m_root,::XML::SAML2META_NS,SHIB_L(EntityDescriptor))) {
1179             if (m_outer->verifySignature(m_root->getOwnerDocument(),m_root,true))
1180                 m_rootProvider=new EntityDescriptor(m_root,this);
1181         }
1182         else if (saml::XML::isElementNamed(m_root,::XML::SHIB_NS,SHIB_L(SiteGroup))) {
1183             if (m_outer->verifySignature(m_root->getOwnerDocument(),m_root,true))
1184                 m_rootGroup=new EntitiesDescriptor(m_root,this);
1185         }
1186         else if (saml::XML::isElementNamed(m_root,::XML::SHIB_NS,SHIB_L(OriginSite))) {
1187             if (m_outer->verifySignature(m_root->getOwnerDocument(),m_root,true))
1188                 m_rootProvider=new EntityDescriptor(m_root,this);
1189         }
1190         else {
1191             log.error("Construction requires a valid SAML metadata file");
1192             throw MetadataException("Construction requires a valid SAML metadata file");
1193         }
1194     }
1195     catch (SAMLException& e)
1196     {
1197         log.errorStream() << "Error while parsing SAML metadata: " << e.what() << CategoryStream::ENDLINE;
1198         this->~XMLMetadataImpl();
1199         throw;
1200     }
1201 #ifndef _DEBUG
1202     catch (...)
1203     {
1204         log.error("Unexpected error while parsing SAML metadata");
1205         this->~XMLMetadataImpl();
1206         throw;
1207     }
1208 #endif
1209
1210     if (!m_rootGroup && !m_rootProvider) {
1211         log.error("Metadata file contained no valid information");
1212         throw MetadataException("Metadata file contained no valid information");
1213     }
1214 }
1215
1216 XMLMetadataImpl::~XMLMetadataImpl()
1217 {
1218     delete m_rootGroup;
1219     delete m_rootProvider;
1220 }
1221
1222 XMLMetadata::XMLMetadata(const DOMElement* e) : ReloadableXMLFile(e), m_exclusions(true), m_verify(false), m_credResolver(NULL)
1223 {
1224     static const XMLCh uri[] = { chLatin_u, chLatin_r, chLatin_i, chNull };
1225     if (e->hasAttributeNS(NULL,uri)) {
1226         // First check for explicit enablement of entities.
1227         DOMNodeList* nlist=e->getElementsByTagName(SHIB_L(Include));
1228         for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
1229             if (nlist->item(i)->hasChildNodes()) {
1230                 auto_ptr_char temp(nlist->item(i)->getFirstChild()->getNodeValue());
1231                 if (temp.get()) {
1232                     m_set.insert(temp.get());
1233                     m_exclusions=false;
1234                 }
1235             }
1236         }
1237         // If there was no explicit enablement, build a set of exclusions.
1238         if (m_exclusions) {
1239             nlist=e->getElementsByTagName(SHIB_L(Exclude));
1240             for (XMLSize_t j=0; nlist && j<nlist->getLength(); j++) {
1241                 if (nlist->item(j)->hasChildNodes()) {
1242                     auto_ptr_char temp(nlist->item(j)->getFirstChild()->getNodeValue());
1243                     if (temp.get())
1244                         m_set.insert(temp.get());
1245                 }
1246             }
1247         }
1248     }
1249     
1250     const XMLCh* v=e->getAttributeNS(NULL,SHIB_L(verify));
1251     m_verify=(v && (*v==chLatin_t || *v==chDigit_1));
1252
1253     string cr_type;
1254     DOMElement* r=saml::XML::getFirstChildElement(e,::XML::CREDS_NS,SHIB_L(FileResolver));
1255     if (r)
1256         cr_type="edu.internet2.middleware.shibboleth.common.Credentials.FileCredentialResolver";            
1257     else {
1258         r=saml::XML::getFirstChildElement(e,::XML::CREDS_NS,SHIB_L(CustomResolver));
1259         if (r) {
1260             auto_ptr_char c(r->getAttributeNS(NULL,SHIB_L(Class)));
1261             cr_type=c.get();
1262         }
1263     }
1264     
1265     if (!cr_type.empty()) {
1266         try {
1267             IPlugIn* plugin=SAMLConfig::getConfig().getPlugMgr().newPlugin(cr_type.c_str(),r);
1268             ICredResolver* cr=dynamic_cast<ICredResolver*>(plugin);
1269             if (cr)
1270                 m_credResolver=cr;
1271             else {
1272                 Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error("plugin was not a credential resolver");
1273                 delete plugin;
1274                 throw UnsupportedExtensionException("plugin was not a credential resolver");
1275             }
1276         }
1277         catch (SAMLException& e) {
1278             Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error("failed to instantiate credential resolver: %s", e.what());
1279             throw;
1280         }
1281     }
1282     
1283     if (m_verify && !m_credResolver) {
1284         delete m_credResolver;
1285         throw MalformedException("Metadata provider told to verify signatures, but a verification key is not available.");
1286     }
1287 }
1288
1289 bool XMLMetadata::verifySignature(DOMDocument* doc, const DOMElement* parent, bool failUnsigned) const
1290 {
1291     if (!m_verify)
1292         return true;
1293
1294 #ifdef _DEBUG
1295     saml::NDC ndc("verifySignature");
1296 #endif
1297     Category& log=Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata");
1298     
1299     DOMElement* sigNode=saml::XML::getFirstChildElement(parent,saml::XML::XMLSIG_NS,L(Signature));
1300     if (!sigNode) {
1301         if (failUnsigned) {
1302             log.error("rejecting unsigned element");
1303             return false;
1304         }
1305         return true;
1306     }
1307     
1308     XSECCryptoX509* cert=NULL;
1309     Iterator<XSECCryptoX509*> certs=m_credResolver->getCertificates();
1310     if (certs.hasNext())
1311         cert=certs.next();
1312     else {
1313         log.error("unable to find any certificates to use in verifying signature");
1314         return false;
1315     }
1316
1317     static const XMLCh ID[]={chLatin_I, chLatin_D, chNull};
1318     static const XMLCh null[]={chDoubleQuote, chDoubleQuote, chNull};
1319
1320     // Load the signature.
1321     XSECProvider prov;
1322     DSIGSignature* sig=NULL;
1323     try {
1324         sig=prov.newSignatureFromDOM(doc,sigNode);
1325         sig->load();
1326
1327         bool valid=false;
1328         const XMLCh* URI=NULL;
1329
1330         // Verify the signature coverage.
1331         DSIGReferenceList* refs=sig->getReferenceList();
1332         if (sig->getSignatureMethod()==SIGNATURE_RSA && refs && refs->getSize()==1) {
1333             DSIGReference* ref=refs->item(0);
1334             if (ref) {
1335                 URI=ref->getURI();
1336                 if (!URI || !*URI || (*URI==chPound &&
1337                         !XMLString::compareString(&URI[1],static_cast<DOMElement*>(sigNode->getParentNode())->getAttributeNS(NULL,ID)))) {
1338                     DSIGTransformList* tlist=ref->getTransforms();
1339                     for (unsigned int i=0; tlist && i<tlist->getSize(); i++) {
1340                         if (tlist->item(i)->getTransformType()==TRANSFORM_ENVELOPED_SIGNATURE)
1341                             valid=true;
1342                         else if (tlist->item(i)->getTransformType()!=TRANSFORM_EXC_C14N &&
1343                                  tlist->item(i)->getTransformType()!=TRANSFORM_C14N) {
1344                             valid=false;
1345                             break;
1346                         }
1347                     }
1348                 }
1349             }
1350         }
1351     
1352         if (!valid) {
1353             auto_ptr_char temp((URI && *URI) ? URI : null);
1354             log.error("detected an invalid signature profile (Reference URI was %s)",temp.get());
1355             return false;
1356         }
1357         
1358         sig->setSigningKey(cert->clonePublicKey());
1359         if (!sig->verify()) {
1360             auto_ptr_char temp((URI && *URI) ? URI : null);
1361             log.error("detected an invalid signature value (Reference URI was %s)",temp.get());
1362             return false;
1363         }
1364         
1365         prov.releaseSignature(sig);
1366     }
1367     catch(XSECException& e) {
1368         auto_ptr_char msg(e.getMsg());
1369         log.errorStream() << "caught XMLSec exception while verifying metadata signature: " << msg.get() << CategoryStream::ENDLINE;
1370         if (sig)
1371             prov.releaseSignature(sig);
1372         return false;
1373     }
1374     catch(XSECCryptoException& e) {
1375         log.errorStream() << "caught XMLSecCrypto exception while verifying metadata signature: " << e.getMsg() << CategoryStream::ENDLINE;
1376         if (sig)
1377             prov.releaseSignature(sig);
1378         return false;
1379     }
1380     catch(...) {
1381         if (sig)
1382             prov.releaseSignature(sig);
1383         log.error("caught unknown exception while verifying metadata signature");
1384         throw;
1385     }
1386     return true;
1387 }
1388
1389 const IEntityDescriptor* XMLMetadata::lookup(const char* providerId, bool strict) const
1390 {
1391     if (strict && m_exclusions && m_set.find(providerId)!=m_set.end())
1392         return NULL;
1393     else if (strict && !m_exclusions && m_set.find(providerId)==m_set.end())
1394         return NULL;
1395         
1396     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1397     pair<XMLMetadataImpl::sitemap_t::iterator,XMLMetadataImpl::sitemap_t::iterator> range=
1398         impl->m_sites.equal_range(providerId);
1399
1400     time_t now=time(NULL);
1401     for (XMLMetadataImpl::sitemap_t::const_iterator i=range.first; i!=range.second; i++)
1402         if (now < i->second->getValidUntil())
1403             return i->second;
1404     
1405     if (!strict && range.first!=range.second)
1406         return range.first->second;
1407         
1408     return NULL;
1409 }
1410
1411 const IEntityDescriptor* XMLMetadata::lookup(const XMLCh* providerId, bool strict) const
1412 {
1413     auto_ptr_char temp(providerId);
1414     return lookup(temp.get(),strict);
1415 }
1416
1417 const IEntityDescriptor* XMLMetadata::lookup(const SAMLArtifact* artifact) const
1418 {
1419     time_t now=time(NULL);
1420     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1421     pair<XMLMetadataImpl::sitemap_t::iterator,XMLMetadataImpl::sitemap_t::iterator> range;
1422     
1423     // Depends on type of artifact.
1424     const SAMLArtifactType0001* type1=dynamic_cast<const SAMLArtifactType0001*>(artifact);
1425     if (type1) {
1426         range=impl->m_sources.equal_range(SAMLArtifact::toHex(type1->getSourceID()));
1427     }
1428     else {
1429         const SAMLArtifactType0002* type2=dynamic_cast<const SAMLArtifactType0002*>(artifact);
1430         if (type2) {
1431             range=impl->m_sources.equal_range(type2->getSourceLocation());
1432         }
1433         else
1434             return NULL;
1435     }
1436
1437     // Check exclude list.
1438     if (range.first!=range.second) {
1439         auto_ptr_char id(range.first->second->getId());
1440         if (m_exclusions && m_set.find(id.get())!=m_set.end())
1441             return NULL;
1442         else if (!m_exclusions && m_set.find(id.get())==m_set.end())
1443             return NULL;
1444
1445         for (XMLMetadataImpl::sitemap_t::iterator i=range.first; i!=range.second; i++)
1446             if (now < i->second->getValidUntil())
1447                 return i->second;
1448     }
1449     
1450     return NULL;
1451 }
1452
1453 const IEntitiesDescriptor* XMLMetadata::lookupGroup(const char* name, bool strict) const
1454 {
1455     if (strict && m_exclusions && m_set.find(name)!=m_set.end())
1456         return NULL;
1457     else if (strict && !m_exclusions && m_set.find(name)==m_set.end())
1458         return NULL;
1459         
1460     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1461     pair<XMLMetadataImpl::groupmap_t::iterator,XMLMetadataImpl::groupmap_t::iterator> range=
1462         impl->m_groups.equal_range(name);
1463
1464     time_t now=time(NULL);
1465     for (XMLMetadataImpl::groupmap_t::iterator i=range.first; i!=range.second; i++)
1466         if (now < i->second->getValidUntil())
1467             return i->second;
1468     
1469     if (!strict && range.first!=range.second)
1470         return range.first->second;
1471         
1472     return NULL;
1473 }
1474
1475 const IEntitiesDescriptor* XMLMetadata::lookupGroup(const XMLCh* name, bool strict) const
1476 {
1477     auto_ptr_char temp(name);
1478     return lookupGroup(temp.get(),strict);
1479 }
1480
1481 pair<const IEntitiesDescriptor*,const IEntityDescriptor*> XMLMetadata::getRoot() const
1482 {
1483     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1484     return pair<const IEntitiesDescriptor*,const IEntityDescriptor*>(impl->m_rootGroup,impl->m_rootProvider);
1485 }
1486