2 * Copyright 2001-2009 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 * FilesystemCredentialResolver.cpp
20 * Supplies credentials from local files.
25 #include "security/BasicX509Credential.h"
26 #include "security/CredentialCriteria.h"
27 #include "security/CredentialResolver.h"
28 #include "security/KeyInfoResolver.h"
29 #include "security/OpenSSLCredential.h"
30 #include "security/SecurityHelper.h"
31 #include "security/XSECCryptoX509CRL.h"
33 #include "util/PathResolver.h"
34 #include "util/Threads.h"
35 #include "util/XMLHelper.h"
39 #include <sys/types.h>
41 #include <openssl/pkcs12.h>
42 #include <xercesc/util/XMLUniDefs.hpp>
43 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
45 using namespace xmlsignature;
46 using namespace xmltooling::logging;
47 using namespace xmltooling;
50 using xercesc::DOMElement;
51 using xercesc::chLatin_f;
52 using xercesc::chDigit_0;
54 namespace xmltooling {
56 // The ManagedResource classes handle memory management, loading of the files
57 // and staleness detection. A copy of the active objects is always stored in
60 class XMLTOOL_DLLLOCAL ManagedResource {
62 ManagedResource() : local(true), reloadChanges(true), filestamp(0), reloadInterval(0) {}
65 SOAPTransport* getTransport() {
66 SOAPTransport::Address addr("FilesystemCredentialResolver", source.c_str(), source.c_str());
67 string scheme(addr.m_endpoint, strchr(addr.m_endpoint,':') - addr.m_endpoint);
68 return XMLToolingConfig::getConfig().SOAPTransportManager.newPlugin(scheme.c_str(), addr);
72 bool stale(Category& log, RWLock* lock=NULL) {
75 struct _stat stat_buf;
76 if (_stat(source.c_str(), &stat_buf) != 0)
80 if (stat(source.c_str(), &stat_buf) != 0)
83 if (filestamp >= stat_buf.st_mtime)
86 // If necessary, elevate lock and recheck.
88 log.debug("timestamp of local resource changed, elevating to a write lock");
91 if (filestamp >= stat_buf.st_mtime) {
92 // Somebody else handled it, just downgrade.
93 log.debug("update of local resource handled by another thread, downgrading lock");
100 // Update the timestamp regardless. No point in repeatedly trying.
101 filestamp = stat_buf.st_mtime;
102 log.info("change detected, reloading local resource...");
105 time_t now = time(NULL);
108 if (now - filestamp < reloadInterval)
111 // If necessary, elevate lock and recheck.
113 log.debug("reload interval for remote resource elapsed, elevating to a write lock");
116 if (now - filestamp < reloadInterval) {
117 // Somebody else handled it, just downgrade.
118 log.debug("update of remote resource handled by another thread, downgrading lock");
126 log.info("reloading remote resource...");
131 bool local,reloadChanges;
132 string format,source,backing;
133 time_t filestamp,reloadInterval;
136 class XMLTOOL_DLLLOCAL ManagedKey : public ManagedResource {
138 ManagedKey() : key(NULL) {}
139 ~ManagedKey() { delete key; }
140 void load(Category& log, const char* password) {
143 XSECCryptoKey* nkey=NULL;
145 nkey = SecurityHelper::loadKeyFromFile(source.c_str(), format.c_str(), password);
148 auto_ptr<SOAPTransport> t(getTransport());
149 log.info("loading private key from URL (%s)", source.c_str());
150 nkey = SecurityHelper::loadKeyFromURL(*t.get(), backing.c_str(), format.c_str(), password);
155 format = SecurityHelper::guessEncodingFormat(local ? source.c_str() : backing.c_str());
161 class XMLTOOL_DLLLOCAL ManagedCert : public ManagedResource {
164 ~ManagedCert() { for_each(certs.begin(), certs.end(), xmltooling::cleanup<XSECCryptoX509>()); }
165 void load(Category& log, const char* password) {
168 vector<XSECCryptoX509*> ncerts;
170 SecurityHelper::loadCertificatesFromFile(ncerts, source.c_str(), format.c_str(), password);
173 auto_ptr<SOAPTransport> t(getTransport());
174 log.info("loading certificate(s) from URL (%s)", source.c_str());
175 SecurityHelper::loadCertificatesFromURL(ncerts, *t.get(), backing.c_str(), format.c_str(), password);
177 for_each(certs.begin(), certs.end(), xmltooling::cleanup<XSECCryptoX509>());
180 format = SecurityHelper::guessEncodingFormat(local ? source.c_str() : backing.c_str());
182 vector<XSECCryptoX509*> certs;
185 class XMLTOOL_DLLLOCAL ManagedCRL : public ManagedResource {
188 ~ManagedCRL() { for_each(crls.begin(), crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>()); }
189 void load(Category& log) {
192 vector<XSECCryptoX509CRL*> ncrls;
194 SecurityHelper::loadCRLsFromFile(ncrls, source.c_str(), format.c_str());
197 auto_ptr<SOAPTransport> t(getTransport());
198 log.info("loading CRL(s) from URL (%s)", source.c_str());
199 SecurityHelper::loadCRLsFromURL(ncrls, *t.get(), backing.c_str(), format.c_str());
201 for_each(crls.begin(), crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
204 format = SecurityHelper::guessEncodingFormat(local ? source.c_str() : backing.c_str());
206 vector<XSECCryptoX509CRL*> crls;
209 class XMLTOOL_DLLLOCAL FilesystemCredential;
210 class XMLTOOL_DLLLOCAL FilesystemCredentialResolver : public CredentialResolver
212 friend class XMLTOOL_DLLLOCAL FilesystemCredential;
214 FilesystemCredentialResolver(const DOMElement* e);
215 virtual ~FilesystemCredentialResolver();
222 const Credential* resolve(const CredentialCriteria* criteria=NULL) const;
224 virtual vector<const Credential*>::size_type resolve(
225 vector<const Credential*>& results, const CredentialCriteria* criteria=NULL
229 Credential* getCredential();
232 Credential* m_credential;
233 string m_keypass,m_certpass;
234 unsigned int m_keyinfomask,m_usage;
235 vector<string> m_keynames;
238 vector<ManagedCert> m_certs;
239 vector<ManagedCRL> m_crls;
242 #if defined (_MSC_VER)
243 #pragma warning( push )
244 #pragma warning( disable : 4250 )
247 class XMLTOOL_DLLLOCAL FilesystemCredential : public OpenSSLCredential, public BasicX509Credential
250 FilesystemCredential(
251 FilesystemCredentialResolver* resolver, XSECCryptoKey* key, const vector<XSECCryptoX509*>& xseccerts, const vector<XSECCryptoX509CRL*>& crls
252 ) : BasicX509Credential(key ? key : (xseccerts.empty() ? NULL : xseccerts.front()->clonePublicKey()), xseccerts, crls), m_resolver(resolver) {
254 m_keyNames.insert(m_resolver->m_keynames.begin(), m_resolver->m_keynames.end());
257 virtual ~FilesystemCredential() {
260 unsigned int getUsage() const {
261 return m_resolver->m_usage;
264 void initKeyInfo(unsigned int types=0) {
265 BasicX509Credential::initKeyInfo(types);
268 void attach(SSL_CTX* ctx) const;
271 FilesystemCredentialResolver* m_resolver;
274 #if defined (_MSC_VER)
275 #pragma warning( pop )
278 CredentialResolver* XMLTOOL_DLLLOCAL FilesystemCredentialResolverFactory(const DOMElement* const & e)
280 return new FilesystemCredentialResolver(e);
283 static const XMLCh backingFilePath[] = UNICODE_LITERAL_15(b,a,c,k,i,n,g,F,i,l,e,P,a,t,h);
284 static const XMLCh _CredentialResolver[] = UNICODE_LITERAL_18(C,r,e,d,e,n,t,i,a,l,R,e,s,o,l,v,e,r);
285 static const XMLCh CAPath[] = UNICODE_LITERAL_6(C,A,P,a,t,h);
286 static const XMLCh Certificate[] = UNICODE_LITERAL_11(C,e,r,t,i,f,i,c,a,t,e);
287 static const XMLCh _certificate[] = UNICODE_LITERAL_11(c,e,r,t,i,f,i,c,a,t,e);
288 static const XMLCh CRL[] = UNICODE_LITERAL_3(C,R,L);
289 static const XMLCh _format[] = UNICODE_LITERAL_6(f,o,r,m,a,t);
290 static const XMLCh Key[] = UNICODE_LITERAL_3(K,e,y);
291 static const XMLCh _key[] = UNICODE_LITERAL_3(k,e,y);
292 static const XMLCh keyInfoMask[] = UNICODE_LITERAL_11(k,e,y,I,n,f,o,M,a,s,k);
293 static const XMLCh keyName[] = UNICODE_LITERAL_7(k,e,y,N,a,m,e);
294 static const XMLCh Name[] = UNICODE_LITERAL_4(N,a,m,e);
295 static const XMLCh password[] = UNICODE_LITERAL_8(p,a,s,s,w,o,r,d);
296 static const XMLCh Path[] = UNICODE_LITERAL_4(P,a,t,h);
297 static const XMLCh _reloadChanges[] = UNICODE_LITERAL_13(r,e,l,o,a,d,C,h,a,n,g,e,s);
298 static const XMLCh _reloadInterval[] = UNICODE_LITERAL_14(r,e,l,o,a,d,I,n,t,e,r,v,a,l);
299 static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
300 static const XMLCh _use[] = UNICODE_LITERAL_3(u,s,e);
303 FilesystemCredentialResolver::FilesystemCredentialResolver(const DOMElement* e)
304 : m_lock(NULL), m_credential(NULL), m_usage(Credential::UNSPECIFIED_CREDENTIAL)
307 NDC ndc("FilesystemCredentialResolver");
309 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver."FILESYSTEM_CREDENTIAL_RESOLVER);
311 // Default to disable X509IssuerSerial due to schema validation issues.
313 Credential::KEYINFO_KEY_NAME |
314 Credential::KEYINFO_KEY_VALUE |
315 X509Credential::KEYINFO_X509_CERTIFICATE |
316 X509Credential::KEYINFO_X509_SUBJECTNAME;
317 if (e && e->hasAttributeNS(NULL,keyInfoMask))
318 m_keyinfomask = XMLString::parseInt(e->getAttributeNS(NULL,keyInfoMask));
320 if (e && (e->hasAttributeNS(NULL,_certificate) || e->hasAttributeNS(NULL,_key))) {
321 // Dummy up a simple file resolver config using these attributes.
322 DOMElement* dummy = e->getOwnerDocument()->createElementNS(NULL,_CredentialResolver);
325 if (e->hasAttributeNS(NULL,_key)) {
326 child = e->getOwnerDocument()->createElementNS(NULL,Key);
327 dummy->appendChild(child);
328 path = e->getOwnerDocument()->createElementNS(NULL,Path);
329 child->appendChild(path);
330 path->appendChild(e->getOwnerDocument()->createTextNode(e->getAttributeNS(NULL,_key)));
331 if (e->hasAttributeNS(NULL,password))
332 child->setAttributeNS(NULL,password,e->getAttributeNS(NULL,password));
333 if (e->hasAttributeNS(NULL,keyName)) {
334 path = e->getOwnerDocument()->createElementNS(NULL,Name);
335 child->appendChild(path);
336 path->appendChild(e->getOwnerDocument()->createTextNode(e->getAttributeNS(NULL,keyName)));
339 if (e->hasAttributeNS(NULL,_certificate)) {
340 child = e->getOwnerDocument()->createElementNS(NULL,Certificate);
341 dummy->appendChild(child);
342 path = e->getOwnerDocument()->createElementNS(NULL,Path);
343 child->appendChild(path);
344 path->appendChild(e->getOwnerDocument()->createTextNode(e->getAttributeNS(NULL,_certificate)));
346 e = dummy; // reset "root" to the dummy config element
350 const DOMElement* root = e;
352 // Save off usage flags.
353 const XMLCh* usage = root->getAttributeNS(NULL,_use);
354 if (usage && *usage) {
355 auto_ptr_char u(usage);
356 if (!strcmp(u.get(), "signing"))
357 m_usage = Credential::SIGNING_CREDENTIAL | Credential::TLS_CREDENTIAL;
358 else if (!strcmp(u.get(), "TLS"))
359 m_usage = Credential::TLS_CREDENTIAL;
360 else if (!strcmp(u.get(), "encryption"))
361 m_usage = Credential::ENCRYPTION_CREDENTIAL;
365 const DOMElement* keynode = XMLHelper::getFirstChildElement(root,Key);
367 prop = keynode->getAttributeNS(NULL,_format);
369 auto_ptr_char f(prop);
370 m_key.format = f.get();
373 prop = keynode->getAttributeNS(NULL,password);
375 auto_ptr_char kp(prop);
376 m_keypass = kp.get();
379 if ((e=XMLHelper::getFirstChildElement(keynode,Path)) && e->hasChildNodes()) {
380 prop = e->getFirstChild()->getNodeValue();
381 auto_ptr_char kpath(prop);
382 m_key.source = kpath.get();
383 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_key.source, PathResolver::XMLTOOLING_CFG_FILE);
385 prop = e->getAttributeNS(NULL,_reloadChanges);
386 if (prop && (*prop==chLatin_f) || (*prop==chDigit_0))
387 m_key.reloadChanges = false;
389 else if ((e=XMLHelper::getFirstChildElement(keynode,_URL)) && e->hasChildNodes()) {
390 prop = e->getFirstChild()->getNodeValue();
391 auto_ptr_char kpath(prop);
392 m_key.source = kpath.get();
394 prop = e->getAttributeNS(NULL,backingFilePath);
396 throw XMLSecurityException("FilesystemCredentialResolver can't access key, backingFilePath missing from URL element.");
397 auto_ptr_char b(prop);
398 m_key.backing = b.get();
399 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_key.backing, PathResolver::XMLTOOLING_RUN_FILE);
400 prop = e->getAttributeNS(NULL,_reloadInterval);
402 m_key.reloadInterval = XMLString::parseInt(prop);
405 log.error("Path/URL element missing inside Key element");
406 throw XMLSecurityException("FilesystemCredentialResolver can't access key, no Path or URL element specified.");
409 e = XMLHelper::getFirstChildElement(keynode, Name);
411 if (e->hasChildNodes()) {
412 auto_ptr_char n(e->getFirstChild()->getNodeValue());
413 if (n.get() && *n.get())
414 m_keynames.push_back(n.get());
416 e = XMLHelper::getNextSiblingElement(e, Name);
421 const DOMElement* crlnode = XMLHelper::getFirstChildElement(root,CRL);
423 const XMLCh* crlformat = crlnode->getAttributeNS(NULL,_format);
424 e = XMLHelper::getFirstChildElement(crlnode,Path);
426 if (e->hasChildNodes()) {
427 m_crls.push_back(ManagedCRL());
428 ManagedResource& crl = m_crls.back();
429 if (crlformat && *crlformat) {
430 auto_ptr_char f(crlformat);
431 crl.format = f.get();
433 prop = e->getFirstChild()->getNodeValue();
434 auto_ptr_char crlpath(prop);
435 crl.source = crlpath.get();
436 XMLToolingConfig::getConfig().getPathResolver()->resolve(crl.source, PathResolver::XMLTOOLING_CFG_FILE);
438 prop = e->getAttributeNS(NULL,_reloadChanges);
439 if (prop && (*prop==chLatin_f) || (*prop==chDigit_0))
440 crl.reloadChanges = false;
442 e = XMLHelper::getNextSiblingElement(e,Path);
445 e=XMLHelper::getFirstChildElement(crlnode,_URL);
447 if (e->hasChildNodes()) {
448 m_crls.push_back(ManagedCRL());
449 ManagedResource& crl = m_crls.back();
450 if (crlformat && *crlformat) {
451 auto_ptr_char f(crlformat);
452 crl.format = f.get();
454 prop = e->getFirstChild()->getNodeValue();
455 auto_ptr_char crlpath(prop);
456 crl.source = crlpath.get();
458 prop = e->getAttributeNS(NULL,backingFilePath);
460 throw XMLSecurityException("FilesystemCredentialResolver can't access CRL, backingFilePath missing from URL element.");
461 auto_ptr_char b(prop);
462 crl.backing = b.get();
463 XMLToolingConfig::getConfig().getPathResolver()->resolve(crl.backing, PathResolver::XMLTOOLING_RUN_FILE);
464 prop = e->getAttributeNS(NULL,_reloadInterval);
466 crl.reloadInterval = XMLString::parseInt(prop);
468 e = XMLHelper::getNextSiblingElement(e,_URL);
470 if (m_crls.empty()) {
471 log.error("Path/URL element missing inside CRL element");
472 throw XMLSecurityException("FilesystemCredentialResolver can't access CRL, no Path or URL element specified.");
476 // Check for Certificate
477 DOMElement* certnode = XMLHelper::getFirstChildElement(root,Certificate);
479 prop = certnode->getAttributeNS(NULL,password);
481 auto_ptr_char certpass(prop);
482 m_certpass = certpass.get();
485 const XMLCh* certformat = certnode->getAttributeNS(NULL,_format);
487 e = XMLHelper::getFirstChildElement(certnode);
489 if (e->hasChildNodes() && (XMLString::equals(e->getLocalName(), Path) || XMLString::equals(e->getLocalName(), CAPath))) {
490 m_certs.push_back(ManagedCert());
491 ManagedResource& cert = m_certs.back();
492 if (certformat && *certformat) {
493 auto_ptr_char f(certformat);
494 cert.format = f.get();
496 prop = e->getFirstChild()->getNodeValue();
497 auto_ptr_char certpath(prop);
498 cert.source = certpath.get();
499 XMLToolingConfig::getConfig().getPathResolver()->resolve(cert.source, PathResolver::XMLTOOLING_CFG_FILE);
501 prop = e->getAttributeNS(NULL,_reloadChanges);
502 if (prop && (*prop==chLatin_f) || (*prop==chDigit_0))
503 cert.reloadChanges = false;
505 else if (e->hasChildNodes() && XMLString::equals(e->getLocalName(), _URL)) {
506 m_certs.push_back(ManagedCert());
507 ManagedResource& cert = m_certs.back();
508 if (certformat && *certformat) {
509 auto_ptr_char f(certformat);
510 cert.format = f.get();
512 prop = e->getFirstChild()->getNodeValue();
513 auto_ptr_char certpath(prop);
514 cert.source = certpath.get();
516 prop = e->getAttributeNS(NULL,backingFilePath);
518 throw XMLSecurityException("FilesystemCredentialResolver can't access certificate, backingFilePath missing from URL element.");
519 auto_ptr_char b(prop);
520 cert.backing = b.get();
521 XMLToolingConfig::getConfig().getPathResolver()->resolve(cert.backing, PathResolver::XMLTOOLING_RUN_FILE);
522 prop = e->getAttributeNS(NULL,_reloadInterval);
524 cert.reloadInterval = XMLString::parseInt(prop);
526 e = XMLHelper::getNextSiblingElement(e);
528 if (m_certs.empty()) {
529 log.error("Path/URL element missing inside Certificate element");
530 throw XMLSecurityException("FilesystemCredentialResolver can't access certificate, no Path or URL element specified.");
534 // Do an initial load of all the objects. If anything blows up here, whatever's
535 // been loaded should be freed during teardown of the embedded objects.
536 time_t now = time(NULL);
537 m_key.filestamp = now;
538 m_key.load(log, m_keypass.c_str());
539 for (vector<ManagedCert>::iterator i = m_certs.begin(); i != m_certs.end(); ++i) {
540 i->load(log, (i==m_certs.begin()) ? m_certpass.c_str() : NULL);
543 for (vector<ManagedCRL>::iterator j = m_crls.begin(); j != m_crls.end(); ++j) {
548 // Load it all into a credential object and then create the lock.
549 auto_ptr<Credential> credential(getCredential());
550 m_lock = RWLock::create();
551 m_credential = credential.release();
554 FilesystemCredentialResolver::~FilesystemCredentialResolver()
560 Credential* FilesystemCredentialResolver::getCredential()
562 // First, verify that the key and certificate match.
563 if (m_key.key && !m_certs.empty()) {
564 auto_ptr<XSECCryptoKey> temp(m_certs.front().certs.front()->clonePublicKey());
565 if (!SecurityHelper::matches(*m_key.key, *temp.get()))
566 throw XMLSecurityException("FilesystemCredentialResolver given mismatched key/certificate, check for consistency.");
569 // We (unfortunately) need to duplicate all the objects and put them in one set of arrays
570 // in order to create the credential wrapper.
571 FilesystemCredential* credential=NULL;
572 auto_ptr<XSECCryptoKey> xseckey(m_key.key ? m_key.key->clone() : NULL);
573 vector<XSECCryptoX509*> xseccerts;
574 vector<XSECCryptoX509CRL*> xseccrls;
576 for (vector<ManagedCert>::iterator i = m_certs.begin(); i != m_certs.end(); ++i) {
577 for (vector<XSECCryptoX509*>::const_iterator y = i->certs.begin(); y != i->certs.end(); ++y)
578 xseccerts.push_back(new OpenSSLCryptoX509(static_cast<OpenSSLCryptoX509*>(*y)->getOpenSSLX509()));
580 for (vector<ManagedCRL>::iterator j = m_crls.begin(); j != m_crls.end(); ++j) {
581 for (vector<XSECCryptoX509CRL*>::const_iterator z = j->crls.begin(); z != j->crls.end(); ++z)
582 xseccrls.push_back((*z)->clone());
584 credential = new FilesystemCredential(this, xseckey.get(), xseccerts, xseccrls);
588 for_each(xseccerts.begin(), xseccerts.end(), xmltooling::cleanup<XSECCryptoX509>());
589 for_each(xseccrls.begin(), xseccrls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
593 // At this point the copies are owned by the credential.
595 credential->initKeyInfo(m_keyinfomask);
605 Lockable* FilesystemCredentialResolver::lock()
610 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver."FILESYSTEM_CREDENTIAL_RESOLVER);
614 // Check each managed resource while holding a read lock for staleness.
615 // If it comes back false, the lock is left as is, and the resource was stable.
616 // If it comes back true, the lock was elevated to a write lock, and the resource
617 // needs to be reloaded, and the credential replaced.
618 // Once a stale check comes back true, further checks leave the lock alone.
620 bool writelock = false, updated = false;
622 if (m_key.stale(log, m_lock)) {
625 m_key.load(log, m_keypass.c_str());
628 catch (exception& ex) {
629 log.crit("maintaining existing key: %s", ex.what());
633 for (vector<ManagedCert>::iterator i = m_certs.begin(); i != m_certs.end(); ++i) {
634 if (i->stale(log, writelock ? NULL : m_lock)) {
637 i->load(log, (i==m_certs.begin()) ? m_certpass.c_str() : NULL);
640 catch (exception& ex) {
641 log.crit("maintaining existing certificate(s): %s", ex.what());
646 for (vector<ManagedCRL>::iterator j = m_crls.begin(); j != m_crls.end(); ++j) {
647 if (j->stale(log, writelock ? NULL : m_lock)) {
653 catch (exception& ex) {
654 log.crit("maintaining existing CRL(s): %s", ex.what());
661 auto_ptr<Credential> credential(getCredential());
663 m_credential = credential.release();
665 catch (exception& ex) {
666 log.crit("maintaining existing credentials, error reloading: %s", ex.what());
677 const Credential* FilesystemCredentialResolver::resolve(const CredentialCriteria* criteria) const
679 return (criteria ? (criteria->matches(*m_credential) ? m_credential : NULL) : m_credential);
682 vector<const Credential*>::size_type FilesystemCredentialResolver::resolve(
683 vector<const Credential*>& results, const CredentialCriteria* criteria
686 if (!criteria || criteria->matches(*m_credential)) {
687 results.push_back(m_credential);
693 // OpenSSL password callback...
694 static int passwd_callback(char* buf, int len, int verify, void* passwd)
698 if(passwd && len > strlen(reinterpret_cast<char*>(passwd)))
700 strcpy(buf,reinterpret_cast<char*>(passwd));
707 void FilesystemCredential::attach(SSL_CTX* ctx) const
714 const char* path = m_resolver->m_key.local ? m_resolver->m_key.source.c_str() : m_resolver->m_key.backing.c_str();
716 throw XMLSecurityException("No key available, unable to attach private key to SSL context.");
718 if (!m_resolver->m_keypass.empty()) {
719 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
720 SSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char*>(m_resolver->m_keypass.c_str()));
723 if (m_resolver->m_key.format == "PEM") {
724 ret=SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM);
726 else if (m_resolver->m_key.format == "DER") {
727 ret=SSL_CTX_use_RSAPrivateKey_file(ctx, path, SSL_FILETYPE_ASN1);
729 else if (m_resolver->m_key.format == "PKCS12") {
730 BIO* in=BIO_new(BIO_s_file_internal());
731 if (in && BIO_read_filename(in,path)>0) {
732 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);
736 PKCS12_parse(p12, const_cast<char*>(m_resolver->m_keypass.c_str()), &pkey, &x, NULL);
741 ret=SSL_CTX_use_PrivateKey(ctx, pkey);
752 throw XMLSecurityException("Unable to attach private key to SSL context.");
756 for (vector<XSECCryptoX509*>::const_iterator i=m_xseccerts.begin(); i!=m_xseccerts.end(); i++) {
757 if (i==m_xseccerts.begin()) {
758 if (SSL_CTX_use_certificate(ctx, static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509()) != 1) {
760 throw XMLSecurityException("Unable to attach client certificate to SSL context.");
764 // When we add certs, they don't get ref counted, so we need to duplicate them.
765 X509* dup = X509_dup(static_cast<OpenSSLCryptoX509*>(*i)->getOpenSSLX509());
766 if (SSL_CTX_add_extra_chain_cert(ctx, dup) != 1) {
769 throw XMLSecurityException("Unable to attach CA certificate to SSL context.");