2 * Copyright 2001-2010 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * InlineKeyResolver.cpp
20 * Resolves key information directly from recognized KeyInfo structures.
25 #include "security/BasicX509Credential.h"
26 #include "security/KeyInfoCredentialContext.h"
27 #include "security/KeyInfoResolver.h"
28 #include "security/SecurityHelper.h"
29 #include "security/XSECCryptoX509CRL.h"
30 #include "signature/KeyInfo.h"
31 #include "signature/Signature.h"
33 #include "util/Threads.h"
34 #include "util/XMLConstants.h"
35 #include "validation/ValidatorSuite.h"
37 #include <xercesc/util/XMLUniDefs.hpp>
38 #include <xsec/dsig/DSIGKeyInfoX509.hpp>
39 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
40 #include <xsec/enc/XSECCryptoX509.hpp>
41 #include <xsec/enc/XSECCryptoKeyRSA.hpp>
42 #include <xsec/enc/XSECCryptoKeyDSA.hpp>
43 #ifdef XMLTOOLING_XMLSEC_ECC
44 # include <xsec/enc/XSECCryptoKeyEC.hpp>
46 #include <xsec/enc/XSECCryptoException.hpp>
47 #include <xsec/framework/XSECException.hpp>
49 using namespace xmlsignature;
50 using namespace xmltooling::logging;
51 using namespace xmltooling;
52 using namespace xercesc;
55 namespace xmltooling {
57 class XMLTOOL_DLLLOCAL InlineCredential : public BasicX509Credential
60 InlineCredential(const KeyInfo* keyInfo=nullptr) : BasicX509Credential(keyInfo!=nullptr), m_credctx(new KeyInfoCredentialContext(keyInfo)) {
62 InlineCredential(DSIGKeyInfoList* keyInfo) : BasicX509Credential(false), m_credctx(new KeyInfoCredentialContext(keyInfo)) {
64 InlineCredential(KeyInfoCredentialContext* context) : BasicX509Credential(context->getKeyInfo()!=nullptr), m_credctx(nullptr) {
66 virtual ~InlineCredential() {
70 XSECCryptoKey* getPrivateKey() const {
74 KeyInfo* getKeyInfo(bool compact=false) const {
75 KeyInfo* ret = m_credctx->getKeyInfo() ? m_credctx->getKeyInfo()->cloneKeyInfo() : nullptr;
78 ret->getRetrievalMethods().clear();
79 ret->getKeyInfoReferences().clear();
81 ret->getKeyValues().clear();
82 ret->getDEREncodedKeyValues().clear();
83 ret->getSPKIDatas().clear();
84 ret->getPGPDatas().clear();
85 ret->getUnknownXMLObjects().clear();
86 VectorOf(X509Data) x509Datas=ret->getX509Datas();
87 for (VectorOf(X509Data)::size_type pos = 0; pos < x509Datas.size();) {
88 x509Datas[pos]->getX509Certificates().clear();
89 x509Datas[pos]->getX509CRLs().clear();
90 x509Datas[pos]->getOCSPResponses().clear();
91 x509Datas[pos]->getUnknownXMLObjects().clear();
92 if (x509Datas[pos]->hasChildren())
95 x509Datas.erase(x509Datas.begin() + pos);
99 if (!ret->hasChildren()) {
106 const CredentialContext* getCredentalContext() const {
110 void setCredentialContext(KeyInfoCredentialContext* context) {
114 void resolve(const KeyInfo* keyInfo, int types=0, bool followRefs=false);
115 void resolve(DSIGKeyInfoList* keyInfo, int types=0, bool followRefs=false);
118 bool resolveCerts(const KeyInfo* keyInfo, bool followRefs=false);
119 bool resolveKey(const KeyInfo* keyInfo, bool followRefs=false);
120 bool resolveCRLs(const KeyInfo* keyInfo, bool followRefs=false);
122 KeyInfoCredentialContext* m_credctx;
125 static const XMLCh keyInfoReferences[] = UNICODE_LITERAL_17(k,e,y,I,n,f,o,R,e,f,e,r,e,n,c,e,s);
127 class XMLTOOL_DLLLOCAL InlineKeyResolver : public KeyInfoResolver
130 InlineKeyResolver(const DOMElement* e)
131 : m_followRefs(XMLHelper::getAttrBool(e, false, keyInfoReferences)) {
134 virtual ~InlineKeyResolver() {}
136 Credential* resolve(const KeyInfo* keyInfo, int types=0) const {
140 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
141 auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
142 credential->resolve(keyInfo, types, m_followRefs);
143 return credential.release();
145 Credential* resolve(DSIGKeyInfoList* keyInfo, int types=0) const {
149 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
150 auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
151 credential->resolve(keyInfo, types, m_followRefs);
152 return credential.release();
154 Credential* resolve(KeyInfoCredentialContext* context, int types=0) const {
158 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
159 auto_ptr<InlineCredential> credential(new InlineCredential(context));
160 if (context->getKeyInfo())
161 credential->resolve(context->getKeyInfo(), types, m_followRefs);
162 else if (context->getNativeKeyInfo())
163 credential->resolve(context->getNativeKeyInfo(), types, m_followRefs);
164 credential->setCredentialContext(context);
165 return credential.release();
172 KeyInfoResolver* XMLTOOL_DLLLOCAL InlineKeyInfoResolverFactory(const DOMElement* const & e)
174 return new InlineKeyResolver(e);
178 void InlineCredential::resolve(const KeyInfo* keyInfo, int types, bool followRefs)
184 if (types & X509Credential::RESOLVE_CERTS)
185 resolveCerts(keyInfo, followRefs);
187 if (types & Credential::RESOLVE_KEYS) {
188 if (types & X509Credential::RESOLVE_CERTS) {
189 // If we have a cert, just use it.
190 if (!m_xseccerts.empty())
191 m_key = m_xseccerts.front()->clonePublicKey();
193 resolveKey(keyInfo, followRefs);
195 // Otherwise try directly for a key and then go for certs if none is found.
196 else if (!resolveKey(keyInfo, followRefs) && resolveCerts(keyInfo, followRefs)) {
197 m_key = m_xseccerts.front()->clonePublicKey();
201 if (types & X509Credential::RESOLVE_CRLS)
202 resolveCRLs(keyInfo, followRefs);
206 const vector<KeyName*>& knames=keyInfo->getKeyNames();
207 for (vector<KeyName*>::const_iterator kn_i=knames.begin(); kn_i!=knames.end(); ++kn_i) {
208 n=(*kn_i)->getName();
211 m_keyNames.insert(kn);
215 const vector<X509Data*> datas=keyInfo->getX509Datas();
216 for (vector<X509Data*>::const_iterator x_i=datas.begin(); x_i!=datas.end(); ++x_i) {
217 const vector<X509SubjectName*> snames = const_cast<const X509Data*>(*x_i)->getX509SubjectNames();
218 for (vector<X509SubjectName*>::const_iterator sn_i = snames.begin(); sn_i!=snames.end(); ++sn_i) {
219 n = (*sn_i)->getName();
222 m_keyNames.insert(kn);
228 const vector<X509IssuerSerial*> inames = const_cast<const X509Data*>(*x_i)->getX509IssuerSerials();
229 if (!inames.empty()) {
230 const X509IssuerName* iname = inames.front()->getX509IssuerName();
232 kn = toUTF8(iname->getName());
238 const X509SerialNumber* ser = inames.front()->getX509SerialNumber();
240 auto_ptr_char sn(ser->getSerialNumber());
247 bool InlineCredential::resolveKey(const KeyInfo* keyInfo, bool followRefs)
249 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
251 // Check for ds:KeyValue
252 const vector<KeyValue*>& keyValues = keyInfo->getKeyValues();
253 for (vector<KeyValue*>::const_iterator i = keyValues.begin(); i != keyValues.end(); ++i) {
255 SchemaValidators.validate(*i); // see if it's a "valid" key
256 RSAKeyValue* rsakv = (*i)->getRSAKeyValue();
258 log.debug("resolving ds:RSAKeyValue");
259 auto_ptr_char mod(rsakv->getModulus()->getValue());
260 auto_ptr_char exp(rsakv->getExponent()->getValue());
261 auto_ptr<XSECCryptoKeyRSA> rsa(XSECPlatformUtils::g_cryptoProvider->keyRSA());
262 rsa->loadPublicModulusBase64BigNums(mod.get(), strlen(mod.get()));
263 rsa->loadPublicExponentBase64BigNums(exp.get(), strlen(exp.get()));
264 m_key = rsa.release();
267 DSAKeyValue* dsakv = (*i)->getDSAKeyValue();
269 log.debug("resolving ds:DSAKeyValue");
270 auto_ptr<XSECCryptoKeyDSA> dsa(XSECPlatformUtils::g_cryptoProvider->keyDSA());
271 auto_ptr_char y(dsakv->getY()->getValue());
272 dsa->loadYBase64BigNums(y.get(), strlen(y.get()));
274 auto_ptr_char p(dsakv->getP()->getValue());
275 dsa->loadPBase64BigNums(p.get(), strlen(p.get()));
278 auto_ptr_char q(dsakv->getQ()->getValue());
279 dsa->loadQBase64BigNums(q.get(), strlen(q.get()));
282 auto_ptr_char g(dsakv->getG()->getValue());
283 dsa->loadGBase64BigNums(g.get(), strlen(g.get()));
285 m_key = dsa.release();
288 #ifdef XMLTOOLING_XMLSEC_ECC
289 ECKeyValue* eckv = (*i)->getECKeyValue();
290 if (eckv && eckv->getNamedCurve() && eckv->getPublicKey()) {
291 log.warn("resolving ds11:ECKeyValue");
292 auto_ptr<XSECCryptoKeyEC> ec(XSECPlatformUtils::g_cryptoProvider->keyEC());
293 auto_ptr_char uri(eckv->getNamedCurve()->getURI());
294 auto_ptr_char val(eckv->getPublicKey()->getValue());
295 if (uri.get() && val.get()) {
296 ec->loadPublicKeyBase64(uri.get(), val.get(), XMLString::stringLen(val.get()));
297 m_key = ec.release();
303 catch (ValidationException& ex) {
304 log.warn("skipping invalid ds:KeyValue (%s)", ex.what());
306 catch(XSECException& e) {
307 auto_ptr_char temp(e.getMsg());
308 log.error("caught XML-Security exception loading key: %s", temp.get());
310 catch(XSECCryptoException& e) {
311 log.error("caught XML-Security exception loading key: %s", e.getMsg());
315 // Check for ds11:DEREncodedKeyValue
316 const vector<DEREncodedKeyValue*>& derValues = keyInfo->getDEREncodedKeyValues();
317 for (vector<DEREncodedKeyValue*>::const_iterator j = derValues.begin(); j != derValues.end(); ++j) {
318 log.debug("resolving ds11:DEREncodedKeyValue");
319 m_key = SecurityHelper::fromDEREncoding((*j)->getValue());
322 log.warn("failed to resolve ds11:DEREncodedKeyValue");
327 // Check for KeyInfoReference.
328 const XMLCh* fragID=nullptr;
329 const XMLObject* treeRoot=nullptr;
330 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
331 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
332 fragID = (*ref)->getURI();
333 if (!fragID || *fragID != chPound || !*(fragID+1)) {
334 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
339 while (treeRoot->getParent())
340 treeRoot = treeRoot->getParent();
342 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
344 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
347 if (resolveKey(keyInfo, false))
355 bool InlineCredential::resolveCerts(const KeyInfo* keyInfo, bool followRefs)
357 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
359 // Check for ds:X509Data
360 const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
361 for (vector<X509Data*>::const_iterator j=x509Datas.begin(); m_xseccerts.empty() && j!=x509Datas.end(); ++j) {
362 const vector<X509Certificate*> x509Certs=const_cast<const X509Data*>(*j)->getX509Certificates();
363 for (vector<X509Certificate*>::const_iterator k=x509Certs.begin(); k!=x509Certs.end(); ++k) {
365 auto_ptr_char x((*k)->getValue());
367 log.warn("skipping empty ds:X509Certificate");
370 log.debug("resolving ds:X509Certificate");
371 auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
372 x509->loadX509Base64Bin(x.get(), strlen(x.get()));
373 m_xseccerts.push_back(x509.release());
376 catch(XSECException& e) {
377 auto_ptr_char temp(e.getMsg());
378 log.error("caught XML-Security exception loading certificate: %s", temp.get());
380 catch(XSECCryptoException& e) {
381 log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
386 if (followRefs && m_xseccerts.empty()) {
387 // Check for KeyInfoReference.
388 const XMLCh* fragID=NULL;
389 const XMLObject* treeRoot=NULL;
390 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
391 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
392 fragID = (*ref)->getURI();
393 if (!fragID || *fragID != chPound || !*(fragID+1)) {
394 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
399 while (treeRoot->getParent())
400 treeRoot = treeRoot->getParent();
402 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
404 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
407 if (resolveCerts(keyInfo, false))
413 log.debug("resolved %d certificate(s)", m_xseccerts.size());
414 return !m_xseccerts.empty();
417 bool InlineCredential::resolveCRLs(const KeyInfo* keyInfo, bool followRefs)
419 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
421 // Check for ds:X509Data
422 const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
423 for (vector<X509Data*>::const_iterator j=x509Datas.begin(); j!=x509Datas.end(); ++j) {
424 const vector<X509CRL*> x509CRLs=const_cast<const X509Data*>(*j)->getX509CRLs();
425 for (vector<X509CRL*>::const_iterator k=x509CRLs.begin(); k!=x509CRLs.end(); ++k) {
427 auto_ptr_char x((*k)->getValue());
429 log.warn("skipping empty ds:X509CRL");
432 log.debug("resolving ds:X509CRL");
433 auto_ptr<XSECCryptoX509CRL> crl(XMLToolingConfig::getConfig().X509CRL());
434 crl->loadX509CRLBase64Bin(x.get(), strlen(x.get()));
435 m_crls.push_back(crl.release());
438 catch(XSECException& e) {
439 auto_ptr_char temp(e.getMsg());
440 log.error("caught XML-Security exception loading CRL: %s", temp.get());
442 catch(XSECCryptoException& e) {
443 log.error("caught XML-Security exception loading CRL: %s", e.getMsg());
448 if (followRefs && m_crls.empty()) {
449 // Check for KeyInfoReference.
450 const XMLCh* fragID=NULL;
451 const XMLObject* treeRoot=NULL;
452 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
453 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
454 fragID = (*ref)->getURI();
455 if (!fragID || *fragID != chPound || !*(fragID+1)) {
456 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
461 while (treeRoot->getParent())
462 treeRoot = treeRoot->getParent();
464 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
466 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
469 if (resolveCRLs(keyInfo, false))
475 log.debug("resolved %d CRL(s)", m_crls.size());
476 return !m_crls.empty();
479 void InlineCredential::resolve(DSIGKeyInfoList* keyInfo, int types, bool followRefs)
485 if (types & Credential::RESOLVE_KEYS) {
486 // Default resolver handles RSA/DSAKeyValue and X509Certificate elements.
488 XSECKeyInfoResolverDefault def;
489 m_key = def.resolveKey(keyInfo);
491 catch(XSECException& e) {
492 auto_ptr_char temp(e.getMsg());
493 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", temp.get());
495 catch(XSECCryptoException& e) {
496 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", e.getMsg());
500 DSIGKeyInfoList::size_type sz = keyInfo->getSize();
502 if (types & X509Credential::RESOLVE_CERTS) {
503 for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
504 if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
505 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
506 int count = x509->getCertificateListSize();
508 for (int j=0; j<count; ++j)
509 m_xseccerts.push_back(x509->getCertificateCryptoItem(j));
516 if (types & X509Credential::RESOLVE_CRLS) {
517 for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
518 if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
519 #ifdef XMLTOOLING_XMLSEC_MULTIPLECRL
520 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
521 int count = x509->getX509CRLListSize();
522 for (int j=0; j<count; ++j) {
523 auto_ptr_char buf(x509->getX509CRLItem(j));
526 auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
527 crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
528 m_crls.push_back(crlobj.release());
530 catch(XSECException& e) {
531 auto_ptr_char temp(e.getMsg());
532 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", temp.get());
534 catch(XSECCryptoException& e) {
535 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", e.getMsg());
540 // The current xmlsec API is limited to one CRL per KeyInfo.
541 // For now, I'm going to process the DOM directly.
542 DOMNode* x509Node = keyInfo->item(i)->getKeyInfoDOMNode();
543 DOMElement* crlElement = x509Node ? XMLHelper::getFirstChildElement(x509Node, xmlconstants::XMLSIG_NS, X509CRL::LOCAL_NAME) : nullptr;
545 if (crlElement->hasChildNodes()) {
546 auto_ptr_char buf(crlElement->getFirstChild()->getNodeValue());
549 auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
550 crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
551 m_crls.push_back(crlobj.release());
553 catch(XSECException& e) {
554 auto_ptr_char temp(e.getMsg());
555 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", temp.get());
557 catch(XSECCryptoException& e) {
558 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", e.getMsg());
562 crlElement = XMLHelper::getNextSiblingElement(crlElement, xmlconstants::XMLSIG_NS, X509CRL::LOCAL_NAME);
572 for (size_t s=0; s<keyInfo->getSize(); s++) {
573 DSIGKeyInfo* dki = keyInfo->item(s);
577 m_keyNames.insert(kn);
578 if (dki->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509)
583 if (dki->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509) {
584 DSIGKeyInfoX509* kix = static_cast<DSIGKeyInfoX509*>(dki);
585 n = kix->getX509IssuerName();
591 n = kix->getX509IssuerSerialNumber();