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)) {}
65 InlineCredential(DSIGKeyInfoList* keyInfo) : BasicX509Credential(false), m_credctx(new KeyInfoCredentialContext(keyInfo)) {}
66 InlineCredential(KeyInfoCredentialContext* context) : BasicX509Credential(context->getKeyInfo()!=nullptr) {}
67 virtual ~InlineCredential() {}
69 XSECCryptoKey* getPrivateKey() const {
73 KeyInfo* getKeyInfo(bool compact=false) const {
74 KeyInfo* ret = m_credctx->getKeyInfo() ? m_credctx->getKeyInfo()->cloneKeyInfo() : nullptr;
77 ret->getRetrievalMethods().clear();
78 ret->getKeyInfoReferences().clear();
80 ret->getKeyValues().clear();
81 ret->getDEREncodedKeyValues().clear();
82 ret->getSPKIDatas().clear();
83 ret->getPGPDatas().clear();
84 ret->getUnknownXMLObjects().clear();
85 VectorOf(X509Data) x509Datas=ret->getX509Datas();
86 for (VectorOf(X509Data)::size_type pos = 0; pos < x509Datas.size();) {
87 x509Datas[pos]->getX509Certificates().clear();
88 x509Datas[pos]->getX509CRLs().clear();
89 x509Datas[pos]->getOCSPResponses().clear();
90 x509Datas[pos]->getUnknownXMLObjects().clear();
91 if (x509Datas[pos]->hasChildren())
94 x509Datas.erase(x509Datas.begin() + pos);
98 if (!ret->hasChildren()) {
105 const CredentialContext* getCredentalContext() const {
106 return m_credctx.get();
109 void setCredentialContext(KeyInfoCredentialContext* context) {
110 m_credctx.reset(context);
113 void resolve(const KeyInfo* keyInfo, int types=0, bool followRefs=false);
114 void resolve(DSIGKeyInfoList* keyInfo, int types=0, bool followRefs=false);
117 bool resolveCerts(const KeyInfo* keyInfo, bool followRefs=false);
118 bool resolveKey(const KeyInfo* keyInfo, bool followRefs=false);
119 bool resolveCRLs(const KeyInfo* keyInfo, bool followRefs=false);
121 auto_ptr<KeyInfoCredentialContext> m_credctx;
124 static const XMLCh keyInfoReferences[] = UNICODE_LITERAL_17(k,e,y,I,n,f,o,R,e,f,e,r,e,n,c,e,s);
126 class XMLTOOL_DLLLOCAL InlineKeyResolver : public KeyInfoResolver
129 InlineKeyResolver(const DOMElement* e)
130 : m_followRefs(XMLHelper::getAttrBool(e, false, keyInfoReferences)) {
133 virtual ~InlineKeyResolver() {}
135 Credential* resolve(const KeyInfo* keyInfo, int types=0) const {
139 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
140 auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
141 credential->resolve(keyInfo, types, m_followRefs);
142 return credential.release();
144 Credential* resolve(DSIGKeyInfoList* keyInfo, int types=0) const {
148 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
149 auto_ptr<InlineCredential> credential(new InlineCredential(keyInfo));
150 credential->resolve(keyInfo, types, m_followRefs);
151 return credential.release();
153 Credential* resolve(KeyInfoCredentialContext* context, int types=0) const {
157 types = Credential::RESOLVE_KEYS|X509Credential::RESOLVE_CERTS|X509Credential::RESOLVE_CRLS;
158 auto_ptr<InlineCredential> credential(new InlineCredential(context));
159 if (context->getKeyInfo())
160 credential->resolve(context->getKeyInfo(), types, m_followRefs);
161 else if (context->getNativeKeyInfo())
162 credential->resolve(context->getNativeKeyInfo(), types, m_followRefs);
163 credential->setCredentialContext(context);
164 return credential.release();
171 KeyInfoResolver* XMLTOOL_DLLLOCAL InlineKeyInfoResolverFactory(const DOMElement* const & e)
173 return new InlineKeyResolver(e);
177 void InlineCredential::resolve(const KeyInfo* keyInfo, int types, bool followRefs)
183 if (types & X509Credential::RESOLVE_CERTS)
184 resolveCerts(keyInfo, followRefs);
186 if (types & Credential::RESOLVE_KEYS) {
187 if (types & X509Credential::RESOLVE_CERTS) {
188 // If we have a cert, just use it.
189 if (!m_xseccerts.empty())
190 m_key = m_xseccerts.front()->clonePublicKey();
192 resolveKey(keyInfo, followRefs);
194 // Otherwise try directly for a key and then go for certs if none is found.
195 else if (!resolveKey(keyInfo, followRefs) && resolveCerts(keyInfo, followRefs)) {
196 m_key = m_xseccerts.front()->clonePublicKey();
200 if (types & X509Credential::RESOLVE_CRLS)
201 resolveCRLs(keyInfo, followRefs);
205 const vector<KeyName*>& knames=keyInfo->getKeyNames();
206 for (vector<KeyName*>::const_iterator kn_i=knames.begin(); kn_i!=knames.end(); ++kn_i) {
207 n=(*kn_i)->getName();
210 m_keyNames.insert(kn);
214 const vector<X509Data*> datas=keyInfo->getX509Datas();
215 for (vector<X509Data*>::const_iterator x_i=datas.begin(); x_i!=datas.end(); ++x_i) {
216 const vector<X509SubjectName*> snames = const_cast<const X509Data*>(*x_i)->getX509SubjectNames();
217 for (vector<X509SubjectName*>::const_iterator sn_i = snames.begin(); sn_i!=snames.end(); ++sn_i) {
218 n = (*sn_i)->getName();
221 m_keyNames.insert(kn);
227 const vector<X509IssuerSerial*> inames = const_cast<const X509Data*>(*x_i)->getX509IssuerSerials();
228 if (!inames.empty()) {
229 const X509IssuerName* iname = inames.front()->getX509IssuerName();
231 kn = toUTF8(iname->getName());
237 const X509SerialNumber* ser = inames.front()->getX509SerialNumber();
239 auto_ptr_char sn(ser->getSerialNumber());
246 bool InlineCredential::resolveKey(const KeyInfo* keyInfo, bool followRefs)
248 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
250 // Check for ds:KeyValue
251 const vector<KeyValue*>& keyValues = keyInfo->getKeyValues();
252 for (vector<KeyValue*>::const_iterator i = keyValues.begin(); i != keyValues.end(); ++i) {
254 SchemaValidators.validate(*i); // see if it's a "valid" key
255 RSAKeyValue* rsakv = (*i)->getRSAKeyValue();
257 log.debug("resolving ds:RSAKeyValue");
258 auto_ptr_char mod(rsakv->getModulus()->getValue());
259 auto_ptr_char exp(rsakv->getExponent()->getValue());
260 auto_ptr<XSECCryptoKeyRSA> rsa(XSECPlatformUtils::g_cryptoProvider->keyRSA());
261 rsa->loadPublicModulusBase64BigNums(mod.get(), strlen(mod.get()));
262 rsa->loadPublicExponentBase64BigNums(exp.get(), strlen(exp.get()));
263 m_key = rsa.release();
266 DSAKeyValue* dsakv = (*i)->getDSAKeyValue();
268 log.debug("resolving ds:DSAKeyValue");
269 auto_ptr<XSECCryptoKeyDSA> dsa(XSECPlatformUtils::g_cryptoProvider->keyDSA());
270 auto_ptr_char y(dsakv->getY()->getValue());
271 dsa->loadYBase64BigNums(y.get(), strlen(y.get()));
273 auto_ptr_char p(dsakv->getP()->getValue());
274 dsa->loadPBase64BigNums(p.get(), strlen(p.get()));
277 auto_ptr_char q(dsakv->getQ()->getValue());
278 dsa->loadQBase64BigNums(q.get(), strlen(q.get()));
281 auto_ptr_char g(dsakv->getG()->getValue());
282 dsa->loadGBase64BigNums(g.get(), strlen(g.get()));
284 m_key = dsa.release();
287 #ifdef XMLTOOLING_XMLSEC_ECC
288 ECKeyValue* eckv = (*i)->getECKeyValue();
289 if (eckv && eckv->getNamedCurve() && eckv->getPublicKey()) {
290 log.warn("resolving ds11:ECKeyValue");
291 auto_ptr<XSECCryptoKeyEC> ec(XSECPlatformUtils::g_cryptoProvider->keyEC());
292 auto_ptr_char uri(eckv->getNamedCurve()->getURI());
293 auto_ptr_char val(eckv->getPublicKey()->getValue());
294 if (uri.get() && val.get()) {
295 ec->loadPublicKeyBase64(uri.get(), val.get(), XMLString::stringLen(val.get()));
296 m_key = ec.release();
302 catch (ValidationException& ex) {
303 log.warn("skipping invalid ds:KeyValue (%s)", ex.what());
305 catch(XSECException& e) {
306 auto_ptr_char temp(e.getMsg());
307 log.error("caught XML-Security exception loading key: %s", temp.get());
309 catch(XSECCryptoException& e) {
310 log.error("caught XML-Security exception loading key: %s", e.getMsg());
314 // Check for ds11:DEREncodedKeyValue
315 const vector<DEREncodedKeyValue*>& derValues = keyInfo->getDEREncodedKeyValues();
316 for (vector<DEREncodedKeyValue*>::const_iterator j = derValues.begin(); j != derValues.end(); ++j) {
317 log.debug("resolving ds11:DEREncodedKeyValue");
318 m_key = SecurityHelper::fromDEREncoding((*j)->getValue());
321 log.warn("failed to resolve ds11:DEREncodedKeyValue");
326 // Check for KeyInfoReference.
327 const XMLCh* fragID=nullptr;
328 const XMLObject* treeRoot=nullptr;
329 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
330 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
331 fragID = (*ref)->getURI();
332 if (!fragID || *fragID != chPound || !*(fragID+1)) {
333 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
338 while (treeRoot->getParent())
339 treeRoot = treeRoot->getParent();
341 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
343 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
346 if (resolveKey(keyInfo, false))
354 bool InlineCredential::resolveCerts(const KeyInfo* keyInfo, bool followRefs)
356 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
358 // Check for ds:X509Data
359 const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
360 for (vector<X509Data*>::const_iterator j=x509Datas.begin(); m_xseccerts.empty() && j!=x509Datas.end(); ++j) {
361 const vector<X509Certificate*> x509Certs=const_cast<const X509Data*>(*j)->getX509Certificates();
362 for (vector<X509Certificate*>::const_iterator k=x509Certs.begin(); k!=x509Certs.end(); ++k) {
364 auto_ptr_char x((*k)->getValue());
366 log.warn("skipping empty ds:X509Certificate");
369 log.debug("resolving ds:X509Certificate");
370 auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
371 x509->loadX509Base64Bin(x.get(), strlen(x.get()));
372 m_xseccerts.push_back(x509.release());
375 catch(XSECException& e) {
376 auto_ptr_char temp(e.getMsg());
377 log.error("caught XML-Security exception loading certificate: %s", temp.get());
379 catch(XSECCryptoException& e) {
380 log.error("caught XML-Security exception loading certificate: %s", e.getMsg());
385 if (followRefs && m_xseccerts.empty()) {
386 // Check for KeyInfoReference.
387 const XMLCh* fragID=NULL;
388 const XMLObject* treeRoot=NULL;
389 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
390 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
391 fragID = (*ref)->getURI();
392 if (!fragID || *fragID != chPound || !*(fragID+1)) {
393 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
398 while (treeRoot->getParent())
399 treeRoot = treeRoot->getParent();
401 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
403 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
406 if (resolveCerts(keyInfo, false))
412 log.debug("resolved %d certificate(s)", m_xseccerts.size());
413 return !m_xseccerts.empty();
416 bool InlineCredential::resolveCRLs(const KeyInfo* keyInfo, bool followRefs)
418 Category& log = Category::getInstance(XMLTOOLING_LOGCAT".KeyInfoResolver."INLINE_KEYINFO_RESOLVER);
420 // Check for ds:X509Data
421 const vector<X509Data*>& x509Datas=keyInfo->getX509Datas();
422 for (vector<X509Data*>::const_iterator j=x509Datas.begin(); j!=x509Datas.end(); ++j) {
423 const vector<X509CRL*> x509CRLs=const_cast<const X509Data*>(*j)->getX509CRLs();
424 for (vector<X509CRL*>::const_iterator k=x509CRLs.begin(); k!=x509CRLs.end(); ++k) {
426 auto_ptr_char x((*k)->getValue());
428 log.warn("skipping empty ds:X509CRL");
431 log.debug("resolving ds:X509CRL");
432 auto_ptr<XSECCryptoX509CRL> crl(XMLToolingConfig::getConfig().X509CRL());
433 crl->loadX509CRLBase64Bin(x.get(), strlen(x.get()));
434 m_crls.push_back(crl.release());
437 catch(XSECException& e) {
438 auto_ptr_char temp(e.getMsg());
439 log.error("caught XML-Security exception loading CRL: %s", temp.get());
441 catch(XSECCryptoException& e) {
442 log.error("caught XML-Security exception loading CRL: %s", e.getMsg());
447 if (followRefs && m_crls.empty()) {
448 // Check for KeyInfoReference.
449 const XMLCh* fragID=NULL;
450 const XMLObject* treeRoot=NULL;
451 const vector<KeyInfoReference*>& refs = keyInfo->getKeyInfoReferences();
452 for (vector<KeyInfoReference*>::const_iterator ref = refs.begin(); ref != refs.end(); ++ref) {
453 fragID = (*ref)->getURI();
454 if (!fragID || *fragID != chPound || !*(fragID+1)) {
455 log.warn("skipping ds11:KeyInfoReference with an empty or non-local reference");
460 while (treeRoot->getParent())
461 treeRoot = treeRoot->getParent();
463 keyInfo = dynamic_cast<const KeyInfo*>(XMLHelper::getXMLObjectById(*treeRoot, fragID+1));
465 log.warn("skipping ds11:KeyInfoReference, local reference did not resolve to a ds:KeyInfo");
468 if (resolveCRLs(keyInfo, false))
474 log.debug("resolved %d CRL(s)", m_crls.size());
475 return !m_crls.empty();
478 void InlineCredential::resolve(DSIGKeyInfoList* keyInfo, int types, bool followRefs)
484 if (types & Credential::RESOLVE_KEYS) {
485 // Default resolver handles RSA/DSAKeyValue and X509Certificate elements.
487 XSECKeyInfoResolverDefault def;
488 m_key = def.resolveKey(keyInfo);
490 catch(XSECException& e) {
491 auto_ptr_char temp(e.getMsg());
492 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", temp.get());
494 catch(XSECCryptoException& e) {
495 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading certificate: %s", e.getMsg());
499 DSIGKeyInfoList::size_type sz = keyInfo->getSize();
501 if (types & X509Credential::RESOLVE_CERTS) {
502 for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
503 if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
504 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
505 int count = x509->getCertificateListSize();
507 for (int j=0; j<count; ++j)
508 m_xseccerts.push_back(x509->getCertificateCryptoItem(j));
515 if (types & X509Credential::RESOLVE_CRLS) {
516 for (DSIGKeyInfoList::size_type i=0; i<sz; ++i) {
517 if (keyInfo->item(i)->getKeyInfoType()==DSIGKeyInfo::KEYINFO_X509) {
518 #ifdef XMLTOOLING_XMLSEC_MULTIPLECRL
519 DSIGKeyInfoX509* x509 = static_cast<DSIGKeyInfoX509*>(keyInfo->item(i));
520 int count = x509->getX509CRLListSize();
521 for (int j=0; j<count; ++j) {
522 auto_ptr_char buf(x509->getX509CRLItem(j));
525 auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
526 crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
527 m_crls.push_back(crlobj.release());
529 catch(XSECException& e) {
530 auto_ptr_char temp(e.getMsg());
531 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", temp.get());
533 catch(XSECCryptoException& e) {
534 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", e.getMsg());
539 // The current xmlsec API is limited to one CRL per KeyInfo.
540 // For now, I'm going to process the DOM directly.
541 DOMNode* x509Node = keyInfo->item(i)->getKeyInfoDOMNode();
542 DOMElement* crlElement = x509Node ? XMLHelper::getFirstChildElement(x509Node, xmlconstants::XMLSIG_NS, X509CRL::LOCAL_NAME) : nullptr;
544 if (crlElement->hasChildNodes()) {
545 auto_ptr_char buf(crlElement->getFirstChild()->getNodeValue());
548 auto_ptr<XSECCryptoX509CRL> crlobj(XMLToolingConfig::getConfig().X509CRL());
549 crlobj->loadX509CRLBase64Bin(buf.get(), strlen(buf.get()));
550 m_crls.push_back(crlobj.release());
552 catch(XSECException& e) {
553 auto_ptr_char temp(e.getMsg());
554 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", temp.get());
556 catch(XSECCryptoException& e) {
557 Category::getInstance(XMLTOOLING_LOGCAT".KeyResolver."INLINE_KEYINFO_RESOLVER).error("caught XML-Security exception loading CRL: %s", e.getMsg());
561 crlElement = XMLHelper::getNextSiblingElement(crlElement, xmlconstants::XMLSIG_NS, X509CRL::LOCAL_NAME);
571 for (size_t s=0; s<keyInfo->getSize(); s++) {
572 DSIGKeyInfo* dki = keyInfo->item(s);
576 m_keyNames.insert(kn);
577 if (dki->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509)
582 if (dki->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509) {
583 DSIGKeyInfoX509* kix = static_cast<DSIGKeyInfoX509*>(dki);
584 n = kix->getX509IssuerName();
590 n = kix->getX509IssuerSerialNumber();