Major revamp of credential and trust handling code, PKIX engine still needs work.
[shibboleth/cpp-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 "security/BasicX509Credential.h"
25 #include "security/KeyInfoResolver.h"
26 #include "signature/KeyInfo.h"
27 #include "util/NDC.h"
28 #include "util/Threads.h"
29 #include "util/XMLConstants.h"
30 #include "validation/ValidatorSuite.h"
31
32 #include <log4cpp/Category.hh>
33 #include <xercesc/util/XMLUniDefs.hpp>
34 #include <xsec/dsig/DSIGKeyInfoX509.hpp>
35 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
36 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
37 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyRSA.hpp>
38 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyDSA.hpp>
39 #include <xsec/enc/XSECCryptoException.hpp>
40 #include <xsec/framework/XSECException.hpp>
41
42 using namespace xmlsignature;
43 using namespace xmltooling;
44 using namespace log4cpp;
45 using namespace std;
46
47 namespace xmltooling {
48
49     class XMLTOOL_DLLLOCAL InlineCredential : public BasicX509Credential
50     {
51         const KeyInfo* m_inlineKeyInfo;
52         DSIGKeyInfoList* m_nativeKeyInfo;
53     public:
54         InlineCredential(const KeyInfo* keyInfo=NULL)
55             : BasicX509Credential(keyInfo!=NULL), m_inlineKeyInfo(keyInfo), m_nativeKeyInfo(NULL) {
56         }
57         InlineCredential(DSIGKeyInfoList* keyInfo)
58             : BasicX509Credential(false), m_inlineKeyInfo(NULL), m_nativeKeyInfo(keyInfo) {
59         }
60         virtual ~InlineCredential() {}
61
62         XSECCryptoKey* getPrivateKey() const {
63             return NULL;
64         }
65
66         const KeyInfo* getKeyInfo(bool compact=false) const {
67             return m_inlineKeyInfo;
68         }
69         
70         vector<string>::size_type getKeyNames(vector<string>& results) const {
71             if (m_inlineKeyInfo) {
72                 const vector<KeyName*>& knames=m_inlineKeyInfo->getKeyNames();
73                 for (vector<KeyName*>::const_iterator kn_i=knames.begin(); kn_i!=knames.end(); ++kn_i) {
74                     const XMLCh* n=(*kn_i)->getName();
75                     if (n && *n) {
76                         char* kn=toUTF8(n);
77                         results.push_back(kn);
78                         delete[] kn;
79                     }
80                 }
81             }
82             else if (m_nativeKeyInfo) {
83                 for (size_t s=0; s<m_nativeKeyInfo->getSize(); s++) {
84                     const XMLCh* n=m_nativeKeyInfo->item(s)->getKeyName();
85                     if (n && *n) {
86                         char* kn=toUTF8(n);
87                         results.push_back(kn);
88                         delete[] kn;
89                     }
90                 }
91             }
92             return results.size();
93         }
94
95         void setKey(XSECCryptoKey* key) {
96             m_key = key;
97         }
98
99         void addCert(XSECCryptoX509* cert) {
100             m_xseccerts.push_back(cert);
101         }
102
103         void setCRL(XSECCryptoX509CRL* crl) {
104             m_crl = crl;
105         }
106     };
107
108     class XMLTOOL_DLLLOCAL InlineKeyResolver : public KeyInfoResolver
109     {
110     public:
111         InlineKeyResolver() : m_log(Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver")) {}
112         virtual ~InlineKeyResolver() {}
113
114         Credential* resolve(const KeyInfo* keyInfo, int types=0) const;
115         Credential* resolve(DSIGKeyInfoList* keyInfo, int types=0) const;
116     
117     private:
118         bool resolveCerts(const KeyInfo* keyInfo, InlineCredential* credential) const;
119         bool resolveKey(const KeyInfo* keyInfo, InlineCredential* credential) const;
120         bool resolveCRL(const KeyInfo* keyInfo, InlineCredential* credential) const;
121
122         Category& m_log;
123     };
124
125     KeyInfoResolver* XMLTOOL_DLLLOCAL InlineKeyInfoResolverFactory(const DOMElement* const & e)
126     {
127         return new InlineKeyResolver();
128     }
129 };
130
131 Credential* InlineKeyResolver::resolve(const KeyInfo* keyInfo, int types) const
132 {
133 #ifdef _DEBUG
134     NDC ndc("resolve");
135 #endif
136
137     if (!keyInfo)
138         return NULL;
139
140     auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
141     if (types == 0)
142         types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
143
144     if (types & X509Credential::RESOLVE_CERTS)
145         resolveCerts(keyInfo, credential.get());
146     
147     if (types & Credential::RESOLVE_KEYS) {
148         // If we have a cert, just use it.
149         if (types & X509Credential::RESOLVE_CERTS && !credential->getEntityCertificateChain().empty())
150             credential->setKey(credential->getEntityCertificateChain().front()->clonePublicKey());
151         // Otherwise try directly for a key and then go for certs if none is found.
152         else if (!resolveKey(keyInfo, credential.get()) && resolveCerts(keyInfo, credential.get()))
153             credential->setKey(credential->getEntityCertificateChain().front()->clonePublicKey());
154     }
155
156     if (types & X509Credential::RESOLVE_CRLS)
157         resolveCRL(keyInfo, credential.get());
158
159     return credential.release();
160 }
161
162 bool InlineKeyResolver::resolveKey(const KeyInfo* keyInfo, InlineCredential* credential) const
163 {
164     // Check for ds:KeyValue
165     const vector<KeyValue*>& keyValues = keyInfo->getKeyValues();
166     for (vector<KeyValue*>::const_iterator i=keyValues.begin(); i!=keyValues.end(); ++i) {
167         try {
168             SchemaValidators.validate(*i);    // see if it's a "valid" key
169             RSAKeyValue* rsakv = (*i)->getRSAKeyValue();
170             if (rsakv) {
171                 m_log.debug("resolving ds:RSAKeyValue");
172                 auto_ptr_char mod(rsakv->getModulus()->getValue());
173                 auto_ptr_char exp(rsakv->getExponent()->getValue());
174                 auto_ptr<XSECCryptoKeyRSA> rsa(XSECPlatformUtils::g_cryptoProvider->keyRSA());
175                 rsa->loadPublicModulusBase64BigNums(mod.get(), strlen(mod.get()));
176                 rsa->loadPublicExponentBase64BigNums(exp.get(), strlen(exp.get()));
177                 credential->setKey(rsa.release());
178                 return true;
179             }
180             DSAKeyValue* dsakv = (*i)->getDSAKeyValue();
181             if (dsakv) {
182                 m_log.debug("resolving ds:DSAKeyValue");
183                 auto_ptr<XSECCryptoKeyDSA> dsa(XSECPlatformUtils::g_cryptoProvider->keyDSA());
184                 auto_ptr_char y(dsakv->getY()->getValue());
185                 dsa->loadYBase64BigNums(y.get(), strlen(y.get()));
186                 if (dsakv->getP()) {
187                     auto_ptr_char p(dsakv->getP()->getValue());
188                     dsa->loadPBase64BigNums(p.get(), strlen(p.get()));
189                 }
190                 if (dsakv->getQ()) {
191                     auto_ptr_char q(dsakv->getQ()->getValue());
192                     dsa->loadQBase64BigNums(q.get(), strlen(q.get()));
193                 }
194                 if (dsakv->getG()) {
195                     auto_ptr_char g(dsakv->getG()->getValue());
196                     dsa->loadGBase64BigNums(g.get(), strlen(g.get()));
197                 }
198                 credential->setKey(dsa.release());
199                 return true;
200             }
201         }
202         catch (ValidationException& ex) {
203             m_log.warn("skipping invalid ds:KeyValue (%s)", ex.what());
204         }
205         catch(XSECException& e) {
206             auto_ptr_char temp(e.getMsg());
207             m_log.error("caught XML-Security exception loading key: %s", temp.get());
208         }
209         catch(XSECCryptoException& e) {
210             m_log.error("caught XML-Security exception loading key: %s", e.getMsg());
211         }
212     }
213
214     // Check for RetrievalMethod.
215     const XMLCh* fragID=NULL;
216     const XMLObject* treeRoot=NULL;
217     const vector<RetrievalMethod*>& methods=keyInfo->getRetrievalMethods();
218     for (vector<RetrievalMethod*>::const_iterator m=methods.begin(); m!=methods.end(); ++m) {
219         if (!XMLString::equals((*m)->getType(),RetrievalMethod::TYPE_RSAKEYVALUE) &&
220             !XMLString::equals((*m)->getType(),RetrievalMethod::TYPE_DSAKEYVALUE))
221             continue;
222         fragID = (*m)->getURI();
223         if (!fragID || *fragID != chPound || !*(fragID+1)) {
224             m_log.warn("skipping ds:RetrievalMethod with an empty or non-local reference");
225             continue;
226         }
227         if (!treeRoot) {
228             treeRoot = keyInfo;
229             while (treeRoot->getParent())
230                 treeRoot = treeRoot->getParent();
231         }
232         keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
233         if (!keyInfo) {
234             m_log.warn("skipping ds:RetrievalMethod, local reference did not resolve to a ds:KeyInfo");
235             continue;
236         }
237         if (resolveKey(keyInfo,credential))
238             return true;
239     }
240     return false;
241 }
242
243 bool InlineKeyResolver::resolveCerts(const KeyInfo* keyInfo, InlineCredential* credential) const
244 {
245     // Check for ds:X509Data
246     const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
247     for (vector<X509Data*>::const_iterator j=x509Datas.begin(); credential->getEntityCertificateChain().empty() && j!=x509Datas.end(); ++j) {
248         const vector<X509Certificate*> x509Certs=const_cast<const X509Data*>(*j)->getX509Certificates();
249         for (vector<X509Certificate*>::const_iterator k=x509Certs.begin(); k!=x509Certs.end(); ++k) {
250             try {
251                 auto_ptr_char x((*k)->getValue());
252                 if (!x.get()) {
253                     m_log.warn("skipping empty ds:X509Certificate");
254                 }
255                 else {
256                     m_log.debug("resolving ds:X509Certificate");
257                     auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
258                     x509->loadX509Base64Bin(x.get(), strlen(x.get()));
259                     credential->addCert(x509.release());
260                 }
261             }
262             catch(XSECException& e) {
263                 auto_ptr_char temp(e.getMsg());
264                 m_log.error("caught XML-Security exception loading certificate: %s", temp.get());
265             }
266             catch(XSECCryptoException& e) {
267                 m_log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
268             }
269         }
270     }
271
272     if (credential->getEntityCertificateChain().empty()) {
273         // Check for RetrievalMethod.
274         const XMLCh* fragID=NULL;
275         const XMLObject* treeRoot=NULL;
276         const vector<RetrievalMethod*> methods=keyInfo->getRetrievalMethods();
277         for (vector<RetrievalMethod*>::const_iterator m=methods.begin(); m!=methods.end(); ++m) {
278             if (!XMLString::equals((*m)->getType(),RetrievalMethod::TYPE_X509DATA))
279                 continue;
280             fragID = (*m)->getURI();
281             if (!fragID || *fragID != chPound || !*(fragID+1)) {
282                 m_log.warn("skipping ds:RetrievalMethod with an empty or non-local reference");
283                 continue;
284             }
285             if (!treeRoot) {
286                 treeRoot = keyInfo;
287                 while (treeRoot->getParent())
288                     treeRoot = treeRoot->getParent();
289             }
290             keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
291             if (!keyInfo) {
292                 m_log.warn("skipping ds:RetrievalMethod, local reference did not resolve to a ds:KeyInfo");
293                 continue;
294             }
295             if (resolveCerts(keyInfo,credential))
296                 return true;
297         }
298         return false;
299     }
300     
301     if (m_log.isDebugEnabled()) {
302         m_log.debug("resolved %d certificate(s)", credential->getEntityCertificateChain().size());
303     }
304     return !credential->getEntityCertificateChain().empty();
305 }
306
307 bool InlineKeyResolver::resolveCRL(const KeyInfo* keyInfo, InlineCredential* credential) const
308 {
309     // Check for ds:X509Data
310     const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
311     for (vector<X509Data*>::const_iterator j=x509Datas.begin(); j!=x509Datas.end(); ++j) {
312         const vector<X509CRL*> x509CRLs=const_cast<const X509Data*>(*j)->getX509CRLs();
313         for (vector<X509CRL*>::const_iterator k=x509CRLs.begin(); k!=x509CRLs.end(); ++k) {
314             try {
315                 auto_ptr_char x((*k)->getValue());
316                 if (!x.get()) {
317                     m_log.warn("skipping empty ds:X509CRL");
318                 }
319                 else {
320                     m_log.debug("resolving ds:X509CRL");
321                     auto_ptr<XSECCryptoX509CRL> crl(XMLToolingConfig::getConfig().X509CRL());
322                     crl->loadX509CRLBase64Bin(x.get(), strlen(x.get()));
323                     credential->setCRL(crl.release());
324                     return true;
325                 }
326             }
327             catch(XSECException& e) {
328                 auto_ptr_char temp(e.getMsg());
329                 m_log.error("caught XML-Security exception loading certificate: %s", temp.get());
330             }
331             catch(XSECCryptoException& e) {
332                 m_log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
333             }
334         }
335     }
336
337     // Check for RetrievalMethod.
338     const XMLCh* fragID=NULL;
339     const XMLObject* treeRoot=NULL;
340     const vector<RetrievalMethod*> methods=keyInfo->getRetrievalMethods();
341     for (vector<RetrievalMethod*>::const_iterator m=methods.begin(); m!=methods.end(); ++m) {
342         if (!XMLString::equals((*m)->getType(),RetrievalMethod::TYPE_X509DATA))
343             continue;
344         fragID = (*m)->getURI();
345         if (!fragID || *fragID != chPound || !*(fragID+1)) {
346             m_log.warn("skipping ds:RetrievalMethod with an empty or non-local reference");
347             continue;
348         }
349         if (!treeRoot) {
350             treeRoot = keyInfo;
351             while (treeRoot->getParent())
352                 treeRoot = treeRoot->getParent();
353         }
354         keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
355         if (!keyInfo) {
356             m_log.warn("skipping ds:RetrievalMethod, local reference did not resolve to a ds:KeyInfo");
357             continue;
358         }
359         if (resolveCRL(keyInfo,credential))
360             return true;
361     }
362
363     return false;
364 }
365
366 Credential* InlineKeyResolver::resolve(DSIGKeyInfoList* keyInfo, int types) const
367 {
368 #ifdef _DEBUG
369     NDC ndc("resolve");
370 #endif
371
372     if (!keyInfo)
373         return NULL;
374
375     if (types == 0)
376         types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
377
378     auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
379
380     if (types & Credential::RESOLVE_KEYS) {
381         // Default resolver handles RSA/DSAKeyValue and X509Certificate elements.
382         try {
383             XSECKeyInfoResolverDefault def;
384             credential->setKey(def.resolveKey(keyInfo));
385         }
386         catch(XSECException& e) {
387             auto_ptr_char temp(e.getMsg());
388             Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver").error("caught XML-Security exception loading certificate: %s", temp.get());
389         }
390         catch(XSECCryptoException& e) {
391             Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver").error("caught XML-Security exception loading certificate: %s", e.getMsg());
392         }
393     }
394
395         DSIGKeyInfoList::size_type sz = keyInfo->getSize();
396
397     if (types & X509Credential::RESOLVE_CERTS) {
398         for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
399             if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
400                 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
401                 int count = x509->getCertificateListSize();
402                 if (count) {
403                     for (int j=0; j<count; ++j)
404                         credential->addCert(x509->getCertificateCryptoItem(j));
405                     break;
406                 }
407             }
408         }
409     }
410
411     if (types & X509Credential::RESOLVE_CRLS) {
412         for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
413             if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
414                 auto_ptr_char buf(static_cast<DSIGKeyInfoX509*>(keyInfo->item(i))->getX509CRL());
415                 if (buf.get()) {
416                     try {
417                         auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
418                         crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
419                         credential->setCRL(crlobj.release());
420                         break;
421                     }
422                     catch(XSECException& e) {
423                         auto_ptr_char temp(e.getMsg());
424                         Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver").error("caught XML-Security exception loading CRL: %s", temp.get());
425                     }
426                     catch(XSECCryptoException& e) {
427                         Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver").error("caught XML-Security exception loading CRL: %s", e.getMsg());
428                     }
429                 }
430             }
431         }
432     }
433
434     return credential.release();
435 }