2c2e87d7a1f1d9efbfbd56e1b3b4cf057f398056
[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/KeyInfoCredentialContext.h"
26 #include "security/KeyInfoResolver.h"
27 #include "signature/KeyInfo.h"
28 #include "signature/Signature.h"
29 #include "util/NDC.h"
30 #include "util/Threads.h"
31 #include "util/XMLConstants.h"
32 #include "validation/ValidatorSuite.h"
33
34 #include <log4cpp/Category.hh>
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;
46 using namespace log4cpp;
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     // Check for RetrievalMethod.
243     const XMLCh* fragID=NULL;
244     const XMLObject* treeRoot=NULL;
245     const vector<RetrievalMethod*>& methods=keyInfo->getRetrievalMethods();
246     for (vector<RetrievalMethod*>::const_iterator m=methods.begin(); m!=methods.end(); ++m) {
247         if (!XMLString::equals((*m)->getType(),RetrievalMethod::TYPE_RSAKEYVALUE) &&
248             !XMLString::equals((*m)->getType(),RetrievalMethod::TYPE_DSAKEYVALUE))
249             continue;
250         fragID = (*m)->getURI();
251         if (!fragID || *fragID != chPound || !*(fragID+1)) {
252             log.warn("skipping ds:RetrievalMethod with an empty or non-local reference");
253             continue;
254         }
255         if (!treeRoot) {
256             treeRoot = keyInfo;
257             while (treeRoot->getParent())
258                 treeRoot = treeRoot->getParent();
259         }
260         keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
261         if (!keyInfo) {
262             log.warn("skipping ds:RetrievalMethod, local reference did not resolve to a ds:KeyInfo");
263             continue;
264         }
265         if (resolveKey(keyInfo))
266             return true;
267     }
268     return false;
269 }
270
271 bool InlineCredential::resolveCerts(const KeyInfo* keyInfo)
272 {
273     Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
274
275     // Check for ds:X509Data
276     const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
277     for (vector<X509Data*>::const_iterator j=x509Datas.begin(); m_xseccerts.empty() && j!=x509Datas.end(); ++j) {
278         const vector<X509Certificate*> x509Certs=const_cast<const X509Data*>(*j)->getX509Certificates();
279         for (vector<X509Certificate*>::const_iterator k=x509Certs.begin(); k!=x509Certs.end(); ++k) {
280             try {
281                 auto_ptr_char x((*k)->getValue());
282                 if (!x.get()) {
283                     log.warn("skipping empty ds:X509Certificate");
284                 }
285                 else {
286                     log.debug("resolving ds:X509Certificate");
287                     auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
288                     x509->loadX509Base64Bin(x.get(), strlen(x.get()));
289                     m_xseccerts.push_back(x509.release());
290                 }
291             }
292             catch(XSECException& e) {
293                 auto_ptr_char temp(e.getMsg());
294                 log.error("caught XML-Security exception loading certificate: %s", temp.get());
295             }
296             catch(XSECCryptoException& e) {
297                 log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
298             }
299         }
300     }
301
302     if (m_xseccerts.empty()) {
303         // Check for RetrievalMethod.
304         const XMLCh* fragID=NULL;
305         const XMLObject* treeRoot=NULL;
306         const vector<RetrievalMethod*> methods=keyInfo->getRetrievalMethods();
307         for (vector<RetrievalMethod*>::const_iterator m=methods.begin(); m!=methods.end(); ++m) {
308             if (!XMLString::equals((*m)->getType(),RetrievalMethod::TYPE_X509DATA))
309                 continue;
310             fragID = (*m)->getURI();
311             if (!fragID || *fragID != chPound || !*(fragID+1)) {
312                 log.warn("skipping ds:RetrievalMethod with an empty or non-local reference");
313                 continue;
314             }
315             if (!treeRoot) {
316                 treeRoot = keyInfo;
317                 while (treeRoot->getParent())
318                     treeRoot = treeRoot->getParent();
319             }
320             keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
321             if (!keyInfo) {
322                 log.warn("skipping ds:RetrievalMethod, local reference did not resolve to a ds:KeyInfo");
323                 continue;
324             }
325             if (resolveCerts(keyInfo))
326                 return true;
327         }
328         return false;
329     }
330     
331     log.debug("resolved %d certificate(s)", m_xseccerts.size());
332     return !m_xseccerts.empty();
333 }
334
335 bool InlineCredential::resolveCRL(const KeyInfo* keyInfo)
336 {
337     Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
338
339     // Check for ds:X509Data
340     const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
341     for (vector<X509Data*>::const_iterator j=x509Datas.begin(); j!=x509Datas.end(); ++j) {
342         const vector<X509CRL*> x509CRLs=const_cast<const X509Data*>(*j)->getX509CRLs();
343         for (vector<X509CRL*>::const_iterator k=x509CRLs.begin(); k!=x509CRLs.end(); ++k) {
344             try {
345                 auto_ptr_char x((*k)->getValue());
346                 if (!x.get()) {
347                     log.warn("skipping empty ds:X509CRL");
348                 }
349                 else {
350                     log.debug("resolving ds:X509CRL");
351                     auto_ptr<XSECCryptoX509CRL> crl(XMLToolingConfig::getConfig().X509CRL());
352                     crl->loadX509CRLBase64Bin(x.get(), strlen(x.get()));
353                     m_crl = crl.release();
354                     return true;
355                 }
356             }
357             catch(XSECException& e) {
358                 auto_ptr_char temp(e.getMsg());
359                 log.error("caught XML-Security exception loading certificate: %s", temp.get());
360             }
361             catch(XSECCryptoException& e) {
362                 log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
363             }
364         }
365     }
366
367     // Check for RetrievalMethod.
368     const XMLCh* fragID=NULL;
369     const XMLObject* treeRoot=NULL;
370     const vector<RetrievalMethod*> methods=keyInfo->getRetrievalMethods();
371     for (vector<RetrievalMethod*>::const_iterator m=methods.begin(); m!=methods.end(); ++m) {
372         if (!XMLString::equals((*m)->getType(),RetrievalMethod::TYPE_X509DATA))
373             continue;
374         fragID = (*m)->getURI();
375         if (!fragID || *fragID != chPound || !*(fragID+1)) {
376             log.warn("skipping ds:RetrievalMethod with an empty or non-local reference");
377             continue;
378         }
379         if (!treeRoot) {
380             treeRoot = keyInfo;
381             while (treeRoot->getParent())
382                 treeRoot = treeRoot->getParent();
383         }
384         keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
385         if (!keyInfo) {
386             log.warn("skipping ds:RetrievalMethod, local reference did not resolve to a ds:KeyInfo");
387             continue;
388         }
389         if (resolveCRL(keyInfo))
390             return true;
391     }
392
393     return false;
394 }
395
396 void InlineCredential::resolve(DSIGKeyInfoList* keyInfo, int types)
397 {
398 #ifdef _DEBUG
399     NDC ndc("resolve");
400 #endif
401
402     if (types & Credential::RESOLVE_KEYS) {
403         // Default resolver handles RSA/DSAKeyValue and X509Certificate elements.
404         try {
405             XSECKeyInfoResolverDefault def;
406             m_key = def.resolveKey(keyInfo);
407         }
408         catch(XSECException& e) {
409             auto_ptr_char temp(e.getMsg());
410             Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", temp.get());
411         }
412         catch(XSECCryptoException& e) {
413             Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", e.getMsg());
414         }
415     }
416
417         DSIGKeyInfoList::size_type sz = keyInfo->getSize();
418
419     if (types & X509Credential::RESOLVE_CERTS) {
420         for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
421             if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
422                 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
423                 int count = x509->getCertificateListSize();
424                 if (count) {
425                     for (int j=0; j<count; ++j)
426                         m_xseccerts.push_back(x509->getCertificateCryptoItem(j));
427                     break;
428                 }
429             }
430         }
431     }
432
433     if (types & X509Credential::RESOLVE_CRLS) {
434         for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
435             if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
436                 auto_ptr_char buf(static_cast<DSIGKeyInfoX509*>(keyInfo->item(i))->getX509CRL());
437                 if (buf.get()) {
438                     try {
439                         auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
440                         crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
441                         m_crl = crlobj.release();
442                         break;
443                     }
444                     catch(XSECException& e) {
445                         auto_ptr_char temp(e.getMsg());
446                         Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", temp.get());
447                     }
448                     catch(XSECCryptoException& e) {
449                         Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", e.getMsg());
450                     }
451                 }
452             }
453         }
454     }
455
456     Signature::extractNames(keyInfo, m_keyNames);
457 }