2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * InlineKeyResolver.cpp
24 * Resolves key information directly from recognized KeyInfo structures.
29 #include "security/BasicX509Credential.h"
30 #include "security/KeyInfoCredentialContext.h"
31 #include "security/KeyInfoResolver.h"
32 #include "security/SecurityHelper.h"
33 #include "security/XSECCryptoX509CRL.h"
34 #include "signature/KeyInfo.h"
35 #include "signature/Signature.h"
37 #include "util/Threads.h"
38 #include "util/XMLConstants.h"
39 #include "validation/ValidatorSuite.h"
41 #include <boost/iterator/indirect_iterator.hpp>
42 #include <xercesc/util/XMLUniDefs.hpp>
43 #include <xsec/dsig/DSIGKeyInfoX509.hpp>
44 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
45 #include <xsec/enc/XSECCryptoX509.hpp>
46 #include <xsec/enc/XSECCryptoKeyRSA.hpp>
47 #include <xsec/enc/XSECCryptoKeyDSA.hpp>
48 #ifdef XMLTOOLING_XMLSEC_ECC
49 # include <xsec/enc/XSECCryptoKeyEC.hpp>
51 #include <xsec/enc/XSECCryptoException.hpp>
52 #include <xsec/framework/XSECException.hpp>
54 using namespace xmlsignature;
55 using namespace xmltooling::logging;
56 using namespace xmltooling;
57 using namespace xercesc;
58 using namespace boost;
61 namespace xmltooling {
63 class XMLTOOL_DLLLOCAL InlineCredential : public BasicX509Credential
66 InlineCredential(const KeyInfo* keyInfo=nullptr) : BasicX509Credential(keyInfo!=nullptr), m_credctx(new KeyInfoCredentialContext(keyInfo)) {}
67 InlineCredential(DSIGKeyInfoList* keyInfo) : BasicX509Credential(false), m_credctx(new KeyInfoCredentialContext(keyInfo)) {}
68 InlineCredential(KeyInfoCredentialContext* context) : BasicX509Credential(context->getKeyInfo()!=nullptr) {}
69 virtual ~InlineCredential() {}
71 XSECCryptoKey* getPrivateKey() const {
75 KeyInfo* getKeyInfo(bool compact=false) const {
76 KeyInfo* ret = m_credctx->getKeyInfo() ? m_credctx->getKeyInfo()->cloneKeyInfo() : nullptr;
79 ret->getRetrievalMethods().clear();
80 ret->getKeyInfoReferences().clear();
82 ret->getKeyValues().clear();
83 ret->getDEREncodedKeyValues().clear();
84 ret->getSPKIDatas().clear();
85 ret->getPGPDatas().clear();
86 ret->getUnknownXMLObjects().clear();
87 VectorOf(X509Data) x509Datas=ret->getX509Datas();
88 for (VectorOf(X509Data)::size_type pos = 0; pos < x509Datas.size();) {
89 x509Datas[pos]->getX509Certificates().clear();
90 x509Datas[pos]->getX509CRLs().clear();
91 x509Datas[pos]->getOCSPResponses().clear();
92 x509Datas[pos]->getUnknownXMLObjects().clear();
93 if (x509Datas[pos]->hasChildren())
96 x509Datas.erase(x509Datas.begin() + pos);
100 if (!ret->hasChildren()) {
107 const CredentialContext* getCredentalContext() const {
108 return m_credctx.get();
111 void setCredentialContext(KeyInfoCredentialContext* context) {
112 m_credctx.reset(context);
115 void resolve(const KeyInfo* keyInfo, int types=0, bool followRefs=false);
116 void resolve(DSIGKeyInfoList* keyInfo, int types=0, bool followRefs=false);
118 bool isEmpty() const {
119 return (!m_key && m_xseccerts.empty() && m_crls.empty() &&
120 m_keyNames.empty() && m_serial.empty() && m_issuerName.empty());
124 bool resolveCerts(const KeyInfo* keyInfo, bool followRefs=false);
125 bool resolveKey(const KeyInfo* keyInfo, bool followRefs=false);
126 bool resolveCRLs(const KeyInfo* keyInfo, bool followRefs=false);
128 auto_ptr<KeyInfoCredentialContext> m_credctx;
131 static const XMLCh keyInfoReferences[] = UNICODE_LITERAL_17(k,e,y,I,n,f,o,R,e,f,e,r,e,n,c,e,s);
133 class XMLTOOL_DLLLOCAL InlineKeyResolver : public KeyInfoResolver
136 InlineKeyResolver(const DOMElement* e)
137 : m_followRefs(XMLHelper::getAttrBool(e, false, keyInfoReferences)) {
140 virtual ~InlineKeyResolver() {}
142 Credential* resolve(const KeyInfo* keyInfo, int types=0) const {
146 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
147 auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
148 credential->resolve(keyInfo, types, m_followRefs);
149 return credential->isEmpty() ? nullptr : credential.release();
151 Credential* resolve(DSIGKeyInfoList* keyInfo, int types=0) const {
155 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
156 auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
157 credential->resolve(keyInfo, types, m_followRefs);
158 return credential->isEmpty() ? nullptr : credential.release();
160 Credential* resolve(KeyInfoCredentialContext* context, int types=0) const {
164 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
165 auto_ptr<InlineCredential> credential(new InlineCredential(context));
166 if (context->getKeyInfo())
167 credential->resolve(context->getKeyInfo(), types, m_followRefs);
168 else if (context->getNativeKeyInfo())
169 credential->resolve(context->getNativeKeyInfo(), types, m_followRefs);
170 if (credential->isEmpty())
172 credential->setCredentialContext(context); // transfers ownership to credential
173 return credential.release();
180 KeyInfoResolver* XMLTOOL_DLLLOCAL InlineKeyInfoResolverFactory(const DOMElement* const & e)
182 return new InlineKeyResolver(e);
186 void InlineCredential::resolve(const KeyInfo* keyInfo, int types, bool followRefs)
192 if (types & X509Credential::RESOLVE_CERTS)
193 resolveCerts(keyInfo, followRefs);
195 if (types & Credential::RESOLVE_KEYS) {
196 if (types & X509Credential::RESOLVE_CERTS) {
197 // If we have a cert, just use it.
198 if (!m_xseccerts.empty())
199 m_key = m_xseccerts.front()->clonePublicKey();
201 resolveKey(keyInfo, followRefs);
203 // Otherwise try directly for a key and then go for certs if none is found.
204 else if (!resolveKey(keyInfo, followRefs) && resolveCerts(keyInfo, followRefs)) {
205 m_key = m_xseccerts.front()->clonePublicKey();
209 if (types & X509Credential::RESOLVE_CRLS)
210 resolveCRLs(keyInfo, followRefs);
214 const vector<KeyName*>& knames=keyInfo->getKeyNames();
215 for (indirect_iterator<vector<KeyName*>::const_iterator> kn_i = make_indirect_iterator(knames.begin());
216 kn_i != make_indirect_iterator(knames.end()); ++kn_i) {
220 m_keyNames.insert(kn);
224 const vector<X509Data*> datas=keyInfo->getX509Datas();
225 for (vector<X509Data*>::const_iterator x_i=datas.begin(); x_i!=datas.end(); ++x_i) {
226 const vector<X509SubjectName*> snames = const_cast<const X509Data*>(*x_i)->getX509SubjectNames();
227 for (vector<X509SubjectName*>::const_iterator sn_i = snames.begin(); sn_i!=snames.end(); ++sn_i) {
228 n = (*sn_i)->getName();
231 m_keyNames.insert(kn);
237 const vector<X509IssuerSerial*> inames = const_cast<const X509Data*>(*x_i)->getX509IssuerSerials();
238 if (!inames.empty()) {
239 const X509IssuerName* iname = inames.front()->getX509IssuerName();
241 kn = toUTF8(iname->getName());
247 const X509SerialNumber* ser = inames.front()->getX509SerialNumber();
249 auto_ptr_char sn(ser->getSerialNumber());
256 bool InlineCredential::resolveKey(const KeyInfo* keyInfo, bool followRefs)
258 Category& log = Category::getInstance(XMLTOOLING_LOGCAT ".KeyInfoResolver." INLINE_KEYINFO_RESOLVER);
260 // Check for ds:KeyValue
261 const vector<KeyValue*>& keyValues = keyInfo->getKeyValues();
262 for (indirect_iterator<vector<KeyValue*>::const_iterator> i = make_indirect_iterator(keyValues.begin());
263 i != make_indirect_iterator(keyValues.end()); ++i) {
265 SchemaValidators.validate(*(i.base())); // see if it's a "valid" key
266 RSAKeyValue* rsakv = i->getRSAKeyValue();
268 log.debug("resolving ds:RSAKeyValue");
269 auto_ptr_char mod(rsakv->getModulus()->getValue());
270 auto_ptr_char exp(rsakv->getExponent()->getValue());
271 auto_ptr<XSECCryptoKeyRSA> rsa(XSECPlatformUtils::g_cryptoProvider->keyRSA());
272 rsa->loadPublicModulusBase64BigNums(mod.get(), strlen(mod.get()));
273 rsa->loadPublicExponentBase64BigNums(exp.get(), strlen(exp.get()));
274 m_key = rsa.release();
277 DSAKeyValue* dsakv = i->getDSAKeyValue();
279 log.debug("resolving ds:DSAKeyValue");
280 auto_ptr<XSECCryptoKeyDSA> dsa(XSECPlatformUtils::g_cryptoProvider->keyDSA());
281 auto_ptr_char y(dsakv->getY()->getValue());
282 dsa->loadYBase64BigNums(y.get(), strlen(y.get()));
284 auto_ptr_char p(dsakv->getP()->getValue());
285 dsa->loadPBase64BigNums(p.get(), strlen(p.get()));
288 auto_ptr_char q(dsakv->getQ()->getValue());
289 dsa->loadQBase64BigNums(q.get(), strlen(q.get()));
292 auto_ptr_char g(dsakv->getG()->getValue());
293 dsa->loadGBase64BigNums(g.get(), strlen(g.get()));
295 m_key = dsa.release();
298 #ifdef XMLTOOLING_XMLSEC_ECC
299 ECKeyValue* eckv = i->getECKeyValue();
300 if (eckv && eckv->getNamedCurve() && eckv->getPublicKey()) {
301 log.warn("resolving ds11:ECKeyValue");
302 auto_ptr<XSECCryptoKeyEC> ec(XSECPlatformUtils::g_cryptoProvider->keyEC());
303 auto_ptr_char uri(eckv->getNamedCurve()->getURI());
304 auto_ptr_char val(eckv->getPublicKey()->getValue());
305 if (uri.get() && val.get()) {
306 ec->loadPublicKeyBase64(uri.get(), val.get(), XMLString::stringLen(val.get()));
307 m_key = ec.release();
313 catch (ValidationException& ex) {
314 log.warn("skipping invalid ds:KeyValue (%s)", ex.what());
316 catch(XSECException& e) {
317 auto_ptr_char temp(e.getMsg());
318 log.error("caught XML-Security exception loading key: %s", temp.get());
320 catch(XSECCryptoException& e) {
321 log.error("caught XML-Security exception loading key: %s", e.getMsg());
325 // Check for ds11:DEREncodedKeyValue
326 const vector<DEREncodedKeyValue*>& derValues = keyInfo->getDEREncodedKeyValues();
327 for (indirect_iterator<vector<DEREncodedKeyValue*>::const_iterator> j = make_indirect_iterator(derValues.begin());
328 j != make_indirect_iterator(derValues.end()); ++j) {
329 log.debug("resolving ds11:DEREncodedKeyValue");
330 m_key = SecurityHelper::fromDEREncoding(j->getValue());
333 log.warn("failed to resolve ds11:DEREncodedKeyValue");
338 // Check for KeyInfoReference.
339 const XMLCh* fragID=nullptr;
340 const XMLObject* treeRoot=nullptr;
341 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
342 for (indirect_iterator<vector<KeyInfoReference*>::const_iterator> ref = make_indirect_iterator(refs.begin());
343 ref != make_indirect_iterator(refs.end()); ++ref) {
344 fragID = ref->getURI();
345 if (!fragID || *fragID != chPound || !*(fragID+1)) {
346 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
351 while (treeRoot->getParent())
352 treeRoot = treeRoot->getParent();
354 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
356 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
359 if (resolveKey(keyInfo, false))
367 bool InlineCredential::resolveCerts(const KeyInfo* keyInfo, bool followRefs)
369 Category& log = Category::getInstance(XMLTOOLING_LOGCAT ".KeyInfoResolver." INLINE_KEYINFO_RESOLVER);
371 // Check for ds:X509Data
372 const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
373 for (vector<X509Data*>::const_iterator j = x509Datas.begin(); m_xseccerts.empty() && j != x509Datas.end(); ++j) {
374 const vector<X509Certificate*> x509Certs=const_cast<const X509Data*>(*j)->getX509Certificates();
375 for (indirect_iterator<vector<X509Certificate*>::const_iterator> k = make_indirect_iterator(x509Certs.begin());
376 k != make_indirect_iterator(x509Certs.end()); ++k) {
378 auto_ptr_char x(k->getValue());
380 log.warn("skipping empty ds:X509Certificate");
383 log.debug("resolving ds:X509Certificate");
384 auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
385 x509->loadX509Base64Bin(x.get(), strlen(x.get()));
386 m_xseccerts.push_back(x509.release());
389 catch(XSECException& e) {
390 auto_ptr_char temp(e.getMsg());
391 log.error("caught XML-Security exception loading certificate: %s", temp.get());
393 catch(XSECCryptoException& e) {
394 log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
399 if (followRefs && m_xseccerts.empty()) {
400 // Check for KeyInfoReference.
401 const XMLCh* fragID=NULL;
402 const XMLObject* treeRoot=NULL;
403 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
404 for (indirect_iterator<vector<KeyInfoReference*>::const_iterator> ref = make_indirect_iterator(refs.begin());
405 ref != make_indirect_iterator(refs.end()); ++ref) {
406 fragID = ref->getURI();
407 if (!fragID || *fragID != chPound || !*(fragID+1)) {
408 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
413 while (treeRoot->getParent())
414 treeRoot = treeRoot->getParent();
416 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
418 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
421 if (resolveCerts(keyInfo, false))
427 log.debug("resolved %d certificate(s)", m_xseccerts.size());
428 return !m_xseccerts.empty();
431 bool InlineCredential::resolveCRLs(const KeyInfo* keyInfo, bool followRefs)
433 Category& log = Category::getInstance(XMLTOOLING_LOGCAT ".KeyInfoResolver." INLINE_KEYINFO_RESOLVER);
435 // Check for ds:X509Data
436 const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
437 for (vector<X509Data*>::const_iterator j=x509Datas.begin(); j!=x509Datas.end(); ++j) {
438 const vector<X509CRL*> x509CRLs=const_cast<const X509Data*>(*j)->getX509CRLs();
439 for (indirect_iterator<vector<X509CRL*>::const_iterator> k = make_indirect_iterator(x509CRLs.begin());
440 k != make_indirect_iterator(x509CRLs.end()); ++k) {
442 auto_ptr_char x(k->getValue());
444 log.warn("skipping empty ds:X509CRL");
447 log.debug("resolving ds:X509CRL");
448 auto_ptr<XSECCryptoX509CRL> crl(XMLToolingConfig::getConfig().X509CRL());
449 crl->loadX509CRLBase64Bin(x.get(), strlen(x.get()));
450 m_crls.push_back(crl.release());
453 catch(XSECException& e) {
454 auto_ptr_char temp(e.getMsg());
455 log.error("caught XML-Security exception loading CRL: %s", temp.get());
457 catch(XSECCryptoException& e) {
458 log.error("caught XML-Security exception loading CRL: %s", e.getMsg());
463 if (followRefs && m_crls.empty()) {
464 // Check for KeyInfoReference.
465 const XMLCh* fragID=NULL;
466 const XMLObject* treeRoot=NULL;
467 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
468 for (indirect_iterator<vector<KeyInfoReference*>::const_iterator> ref = make_indirect_iterator(refs.begin());
469 ref != make_indirect_iterator(refs.end()); ++ref) {
470 fragID = ref->getURI();
471 if (!fragID || *fragID != chPound || !*(fragID+1)) {
472 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
477 while (treeRoot->getParent())
478 treeRoot = treeRoot->getParent();
480 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
482 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
485 if (resolveCRLs(keyInfo, false))
491 log.debug("resolved %d CRL(s)", m_crls.size());
492 return !m_crls.empty();
495 void InlineCredential::resolve(DSIGKeyInfoList* keyInfo, int types, bool followRefs)
501 if (types & Credential::RESOLVE_KEYS) {
502 // Default resolver handles RSA/DSAKeyValue and X509Certificate elements.
504 XSECKeyInfoResolverDefault def;
505 m_key = def.resolveKey(keyInfo);
507 catch(XSECException& e) {
508 auto_ptr_char temp(e.getMsg());
509 Category::getInstance(XMLTOOLING_LOGCAT ".KeyResolver." INLINE_KEYINFO_RESOLVER).error(
510 "caught XML-Security exception loading certificate: %s", temp.get());
512 catch(XSECCryptoException& e) {
513 Category::getInstance(XMLTOOLING_LOGCAT ".KeyResolver." INLINE_KEYINFO_RESOLVER).error(
514 "caught XML-Security exception loading certificate: %s", e.getMsg());
518 DSIGKeyInfoList::size_type sz = keyInfo->getSize();
520 if (types & X509Credential::RESOLVE_CERTS) {
521 for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
522 if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
523 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
524 int count = x509->getCertificateListSize();
526 for (int j=0; j<count; ++j)
527 m_xseccerts.push_back(x509->getCertificateCryptoItem(j));
534 if (types & X509Credential::RESOLVE_CRLS) {
535 for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
536 if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
537 #ifdef XMLTOOLING_XMLSEC_MULTIPLECRL
538 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
539 int count = x509->getX509CRLListSize();
540 for (int j=0; j<count; ++j) {
541 auto_ptr_char buf(x509->getX509CRLItem(j));
544 auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
545 crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
546 m_crls.push_back(crlobj.release());
548 catch(XSECException& e) {
549 auto_ptr_char temp(e.getMsg());
550 Category::getInstance(XMLTOOLING_LOGCAT ".KeyResolver." INLINE_KEYINFO_RESOLVER).error(
551 "caught XML-Security exception loading CRL: %s", temp.get());
553 catch(XSECCryptoException& e) {
554 Category::getInstance(XMLTOOLING_LOGCAT ".KeyResolver." INLINE_KEYINFO_RESOLVER).error(
555 "caught XML-Security exception loading CRL: %s", e.getMsg());
560 // The current xmlsec API is limited to one CRL per KeyInfo.
561 // For now, I'm going to process the DOM directly.
562 DOMNode* x509Node = keyInfo->item(i)->getKeyInfoDOMNode();
563 DOMElement* crlElement = x509Node ? XMLHelper::getFirstChildElement(x509Node, xmlconstants::XMLSIG_NS, X509CRL::LOCAL_NAME) : nullptr;
565 if (crlElement->hasChildNodes()) {
566 auto_ptr_char buf(crlElement->getFirstChild()->getNodeValue());
569 auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
570 crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
571 m_crls.push_back(crlobj.release());
573 catch(XSECException& e) {
574 auto_ptr_char temp(e.getMsg());
575 Category::getInstance(XMLTOOLING_LOGCAT ".KeyResolver." INLINE_KEYINFO_RESOLVER).error(
576 "caught XML-Security exception loading CRL: %s", temp.get());
578 catch(XSECCryptoException& e) {
579 Category::getInstance(XMLTOOLING_LOGCAT ".KeyResolver." INLINE_KEYINFO_RESOLVER).error(
580 "caught XML-Security exception loading CRL: %s", e.getMsg());
584 crlElement = XMLHelper::getNextSiblingElement(crlElement, xmlconstants::XMLSIG_NS, X509CRL::LOCAL_NAME);
594 for (size_t s=0; s<keyInfo->getSize(); s++) {
595 DSIGKeyInfo* dki = keyInfo->item(s);
599 m_keyNames.insert(kn);
600 if (dki->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509)
605 if (dki->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509) {
606 DSIGKeyInfoX509* kix = static_cast<DSIGKeyInfoX509*>(dki);
607 n = kix->getX509IssuerName();
613 n = kix->getX509IssuerSerialNumber();