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 <xercesc/util/XMLUniDefs.hpp>
42 #include <xsec/dsig/DSIGKeyInfoX509.hpp>
43 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
44 #include <xsec/enc/XSECCryptoX509.hpp>
45 #include <xsec/enc/XSECCryptoKeyRSA.hpp>
46 #include <xsec/enc/XSECCryptoKeyDSA.hpp>
47 #ifdef XMLTOOLING_XMLSEC_ECC
48 # include <xsec/enc/XSECCryptoKeyEC.hpp>
50 #include <xsec/enc/XSECCryptoException.hpp>
51 #include <xsec/framework/XSECException.hpp>
53 using namespace xmlsignature;
54 using namespace xmltooling::logging;
55 using namespace xmltooling;
56 using namespace xercesc;
59 namespace xmltooling {
61 class XMLTOOL_DLLLOCAL InlineCredential : public BasicX509Credential
64 InlineCredential(const KeyInfo* keyInfo=nullptr) : BasicX509Credential(keyInfo!=nullptr), m_credctx(new KeyInfoCredentialContext(keyInfo)) {
66 InlineCredential(DSIGKeyInfoList* keyInfo) : BasicX509Credential(false), m_credctx(new KeyInfoCredentialContext(keyInfo)) {
68 InlineCredential(KeyInfoCredentialContext* context) : BasicX509Credential(context->getKeyInfo()!=nullptr), m_credctx(nullptr) {
70 virtual ~InlineCredential() {
74 XSECCryptoKey* getPrivateKey() const {
78 KeyInfo* getKeyInfo(bool compact=false) const {
79 KeyInfo* ret = m_credctx->getKeyInfo() ? m_credctx->getKeyInfo()->cloneKeyInfo() : nullptr;
82 ret->getRetrievalMethods().clear();
83 ret->getKeyInfoReferences().clear();
85 ret->getKeyValues().clear();
86 ret->getDEREncodedKeyValues().clear();
87 ret->getSPKIDatas().clear();
88 ret->getPGPDatas().clear();
89 ret->getUnknownXMLObjects().clear();
90 VectorOf(X509Data) x509Datas=ret->getX509Datas();
91 for (VectorOf(X509Data)::size_type pos = 0; pos < x509Datas.size();) {
92 x509Datas[pos]->getX509Certificates().clear();
93 x509Datas[pos]->getX509CRLs().clear();
94 x509Datas[pos]->getOCSPResponses().clear();
95 x509Datas[pos]->getUnknownXMLObjects().clear();
96 if (x509Datas[pos]->hasChildren())
99 x509Datas.erase(x509Datas.begin() + pos);
103 if (!ret->hasChildren()) {
110 const CredentialContext* getCredentalContext() const {
114 void setCredentialContext(KeyInfoCredentialContext* context) {
118 void resolve(const KeyInfo* keyInfo, int types=0, bool followRefs=false);
119 void resolve(DSIGKeyInfoList* keyInfo, int types=0, bool followRefs=false);
122 bool resolveCerts(const KeyInfo* keyInfo, bool followRefs=false);
123 bool resolveKey(const KeyInfo* keyInfo, bool followRefs=false);
124 bool resolveCRLs(const KeyInfo* keyInfo, bool followRefs=false);
126 KeyInfoCredentialContext* m_credctx;
129 static const XMLCh keyInfoReferences[] = UNICODE_LITERAL_17(k,e,y,I,n,f,o,R,e,f,e,r,e,n,c,e,s);
131 class XMLTOOL_DLLLOCAL InlineKeyResolver : public KeyInfoResolver
134 InlineKeyResolver(const DOMElement* e)
135 : m_followRefs(XMLHelper::getAttrBool(e, false, keyInfoReferences)) {
138 virtual ~InlineKeyResolver() {}
140 Credential* resolve(const KeyInfo* keyInfo, int types=0) const {
144 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
145 auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
146 credential->resolve(keyInfo, types, m_followRefs);
147 return credential.release();
149 Credential* resolve(DSIGKeyInfoList* keyInfo, int types=0) const {
153 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
154 auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
155 credential->resolve(keyInfo, types, m_followRefs);
156 return credential.release();
158 Credential* resolve(KeyInfoCredentialContext* context, int types=0) const {
162 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
163 auto_ptr<InlineCredential> credential(new InlineCredential(context));
164 if (context->getKeyInfo())
165 credential->resolve(context->getKeyInfo(), types, m_followRefs);
166 else if (context->getNativeKeyInfo())
167 credential->resolve(context->getNativeKeyInfo(), types, m_followRefs);
168 credential->setCredentialContext(context);
169 return credential.release();
176 KeyInfoResolver* XMLTOOL_DLLLOCAL InlineKeyInfoResolverFactory(const DOMElement* const & e)
178 return new InlineKeyResolver(e);
182 void InlineCredential::resolve(const KeyInfo* keyInfo, int types, bool followRefs)
188 if (types & X509Credential::RESOLVE_CERTS)
189 resolveCerts(keyInfo, followRefs);
191 if (types & Credential::RESOLVE_KEYS) {
192 if (types & X509Credential::RESOLVE_CERTS) {
193 // If we have a cert, just use it.
194 if (!m_xseccerts.empty())
195 m_key = m_xseccerts.front()->clonePublicKey();
197 resolveKey(keyInfo, followRefs);
199 // Otherwise try directly for a key and then go for certs if none is found.
200 else if (!resolveKey(keyInfo, followRefs) && resolveCerts(keyInfo, followRefs)) {
201 m_key = m_xseccerts.front()->clonePublicKey();
205 if (types & X509Credential::RESOLVE_CRLS)
206 resolveCRLs(keyInfo, followRefs);
210 const vector<KeyName*>& knames=keyInfo->getKeyNames();
211 for (vector<KeyName*>::const_iterator kn_i=knames.begin(); kn_i!=knames.end(); ++kn_i) {
212 n=(*kn_i)->getName();
215 m_keyNames.insert(kn);
219 const vector<X509Data*> datas=keyInfo->getX509Datas();
220 for (vector<X509Data*>::const_iterator x_i=datas.begin(); x_i!=datas.end(); ++x_i) {
221 const vector<X509SubjectName*> snames = const_cast<const X509Data*>(*x_i)->getX509SubjectNames();
222 for (vector<X509SubjectName*>::const_iterator sn_i = snames.begin(); sn_i!=snames.end(); ++sn_i) {
223 n = (*sn_i)->getName();
226 m_keyNames.insert(kn);
232 const vector<X509IssuerSerial*> inames = const_cast<const X509Data*>(*x_i)->getX509IssuerSerials();
233 if (!inames.empty()) {
234 const X509IssuerName* iname = inames.front()->getX509IssuerName();
236 kn = toUTF8(iname->getName());
242 const X509SerialNumber* ser = inames.front()->getX509SerialNumber();
244 auto_ptr_char sn(ser->getSerialNumber());
251 bool InlineCredential::resolveKey(const KeyInfo* keyInfo, bool followRefs)
253 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
255 // Check for ds:KeyValue
256 const vector<KeyValue*>& keyValues = keyInfo->getKeyValues();
257 for (vector<KeyValue*>::const_iterator i = keyValues.begin(); i != keyValues.end(); ++i) {
259 SchemaValidators.validate(*i); // see if it's a "valid" key
260 RSAKeyValue* rsakv = (*i)->getRSAKeyValue();
262 log.debug("resolving ds:RSAKeyValue");
263 auto_ptr_char mod(rsakv->getModulus()->getValue());
264 auto_ptr_char exp(rsakv->getExponent()->getValue());
265 auto_ptr<XSECCryptoKeyRSA> rsa(XSECPlatformUtils::g_cryptoProvider->keyRSA());
266 rsa->loadPublicModulusBase64BigNums(mod.get(), strlen(mod.get()));
267 rsa->loadPublicExponentBase64BigNums(exp.get(), strlen(exp.get()));
268 m_key = rsa.release();
271 DSAKeyValue* dsakv = (*i)->getDSAKeyValue();
273 log.debug("resolving ds:DSAKeyValue");
274 auto_ptr<XSECCryptoKeyDSA> dsa(XSECPlatformUtils::g_cryptoProvider->keyDSA());
275 auto_ptr_char y(dsakv->getY()->getValue());
276 dsa->loadYBase64BigNums(y.get(), strlen(y.get()));
278 auto_ptr_char p(dsakv->getP()->getValue());
279 dsa->loadPBase64BigNums(p.get(), strlen(p.get()));
282 auto_ptr_char q(dsakv->getQ()->getValue());
283 dsa->loadQBase64BigNums(q.get(), strlen(q.get()));
286 auto_ptr_char g(dsakv->getG()->getValue());
287 dsa->loadGBase64BigNums(g.get(), strlen(g.get()));
289 m_key = dsa.release();
292 #ifdef XMLTOOLING_XMLSEC_ECC
293 ECKeyValue* eckv = (*i)->getECKeyValue();
294 if (eckv && eckv->getNamedCurve() && eckv->getPublicKey()) {
295 log.warn("resolving ds11:ECKeyValue");
296 auto_ptr<XSECCryptoKeyEC> ec(XSECPlatformUtils::g_cryptoProvider->keyEC());
297 auto_ptr_char uri(eckv->getNamedCurve()->getURI());
298 auto_ptr_char val(eckv->getPublicKey()->getValue());
299 if (uri.get() && val.get()) {
300 ec->loadPublicKeyBase64(uri.get(), val.get(), XMLString::stringLen(val.get()));
301 m_key = ec.release();
307 catch (ValidationException& ex) {
308 log.warn("skipping invalid ds:KeyValue (%s)", ex.what());
310 catch(XSECException& e) {
311 auto_ptr_char temp(e.getMsg());
312 log.error("caught XML-Security exception loading key: %s", temp.get());
314 catch(XSECCryptoException& e) {
315 log.error("caught XML-Security exception loading key: %s", e.getMsg());
319 // Check for ds11:DEREncodedKeyValue
320 const vector<DEREncodedKeyValue*>& derValues = keyInfo->getDEREncodedKeyValues();
321 for (vector<DEREncodedKeyValue*>::const_iterator j = derValues.begin(); j != derValues.end(); ++j) {
322 log.debug("resolving ds11:DEREncodedKeyValue");
323 m_key = SecurityHelper::fromDEREncoding((*j)->getValue());
326 log.warn("failed to resolve ds11:DEREncodedKeyValue");
331 // Check for KeyInfoReference.
332 const XMLCh* fragID=nullptr;
333 const XMLObject* treeRoot=nullptr;
334 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
335 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
336 fragID = (*ref)->getURI();
337 if (!fragID || *fragID != chPound || !*(fragID+1)) {
338 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
343 while (treeRoot->getParent())
344 treeRoot = treeRoot->getParent();
346 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
348 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
351 if (resolveKey(keyInfo, false))
359 bool InlineCredential::resolveCerts(const KeyInfo* keyInfo, bool followRefs)
361 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
363 // Check for ds:X509Data
364 const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
365 for (vector<X509Data*>::const_iterator j=x509Datas.begin(); m_xseccerts.empty() && j!=x509Datas.end(); ++j) {
366 const vector<X509Certificate*> x509Certs=const_cast<const X509Data*>(*j)->getX509Certificates();
367 for (vector<X509Certificate*>::const_iterator k=x509Certs.begin(); k!=x509Certs.end(); ++k) {
369 auto_ptr_char x((*k)->getValue());
371 log.warn("skipping empty ds:X509Certificate");
374 log.debug("resolving ds:X509Certificate");
375 auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
376 x509->loadX509Base64Bin(x.get(), strlen(x.get()));
377 m_xseccerts.push_back(x509.release());
380 catch(XSECException& e) {
381 auto_ptr_char temp(e.getMsg());
382 log.error("caught XML-Security exception loading certificate: %s", temp.get());
384 catch(XSECCryptoException& e) {
385 log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
390 if (followRefs && m_xseccerts.empty()) {
391 // Check for KeyInfoReference.
392 const XMLCh* fragID=NULL;
393 const XMLObject* treeRoot=NULL;
394 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
395 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
396 fragID = (*ref)->getURI();
397 if (!fragID || *fragID != chPound || !*(fragID+1)) {
398 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
403 while (treeRoot->getParent())
404 treeRoot = treeRoot->getParent();
406 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
408 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
411 if (resolveCerts(keyInfo, false))
417 log.debug("resolved %d certificate(s)", m_xseccerts.size());
418 return !m_xseccerts.empty();
421 bool InlineCredential::resolveCRLs(const KeyInfo* keyInfo, bool followRefs)
423 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
425 // Check for ds:X509Data
426 const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
427 for (vector<X509Data*>::const_iterator j=x509Datas.begin(); j!=x509Datas.end(); ++j) {
428 const vector<X509CRL*> x509CRLs=const_cast<const X509Data*>(*j)->getX509CRLs();
429 for (vector<X509CRL*>::const_iterator k=x509CRLs.begin(); k!=x509CRLs.end(); ++k) {
431 auto_ptr_char x((*k)->getValue());
433 log.warn("skipping empty ds:X509CRL");
436 log.debug("resolving ds:X509CRL");
437 auto_ptr<XSECCryptoX509CRL> crl(XMLToolingConfig::getConfig().X509CRL());
438 crl->loadX509CRLBase64Bin(x.get(), strlen(x.get()));
439 m_crls.push_back(crl.release());
442 catch(XSECException& e) {
443 auto_ptr_char temp(e.getMsg());
444 log.error("caught XML-Security exception loading CRL: %s", temp.get());
446 catch(XSECCryptoException& e) {
447 log.error("caught XML-Security exception loading CRL: %s", e.getMsg());
452 if (followRefs && m_crls.empty()) {
453 // Check for KeyInfoReference.
454 const XMLCh* fragID=NULL;
455 const XMLObject* treeRoot=NULL;
456 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
457 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
458 fragID = (*ref)->getURI();
459 if (!fragID || *fragID != chPound || !*(fragID+1)) {
460 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
465 while (treeRoot->getParent())
466 treeRoot = treeRoot->getParent();
468 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
470 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
473 if (resolveCRLs(keyInfo, false))
479 log.debug("resolved %d CRL(s)", m_crls.size());
480 return !m_crls.empty();
483 void InlineCredential::resolve(DSIGKeyInfoList* keyInfo, int types, bool followRefs)
489 if (types & Credential::RESOLVE_KEYS) {
490 // Default resolver handles RSA/DSAKeyValue and X509Certificate elements.
492 XSECKeyInfoResolverDefault def;
493 m_key = def.resolveKey(keyInfo);
495 catch(XSECException& e) {
496 auto_ptr_char temp(e.getMsg());
497 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", temp.get());
499 catch(XSECCryptoException& e) {
500 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", e.getMsg());
504 DSIGKeyInfoList::size_type sz = keyInfo->getSize();
506 if (types & X509Credential::RESOLVE_CERTS) {
507 for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
508 if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
509 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
510 int count = x509->getCertificateListSize();
512 for (int j=0; j<count; ++j)
513 m_xseccerts.push_back(x509->getCertificateCryptoItem(j));
520 if (types & X509Credential::RESOLVE_CRLS) {
521 for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
522 if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
523 #ifdef XMLTOOLING_XMLSEC_MULTIPLECRL
524 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
525 int count = x509->getX509CRLListSize();
526 for (int j=0; j<count; ++j) {
527 auto_ptr_char buf(x509->getX509CRLItem(j));
530 auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
531 crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
532 m_crls.push_back(crlobj.release());
534 catch(XSECException& e) {
535 auto_ptr_char temp(e.getMsg());
536 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", temp.get());
538 catch(XSECCryptoException& e) {
539 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", e.getMsg());
544 // The current xmlsec API is limited to one CRL per KeyInfo.
545 // For now, I'm going to process the DOM directly.
546 DOMNode* x509Node = keyInfo->item(i)->getKeyInfoDOMNode();
547 DOMElement* crlElement = x509Node ? XMLHelper::getFirstChildElement(x509Node, xmlconstants::XMLSIG_NS, X509CRL::LOCAL_NAME) : nullptr;
549 if (crlElement->hasChildNodes()) {
550 auto_ptr_char buf(crlElement->getFirstChild()->getNodeValue());
553 auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
554 crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
555 m_crls.push_back(crlobj.release());
557 catch(XSECException& e) {
558 auto_ptr_char temp(e.getMsg());
559 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", temp.get());
561 catch(XSECCryptoException& e) {
562 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", e.getMsg());
566 crlElement = XMLHelper::getNextSiblingElement(crlElement, xmlconstants::XMLSIG_NS, X509CRL::LOCAL_NAME);
576 for (size_t s=0; s<keyInfo->getSize(); s++) {
577 DSIGKeyInfo* dki = keyInfo->item(s);
581 m_keyNames.insert(kn);
582 if (dki->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509)
587 if (dki->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509) {
588 DSIGKeyInfoX509* kix = static_cast<DSIGKeyInfoX509*>(dki);
589 n = kix->getX509IssuerName();
595 n = kix->getX509IssuerSerialNumber();