2 * Copyright 2001-2005 Internet2
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
18 * FilesystemCredentialResolver.cpp
\r
20 * Supplies credentials from local files
\r
23 #include "internal.h"
\r
24 #include "signature/OpenSSLCredentialResolver.h"
\r
25 #include "util/NDC.h"
\r
26 #include "util/XMLHelper.h"
\r
28 using namespace xmlsignature;
\r
29 using namespace xmltooling;
\r
31 #include <sys/types.h>
\r
32 #include <sys/stat.h>
\r
33 #include <algorithm>
\r
34 #include <openssl/pkcs12.h>
\r
35 #include <log4cpp/Category.hh>
\r
36 #include <xercesc/util/XMLUniDefs.hpp>
\r
37 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
\r
38 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyRSA.hpp>
\r
39 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyDSA.hpp>
\r
41 using namespace xmlsignature;
\r
42 using namespace xmltooling;
\r
43 using namespace log4cpp;
\r
44 using namespace std;
\r
46 // OpenSSL password callback...
\r
47 static int passwd_callback(char* buf, int len, int verify, void* passwd)
\r
51 if(passwd && len > strlen(reinterpret_cast<char*>(passwd)))
\r
53 strcpy(buf,reinterpret_cast<char*>(passwd));
\r
60 namespace xmlsignature {
\r
61 class FilesystemCredentialResolver : public CredentialResolver
\r
64 FilesystemCredentialResolver(const DOMElement* e);
\r
65 ~FilesystemCredentialResolver();
\r
67 Lockable* lock() { return this; }
\r
70 XSECCryptoKey* loadKey();
\r
72 void attach(SSL_CTX* ctx) const;
\r
73 XSECCryptoKey* getKey() const { return m_key->clone(); }
\r
74 const vector<XSECCryptoX509*>& getCertificates() const { return m_xseccerts; }
\r
77 enum format_t { PEM=SSL_FILETYPE_PEM, DER=SSL_FILETYPE_ASN1, _PKCS12, UNKNOWN };
\r
79 format_t getEncodingFormat(BIO* in) const;
\r
80 string formatToString(format_t format) const;
\r
81 format_t xmlFormatToFormat(const XMLCh* format_xml) const;
\r
83 format_t m_keyformat;
\r
84 string m_keypath,m_keypass;
\r
85 vector<X509*> m_certs;
\r
86 vector<XSECCryptoX509*> m_xseccerts;
\r
87 XSECCryptoKey* m_key;
\r
90 CredentialResolver* XMLTOOL_DLLLOCAL FilesystemCredentialResolverFactory(const DOMElement* const & e)
\r
92 return new FilesystemCredentialResolver(e);
\r
96 static const XMLCh CAPath[] = UNICODE_LITERAL_6(C,A,P,a,t,h);
\r
97 static const XMLCh Certificate[] = UNICODE_LITERAL_11(C,e,r,t,i,f,i,c,a,t,e);
\r
98 static const XMLCh format[] = UNICODE_LITERAL_6(f,o,r,m,a,t);
\r
99 static const XMLCh Key[] = UNICODE_LITERAL_3(K,e,y);
\r
100 static const XMLCh password[] = UNICODE_LITERAL_8(p,a,s,s,w,o,r,d);
\r
101 static const XMLCh Path[] = UNICODE_LITERAL_4(P,a,t,h);
\r
103 FilesystemCredentialResolver::FilesystemCredentialResolver(const DOMElement* e)
\r
106 NDC ndc("FilesystemCredentialResolver");
\r
108 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver");
\r
111 const XMLCh* format_xml=NULL;
\r
115 const DOMElement* root=e;
\r
116 e=XMLHelper::getFirstChildElement(root,Key);
\r
119 // Get raw format attrib value, but defer processing til later since may need to
\r
120 // determine format dynamically, and we need the Path for that.
\r
121 format_xml=e->getAttributeNS(NULL,format);
\r
123 const XMLCh* password_xml=e->getAttributeNS(NULL,password);
\r
124 if (password_xml) {
\r
125 auto_ptr_char kp(password_xml);
\r
126 m_keypass=kp.get();
\r
129 e=XMLHelper::getFirstChildElement(e,Path);
\r
130 if (e && e->hasChildNodes()) {
\r
131 const XMLCh* s=e->getFirstChild()->getNodeValue();
\r
132 auto_ptr_char kpath(s);
\r
134 struct _stat stat_buf;
\r
135 if (_stat(kpath.get(), &stat_buf) != 0)
\r
137 struct stat stat_buf;
\r
138 if (stat(kpath.get(), &stat_buf) != 0)
\r
141 log.error("key file (%s) can't be opened", kpath.get());
\r
142 throw XMLSecurityException("FilesystemCredentialResolver can't access key file ($1)",params(1,kpath.get()));
\r
144 m_keypath=kpath.get();
\r
147 log.error("Path element missing inside Key element");
\r
148 throw XMLSecurityException("FilesystemCredentialResolver can't access key file, no Path element specified.");
\r
151 // Determine the key encoding format dynamically, if not explicitly specified
\r
152 if (format_xml && *format_xml) {
\r
153 fformat = xmlFormatToFormat(format_xml);
\r
154 if (fformat != UNKNOWN) {
\r
155 m_keyformat = fformat;
\r
158 auto_ptr_char unknown(format_xml);
\r
159 log.error("configuration specifies unknown key encoding format (%s)", unknown.get());
\r
160 throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown key encoding format ($1)",params(1,unknown.get()));
\r
164 in=BIO_new(BIO_s_file_internal());
\r
165 if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
\r
166 m_keyformat = getEncodingFormat(in);
\r
167 log.debug("key encoding format for (%s) dynamically resolved as (%s)", m_keypath.c_str(), formatToString(m_keyformat).c_str());
\r
170 log.error("key file (%s) can't be read to determine encoding format", m_keypath.c_str());
\r
171 throw XMLSecurityException("FilesystemCredentialResolver can't read key file ($1) to determine encoding format",params(1,m_keypath.c_str()));
\r
182 // Check for Certificate
\r
183 e=XMLHelper::getFirstChildElement(root,Certificate);
\r
186 auto_ptr_char certpass(e->getAttributeNS(NULL,password));
\r
188 DOMElement* ep=XMLHelper::getFirstChildElement(e,Path);
\r
189 if (!ep || !ep->hasChildNodes()) {
\r
190 log.error("Path element missing inside Certificate element or is empty");
\r
191 throw XMLSecurityException("FilesystemCredentialResolver can't access certificate file, missing or empty Path element.");
\r
194 auto_ptr_char certpath(ep->getFirstChild()->getNodeValue());
\r
195 format_xml=e->getAttributeNS(NULL,format);
\r
196 if (format_xml && *format_xml) {
\r
197 fformat = xmlFormatToFormat(format_xml);
\r
198 if (fformat == UNKNOWN) {
\r
199 auto_ptr_char unknown(format_xml);
\r
200 log.error("configuration specifies unknown certificate encoding format (%s)", unknown.get());
\r
201 throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown certificate encoding format ($1)",params(1,unknown.get()));
\r
208 in=BIO_new(BIO_s_file_internal());
\r
209 if (in && BIO_read_filename(in,certpath.get())>0) {
\r
210 if (!format_xml || !*format_xml) {
\r
211 // Determine the cert encoding format dynamically, if not explicitly specified
\r
212 fformat = getEncodingFormat(in);
\r
213 log.debug("certificate encoding format for (%s) dynamically resolved as (%s)", certpath.get(), formatToString(fformat).c_str());
\r
218 while (x=PEM_read_bio_X509(in,NULL,passwd_callback,const_cast<char*>(certpass.get())))
\r
219 m_certs.push_back(x);
\r
223 x=d2i_X509_bio(in,NULL);
\r
225 m_certs.push_back(x);
\r
229 throw XMLSecurityException("FilesystemCredentialResolver unable to load DER certificate from file ($1)",params(1,certpath.get()));
\r
234 p12=d2i_PKCS12_bio(in,NULL);
\r
236 PKCS12_parse(p12, certpass.get(), NULL, &x, NULL);
\r
240 m_certs.push_back(x);
\r
245 throw XMLSecurityException("FilesystemCredentialResolver unable to load PKCS12 certificate from file ($1)",params(1,certpath.get()));
\r
256 throw XMLSecurityException("FilesystemCredentialResolver unable to load certificate(s) from file ($1)",params(1,certpath.get()));
\r
263 if (m_certs.empty()) {
\r
264 throw XMLSecurityException("FilesystemCredentialResolver unable to load any certificate(s)");
\r
267 // Load any extra CA files.
\r
268 DOMElement* extra=XMLHelper::getFirstChildElement(e,CAPath);
\r
270 if (!extra->hasChildNodes()) {
\r
271 log.warn("skipping empty CAPath element");
\r
272 extra = XMLHelper::getNextSiblingElement(extra,CAPath);
\r
275 auto_ptr_char capath(extra->getFirstChild()->getNodeValue());
\r
278 in=BIO_new(BIO_s_file_internal());
\r
279 if (in && BIO_read_filename(in,capath.get())>0) {
\r
280 if (!format_xml || !*format_xml) {
\r
281 // Determine the cert encoding format dynamically, if not explicitly specified
\r
282 fformat = getEncodingFormat(in);
\r
283 log.debug("CA certificate encoding format for (%s) dynamically resolved as (%s)", certpath.get(), formatToString(fformat).c_str());
\r
288 while (x=PEM_read_bio_X509(in,NULL,passwd_callback,const_cast<char*>(certpass.get())))
\r
289 m_certs.push_back(x);
\r
293 x=d2i_X509_bio(in,NULL);
\r
295 m_certs.push_back(x);
\r
299 throw XMLSecurityException("FilesystemCredentialResolver unable to load DER CA certificate from file ($1)",params(1,capath.get()));
\r
304 p12 = d2i_PKCS12_bio(in, NULL);
\r
306 PKCS12_parse(p12, certpass.get(), NULL, &x, NULL);
\r
310 m_certs.push_back(x);
\r
316 throw XMLSecurityException("FilesystemCredentialResolver unable to load PKCS12 CA certificate from file ($1)",params(1,capath.get()));
\r
327 log.error("CA file (%s) can't be opened", capath.get());
\r
328 throw XMLSecurityException("FilesystemCredentialResolver can't open CA file ($1)",params(1,capath.get()));
\r
331 extra = XMLHelper::getNextSiblingElement(extra,CAPath);
\r
334 catch (XMLToolingException&) {
\r
335 for (vector<X509*>::iterator j=m_certs.begin(); j!=m_certs.end(); j++)
\r
340 // Reflect certs over to XSEC form.
\r
341 for (vector<X509*>::iterator j=m_certs.begin(); j!=m_certs.end(); j++)
\r
342 m_xseccerts.push_back(new OpenSSLCryptoX509(*j));
\r
345 XSECCryptoKey* FilesystemCredentialResolver::loadKey()
\r
348 NDC ndc("loadKey");
\r
352 EVP_PKEY* pkey=NULL;
\r
353 BIO* in=BIO_new(BIO_s_file_internal());
\r
354 if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
\r
355 switch (m_keyformat) {
\r
357 pkey=PEM_read_bio_PrivateKey(in, NULL, passwd_callback, const_cast<char*>(m_keypass.c_str()));
\r
361 pkey=d2i_PrivateKey_bio(in, NULL);
\r
365 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);
\r
367 PKCS12_parse(p12, const_cast<char*>(m_keypass.c_str()), &pkey, NULL, NULL);
\r
376 // Now map it to an XSEC wrapper.
\r
378 XSECCryptoKey* ret=NULL;
\r
379 switch (pkey->type) {
\r
381 ret=new OpenSSLCryptoKeyRSA(pkey);
\r
385 ret=new OpenSSLCryptoKeyDSA(pkey);
\r
389 Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver").error("unsupported private key type");
\r
391 EVP_PKEY_free(pkey);
\r
397 throw XMLSecurityException("FilesystemCredentialResolver unable to load private key from file.");
\r
400 FilesystemCredentialResolver::~FilesystemCredentialResolver()
\r
402 for_each(m_certs.begin(),m_certs.end(),X509_free);
\r
403 for_each(m_xseccerts.begin(),m_xseccerts.end(),xmltooling::cleanup<XSECCryptoX509>());
\r
406 void FilesystemCredentialResolver::attach(SSL_CTX* ctx) const
\r
413 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
\r
414 SSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char*>(m_keypass.c_str()));
\r
417 switch (m_keyformat) {
\r
419 ret=SSL_CTX_use_PrivateKey_file(ctx, m_keypath.c_str(), m_keyformat);
\r
423 ret=SSL_CTX_use_RSAPrivateKey_file(ctx, m_keypath.c_str(), m_keyformat);
\r
427 BIO* in=BIO_new(BIO_s_file_internal());
\r
428 if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
\r
429 EVP_PKEY* pkey=NULL;
\r
430 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);
\r
432 PKCS12_parse(p12, const_cast<char*>(m_keypass.c_str()), &pkey, NULL, NULL);
\r
435 ret=SSL_CTX_use_PrivateKey(ctx, pkey);
\r
436 EVP_PKEY_free(pkey);
\r
447 throw XMLSecurityException("Unable to attach private key to SSL context.");
\r
451 for (vector<X509*>::const_iterator i=m_certs.begin(); i!=m_certs.end(); i++) {
\r
452 if (i==m_certs.begin()) {
\r
453 if (SSL_CTX_use_certificate(ctx, *i) != 1) {
\r
455 throw XMLSecurityException("Unable to attach client certificate to SSL context.");
\r
459 // When we add certs, they don't get ref counted, so we need to duplicate them.
\r
460 X509* dup = X509_dup(*i);
\r
461 if (SSL_CTX_add_extra_chain_cert(ctx, dup) != 1) {
\r
464 throw XMLSecurityException("Unable to attach CA certificate to SSL context.");
\r
470 // Used to determine the encoding format of credentials files
\r
471 // dynamically. Supports: PEM, DER, PKCS12.
\r
472 FilesystemCredentialResolver::format_t FilesystemCredentialResolver::getEncodingFormat(BIO* in) const
\r
474 PKCS12* p12 = NULL;
\r
477 const int READSIZE = 1;
\r
478 char buf[READSIZE];
\r
483 if ( (mark = BIO_tell(in)) < 0 )
\r
484 throw XMLSecurityException("getEncodingFormat: BIO_tell() can't get the file position");
\r
485 if ( BIO_read(in, buf, READSIZE) <= 0 )
\r
486 throw XMLSecurityException("getEncodingFormat: BIO_read() can't read from the stream");
\r
487 if ( BIO_seek(in, mark) < 0 )
\r
488 throw XMLSecurityException("getEncodingFormat: BIO_seek() can't reset the file position");
\r
497 // This is a slight variation of the Java code by Chad La Joie.
\r
499 // Check the first byte of the file. If it's some kind of
\r
500 // DER-encoded structure (including PKCS12), it will begin with ASCII 048.
\r
501 // Otherwise, assume it's PEM.
\r
505 // Here we know it's DER-encoded, now try to parse it as a PKCS12
\r
506 // ASN.1 structure. If it fails, must be another kind of DER-encoded
\r
507 // key/cert structure. A little inefficient...but it works.
\r
508 if ( (p12=d2i_PKCS12_bio(in,NULL)) == NULL ) {
\r
515 if ( BIO_seek(in, mark) < 0 ) {
\r
517 throw XMLSecurityException("getEncodingFormat: BIO_seek() can't reset the file position");
\r
524 // Convert key/cert format_t types to a human-meaningful string for debug output
\r
525 string FilesystemCredentialResolver::formatToString(format_t format) const
\r
539 // Convert key/cert raw XML format attribute (XMLCh[]) to format_t type
\r
540 FilesystemCredentialResolver::format_t FilesystemCredentialResolver::xmlFormatToFormat(const XMLCh* format_xml) const
\r
542 static const XMLCh cPEM[] = UNICODE_LITERAL_3(P,E,M);
\r
543 static const XMLCh cDER[] = UNICODE_LITERAL_3(D,E,R);
\r
544 static const XMLCh cPKCS12[] = { chLatin_P, chLatin_K, chLatin_C, chLatin_S, chDigit_1, chDigit_2, chNull };
\r
547 if (!XMLString::compareString(format_xml,cPEM))
\r
549 else if (!XMLString::compareString(format_xml,cDER))
\r
551 else if (!XMLString::compareString(format_xml,cPKCS12))
\r