Imported Upstream version 2.2.1+dfsg
[shibboleth/sp.git] / shibsp / security / PKIXTrustEngine.cpp
1 /*
2  *  Copyright 2001-2009 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  * PKIXTrustEngine.cpp
19  * 
20  * Shibboleth-specific PKIX-validation TrustEngine
21  */
22
23 #include "internal.h"
24 #include "metadata/MetadataExt.h"
25 #include "security/PKIXTrustEngine.h"
26
27 #include <saml/saml2/metadata/Metadata.h>
28 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
29 #include <saml/saml2/metadata/ObservableMetadataProvider.h>
30 #include <xmltooling/XMLToolingConfig.h>
31 #include <xmltooling/security/AbstractPKIXTrustEngine.h>
32 #include <xmltooling/security/KeyInfoResolver.h>
33 #include <xmltooling/security/X509Credential.h>
34
35 using namespace shibsp;
36 using namespace opensaml::saml2md;
37 using namespace xmlsignature;
38 using namespace xmltooling;
39 using namespace std;
40
41 namespace shibsp {
42
43     class SHIBSP_DLLLOCAL PKIXTrustEngine : public AbstractPKIXTrustEngine, public ObservableMetadataProvider::Observer
44     {
45     public:
46         PKIXTrustEngine(const DOMElement* e=NULL) : AbstractPKIXTrustEngine(e), m_credLock(RWLock::create()) {
47         }
48         virtual ~PKIXTrustEngine() {
49             for (map<const ObservableMetadataProvider*,credmap_t>::iterator i=m_credentialMap.begin(); i!=m_credentialMap.end(); ++i) {
50                 i->first->removeObserver(this);
51                 for (credmap_t::iterator creds = i->second.begin(); creds!=i->second.end(); ++creds)
52                     for_each(creds->second.begin(), creds->second.end(), xmltooling::cleanup<X509Credential>());
53             }
54             delete m_credLock;
55         }
56         
57         AbstractPKIXTrustEngine::PKIXValidationInfoIterator* getPKIXValidationInfoIterator(
58             const CredentialResolver& pkixSource, CredentialCriteria* criteria=NULL
59             ) const;
60
61         void onEvent(const ObservableMetadataProvider& metadata) const {
62             // Destroy credentials we cached from this provider.
63             m_credLock->wrlock();
64             credmap_t& cmap = m_credentialMap[&metadata];
65             for (credmap_t::iterator creds = cmap.begin(); creds!=cmap.end(); ++creds)
66                 for_each(creds->second.begin(), creds->second.end(), xmltooling::cleanup<X509Credential>());
67             cmap.clear();
68             m_credLock->unlock();
69         }
70
71         const KeyInfoResolver* getKeyInfoResolver() const {
72             return m_keyInfoResolver ? m_keyInfoResolver : XMLToolingConfig::getConfig().getKeyInfoResolver();
73         }
74
75     private:
76         friend class SHIBSP_DLLLOCAL MetadataPKIXIterator;
77         mutable RWLock* m_credLock;
78         typedef map< const KeyAuthority*,vector<X509Credential*> > credmap_t;
79         mutable map<const ObservableMetadataProvider*,credmap_t> m_credentialMap;
80     };
81     
82     SHIBSP_DLLLOCAL PluginManager<TrustEngine,string,const DOMElement*>::Factory PKIXTrustEngineFactory;
83
84     TrustEngine* SHIBSP_DLLLOCAL PKIXTrustEngineFactory(const DOMElement* const & e)
85     {
86         return new PKIXTrustEngine(e);
87     }
88
89     class SHIBSP_DLLLOCAL MetadataPKIXIterator : public AbstractPKIXTrustEngine::PKIXValidationInfoIterator
90     {
91     public:
92         MetadataPKIXIterator(const PKIXTrustEngine& engine, const MetadataProvider& pkixSource, MetadataCredentialCriteria& criteria);
93
94         virtual ~MetadataPKIXIterator() {
95             if (m_caching)
96                 m_engine.m_credLock->unlock();
97             for_each(m_ownedCreds.begin(), m_ownedCreds.end(), xmltooling::cleanup<Credential>());
98         }
99
100         bool next();
101
102         int getVerificationDepth() const {
103             pair<bool,int> vd = m_current->getVerifyDepth();
104             return vd.first ? vd.second : 1;
105         }
106         
107         const vector<XSECCryptoX509*>& getTrustAnchors() const {
108             return m_certs;
109         }
110
111         const vector<XSECCryptoX509CRL*>& getCRLs() const {
112             return m_crls;
113         }
114     
115     private:
116         void populate();
117         bool m_caching;
118         const PKIXTrustEngine& m_engine;
119         map<const ObservableMetadataProvider*,PKIXTrustEngine::credmap_t>::iterator m_credCache;
120         const XMLObject* m_obj;
121         const Extensions* m_extBlock;
122         const KeyAuthority* m_current;
123         vector<XMLObject*>::const_iterator m_iter;
124         vector<XSECCryptoX509*> m_certs;
125         vector<XSECCryptoX509CRL*> m_crls;
126         vector<X509Credential*> m_ownedCreds;
127     };
128 };
129
130 void shibsp::registerPKIXTrustEngine()
131 {
132     XMLToolingConfig::getConfig().TrustEngineManager.registerFactory(SHIBBOLETH_PKIX_TRUSTENGINE, PKIXTrustEngineFactory);
133 }
134
135 AbstractPKIXTrustEngine::PKIXValidationInfoIterator* PKIXTrustEngine::getPKIXValidationInfoIterator(
136     const CredentialResolver& pkixSource, CredentialCriteria* criteria
137     ) const
138 {
139     // Make sure these are metadata objects.
140     const MetadataProvider& metadata = dynamic_cast<const MetadataProvider&>(pkixSource);
141     MetadataCredentialCriteria* metacrit = dynamic_cast<MetadataCredentialCriteria*>(criteria);
142     if (!metacrit)
143         throw MetadataException("Cannot obtain PKIX information without a MetadataCredentialCriteria object.");
144
145     return new MetadataPKIXIterator(*this, metadata,*metacrit);
146 }
147
148 MetadataPKIXIterator::MetadataPKIXIterator(
149     const PKIXTrustEngine& engine, const MetadataProvider& pkixSource, MetadataCredentialCriteria& criteria
150     ) : m_caching(false), m_engine(engine), m_obj(criteria.getRole().getParent()), m_extBlock(NULL), m_current(NULL)
151 {
152     // If we can't hook the metadata for changes, then we can't do any caching and the rest of this is academic.
153     const ObservableMetadataProvider* observable = dynamic_cast<const ObservableMetadataProvider*>(&pkixSource);
154     if (!observable)
155         return;
156
157     // While holding read lock, see if this metadata plugin has been seen before.
158     m_engine.m_credLock->rdlock();
159     m_credCache = m_engine.m_credentialMap.find(observable);
160     if (m_credCache==m_engine.m_credentialMap.end()) {
161
162         // We need to elevate the lock and retry.
163         m_engine.m_credLock->unlock();
164         m_engine.m_credLock->wrlock();
165         m_credCache = m_engine.m_credentialMap.find(observable);
166         if (m_credCache==m_engine.m_credentialMap.end()) {
167
168             // It's still brand new, so hook it for cache activation.
169             observable->addObserver(&m_engine);
170
171             // Prime the map reference with an empty credential map.
172             m_credCache = m_engine.m_credentialMap.insert(make_pair(observable,PKIXTrustEngine::credmap_t())).first;
173             
174             // Downgrade the lock.
175             // We don't have to recheck because we never erase the master map entry entirely, even on changes.
176             m_engine.m_credLock->unlock();
177             m_engine.m_credLock->rdlock();
178         }
179     }
180     
181     // We've hooked the metadata for changes, and we know we can cache against it.
182     m_caching = true;
183 }
184
185
186 bool MetadataPKIXIterator::next()
187 {
188     // If we had an active block, look for another in the same block.
189     if (m_extBlock) {
190         // Keep going until we hit the end of the block.
191         vector<XMLObject*>::const_iterator end = m_extBlock->getUnknownXMLObjects().end();
192         while (m_iter != end) {
193             // If we hit a KeyAuthority, remember it and signal.
194             if (m_current=dynamic_cast<KeyAuthority*>(*m_iter++)) {
195                 populate();
196                 return true;
197             }
198         }
199         
200         // If we get here, we hit the end of this Extensions block.
201         // Climb a level, if possible.
202         m_obj = m_obj->getParent();
203         m_current = NULL;
204         m_extBlock = NULL;
205     }
206
207     // If we get here, we try and find an Extensions block.
208     while (m_obj) {
209         const EntityDescriptor* entity = dynamic_cast<const EntityDescriptor*>(m_obj);
210         if (entity) {
211             m_extBlock = entity->getExtensions();
212         }
213         else {
214             const EntitiesDescriptor* entities = dynamic_cast<const EntitiesDescriptor*>(m_obj);
215             if (entities) {
216                 m_extBlock = entities->getExtensions();
217             }
218         }
219         
220         if (m_extBlock) {
221             m_iter = m_extBlock->getUnknownXMLObjects().begin();
222             return next();
223         }
224         
225         // Jump a level and try again.
226         m_obj = m_obj->getParent();
227     }
228
229     return false;
230 }
231
232 void MetadataPKIXIterator::populate()
233 {
234     // Dump anything old.
235     m_certs.clear();
236     m_crls.clear();
237     for_each(m_ownedCreds.begin(), m_ownedCreds.end(), xmltooling::cleanup<Credential>());
238
239     if (m_caching) {
240         // We're holding a read lock. Search for "resolved" creds.
241         PKIXTrustEngine::credmap_t::iterator cached = m_credCache->second.find(m_current);
242         if (cached!=m_credCache->second.end()) {
243             // Copy over the information.
244             for (vector<X509Credential*>::const_iterator c=cached->second.begin(); c!=cached->second.end(); ++c) {
245                 m_certs.insert(m_certs.end(), (*c)->getEntityCertificateChain().begin(), (*c)->getEntityCertificateChain().end());
246                 if ((*c)->getCRL())
247                     m_crls.push_back((*c)->getCRL());
248             }
249             return;
250         }
251     }
252
253     // We're either not caching or didn't find the results we need, so we have to resolve them.
254     const vector<KeyInfo*>& keyInfos = m_current->getKeyInfos();
255     for (vector<KeyInfo*>::const_iterator k = keyInfos.begin(); k!=keyInfos.end(); ++k) {
256         auto_ptr<Credential> cred (m_engine.getKeyInfoResolver()->resolve(*k, X509Credential::RESOLVE_CERTS | X509Credential::RESOLVE_CRLS));
257         X509Credential* xcred = dynamic_cast<X509Credential*>(cred.get());
258         if (xcred) {
259             m_ownedCreds.push_back(xcred);
260             cred.release();
261         }
262     }
263
264     // Copy over the new information.
265     for (vector<X509Credential*>::const_iterator c=m_ownedCreds.begin(); c!=m_ownedCreds.end(); ++c) {
266         m_certs.insert(m_certs.end(), (*c)->getEntityCertificateChain().begin(), (*c)->getEntityCertificateChain().end());
267         if ((*c)->getCRL())
268             m_crls.push_back((*c)->getCRL());
269     }
270
271     // As a last step, if we're caching, try and elevate to a write lock for cache insertion.
272     if (m_caching) {
273         m_engine.m_credLock->unlock();
274         m_engine.m_credLock->wrlock();
275         if (m_credCache->second.count(m_current)==0) {
276             // Transfer objects into cache.
277             m_credCache->second[m_current] = m_ownedCreds;
278             m_ownedCreds.clear();
279         }
280         m_engine.m_credLock->unlock();
281         m_engine.m_credLock->rdlock();
282
283         // In theory we could have lost the objects but that shouldn't be possible
284         // since the metadata itself is locked and shouldn't change behind us.
285     }
286 }