Major revamp of credential and trust handling code, PKIX engine still needs work.
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / AbstractMetadataProvider.cpp
1 /*
2  *  Copyright 2001-2007 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  * AbstractMetadataProvider.cpp
19  * 
20  * Base class for caching metadata providers.
21  */
22
23 #include "internal.h"
24 #include "binding/SAMLArtifact.h"
25 #include "saml2/metadata/Metadata.h"
26 #include "saml2/metadata/AbstractMetadataProvider.h"
27 #include "saml2/metadata/MetadataCredentialCriteria.h"
28
29 #include <xercesc/util/XMLUniDefs.hpp>
30 #include <xmltooling/security/KeyInfoResolver.h>
31 #include <xmltooling/util/XMLHelper.h>
32
33 using namespace opensaml::saml2md;
34 using namespace xmltooling;
35 using namespace std;
36 using opensaml::SAMLArtifact;
37
38 static const XMLCh _KeyInfoResolver[] = UNICODE_LITERAL_15(K,e,y,I,n,f,o,R,e,s,o,l,v,e,r);
39 static const XMLCh type[] =             UNICODE_LITERAL_4(t,y,p,e);
40
41 AbstractMetadataProvider::AbstractMetadataProvider(const DOMElement* e)
42     : ObservableMetadataProvider(e), m_resolver(NULL), m_credentialLock(NULL)
43 {
44     e = e ? XMLHelper::getFirstChildElement(e, _KeyInfoResolver) : NULL;
45     if (e) {
46         auto_ptr_char t(e->getAttributeNS(NULL,type));
47         if (t.get())
48             m_resolver = XMLToolingConfig::getConfig().KeyInfoResolverManager.newPlugin(t.get(),e);
49         else
50             throw UnknownExtensionException("<KeyInfoResolver> element found with no type attribute");
51     }
52     m_credentialLock = Mutex::create();
53 }
54
55 AbstractMetadataProvider::~AbstractMetadataProvider()
56 {
57     for (credmap_t::iterator c = m_credentialMap.begin(); c!=m_credentialMap.end(); ++c)
58         for_each(c->second.begin(), c->second.end(), cleanup_pair<const XMLCh*,Credential>());
59     delete m_credentialLock;
60     delete m_resolver;
61 }
62
63 void AbstractMetadataProvider::emitChangeEvent()
64 {
65     for (credmap_t::iterator c = m_credentialMap.begin(); c!=m_credentialMap.end(); ++c)
66         for_each(c->second.begin(), c->second.end(), cleanup_pair<const XMLCh*,Credential>());
67     m_credentialMap.clear();
68     ObservableMetadataProvider::emitChangeEvent();
69 }
70
71 void AbstractMetadataProvider::index(EntityDescriptor* site, time_t validUntil)
72 {
73     if (validUntil < site->getValidUntilEpoch())
74         site->setValidUntil(validUntil);
75
76     auto_ptr_char id(site->getEntityID());
77     if (id.get()) {
78         m_sites.insert(make_pair(id.get(),site));
79     }
80     
81     // Process each IdP role.
82     const vector<IDPSSODescriptor*>& roles=const_cast<const EntityDescriptor*>(site)->getIDPSSODescriptors();
83     for (vector<IDPSSODescriptor*>::const_iterator i=roles.begin(); i!=roles.end(); i++) {
84         // SAML 1.x?
85         if ((*i)->hasSupport(samlconstants::SAML10_PROTOCOL_ENUM) || (*i)->hasSupport(samlconstants::SAML11_PROTOCOL_ENUM)) {
86             // Check for SourceID extension element.
87             const Extensions* exts=(*i)->getExtensions();
88             if (exts && exts->hasChildren()) {
89                 const vector<XMLObject*>& children=exts->getUnknownXMLObjects();
90                 for (vector<XMLObject*>::const_iterator ext=children.begin(); ext!=children.end(); ++ext) {
91                     SourceID* sid=dynamic_cast<SourceID*>(*ext);
92                     if (sid) {
93                         auto_ptr_char sourceid(sid->getID());
94                         if (sourceid.get()) {
95                             m_sources.insert(pair<string,const EntityDescriptor*>(sourceid.get(),site));
96                             break;
97                         }
98                     }
99                 }
100             }
101             
102             // Hash the ID.
103             m_sources.insert(
104                 pair<string,const EntityDescriptor*>(SAMLConfig::getConfig().hashSHA1(id.get(), true),site)
105                 );
106                 
107             // Load endpoints for type 0x0002 artifacts.
108             const vector<ArtifactResolutionService*>& locs=const_cast<const IDPSSODescriptor*>(*i)->getArtifactResolutionServices();
109             for (vector<ArtifactResolutionService*>::const_iterator loc=locs.begin(); loc!=locs.end(); loc++) {
110                 auto_ptr_char location((*loc)->getLocation());
111                 if (location.get())
112                     m_sources.insert(pair<string,const EntityDescriptor*>(location.get(),site));
113             }
114         }
115         
116         // SAML 2.0?
117         if ((*i)->hasSupport(samlconstants::SAML20P_NS)) {
118             // Hash the ID.
119             m_sources.insert(
120                 pair<string,const EntityDescriptor*>(SAMLConfig::getConfig().hashSHA1(id.get(), true),site)
121                 );
122         }
123     }
124 }
125
126 void AbstractMetadataProvider::index(EntitiesDescriptor* group, time_t validUntil)
127 {
128     if (validUntil < group->getValidUntilEpoch())
129         group->setValidUntil(validUntil);
130
131     auto_ptr_char name(group->getName());
132     if (name.get()) {
133         m_groups.insert(make_pair(name.get(),group));
134     }
135     
136     const vector<EntitiesDescriptor*>& groups=const_cast<const EntitiesDescriptor*>(group)->getEntitiesDescriptors();
137     for (vector<EntitiesDescriptor*>::const_iterator i=groups.begin(); i!=groups.end(); i++)
138         index(*i,group->getValidUntilEpoch());
139
140     const vector<EntityDescriptor*>& sites=const_cast<const EntitiesDescriptor*>(group)->getEntityDescriptors();
141     for (vector<EntityDescriptor*>::const_iterator j=sites.begin(); j!=sites.end(); j++)
142         index(*j,group->getValidUntilEpoch());
143 }
144
145 void AbstractMetadataProvider::clearDescriptorIndex()
146 {
147     m_sources.clear();
148     m_sites.clear();
149     m_groups.clear();
150 }
151
152 const EntitiesDescriptor* AbstractMetadataProvider::getEntitiesDescriptor(const char* name, bool strict) const
153 {
154     pair<groupmap_t::const_iterator,groupmap_t::const_iterator> range=m_groups.equal_range(name);
155
156     time_t now=time(NULL);
157     for (groupmap_t::const_iterator i=range.first; i!=range.second; i++)
158         if (now < i->second->getValidUntilEpoch())
159             return i->second;
160     
161     if (!strict && range.first!=range.second)
162         return range.first->second;
163         
164     return NULL;
165 }
166
167 const EntityDescriptor* AbstractMetadataProvider::getEntityDescriptor(const char* name, bool strict) const
168 {
169     pair<sitemap_t::const_iterator,sitemap_t::const_iterator> range=m_sites.equal_range(name);
170
171     time_t now=time(NULL);
172     for (sitemap_t::const_iterator i=range.first; i!=range.second; i++)
173         if (now < i->second->getValidUntilEpoch())
174             return i->second;
175     
176     if (!strict && range.first!=range.second)
177         return range.first->second;
178         
179     return NULL;
180 }
181
182 const EntityDescriptor* AbstractMetadataProvider::getEntityDescriptor(const SAMLArtifact* artifact) const
183 {
184     pair<sitemap_t::const_iterator,sitemap_t::const_iterator> range=m_sources.equal_range(artifact->getSource());
185
186     time_t now=time(NULL);
187     for (sitemap_t::const_iterator i=range.first; i!=range.second; i++)
188         if (now < i->second->getValidUntilEpoch())
189             return i->second;
190
191     return NULL;
192 }
193
194 const Credential* AbstractMetadataProvider::resolve(const CredentialCriteria* criteria) const
195 {
196     const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
197     if (!metacrit)
198         throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
199
200     Lock lock(m_credentialLock);
201     const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
202
203     for (credmap_t::mapped_type::const_iterator c = creds.begin(); c!=creds.end(); ++c)
204         if (matches(*c,criteria))
205             return c->second;
206     return NULL;
207 }
208
209 vector<const Credential*>::size_type AbstractMetadataProvider::resolve(
210     vector<const Credential*>& results, const CredentialCriteria* criteria
211     ) const
212 {
213     const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
214     if (!metacrit)
215         throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
216
217     Lock lock(m_credentialLock);
218     const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
219
220     for (credmap_t::mapped_type::const_iterator c = creds.begin(); c!=creds.end(); ++c)
221         if (matches(*c,criteria))
222             results.push_back(c->second);
223     return results.size();
224 }
225
226 const AbstractMetadataProvider::credmap_t::mapped_type& AbstractMetadataProvider::resolveCredentials(const RoleDescriptor& role) const
227 {
228     credmap_t::const_iterator i = m_credentialMap.find(&role);
229     if (i!=m_credentialMap.end())
230         return i->second;
231
232     const KeyInfoResolver* resolver = m_resolver ? m_resolver : XMLToolingConfig::getConfig().getKeyInfoResolver();
233     const vector<KeyDescriptor*>& keys = role.getKeyDescriptors();
234     AbstractMetadataProvider::credmap_t::mapped_type& resolved = m_credentialMap[&role];
235     for (vector<KeyDescriptor*>::const_iterator k = keys.begin(); k!=keys.end(); ++k) {
236         if ((*k)->getKeyInfo()) {
237             Credential* c = resolver->resolve((*k)->getKeyInfo());
238             resolved.push_back(make_pair((*k)->getUse(), c));
239         }
240     }
241     return resolved;
242 }
243
244 bool AbstractMetadataProvider::matches(const pair<const XMLCh*,Credential*>& cred, const CredentialCriteria* criteria) const
245 {
246     if (criteria) {
247         // Check for a usage mismatch.
248         if ((criteria->getUsage()==CredentialCriteria::SIGNING_CREDENTIAL || criteria->getUsage()==CredentialCriteria::TLS_CREDENTIAL) &&
249                 XMLString::equals(cred.first,KeyDescriptor::KEYTYPE_ENCRYPTION))
250             return false;
251         else if (criteria->getUsage()==CredentialCriteria::ENCRYPTION_CREDENTIAL && XMLString::equals(cred.first,KeyDescriptor::KEYTYPE_SIGNING))
252             return false;
253
254         if (cred.second->getPublicKey()) {
255             // See if we have to match a specific key.
256             auto_ptr<Credential> critcred(
257                 XMLToolingConfig::getConfig().getKeyInfoResolver()->resolve(*criteria,Credential::RESOLVE_KEYS)
258                 );
259             if (critcred.get())
260                 if (!critcred->isEqual(*(cred.second->getPublicKey())))
261                     return false;
262         }
263     }
264     return true;
265 }