Yank RetrievalMethod logic.
[shibboleth/xmltooling.git] / xmltooling / security / impl / InlineKeyResolver.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  * InlineKeyResolver.cpp
19  * 
20  * Resolves key information directly from recognized KeyInfo structures.
21  */
22
23 #include "internal.h"
24 #include "logging.h"
25 #include "security/BasicX509Credential.h"
26 #include "security/KeyInfoCredentialContext.h"
27 #include "security/KeyInfoResolver.h"
28 #include "signature/KeyInfo.h"
29 #include "signature/Signature.h"
30 #include "util/NDC.h"
31 #include "util/Threads.h"
32 #include "util/XMLConstants.h"
33 #include "validation/ValidatorSuite.h"
34
35 #include <xercesc/util/XMLUniDefs.hpp>
36 #include <xsec/dsig/DSIGKeyInfoX509.hpp>
37 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
38 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
39 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyRSA.hpp>
40 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyDSA.hpp>
41 #include <xsec/enc/XSECCryptoException.hpp>
42 #include <xsec/framework/XSECException.hpp>
43
44 using namespace xmlsignature;
45 using namespace xmltooling::logging;
46 using namespace xmltooling;
47 using namespace std;
48
49 namespace xmltooling {
50
51     class XMLTOOL_DLLLOCAL InlineCredential : public BasicX509Credential
52     {
53     public:
54         InlineCredential(const KeyInfo* keyInfo=NULL) : BasicX509Credential(keyInfo!=NULL), m_credctx(new KeyInfoCredentialContext(keyInfo)) {
55         }
56         InlineCredential(DSIGKeyInfoList* keyInfo) : BasicX509Credential(false), m_credctx(new KeyInfoCredentialContext(keyInfo)) {
57         }
58         InlineCredential(KeyInfoCredentialContext* context) : BasicX509Credential(context->getKeyInfo()!=NULL), m_credctx(NULL) {
59         }
60         virtual ~InlineCredential() {
61             delete m_credctx;
62         }
63
64         XSECCryptoKey* getPrivateKey() const {
65             return NULL;
66         }
67
68         KeyInfo* getKeyInfo(bool compact=false) const {
69             KeyInfo* ret = m_credctx->getKeyInfo() ? m_credctx->getKeyInfo()->cloneKeyInfo() : NULL;
70             if (ret) {
71                 ret->setId(NULL);
72                 ret->getRetrievalMethods().clear();
73                 if (compact) {
74                     ret->getKeyValues().clear();
75                     ret->getSPKIDatas().clear();
76                     ret->getPGPDatas().clear();
77                     ret->getUnknownXMLObjects().clear();
78                     VectorOf(X509Data) x509Datas=ret->getX509Datas();
79                     for (VectorOf(X509Data)::size_type pos = 0; pos < x509Datas.size();) {
80                         x509Datas[pos]->getX509Certificates().clear();
81                         x509Datas[pos]->getX509CRLs().clear();
82                         x509Datas[pos]->getUnknownXMLObjects().clear();
83                         if (x509Datas[pos]->hasChildren())
84                             ++pos;
85                         else
86                             x509Datas.erase(x509Datas.begin() + pos);
87                     }
88                 }
89             }
90             if (!ret->hasChildren()) {
91                 delete ret;
92                 ret = NULL;
93             }
94             return ret;
95         }
96         
97         const CredentialContext* getCredentialContext() const {
98             return m_credctx;
99         }
100
101         void setCredentialContext(KeyInfoCredentialContext* context) {
102             m_credctx = context;
103         }
104
105         void resolve(const KeyInfo* keyInfo, int types=0);
106         void resolve(DSIGKeyInfoList* keyInfo, int types=0);
107
108     private:
109         bool resolveCerts(const KeyInfo* keyInfo);
110         bool resolveKey(const KeyInfo* keyInfo);
111         bool resolveCRL(const KeyInfo* keyInfo);
112
113         KeyInfoCredentialContext* m_credctx;
114     };
115
116     class XMLTOOL_DLLLOCAL InlineKeyResolver : public KeyInfoResolver
117     {
118     public:
119         InlineKeyResolver() {}
120         virtual ~InlineKeyResolver() {}
121
122         Credential* resolve(const KeyInfo* keyInfo, int types=0) const {
123             if (!keyInfo)
124                 return NULL;
125             if (types == 0)
126                 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
127             auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
128             credential->resolve(keyInfo, types);
129             return credential.release();
130         }
131         Credential* resolve(DSIGKeyInfoList* keyInfo, int types=0) const {
132             if (!keyInfo)
133                 return NULL;
134             if (types == 0)
135                 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
136             auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
137             credential->resolve(keyInfo, types);
138             return credential.release();
139         }
140         Credential* resolve(KeyInfoCredentialContext* context, int types=0) const {
141             if (!context)
142                 return NULL;
143             if (types == 0)
144                 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
145             auto_ptr<InlineCredential> credential(new InlineCredential(context));
146             if (context->getKeyInfo())
147                 credential->resolve(context->getKeyInfo(), types);
148             else if (context->getNativeKeyInfo())
149                 credential->resolve(context->getNativeKeyInfo(), types);
150             credential->setCredentialContext(context);
151             return credential.release();
152         }
153     };
154
155     KeyInfoResolver* XMLTOOL_DLLLOCAL InlineKeyInfoResolverFactory(const DOMElement* const & e)
156     {
157         return new InlineKeyResolver();
158     }
159 };
160
161 void InlineCredential::resolve(const KeyInfo* keyInfo, int types)
162 {
163 #ifdef _DEBUG
164     NDC ndc("resolve");
165 #endif
166
167     if (types & X509Credential::RESOLVE_CERTS)
168         resolveCerts(keyInfo);
169     
170     if (types & Credential::RESOLVE_KEYS) {
171         if (types & X509Credential::RESOLVE_CERTS) {
172             // If we have a cert, just use it.
173             if (!m_xseccerts.empty())
174                 m_key = m_xseccerts.front()->clonePublicKey();
175         }
176         // Otherwise try directly for a key and then go for certs if none is found.
177         else if (!resolveKey(keyInfo) && resolveCerts(keyInfo)) {
178             m_key = m_xseccerts.front()->clonePublicKey();
179         }
180     }
181
182     if (types & X509Credential::RESOLVE_CRLS)
183         resolveCRL(keyInfo);
184
185     keyInfo->extractNames(m_keyNames);
186 }
187
188 bool InlineCredential::resolveKey(const KeyInfo* keyInfo)
189 {
190     Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
191
192     // Check for ds:KeyValue
193     const vector<KeyValue*>& keyValues = keyInfo->getKeyValues();
194     for (vector<KeyValue*>::const_iterator i=keyValues.begin(); i!=keyValues.end(); ++i) {
195         try {
196             SchemaValidators.validate(*i);    // see if it's a "valid" key
197             RSAKeyValue* rsakv = (*i)->getRSAKeyValue();
198             if (rsakv) {
199                 log.debug("resolving ds:RSAKeyValue");
200                 auto_ptr_char mod(rsakv->getModulus()->getValue());
201                 auto_ptr_char exp(rsakv->getExponent()->getValue());
202                 auto_ptr<XSECCryptoKeyRSA> rsa(XSECPlatformUtils::g_cryptoProvider->keyRSA());
203                 rsa->loadPublicModulusBase64BigNums(mod.get(), strlen(mod.get()));
204                 rsa->loadPublicExponentBase64BigNums(exp.get(), strlen(exp.get()));
205                 m_key = rsa.release();
206                 return true;
207             }
208             DSAKeyValue* dsakv = (*i)->getDSAKeyValue();
209             if (dsakv) {
210                 log.debug("resolving ds:DSAKeyValue");
211                 auto_ptr<XSECCryptoKeyDSA> dsa(XSECPlatformUtils::g_cryptoProvider->keyDSA());
212                 auto_ptr_char y(dsakv->getY()->getValue());
213                 dsa->loadYBase64BigNums(y.get(), strlen(y.get()));
214                 if (dsakv->getP()) {
215                     auto_ptr_char p(dsakv->getP()->getValue());
216                     dsa->loadPBase64BigNums(p.get(), strlen(p.get()));
217                 }
218                 if (dsakv->getQ()) {
219                     auto_ptr_char q(dsakv->getQ()->getValue());
220                     dsa->loadQBase64BigNums(q.get(), strlen(q.get()));
221                 }
222                 if (dsakv->getG()) {
223                     auto_ptr_char g(dsakv->getG()->getValue());
224                     dsa->loadGBase64BigNums(g.get(), strlen(g.get()));
225                 }
226                 m_key = dsa.release();
227                 return true;
228             }
229         }
230         catch (ValidationException& ex) {
231             log.warn("skipping invalid ds:KeyValue (%s)", ex.what());
232         }
233         catch(XSECException& e) {
234             auto_ptr_char temp(e.getMsg());
235             log.error("caught XML-Security exception loading key: %s", temp.get());
236         }
237         catch(XSECCryptoException& e) {
238             log.error("caught XML-Security exception loading key: %s", e.getMsg());
239         }
240     }
241
242     return false;
243 }
244
245 bool InlineCredential::resolveCerts(const KeyInfo* keyInfo)
246 {
247     Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
248
249     // Check for ds:X509Data
250     const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
251     for (vector<X509Data*>::const_iterator j=x509Datas.begin(); m_xseccerts.empty() && j!=x509Datas.end(); ++j) {
252         const vector<X509Certificate*> x509Certs=const_cast<const X509Data*>(*j)->getX509Certificates();
253         for (vector<X509Certificate*>::const_iterator k=x509Certs.begin(); k!=x509Certs.end(); ++k) {
254             try {
255                 auto_ptr_char x((*k)->getValue());
256                 if (!x.get()) {
257                     log.warn("skipping empty ds:X509Certificate");
258                 }
259                 else {
260                     log.debug("resolving ds:X509Certificate");
261                     auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
262                     x509->loadX509Base64Bin(x.get(), strlen(x.get()));
263                     m_xseccerts.push_back(x509.release());
264                 }
265             }
266             catch(XSECException& e) {
267                 auto_ptr_char temp(e.getMsg());
268                 log.error("caught XML-Security exception loading certificate: %s", temp.get());
269             }
270             catch(XSECCryptoException& e) {
271                 log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
272             }
273         }
274     }
275     
276     log.debug("resolved %d certificate(s)", m_xseccerts.size());
277     return !m_xseccerts.empty();
278 }
279
280 bool InlineCredential::resolveCRL(const KeyInfo* keyInfo)
281 {
282     Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
283
284     // Check for ds:X509Data
285     const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
286     for (vector<X509Data*>::const_iterator j=x509Datas.begin(); j!=x509Datas.end(); ++j) {
287         const vector<X509CRL*> x509CRLs=const_cast<const X509Data*>(*j)->getX509CRLs();
288         for (vector<X509CRL*>::const_iterator k=x509CRLs.begin(); k!=x509CRLs.end(); ++k) {
289             try {
290                 auto_ptr_char x((*k)->getValue());
291                 if (!x.get()) {
292                     log.warn("skipping empty ds:X509CRL");
293                 }
294                 else {
295                     log.debug("resolving ds:X509CRL");
296                     auto_ptr<XSECCryptoX509CRL> crl(XMLToolingConfig::getConfig().X509CRL());
297                     crl->loadX509CRLBase64Bin(x.get(), strlen(x.get()));
298                     m_crl = crl.release();
299                     return true;
300                 }
301             }
302             catch(XSECException& e) {
303                 auto_ptr_char temp(e.getMsg());
304                 log.error("caught XML-Security exception loading certificate: %s", temp.get());
305             }
306             catch(XSECCryptoException& e) {
307                 log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
308             }
309         }
310     }
311
312     return false;
313 }
314
315 void InlineCredential::resolve(DSIGKeyInfoList* keyInfo, int types)
316 {
317 #ifdef _DEBUG
318     NDC ndc("resolve");
319 #endif
320
321     if (types & Credential::RESOLVE_KEYS) {
322         // Default resolver handles RSA/DSAKeyValue and X509Certificate elements.
323         try {
324             XSECKeyInfoResolverDefault def;
325             m_key = def.resolveKey(keyInfo);
326         }
327         catch(XSECException& e) {
328             auto_ptr_char temp(e.getMsg());
329             Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", temp.get());
330         }
331         catch(XSECCryptoException& e) {
332             Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", e.getMsg());
333         }
334     }
335
336         DSIGKeyInfoList::size_type sz = keyInfo->getSize();
337
338     if (types & X509Credential::RESOLVE_CERTS) {
339         for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
340             if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
341                 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
342                 int count = x509->getCertificateListSize();
343                 if (count) {
344                     for (int j=0; j<count; ++j)
345                         m_xseccerts.push_back(x509->getCertificateCryptoItem(j));
346                     break;
347                 }
348             }
349         }
350     }
351
352     if (types & X509Credential::RESOLVE_CRLS) {
353         for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
354             if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
355                 auto_ptr_char buf(static_cast<DSIGKeyInfoX509*>(keyInfo->item(i))->getX509CRL());
356                 if (buf.get()) {
357                     try {
358                         auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
359                         crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
360                         m_crl = crlobj.release();
361                         break;
362                     }
363                     catch(XSECException& e) {
364                         auto_ptr_char temp(e.getMsg());
365                         Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", temp.get());
366                     }
367                     catch(XSECCryptoException& e) {
368                         Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", e.getMsg());
369                     }
370                 }
371             }
372         }
373     }
374
375     Signature::extractNames(keyInfo, m_keyNames);
376 }