Update revision.
[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)
470     : m_root(e), m_type(IContactPerson::other), m_givenName(NULL), m_surName(NULL), m_company(NULL)
471 {
472     const XMLCh* type=NULL;
473
474     // Old metadata or new?
475     if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(Contact))) {
476         type=e->getAttributeNS(NULL,SHIB_L(Type));
477         m_surName=toUTF8(e->getAttributeNS(NULL,SHIB_L(Name)));
478         if (e->hasAttributeNS(NULL,SHIB_L(Email))) {
479             char* temp = toUTF8(e->getAttributeNS(NULL,SHIB_L(Email)));
480             if (temp)
481                 m_emails.push_back(temp);
482             delete[] temp;
483         }
484     }
485     else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(ContactPerson))) {
486         type=e->getAttributeNS(NULL,SHIB_L(contactType));
487         DOMNode* n=NULL;
488         e=saml::XML::getFirstChildElement(e);
489         while (e) {
490             if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(Company))) {
491                 n=e->getFirstChild();
492                 if (n) m_company=toUTF8(n->getNodeValue());
493             }
494             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(GivenName))) {
495                 n=e->getFirstChild();
496                 if (n) m_givenName=toUTF8(n->getNodeValue());
497             }
498             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(SurName))) {
499                 n=e->getFirstChild();
500                 if (n) m_surName=toUTF8(n->getNodeValue());
501             }
502             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EmailAddress))) {
503                 n=e->getFirstChild();
504                 if (n) {
505                     char* temp = toUTF8(n->getNodeValue());
506                     if (temp) m_emails.push_back(temp);
507                     delete[] temp;
508                 }
509             }
510             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(TelephoneNumber))) {
511                 n=e->getFirstChild();
512                 if (n) {
513                     char* temp = toUTF8(n->getNodeValue());
514                     if (temp) m_phones.push_back(temp);
515                     delete[] temp;
516                 }
517             }
518             e=saml::XML::getNextSiblingElement(e);
519         }
520     }
521
522     if (!XMLString::compareString(type,SHIB_L(technical)))
523         m_type=IContactPerson::technical;
524     else if (!XMLString::compareString(type,SHIB_L(support)))
525         m_type=IContactPerson::support;
526     else if (!XMLString::compareString(type,SHIB_L(administrative)))
527         m_type=IContactPerson::administrative;
528     else if (!XMLString::compareString(type,SHIB_L(billing)))
529         m_type=IContactPerson::billing;
530 }
531
532 XMLMetadataImpl::Organization::Organization(const DOMElement* e) : m_root(e)
533 {
534     DOMNode* n=NULL;
535     e=saml::XML::getFirstChildElement(e);
536     while (e) {
537         if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationName))) {
538             n=e->getFirstChild();
539             if (n) {
540                 char* name = toUTF8(n->getNodeValue());
541                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
542                 m_names[lang.get()]=name;
543                 delete[] name;
544             }
545         }
546         else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationDisplayName))) {
547             n=e->getFirstChild();
548             if (n) {
549                 char* display = toUTF8(n->getNodeValue());
550                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
551                 m_displays[lang.get()]=display;
552                 delete[] display;
553             }
554         }
555         else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationURL))) {
556             n=e->getFirstChild();
557             if (n) {
558                 char* url = toUTF8(n->getNodeValue());
559                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
560                 m_urls[lang.get()]=url;
561                 delete[] url;
562             }
563         }
564         e=saml::XML::getNextSiblingElement(e);
565     }
566 }
567
568 XMLMetadataImpl::EncryptionMethod::EncryptionMethod(const DOMElement* e) : m_root(e)
569 {
570     m_alg=e->getAttributeNS(NULL,SHIB_L(Algorithm));
571     e=saml::XML::getFirstChildElement(e);
572     while (e) {
573         if (saml::XML::isElementNamed(e,::XML::XMLENC_NS,SHIB_L(KeySize))) {
574             DOMNode* n=e->getFirstChild();
575             if (n) m_size=XMLString::parseInt(n->getNodeValue());
576         }
577         else if (saml::XML::isElementNamed(e,saml::XML::XMLSIG_NS,SHIB_L(DigestMethod))) {
578             DOMNode* n=e->getFirstChild();
579             if (n) m_digest=n->getNodeValue();
580         }
581         else if (saml::XML::isElementNamed(e,::XML::XMLENC_NS,SHIB_L(OAEParams))) {
582             DOMNode* n=e->getFirstChild();
583             if (n) m_params=n->getNodeValue();
584         }
585         e=saml::XML::getNextSiblingElement(e);
586     }
587 }
588
589 XMLMetadataImpl::KeyDescriptor::KeyDescriptor(const DOMElement* e) : m_root(e), m_use(unspecified), m_klist(NULL)
590 {
591 #ifdef _DEBUG
592     saml::NDC ndc("KeyDescriptor");
593 #endif
594     if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(use)),SHIB_L(encryption)))
595         m_use=encryption;
596     else if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(use)),SHIB_L(signing)))
597         m_use=signing;
598
599     m_klist = new DSIGKeyInfoList(NULL);
600
601     // Process ds:KeyInfo
602     e=saml::XML::getFirstChildElement(e);
603
604     // We let XMLSec hack through anything it can. This should evolve over time, or we can
605     // plug in our own KeyResolver later...
606     try {
607         if (!m_klist->loadListFromXML(const_cast<DOMElement*>(e)))
608             Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
609                 "skipping ds:KeyInfo element containing unsupported children"
610                 );
611     }
612     catch (XSECException& xe) {
613         auto_ptr_char msg(xe.getMsg());
614         Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error("unable to process ds:KeyInfo element: %s",msg.get());
615     }
616     catch (XSECCryptoException& xe) {
617         Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error("unable to process ds:KeyInfo element: %s",xe.getMsg());
618     }
619
620     // Check for encryption methods.
621     e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(EncryptionMethod));
622     while (e) {
623         m_methods.push_back(new EncryptionMethod(e));
624         e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(EncryptionMethod));
625     }
626 }
627
628 XMLMetadataImpl::KeyDescriptor::~KeyDescriptor()
629 {
630     for (vector<const XENCEncryptionMethod*>::iterator i=m_methods.begin(); i!=m_methods.end(); i++)
631         delete const_cast<XENCEncryptionMethod*>(*i);
632     delete m_klist;
633 }
634
635 XMLMetadataImpl::KeyAuthority::KeyAuthority(const DOMElement* e) : m_depth(1)
636 {
637 #ifdef _DEBUG
638     saml::NDC ndc("KeyAuthority");
639 #endif
640     if (e->hasAttributeNS(NULL,SHIB_L(VerifyDepth)))
641         m_depth=XMLString::parseInt(e->getAttributeNS(NULL,SHIB_L(VerifyDepth)));
642
643     // Process ds:KeyInfo children
644     e=saml::XML::getFirstChildElement(e,saml::XML::XMLSIG_NS,L(KeyInfo));
645     while (e) {
646         auto_ptr<DSIGKeyInfoList> klist(new DSIGKeyInfoList(NULL));
647
648         // We let XMLSec hack through anything it can. This should evolve over time, or we can
649         // plug in our own KeyResolver later...
650         DOMElement* child=saml::XML::getFirstChildElement(e);
651         while (child) {
652             try {
653                 if (!klist->addXMLKeyInfo(child)) {
654                     Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
655                         "skipped unresolvable ds:KeyInfo child element");
656                 }
657             }
658             catch (XSECCryptoException& xe) {
659                 Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error(
660                     "unable to process ds:KeyInfo child element: %s",xe.getMsg());
661             }
662             child=saml::XML::getNextSiblingElement(child);
663         }
664
665         if (klist->getSize()>0)
666             m_klists.push_back(klist.release());
667         else
668             Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
669                 "skipping ds:KeyInfo with no resolvable child elements");
670         e=saml::XML::getNextSiblingElement(e,saml::XML::XMLSIG_NS,L(KeyInfo));
671     }
672 }
673
674 XMLMetadataImpl::KeyAuthority::~KeyAuthority()
675 {
676     for (vector<DSIGKeyInfoList*>::iterator i=m_klists.begin(); i!=m_klists.end(); i++)
677         delete (*i);
678 }
679
680 XMLMetadataImpl::Role::Role(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
681     : m_provider(provider), m_root(e), m_protocolEnumCopy(NULL), m_errorURL(NULL), m_org(NULL), m_validUntil(validUntil)
682 {
683     // Check the root element namespace. If SAML2, assume it's the std schema.
684     if (e && !XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
685
686         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
687             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
688             exp.parseDateTime();
689             m_validUntil=min(m_validUntil,exp.getEpoch());
690         }
691
692         if (e->hasAttributeNS(NULL,SHIB_L(errorURL)))
693             m_errorURL=toUTF8(e->getAttributeNS(NULL,SHIB_L(errorURL)));
694
695         // Chop the protocol list into pieces...assume any whitespace can appear in between.
696         m_protocolEnumCopy=XMLString::replicate(e->getAttributeNS(NULL,SHIB_L(protocolSupportEnumeration)));
697         XMLCh* temp=m_protocolEnumCopy;
698         while (temp && *temp) {
699             XMLCh* start=temp++;
700             while (*temp && !XMLChar1_1::isWhitespace(*temp)) temp++;
701             if (*temp)
702                 *temp++=chNull;
703             m_protocolEnum.push_back(start);
704             while (*temp && XMLChar1_1::isWhitespace(*temp)) temp++;
705         }
706
707         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
708         while (e) {
709             m_keys.push_back(new KeyDescriptor(e));
710             e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
711         }
712
713         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(Organization));
714         if (e)
715             m_org=new Organization(e);
716
717         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(ContactPerson));
718         while (e) {
719             m_contacts.push_back(new ContactPerson(e));
720             e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(ContactPerson));
721         }
722     }
723 }
724
725 XMLMetadataImpl::Role::~Role()
726 {
727     delete m_org;
728     delete m_errorURL;
729     if (m_protocolEnumCopy) XMLString::release(&m_protocolEnumCopy);
730     for (vector<const IKeyDescriptor*>::iterator i=m_keys.begin(); i!=m_keys.end(); i++)
731         delete const_cast<IKeyDescriptor*>(*i);
732     for (vector<const IContactPerson*>::iterator j=m_contacts.begin(); j!=m_contacts.end(); j++)
733         delete const_cast<IContactPerson*>(*j);
734 }
735
736 bool XMLMetadataImpl::Role::hasSupport(const XMLCh* protocol) const
737 {
738     Iterator<const XMLCh*> i(m_protocolEnum);
739     while (i.hasNext()) {
740         if (!XMLString::compareString(protocol,i.next()))
741             return true;
742     }
743     return false;
744 }
745
746 XMLMetadataImpl::SSORole::SSORole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
747     : Role(provider,validUntil,e)
748 {
749     // Check the root element namespace. If SAML2, assume it's the std schema.
750     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
751         XMLSize_t i;
752         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(ArtifactResolutionService));
753         for (i=0; nlist && i<nlist->getLength(); i++)
754             m_artifact.add(new IndexedEndpoint(static_cast<DOMElement*>(nlist->item(i))));
755
756         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(SingleLogoutService));
757         for (i=0; nlist && i<nlist->getLength(); i++)
758             m_logout.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
759
760         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(ManageNameIDService));
761         for (i=0; nlist && i<nlist->getLength(); i++)
762             m_nameid.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
763
764         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDFormat));
765         for (i=0; nlist && i<nlist->getLength(); i++) {
766             DOMNode* n=nlist->item(i)->getFirstChild();
767             if (n) m_formats.push_back(n->getNodeValue());
768         }
769     }
770     else {
771         // For old style, we just do SAML 1.1 compatibility with Shib handles.
772         m_protocolEnum.push_back(saml::XML::SAML11_PROTOCOL_ENUM);
773         m_formats.push_back(shibboleth::Constants::SHIB_NAMEID_FORMAT_URI);
774     }
775 }
776
777 XMLMetadataImpl::ScopedRole::ScopedRole(const DOMElement* e)
778 {
779     // Check the root element namespace. If SAML2, assume it's the std schema.
780     DOMNodeList* nlist=NULL;
781     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
782         e=saml::XML::getFirstChildElement(e,::XML::SAML2META_NS,SHIB_L(Extensions));
783         if (e) nlist=e->getElementsByTagNameNS(::XML::SHIBMETA_NS,SHIB_L(Scope));
784     }
785     else {
786         nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(Domain));
787     }
788
789     for (XMLSize_t i=0; nlist && i < nlist->getLength(); i++) {
790         const XMLCh* dom=(nlist->item(i)->hasChildNodes()) ? nlist->item(i)->getFirstChild()->getNodeValue() : NULL;
791         if (dom && *dom) {
792             const XMLCh* regexp=static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(regexp));
793             m_scopes.push_back(
794                 pair<const XMLCh*,bool>(dom,(regexp && (*regexp==chLatin_t || *regexp==chDigit_1)))
795                 );
796         }
797     }
798 }
799
800 XMLMetadataImpl::IDPRole::IDPRole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
801     : SSORole(provider,validUntil,e), ScopedRole(e), m_wantAuthnRequestsSigned(false), m_sourceId(NULL)
802 {
803     // Check the root element namespace. If SAML2, assume it's the std schema.
804     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
805         const XMLCh* flag=e->getAttributeNS(NULL,SHIB_L(WantAuthnRequestsSigned));
806         m_wantAuthnRequestsSigned=(flag && (*flag==chDigit_1 || *flag==chLatin_t));
807
808         // Check for SourceID extension.
809         DOMElement* ext=saml::XML::getFirstChildElement(e,::XML::SAML2META_NS,SHIB_L(Extensions));
810         if (ext) {
811             ext=saml::XML::getFirstChildElement(ext,saml::XML::SAML_ARTIFACT_SOURCEID,SHIB_L(SourceID));
812             if (ext && ext->hasChildNodes())
813                 m_sourceId=ext->getFirstChild()->getNodeValue();
814         }
815
816         XMLSize_t i;
817         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(SingleSignOnService));
818         for (i=0; nlist && i<nlist->getLength(); i++)
819             m_sso.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
820
821         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDMappingService));
822         for (i=0; nlist && i<nlist->getLength(); i++)
823             m_mapping.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
824
825         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AssertionIDRequestService));
826         for (i=0; nlist && i<nlist->getLength(); i++)
827             m_idreq.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
828
829         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeProfile));
830         for (i=0; nlist && i<nlist->getLength(); i++) {
831             DOMNode* n=nlist->item(i)->getFirstChild();
832             if (n) m_attrprofs.push_back(n->getNodeValue());
833         }
834
835         nlist=e->getElementsByTagNameNS(::XML::SAML2ASSERT_NS,L(Attribute));
836         for (i=0; nlist && i<nlist->getLength(); i++) {
837             // For now, we need to convert these to plain SAML 1.1 attributes.
838             DOMElement* src=static_cast<DOMElement*>(nlist->item(i));
839             DOMElement* copy=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(Attribute));
840             copy->setAttributeNS(NULL,L(AttributeName),src->getAttributeNS(NULL,SHIB_L(Name)));
841             copy->setAttributeNS(NULL,L(AttributeNamespace),src->getAttributeNS(NULL,SHIB_L(NameFormat)));
842             src=saml::XML::getFirstChildElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
843             while (src) {
844                 src=saml::XML::getNextSiblingElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
845                 DOMElement* val=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(AttributeValue));
846                 DOMNamedNodeMap* attrs = src->getAttributes();
847                 for (XMLSize_t j=0; j<attrs->getLength(); j++)
848                     val->setAttributeNodeNS(static_cast<DOMAttr*>(e->getOwnerDocument()->importNode(attrs->item(j),true)));
849                 while (src->hasChildNodes())
850                     val->appendChild(src->getFirstChild());
851                 copy->appendChild(val);
852             }
853             m_attrs.push_back(SAMLAttribute::getInstance(copy));
854         }
855     }
856     else {
857         m_protocolEnum.push_back(Constants::SHIB_NS);
858         m_attrprofs.push_back(Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
859         XMLSize_t i;
860         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(HandleService));
861         for (i=0; nlist && i<nlist->getLength(); i++) {
862             // Manufacture an endpoint for the "Shib" binding.
863             m_sso.add(
864                 new Endpoint(Constants::SHIB_AUTHNREQUEST_PROFILE_URI,static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,L(Location)))
865                 );
866
867             // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
868             DOMElement* kd=e->getOwnerDocument()->createElementNS(::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
869             DOMElement* ki=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,L(KeyInfo));
870             DOMElement* kn=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,SHIB_L(KeyName));
871             kn->appendChild(
872                 e->getOwnerDocument()->createTextNode(
873                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Name))
874                     )
875                 );
876             ki->appendChild(kn);
877             kd->appendChild(ki);
878             kd->setAttributeNS(NULL,SHIB_L(use),SHIB_L(signing));
879             m_keys.push_back(new KeyDescriptor(kd));
880         }
881     }
882 }
883
884 XMLMetadataImpl::IDPRole::~IDPRole()
885 {
886     for (vector<const SAMLAttribute*>::iterator i=m_attrs.begin(); i!=m_attrs.end(); i++)
887         delete const_cast<SAMLAttribute*>(*i);
888 }
889
890 XMLMetadataImpl::AARole::AARole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
891     : Role(provider,validUntil,e), ScopedRole(e)
892 {
893     // Check the root element namespace. If SAML2, assume it's the std schema.
894     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
895         XMLSize_t i;
896         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeService));
897         for (i=0; nlist && i<nlist->getLength(); i++)
898             m_query.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
899
900         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AssertionIDRequestService));
901         for (i=0; nlist && i<nlist->getLength(); i++)
902             m_idreq.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
903
904         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDFormat));
905         for (i=0; nlist && i<nlist->getLength(); i++) {
906             DOMNode* n=nlist->item(i)->getFirstChild();
907             if (n) m_formats.push_back(n->getNodeValue());
908         }
909
910         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeProfile));
911         for (i=0; nlist && i<nlist->getLength(); i++) {
912             DOMNode* n=nlist->item(i)->getFirstChild();
913             if (n) m_attrprofs.push_back(n->getNodeValue());
914         }
915
916         nlist=e->getElementsByTagNameNS(::XML::SAML2ASSERT_NS,L(Attribute));
917         for (i=0; nlist && i<nlist->getLength(); i++) {
918             // For now, we need to convert these to plain SAML 1.1 attributes.
919             DOMElement* src=static_cast<DOMElement*>(nlist->item(i));
920             DOMElement* copy=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(Attribute));
921             copy->setAttributeNS(NULL,L(AttributeName),src->getAttributeNS(NULL,SHIB_L(Name)));
922             copy->setAttributeNS(NULL,L(AttributeNamespace),src->getAttributeNS(NULL,SHIB_L(NameFormat)));
923             src=saml::XML::getFirstChildElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
924             while (src) {
925                 src=saml::XML::getNextSiblingElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
926                 DOMElement* val=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(AttributeValue));
927                 DOMNamedNodeMap* attrs = src->getAttributes();
928                 for (XMLSize_t j=0; j<attrs->getLength(); j++)
929                     val->setAttributeNodeNS(static_cast<DOMAttr*>(e->getOwnerDocument()->importNode(attrs->item(j),true)));
930                 while (src->hasChildNodes())
931                     val->appendChild(src->getFirstChild());
932                 copy->appendChild(val);
933             }
934             m_attrs.push_back(SAMLAttribute::getInstance(copy));
935         }
936     }
937     else {
938         // For old style, we just do SAML 1.1 compatibility with Shib handles.
939         m_protocolEnum.push_back(saml::XML::SAML11_PROTOCOL_ENUM);
940         m_formats.push_back(Constants::SHIB_NAMEID_FORMAT_URI);
941         m_attrprofs.push_back(Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
942         XMLSize_t i;
943         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(AttributeAuthority));
944         for (i=0; nlist && i<nlist->getLength(); i++) {
945             // Manufacture an endpoint for the SOAP binding.
946             m_query.add(
947                 new Endpoint(
948                     SAMLBinding::SOAP,
949                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,L(Location))
950                     )
951                 );
952
953             // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
954             DOMElement* kd=e->getOwnerDocument()->createElementNS(::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
955             DOMElement* ki=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,L(KeyInfo));
956             DOMElement* kn=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,SHIB_L(KeyName));
957             kn->appendChild(
958                 e->getOwnerDocument()->createTextNode(
959                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Name))
960                     )
961                 );
962             ki->appendChild(kn);
963             kd->appendChild(ki);
964             m_keys.push_back(new KeyDescriptor(kd));
965         }
966     }
967 }
968
969 XMLMetadataImpl::AARole::~AARole()
970 {
971     for (vector<const SAMLAttribute*>::iterator i=m_attrs.begin(); i!=m_attrs.end(); i++)
972         delete const_cast<SAMLAttribute*>(*i);
973 }
974
975 XMLMetadataImpl::EntityDescriptor::EntityDescriptor(
976     const DOMElement* e, XMLMetadataImpl* wrapper, time_t validUntil, const IEntitiesDescriptor* parent
977     ) : m_root(e), m_parent(parent), m_id(NULL), m_errorURL(NULL), m_org(NULL), m_validUntil(validUntil)
978 {
979     // Check the root element namespace. If SAML2, assume it's the std schema.
980     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
981         m_id=e->getAttributeNS(NULL,SHIB_L(entityID));
982
983         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
984             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
985             exp.parseDateTime();
986             m_validUntil=min(validUntil,exp.getEpoch());
987         }
988
989         DOMElement* child=saml::XML::getFirstChildElement(e);
990         while (child) {
991             // Process the various kinds of children that we care about...
992             if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(Extensions))) {
993                 DOMElement* ext = saml::XML::getFirstChildElement(child,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
994                 while (ext) {
995                     m_keyauths.push_back(new KeyAuthority(ext));
996                     ext = saml::XML::getNextSiblingElement(ext,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
997                 }
998             }
999             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(ContactPerson))) {
1000                 m_contacts.push_back(new ContactPerson(child));
1001             }
1002             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(Organization))) {
1003                 m_org=new Organization(child);
1004             }
1005             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(AdditionalMetadataLocation))) {
1006                 DOMNode* loc=child->getFirstChild();
1007                 if (loc)
1008                     m_locs.push_back(
1009                     pair<const XMLCh*,const XMLCh*>(child->getAttributeNS(NULL,::XML::Literals::_namespace),loc->getNodeValue())
1010                         );
1011             }
1012             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(IDPSSODescriptor))) {
1013                 if (wrapper->m_outer->verifySignature(child->getOwnerDocument(),child,false))
1014                     m_roles.push_back(new IDPRole(this,m_validUntil,child));
1015             }
1016             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(AttributeAuthorityDescriptor))) {
1017                 if (wrapper->m_outer->verifySignature(child->getOwnerDocument(),child,false))
1018                     m_roles.push_back(new AARole(this,m_validUntil,child));
1019             }
1020             child = saml::XML::getNextSiblingElement(child);
1021         }
1022     }
1023     else {
1024         m_id=e->getAttributeNS(NULL,SHIB_L(Name));
1025         m_errorURL=toUTF8(e->getAttributeNS(NULL,SHIB_L(ErrorURL)));
1026
1027         bool idp=false,aa=false;    // only want to build a role once
1028         DOMElement* child=saml::XML::getFirstChildElement(e);
1029         while (child) {
1030             // Process the various kinds of OriginSite children that we care about...
1031             if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(Contact))) {
1032                 m_contacts.push_back(new ContactPerson(child));
1033             }
1034             else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(HandleService)) && !idp) {
1035                 // Create the IDP role if needed.
1036                 m_roles.push_back(new IDPRole(this, m_validUntil, e));
1037                 idp=true;
1038             }
1039             else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(AttributeAuthority)) && !aa) {
1040                 // Create the AA role if needed.
1041                 m_roles.push_back(new AARole(this, m_validUntil, e));
1042                 aa=true;
1043             }
1044             child = saml::XML::getNextSiblingElement(child);
1045         }
1046     }
1047
1048     if (m_id && *m_id) {
1049         auto_ptr_char id(m_id);
1050         wrapper->m_sites.insert(pair<const string,const EntityDescriptor*>(id.get(),this));
1051
1052         // Look for an IdP role, and register the artifact source ID and endpoints.
1053         const IDPRole* idp=NULL;
1054         for (vector<const IRoleDescriptor*>::const_iterator r=m_roles.begin(); r!=m_roles.end(); r++) {
1055             if (idp=dynamic_cast<const IDPRole*>(*r)) {
1056                 if (idp->m_sourceId) {
1057                     auto_ptr_char sourceid(idp->m_sourceId);
1058                     wrapper->m_sources.insert(pair<const string,const EntityDescriptor*>(sourceid.get(),this));
1059                 }
1060                 else {
1061                     string sourceid=SAMLArtifact::toHex(SAMLArtifactType0001::generateSourceId(id.get()));
1062                     wrapper->m_sources.insert(pair<const string,const EntityDescriptor*>(sourceid,this));
1063                 }
1064                 Iterator<const IEndpoint*> locs=idp->getArtifactResolutionServiceManager()->getEndpoints();
1065                 while (locs.hasNext()) {
1066                     auto_ptr_char loc(locs.next()->getLocation());
1067                     wrapper->m_sources.insert(pair<const string,const EntityDescriptor*>(loc.get(),this));
1068                 }
1069             }
1070         }
1071     }
1072 }
1073
1074 const IIDPSSODescriptor* XMLMetadataImpl::EntityDescriptor::getIDPSSODescriptor(const XMLCh* protocol) const
1075 {
1076     const IIDPSSODescriptor* ret=NULL;
1077     for (vector<const IRoleDescriptor*>::const_iterator i=m_roles.begin(); i!=m_roles.end(); i++) {
1078         if ((*i)->hasSupport(protocol) && (*i)->isValid() && (ret=dynamic_cast<const IIDPSSODescriptor*>(*i)))
1079             return ret;
1080     }
1081     return NULL;
1082 }
1083
1084 const IAttributeAuthorityDescriptor* XMLMetadataImpl::EntityDescriptor::getAttributeAuthorityDescriptor(const XMLCh* protocol) const
1085 {
1086     const IAttributeAuthorityDescriptor* ret=NULL;
1087     for (vector<const IRoleDescriptor*>::const_iterator i=m_roles.begin(); i!=m_roles.end(); i++) {
1088         if ((*i)->hasSupport(protocol) && (*i)->isValid() && (ret=dynamic_cast<const IAttributeAuthorityDescriptor*>(*i)))
1089             return ret;
1090     }
1091     return NULL;
1092 }
1093
1094 XMLMetadataImpl::EntityDescriptor::~EntityDescriptor()
1095 {
1096     delete[] m_errorURL;
1097     delete m_org;
1098     for (vector<const IContactPerson*>::iterator i=m_contacts.begin(); i!=m_contacts.end(); i++)
1099         delete const_cast<IContactPerson*>(*i);
1100     for (vector<const IRoleDescriptor*>::iterator j=m_roles.begin(); j!=m_roles.end(); j++)
1101         delete const_cast<IRoleDescriptor*>(*j);
1102     for (vector<const IKeyAuthority*>::iterator k=m_keyauths.begin(); k!=m_keyauths.end(); k++)
1103         delete const_cast<IKeyAuthority*>(*k);
1104 }
1105
1106 XMLMetadataImpl::EntitiesDescriptor::EntitiesDescriptor(
1107     const DOMElement* e, XMLMetadataImpl* wrapper, time_t validUntil, const IEntitiesDescriptor* parent
1108     ) : m_root(e),  m_parent(parent), m_name(e->getAttributeNS(NULL,SHIB_L(Name))), m_validUntil(validUntil)
1109 {
1110     // Check the root element namespace. If SAML2, assume it's the std schema.
1111     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
1112
1113         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
1114             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
1115             exp.parseDateTime();
1116             m_validUntil=min(validUntil,exp.getEpoch());
1117         }
1118
1119         e=saml::XML::getFirstChildElement(e);
1120         while (e) {
1121             if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(Extensions))) {
1122                 DOMElement* ext = saml::XML::getFirstChildElement(e,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
1123                 while (ext) {
1124                     m_keyauths.push_back(new KeyAuthority(ext));
1125                     ext = saml::XML::getNextSiblingElement(ext,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
1126                 }
1127             }
1128             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EntitiesDescriptor))) {
1129                 if (wrapper->m_outer->verifySignature(e->getOwnerDocument(),e,false))
1130                     m_groups.push_back(new EntitiesDescriptor(e,wrapper,m_validUntil,this));
1131             }
1132             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EntityDescriptor))) {
1133                 if (wrapper->m_outer->verifySignature(e->getOwnerDocument(),e,false))
1134                     m_providers.push_back(new EntityDescriptor(e,wrapper,m_validUntil,this));
1135             }
1136             e=saml::XML::getNextSiblingElement(e);
1137         }
1138     }
1139     else {
1140         e=saml::XML::getFirstChildElement(e);
1141         while (e) {
1142             if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(SiteGroup))) {
1143                 if (wrapper->m_outer->verifySignature(e->getOwnerDocument(),e,false))
1144                     m_groups.push_back(new EntitiesDescriptor(e,wrapper,m_validUntil,this));
1145             }
1146             else if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(OriginSite)))
1147                 m_providers.push_back(new EntityDescriptor(e,wrapper,m_validUntil,this));
1148             e=saml::XML::getNextSiblingElement(e);
1149         }
1150     }
1151
1152     if (!saml::XML::isEmpty(m_name)) {
1153         auto_ptr_char n(m_name);
1154         wrapper->m_groups.insert(pair<const string,const EntitiesDescriptor*>(n.get(),this));
1155     }
1156     else
1157         m_name=NULL;
1158 }
1159
1160 XMLMetadataImpl::EntitiesDescriptor::~EntitiesDescriptor()
1161 {
1162     for (vector<const IEntityDescriptor*>::iterator i=m_providers.begin(); i!=m_providers.end(); i++)
1163         delete const_cast<IEntityDescriptor*>(*i);
1164     for (vector<const IEntitiesDescriptor*>::iterator j=m_groups.begin(); j!=m_groups.end(); j++)
1165         delete const_cast<IEntitiesDescriptor*>(*j);
1166     for (vector<const IKeyAuthority*>::iterator k=m_keyauths.begin(); k!=m_keyauths.end(); k++)
1167         delete const_cast<IKeyAuthority*>(*k);
1168 }
1169
1170 void XMLMetadataImpl::init()
1171 {
1172 #ifdef _DEBUG
1173     NDC ndc("init");
1174 #endif
1175     Category& log=Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata");
1176
1177     try
1178     {
1179         if (saml::XML::isElementNamed(m_root,::XML::SAML2META_NS,SHIB_L(EntitiesDescriptor))) {
1180             if (m_outer->verifySignature(m_root->getOwnerDocument(),m_root,true))
1181                 m_rootGroup=new EntitiesDescriptor(m_root,this);
1182         }
1183         else if (saml::XML::isElementNamed(m_root,::XML::SAML2META_NS,SHIB_L(EntityDescriptor))) {
1184             if (m_outer->verifySignature(m_root->getOwnerDocument(),m_root,true))
1185                 m_rootProvider=new EntityDescriptor(m_root,this);
1186         }
1187         else if (saml::XML::isElementNamed(m_root,::XML::SHIB_NS,SHIB_L(SiteGroup))) {
1188             if (m_outer->verifySignature(m_root->getOwnerDocument(),m_root,true))
1189                 m_rootGroup=new EntitiesDescriptor(m_root,this);
1190         }
1191         else if (saml::XML::isElementNamed(m_root,::XML::SHIB_NS,SHIB_L(OriginSite))) {
1192             if (m_outer->verifySignature(m_root->getOwnerDocument(),m_root,true))
1193                 m_rootProvider=new EntityDescriptor(m_root,this);
1194         }
1195         else {
1196             log.error("Construction requires a valid SAML metadata file");
1197             throw MetadataException("Construction requires a valid SAML metadata file");
1198         }
1199     }
1200     catch (SAMLException& e)
1201     {
1202         log.errorStream() << "Error while parsing SAML metadata: " << e.what() << xmlproviders::logging::eol;
1203         this->~XMLMetadataImpl();
1204         throw;
1205     }
1206 #ifndef _DEBUG
1207     catch (...)
1208     {
1209         log.error("Unexpected error while parsing SAML metadata");
1210         this->~XMLMetadataImpl();
1211         throw;
1212     }
1213 #endif
1214
1215     if (!m_rootGroup && !m_rootProvider) {
1216         log.error("Metadata file contained no valid information");
1217         throw MetadataException("Metadata file contained no valid information");
1218     }
1219 }
1220
1221 XMLMetadataImpl::~XMLMetadataImpl()
1222 {
1223     delete m_rootGroup;
1224     delete m_rootProvider;
1225 }
1226
1227 XMLMetadata::XMLMetadata(const DOMElement* e) : ReloadableXMLFile(e), m_exclusions(true), m_verify(false), m_credResolver(NULL)
1228 {
1229     static const XMLCh uri[] = { chLatin_u, chLatin_r, chLatin_i, chNull };
1230     if (e->hasAttributeNS(NULL,uri)) {
1231         // First check for explicit enablement of entities.
1232         DOMNodeList* nlist=e->getElementsByTagName(SHIB_L(Include));
1233         for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
1234             if (nlist->item(i)->hasChildNodes()) {
1235                 auto_ptr_char temp(nlist->item(i)->getFirstChild()->getNodeValue());
1236                 if (temp.get()) {
1237                     m_set.insert(temp.get());
1238                     m_exclusions=false;
1239                 }
1240             }
1241         }
1242         // If there was no explicit enablement, build a set of exclusions.
1243         if (m_exclusions) {
1244             nlist=e->getElementsByTagName(SHIB_L(Exclude));
1245             for (XMLSize_t j=0; nlist && j<nlist->getLength(); j++) {
1246                 if (nlist->item(j)->hasChildNodes()) {
1247                     auto_ptr_char temp(nlist->item(j)->getFirstChild()->getNodeValue());
1248                     if (temp.get())
1249                         m_set.insert(temp.get());
1250                 }
1251             }
1252         }
1253     }
1254
1255     const XMLCh* v=e->getAttributeNS(NULL,SHIB_L(verify));
1256     m_verify=(v && (*v==chLatin_t || *v==chDigit_1));
1257
1258     string cr_type;
1259     DOMElement* r=saml::XML::getFirstChildElement(e,::XML::CREDS_NS,SHIB_L(FileResolver));
1260     if (r)
1261         cr_type="edu.internet2.middleware.shibboleth.common.Credentials.FileCredentialResolver";
1262     else {
1263         r=saml::XML::getFirstChildElement(e,::XML::CREDS_NS,SHIB_L(CustomResolver));
1264         if (r) {
1265             auto_ptr_char c(r->getAttributeNS(NULL,SHIB_L(Class)));
1266             cr_type=c.get();
1267         }
1268     }
1269
1270     if (!cr_type.empty()) {
1271         try {
1272             IPlugIn* plugin=SAMLConfig::getConfig().getPlugMgr().newPlugin(cr_type.c_str(),r);
1273             ICredResolver* cr=dynamic_cast<ICredResolver*>(plugin);
1274             if (cr)
1275                 m_credResolver=cr;
1276             else {
1277                 Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error("plugin was not a credential resolver");
1278                 delete plugin;
1279                 throw UnsupportedExtensionException("plugin was not a credential resolver");
1280             }
1281         }
1282         catch (SAMLException& e) {
1283             Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error("failed to instantiate credential resolver: %s", e.what());
1284             throw;
1285         }
1286     }
1287
1288     if (m_verify && !m_credResolver) {
1289         delete m_credResolver;
1290         throw MalformedException("Metadata provider told to verify signatures, but a verification key is not available.");
1291     }
1292 }
1293
1294 bool XMLMetadata::verifySignature(DOMDocument* doc, const DOMElement* parent, bool failUnsigned) const
1295 {
1296     if (!m_verify)
1297         return true;
1298
1299 #ifdef _DEBUG
1300     saml::NDC ndc("verifySignature");
1301 #endif
1302     Category& log=Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata");
1303
1304     DOMElement* sigNode=saml::XML::getFirstChildElement(parent,saml::XML::XMLSIG_NS,L(Signature));
1305     if (!sigNode) {
1306         if (failUnsigned) {
1307             log.error("rejecting unsigned element");
1308             return false;
1309         }
1310         return true;
1311     }
1312
1313     XSECCryptoX509* cert=NULL;
1314     Iterator<XSECCryptoX509*> certs=m_credResolver->getCertificates();
1315     if (certs.hasNext())
1316         cert=certs.next();
1317     else {
1318         log.error("unable to find any certificates to use in verifying signature");
1319         return false;
1320     }
1321
1322     static const XMLCh ID[]={chLatin_I, chLatin_D, chNull};
1323     static const XMLCh null[]={chDoubleQuote, chDoubleQuote, chNull};
1324
1325     // Load the signature.
1326     XSECProvider prov;
1327     DSIGSignature* sig=NULL;
1328     try {
1329         sig=prov.newSignatureFromDOM(doc,sigNode);
1330         sig->load();
1331
1332         bool valid=false;
1333         const XMLCh* URI=NULL;
1334
1335         // Verify the signature coverage.
1336         DSIGReferenceList* refs=sig->getReferenceList();
1337         if (sig->getSignatureMethod()==SIGNATURE_RSA && refs && refs->getSize()==1) {
1338             DSIGReference* ref=refs->item(0);
1339             if (ref) {
1340                 URI=ref->getURI();
1341                 if (!URI || !*URI || (*URI==chPound &&
1342                         !XMLString::compareString(&URI[1],static_cast<DOMElement*>(sigNode->getParentNode())->getAttributeNS(NULL,ID)))) {
1343                     DSIGTransformList* tlist=ref->getTransforms();
1344                     for (unsigned int i=0; tlist && i<tlist->getSize(); i++) {
1345                         if (tlist->item(i)->getTransformType()==TRANSFORM_ENVELOPED_SIGNATURE)
1346                             valid=true;
1347                         else if (tlist->item(i)->getTransformType()!=TRANSFORM_EXC_C14N &&
1348                                  tlist->item(i)->getTransformType()!=TRANSFORM_C14N) {
1349                             valid=false;
1350                             break;
1351                         }
1352                     }
1353                 }
1354             }
1355         }
1356
1357         if (!valid) {
1358             auto_ptr_char temp((URI && *URI) ? URI : null);
1359             log.error("detected an invalid signature profile (Reference URI was %s)",temp.get());
1360             return false;
1361         }
1362
1363         sig->setSigningKey(cert->clonePublicKey());
1364         if (!sig->verify()) {
1365             auto_ptr_char temp((URI && *URI) ? URI : null);
1366             log.error("detected an invalid signature value (Reference URI was %s)",temp.get());
1367             return false;
1368         }
1369
1370         prov.releaseSignature(sig);
1371     }
1372     catch(XSECException& e) {
1373         auto_ptr_char msg(e.getMsg());
1374         log.errorStream() << "caught XMLSec exception while verifying metadata signature: " << msg.get() << xmlproviders::logging::eol;
1375         if (sig)
1376             prov.releaseSignature(sig);
1377         return false;
1378     }
1379     catch(XSECCryptoException& e) {
1380         log.errorStream() << "caught XMLSecCrypto exception while verifying metadata signature: " << e.getMsg() << xmlproviders::logging::eol;
1381         if (sig)
1382             prov.releaseSignature(sig);
1383         return false;
1384     }
1385     catch(...) {
1386         if (sig)
1387             prov.releaseSignature(sig);
1388         log.error("caught unknown exception while verifying metadata signature");
1389         throw;
1390     }
1391     return true;
1392 }
1393
1394 const IEntityDescriptor* XMLMetadata::lookup(const char* providerId, bool strict) const
1395 {
1396     if (strict && m_exclusions && m_set.find(providerId)!=m_set.end())
1397         return NULL;
1398     else if (strict && !m_exclusions && m_set.find(providerId)==m_set.end())
1399         return NULL;
1400
1401     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1402     pair<XMLMetadataImpl::sitemap_t::iterator,XMLMetadataImpl::sitemap_t::iterator> range=
1403         impl->m_sites.equal_range(providerId);
1404
1405     time_t now=time(NULL);
1406     for (XMLMetadataImpl::sitemap_t::const_iterator i=range.first; i!=range.second; i++)
1407         if (now < i->second->getValidUntil())
1408             return i->second;
1409
1410     if (!strict && range.first!=range.second)
1411         return range.first->second;
1412
1413     return NULL;
1414 }
1415
1416 const IEntityDescriptor* XMLMetadata::lookup(const XMLCh* providerId, bool strict) const
1417 {
1418     auto_ptr_char temp(providerId);
1419     return lookup(temp.get(),strict);
1420 }
1421
1422 const IEntityDescriptor* XMLMetadata::lookup(const SAMLArtifact* artifact) const
1423 {
1424     time_t now=time(NULL);
1425     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1426     pair<XMLMetadataImpl::sitemap_t::iterator,XMLMetadataImpl::sitemap_t::iterator> range;
1427
1428     // Depends on type of artifact.
1429     const SAMLArtifactType0001* type1=dynamic_cast<const SAMLArtifactType0001*>(artifact);
1430     if (type1) {
1431         range=impl->m_sources.equal_range(SAMLArtifact::toHex(type1->getSourceID()));
1432     }
1433     else {
1434         const SAMLArtifactType0002* type2=dynamic_cast<const SAMLArtifactType0002*>(artifact);
1435         if (type2) {
1436             range=impl->m_sources.equal_range(type2->getSourceLocation());
1437         }
1438         else
1439             return NULL;
1440     }
1441
1442     // Check exclude list.
1443     if (range.first!=range.second) {
1444         auto_ptr_char id(range.first->second->getId());
1445         if (m_exclusions && m_set.find(id.get())!=m_set.end())
1446             return NULL;
1447         else if (!m_exclusions && m_set.find(id.get())==m_set.end())
1448             return NULL;
1449
1450         for (XMLMetadataImpl::sitemap_t::iterator i=range.first; i!=range.second; i++)
1451             if (now < i->second->getValidUntil())
1452                 return i->second;
1453     }
1454
1455     return NULL;
1456 }
1457
1458 const IEntitiesDescriptor* XMLMetadata::lookupGroup(const char* name, bool strict) const
1459 {
1460     if (strict && m_exclusions && m_set.find(name)!=m_set.end())
1461         return NULL;
1462     else if (strict && !m_exclusions && m_set.find(name)==m_set.end())
1463         return NULL;
1464
1465     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1466     pair<XMLMetadataImpl::groupmap_t::iterator,XMLMetadataImpl::groupmap_t::iterator> range=
1467         impl->m_groups.equal_range(name);
1468
1469     time_t now=time(NULL);
1470     for (XMLMetadataImpl::groupmap_t::iterator i=range.first; i!=range.second; i++)
1471         if (now < i->second->getValidUntil())
1472             return i->second;
1473
1474     if (!strict && range.first!=range.second)
1475         return range.first->second;
1476
1477     return NULL;
1478 }
1479
1480 const IEntitiesDescriptor* XMLMetadata::lookupGroup(const XMLCh* name, bool strict) const
1481 {
1482     auto_ptr_char temp(name);
1483     return lookupGroup(temp.get(),strict);
1484 }
1485
1486 pair<const IEntitiesDescriptor*,const IEntityDescriptor*> XMLMetadata::getRoot() const
1487 {
1488     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1489     return pair<const IEntitiesDescriptor*,const IEntityDescriptor*>(impl->m_rootGroup,impl->m_rootProvider);
1490 }
1491