2 * Copyright 2001-2007 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
24 #include "security/BasicX509Credential.h"
25 #include "security/CredentialCriteria.h"
26 #include "security/CredentialResolver.h"
27 #include "security/KeyInfoResolver.h"
28 #include "security/OpenSSLCredential.h"
30 #include "util/XMLHelper.h"
32 #include <sys/types.h>
34 #include <openssl/pkcs12.h>
35 #include <log4cpp/Category.hh>
36 #include <xercesc/util/XMLUniDefs.hpp>
37 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
38 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyRSA.hpp>
39 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyDSA.hpp>
41 using namespace xmlsignature;
42 using namespace xmltooling;
43 using namespace log4cpp;
46 // OpenSSL password callback...
47 static int passwd_callback(char* buf, int len, int verify, void* passwd)
51 if(passwd && len > strlen(reinterpret_cast<char*>(passwd)))
53 strcpy(buf,reinterpret_cast<char*>(passwd));
60 namespace xmltooling {
62 #if defined (_MSC_VER)
63 #pragma warning( push )
64 #pragma warning( disable : 4250 )
67 class XMLTOOL_DLLLOCAL FilesystemCredentialResolver;
68 class XMLTOOL_DLLLOCAL FilesystemCredential : public OpenSSLCredential, public BasicX509Credential
71 FilesystemCredential(FilesystemCredentialResolver* resolver, XSECCryptoKey* key, const std::vector<XSECCryptoX509*>& xseccerts)
72 : BasicX509Credential(key, xseccerts), m_resolver(resolver) {
73 if (!m_xseccerts.empty())
74 extractNames(m_xseccerts.front(), m_keyNames);
77 virtual ~FilesystemCredential() {
80 void attach(SSL_CTX* ctx) const;
83 FilesystemCredentialResolver* m_resolver;
86 #if defined (_MSC_VER)
87 #pragma warning( pop )
90 class XMLTOOL_DLLLOCAL FilesystemCredentialResolver : public CredentialResolver
93 FilesystemCredentialResolver(const DOMElement* e);
94 virtual ~FilesystemCredentialResolver() {
96 for_each(m_certs.begin(),m_certs.end(),X509_free);
99 Lockable* lock() { return this; }
102 const Credential* resolve(const CredentialCriteria* criteria=NULL) const {
103 return (criteria ? (criteria->matches(*m_credential) ? m_credential : NULL) : m_credential);
106 virtual vector<const Credential*>::size_type resolve(
107 vector<const Credential*>& results, const CredentialCriteria* criteria=NULL
109 if (!criteria || criteria->matches(*m_credential)) {
110 results.push_back(m_credential);
116 void attach(SSL_CTX* ctx) const;
119 XSECCryptoKey* loadKey();
121 enum format_t { PEM=SSL_FILETYPE_PEM, DER=SSL_FILETYPE_ASN1, _PKCS12, UNKNOWN };
123 format_t getEncodingFormat(BIO* in) const;
124 string formatToString(format_t format) const;
125 format_t xmlFormatToFormat(const XMLCh* format_xml) const;
127 format_t m_keyformat;
128 string m_keypath,m_keypass;
129 vector<X509*> m_certs;
130 FilesystemCredential* m_credential;
133 CredentialResolver* XMLTOOL_DLLLOCAL FilesystemCredentialResolverFactory(const DOMElement* const & e)
135 return new FilesystemCredentialResolver(e);
139 static const XMLCh CAPath[] = UNICODE_LITERAL_6(C,A,P,a,t,h);
140 static const XMLCh Certificate[] = UNICODE_LITERAL_11(C,e,r,t,i,f,i,c,a,t,e);
141 static const XMLCh format[] = UNICODE_LITERAL_6(f,o,r,m,a,t);
142 static const XMLCh Key[] = UNICODE_LITERAL_3(K,e,y);
143 static const XMLCh password[] = UNICODE_LITERAL_8(p,a,s,s,w,o,r,d);
144 static const XMLCh Path[] = UNICODE_LITERAL_4(P,a,t,h);
146 FilesystemCredentialResolver::FilesystemCredentialResolver(const DOMElement* e) : m_credential(NULL)
149 NDC ndc("FilesystemCredentialResolver");
151 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver");
153 const DOMElement* root=e;
155 XSECCryptoKey* key=NULL;
156 vector<XSECCryptoX509*> xseccerts;
159 const XMLCh* format_xml=NULL;
163 e=XMLHelper::getFirstChildElement(root,Key);
166 // Get raw format attrib value, but defer processing til later since may need to
167 // determine format dynamically, and we need the Path for that.
168 format_xml=e->getAttributeNS(NULL,format);
170 const XMLCh* password_xml=e->getAttributeNS(NULL,password);
172 auto_ptr_char kp(password_xml);
176 e=XMLHelper::getFirstChildElement(e,Path);
177 if (e && e->hasChildNodes()) {
178 const XMLCh* s=e->getFirstChild()->getNodeValue();
179 auto_ptr_char kpath(s);
181 struct _stat stat_buf;
182 if (_stat(kpath.get(), &stat_buf) != 0)
184 struct stat stat_buf;
185 if (stat(kpath.get(), &stat_buf) != 0)
188 log.error("key file (%s) can't be opened", kpath.get());
189 throw XMLSecurityException("FilesystemCredentialResolver can't access key file ($1)",params(1,kpath.get()));
191 m_keypath=kpath.get();
194 log.error("Path element missing inside Key element");
195 throw XMLSecurityException("FilesystemCredentialResolver can't access key file, no Path element specified.");
198 // Determine the key encoding format dynamically, if not explicitly specified
199 if (format_xml && *format_xml) {
200 fformat = xmlFormatToFormat(format_xml);
201 if (fformat != UNKNOWN) {
202 m_keyformat = fformat;
205 auto_ptr_char unknown(format_xml);
206 log.error("configuration specifies unknown key encoding format (%s)", unknown.get());
207 throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown key encoding format ($1)",params(1,unknown.get()));
211 in=BIO_new(BIO_s_file_internal());
212 if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
213 m_keyformat = getEncodingFormat(in);
214 log.debug("key encoding format for (%s) dynamically resolved as (%s)", m_keypath.c_str(), formatToString(m_keyformat).c_str());
217 log.error("key file (%s) can't be read to determine encoding format", m_keypath.c_str());
218 throw XMLSecurityException("FilesystemCredentialResolver can't read key file ($1) to determine encoding format",params(1,m_keypath.c_str()));
229 // Check for Certificate
230 e=XMLHelper::getFirstChildElement(root,Certificate);
232 m_credential = new FilesystemCredential(this,key,xseccerts);
235 auto_ptr_char certpass(e->getAttributeNS(NULL,password));
237 DOMElement* ep=XMLHelper::getFirstChildElement(e,Path);
238 if (!ep || !ep->hasChildNodes()) {
239 log.error("Path element missing inside Certificate element or is empty");
241 throw XMLSecurityException("FilesystemCredentialResolver can't access certificate file, missing or empty Path element.");
244 auto_ptr_char certpath(ep->getFirstChild()->getNodeValue());
245 format_xml=e->getAttributeNS(NULL,format);
246 if (format_xml && *format_xml) {
247 fformat = xmlFormatToFormat(format_xml);
248 if (fformat == UNKNOWN) {
249 auto_ptr_char unknown(format_xml);
250 log.error("configuration specifies unknown certificate encoding format (%s)", unknown.get());
252 throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown certificate encoding format ($1)",params(1,unknown.get()));
259 in=BIO_new(BIO_s_file_internal());
260 if (in && BIO_read_filename(in,certpath.get())>0) {
261 if (!format_xml || !*format_xml) {
262 // Determine the cert encoding format dynamically, if not explicitly specified
263 fformat = getEncodingFormat(in);
264 log.debug("certificate encoding format for (%s) dynamically resolved as (%s)", certpath.get(), formatToString(fformat).c_str());
269 while (x=PEM_read_bio_X509(in,NULL,passwd_callback,const_cast<char*>(certpass.get())))
270 m_certs.push_back(x);
274 x=d2i_X509_bio(in,NULL);
276 m_certs.push_back(x);
280 throw XMLSecurityException("FilesystemCredentialResolver unable to load DER certificate from file ($1)",params(1,certpath.get()));
285 p12=d2i_PKCS12_bio(in,NULL);
287 PKCS12_parse(p12, certpass.get(), NULL, &x, NULL);
291 m_certs.push_back(x);
296 throw XMLSecurityException("FilesystemCredentialResolver unable to load PKCS12 certificate from file ($1)",params(1,certpath.get()));
307 throw XMLSecurityException("FilesystemCredentialResolver unable to load certificate(s) from file ($1)",params(1,certpath.get()));
315 throw XMLSecurityException("FilesystemCredentialResolver unable to load any certificate(s)");
317 // Load any extra CA files.
318 DOMElement* extra=XMLHelper::getFirstChildElement(e,CAPath);
320 if (!extra->hasChildNodes()) {
321 log.warn("skipping empty CAPath element");
322 extra = XMLHelper::getNextSiblingElement(extra,CAPath);
325 auto_ptr_char capath(extra->getFirstChild()->getNodeValue());
328 in=BIO_new(BIO_s_file_internal());
329 if (in && BIO_read_filename(in,capath.get())>0) {
330 if (!format_xml || !*format_xml) {
331 // Determine the cert encoding format dynamically, if not explicitly specified
332 fformat = getEncodingFormat(in);
333 log.debug("CA certificate encoding format for (%s) dynamically resolved as (%s)", certpath.get(), formatToString(fformat).c_str());
338 while (x=PEM_read_bio_X509(in,NULL,passwd_callback,const_cast<char*>(certpass.get())))
339 m_certs.push_back(x);
343 x=d2i_X509_bio(in,NULL);
345 m_certs.push_back(x);
349 throw XMLSecurityException("FilesystemCredentialResolver unable to load DER CA certificate from file ($1)",params(1,capath.get()));
354 p12 = d2i_PKCS12_bio(in, NULL);
356 PKCS12_parse(p12, certpass.get(), NULL, &x, NULL);
360 m_certs.push_back(x);
366 throw XMLSecurityException("FilesystemCredentialResolver unable to load PKCS12 CA certificate from file ($1)",params(1,capath.get()));
377 log.error("CA file (%s) can't be opened", capath.get());
378 throw XMLSecurityException("FilesystemCredentialResolver can't open CA file ($1)",params(1,capath.get()));
381 extra = XMLHelper::getNextSiblingElement(extra,CAPath);
384 catch (XMLToolingException&) {
386 for_each(m_certs.begin(), m_certs.end(), X509_free);
390 // Reflect certs over to XSEC form and wrap with credential object.
391 for (vector<X509*>::iterator j=m_certs.begin(); j!=m_certs.end(); j++)
392 xseccerts.push_back(new OpenSSLCryptoX509(*j));
393 if (!key && !xseccerts.empty())
394 key = xseccerts.front()->clonePublicKey();
395 m_credential = new FilesystemCredential(this, key, xseccerts);
398 XSECCryptoKey* FilesystemCredentialResolver::loadKey()
406 BIO* in=BIO_new(BIO_s_file_internal());
407 if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
408 switch (m_keyformat) {
410 pkey=PEM_read_bio_PrivateKey(in, NULL, passwd_callback, const_cast<char*>(m_keypass.c_str()));
414 pkey=d2i_PrivateKey_bio(in, NULL);
418 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);
420 PKCS12_parse(p12, const_cast<char*>(m_keypass.c_str()), &pkey, NULL, NULL);
429 // Now map it to an XSEC wrapper.
431 XSECCryptoKey* ret=NULL;
432 switch (pkey->type) {
434 ret=new OpenSSLCryptoKeyRSA(pkey);
438 ret=new OpenSSLCryptoKeyDSA(pkey);
442 Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver").error("unsupported private key type");
450 throw XMLSecurityException("FilesystemCredentialResolver unable to load private key from file.");
453 // Used to determine the encoding format of credentials files
454 // dynamically. Supports: PEM, DER, PKCS12.
455 FilesystemCredentialResolver::format_t FilesystemCredentialResolver::getEncodingFormat(BIO* in) const
460 const int READSIZE = 1;
466 if ( (mark = BIO_tell(in)) < 0 )
467 throw XMLSecurityException("getEncodingFormat: BIO_tell() can't get the file position");
468 if ( BIO_read(in, buf, READSIZE) <= 0 )
469 throw XMLSecurityException("getEncodingFormat: BIO_read() can't read from the stream");
470 if ( BIO_seek(in, mark) < 0 )
471 throw XMLSecurityException("getEncodingFormat: BIO_seek() can't reset the file position");
480 // This is a slight variation of the Java code by Chad La Joie.
482 // Check the first byte of the file. If it's some kind of
483 // DER-encoded structure (including PKCS12), it will begin with ASCII 048.
484 // Otherwise, assume it's PEM.
488 // Here we know it's DER-encoded, now try to parse it as a PKCS12
489 // ASN.1 structure. If it fails, must be another kind of DER-encoded
490 // key/cert structure. A little inefficient...but it works.
491 if ( (p12=d2i_PKCS12_bio(in,NULL)) == NULL ) {
498 if ( BIO_seek(in, mark) < 0 ) {
500 throw XMLSecurityException("getEncodingFormat: BIO_seek() can't reset the file position");
507 // Convert key/cert format_t types to a human-meaningful string for debug output
508 string FilesystemCredentialResolver::formatToString(format_t format) const
522 // Convert key/cert raw XML format attribute (XMLCh[]) to format_t type
523 FilesystemCredentialResolver::format_t FilesystemCredentialResolver::xmlFormatToFormat(const XMLCh* format_xml) const
525 static const XMLCh cPEM[] = UNICODE_LITERAL_3(P,E,M);
526 static const XMLCh cDER[] = UNICODE_LITERAL_3(D,E,R);
527 static const XMLCh cPKCS12[] = { chLatin_P, chLatin_K, chLatin_C, chLatin_S, chDigit_1, chDigit_2, chNull };
530 if (!XMLString::compareString(format_xml,cPEM))
532 else if (!XMLString::compareString(format_xml,cDER))
534 else if (!XMLString::compareString(format_xml,cPKCS12))
542 void FilesystemCredentialResolver::attach(SSL_CTX* ctx) const
549 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
550 SSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char*>(m_keypass.c_str()));
553 switch (m_keyformat) {
555 ret=SSL_CTX_use_PrivateKey_file(ctx, m_keypath.c_str(), m_keyformat);
559 ret=SSL_CTX_use_RSAPrivateKey_file(ctx, m_keypath.c_str(), m_keyformat);
563 BIO* in=BIO_new(BIO_s_file_internal());
564 if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
566 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);
568 PKCS12_parse(p12, const_cast<char*>(m_keypass.c_str()), &pkey, NULL, NULL);
571 ret=SSL_CTX_use_PrivateKey(ctx, pkey);
583 throw XMLSecurityException("Unable to attach private key to SSL context.");
587 for (vector<X509*>::const_iterator i=m_certs.begin(); i!=m_certs.end(); i++) {
588 if (i==m_certs.begin()) {
589 if (SSL_CTX_use_certificate(ctx, *i) != 1) {
591 throw XMLSecurityException("Unable to attach client certificate to SSL context.");
595 // When we add certs, they don't get ref counted, so we need to duplicate them.
596 X509* dup = X509_dup(*i);
597 if (SSL_CTX_add_extra_chain_cert(ctx, dup) != 1) {
600 throw XMLSecurityException("Unable to attach CA certificate to SSL context.");
606 void FilesystemCredential::attach(SSL_CTX* ctx) const
608 return m_resolver->attach(ctx);