Multi-line svn commit, see body.
[shibboleth/cpp-xmltooling.git] / xmltooling / security / impl / FilesystemCredentialResolver.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * FilesystemCredentialResolver.cpp
19  *
20  * Supplies credentials from local files
21  */
22
23 #include "internal.h"
24 #include "logging.h"
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/OpenSSLCryptoX509CRL.h"
31 #include "util/NDC.h"
32 #include "util/PathResolver.h"
33 #include "util/XMLHelper.h"
34
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <openssl/pkcs12.h>
38 #include <xercesc/util/XMLUniDefs.hpp>
39 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
40 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyRSA.hpp>
41 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyDSA.hpp>
42
43 using namespace xmlsignature;
44 using namespace xmltooling::logging;
45 using namespace xmltooling;
46 using namespace std;
47
48 // OpenSSL password callback...
49 static int passwd_callback(char* buf, int len, int verify, void* passwd)
50 {
51     if(!verify)
52     {
53         if(passwd && len > strlen(reinterpret_cast<char*>(passwd)))
54         {
55             strcpy(buf,reinterpret_cast<char*>(passwd));
56             return strlen(buf);
57         }
58     }
59     return 0;
60 }
61
62 namespace xmltooling {
63
64 #if defined (_MSC_VER)
65     #pragma warning( push )
66     #pragma warning( disable : 4250 )
67 #endif
68
69     class XMLTOOL_DLLLOCAL FilesystemCredentialResolver;
70     class XMLTOOL_DLLLOCAL FilesystemCredential : public OpenSSLCredential, public BasicX509Credential
71     {
72     public:
73         FilesystemCredential(
74             FilesystemCredentialResolver* resolver, XSECCryptoKey* key, const std::vector<XSECCryptoX509*>& xseccerts, XSECCryptoX509CRL* crl=NULL
75             ) : BasicX509Credential(key, xseccerts, crl), m_resolver(resolver), m_usage(UNSPECIFIED_CREDENTIAL) {
76             extract();
77         }
78         virtual ~FilesystemCredential() {
79         }
80
81         unsigned int getUsage() const {
82             return m_usage;
83         }
84
85         void setUsage(const XMLCh* usage) {
86             if (usage && *usage) {
87                 auto_ptr_char u(usage);
88                 if (!strcmp(u.get(), "signing"))
89                     m_usage = SIGNING_CREDENTIAL | TLS_CREDENTIAL;
90                 else if (!strcmp(u.get(), "TLS"))
91                     m_usage = TLS_CREDENTIAL;
92                 else if (!strcmp(u.get(), "encryption"))
93                     m_usage = ENCRYPTION_CREDENTIAL;
94             }
95         }
96
97         void addKeyNames(const DOMElement* e);
98
99         void initKeyInfo(unsigned int types=0) {
100             BasicX509Credential::initKeyInfo(types);
101         }
102
103         void attach(SSL_CTX* ctx) const;
104
105     private:
106         FilesystemCredentialResolver* m_resolver;
107         unsigned int m_usage;
108     };
109
110 #if defined (_MSC_VER)
111     #pragma warning( pop )
112 #endif
113
114     class XMLTOOL_DLLLOCAL FilesystemCredentialResolver : public CredentialResolver
115     {
116     public:
117         FilesystemCredentialResolver(const DOMElement* e);
118         virtual ~FilesystemCredentialResolver() {
119             delete m_credential;
120             for_each(m_certs.begin(),m_certs.end(),X509_free);
121         }
122
123         Lockable* lock() { return this; }
124         void unlock() {}
125
126         const Credential* resolve(const CredentialCriteria* criteria=NULL) const {
127             return (criteria ? (criteria->matches(*m_credential) ? m_credential : NULL) : m_credential);
128         }
129
130         virtual vector<const Credential*>::size_type resolve(
131             vector<const Credential*>& results, const CredentialCriteria* criteria=NULL
132             ) const {
133             if (!criteria || criteria->matches(*m_credential)) {
134                 results.push_back(m_credential);
135                 return 1;
136             }
137             return 0;
138         }
139
140         void attach(SSL_CTX* ctx) const;
141
142     private:
143         XSECCryptoKey* loadKey();
144         XSECCryptoX509CRL* loadCRL();
145
146         enum format_t { PEM=SSL_FILETYPE_PEM, DER=SSL_FILETYPE_ASN1, _PKCS12, UNKNOWN };
147
148         format_t getEncodingFormat(BIO* in) const;
149         string formatToString(format_t format) const;
150         format_t xmlFormatToFormat(const XMLCh* format_xml) const;
151
152         format_t m_keyformat,m_crlformat;
153         string m_keypath,m_keypass,m_crlpath;
154         vector<X509*> m_certs;
155         FilesystemCredential* m_credential;
156     };
157
158     CredentialResolver* XMLTOOL_DLLLOCAL FilesystemCredentialResolverFactory(const DOMElement* const & e)
159     {
160         return new FilesystemCredentialResolver(e);
161     }
162
163     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);
164     static const XMLCh CAPath[] =           UNICODE_LITERAL_6(C,A,P,a,t,h);
165     static const XMLCh Certificate[] =      UNICODE_LITERAL_11(C,e,r,t,i,f,i,c,a,t,e);
166     static const XMLCh _certificate[] =     UNICODE_LITERAL_11(c,e,r,t,i,f,i,c,a,t,e);
167     static const XMLCh CRL[] =              UNICODE_LITERAL_3(C,R,L);
168     static const XMLCh format[] =           UNICODE_LITERAL_6(f,o,r,m,a,t);
169     static const XMLCh Key[] =              UNICODE_LITERAL_3(K,e,y);
170     static const XMLCh _key[] =             UNICODE_LITERAL_3(k,e,y);
171     static const XMLCh keyInfoMask[] =      UNICODE_LITERAL_11(k,e,y,I,n,f,o,M,a,s,k);
172     static const XMLCh keyName[] =          UNICODE_LITERAL_7(k,e,y,N,a,m,e);
173     static const XMLCh Name[] =             UNICODE_LITERAL_4(N,a,m,e);
174     static const XMLCh password[] =         UNICODE_LITERAL_8(p,a,s,s,w,o,r,d);
175     static const XMLCh Path[] =             UNICODE_LITERAL_4(P,a,t,h);
176     static const XMLCh _use[] =             UNICODE_LITERAL_3(u,s,e);
177 };
178
179 FilesystemCredentialResolver::FilesystemCredentialResolver(const DOMElement* e) : m_credential(NULL)
180 {
181 #ifdef _DEBUG
182     NDC ndc("FilesystemCredentialResolver");
183 #endif
184     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver."FILESYSTEM_CREDENTIAL_RESOLVER);
185
186     // Default to disable X509IssuerSerial due to schema validation issues.
187     unsigned int mask =
188         Credential::KEYINFO_KEY_NAME |
189         Credential::KEYINFO_KEY_VALUE |
190         X509Credential::KEYINFO_X509_CERTIFICATE |
191         X509Credential::KEYINFO_X509_SUBJECTNAME;
192     if (e && e->hasAttributeNS(NULL,keyInfoMask))
193         mask = XMLString::parseInt(e->getAttributeNS(NULL,keyInfoMask));
194
195     if (e && (e->hasAttributeNS(NULL,_certificate) || e->hasAttributeNS(NULL,_key))) {
196         // Dummy up a simple file resolver config using these attributes.
197         DOMElement* dummy = e->getOwnerDocument()->createElementNS(NULL,_CredentialResolver);
198         DOMElement* child;
199         DOMElement* path;
200         if (e->hasAttributeNS(NULL,_key)) {
201             child = e->getOwnerDocument()->createElementNS(NULL,Key);
202             dummy->appendChild(child);
203             path = e->getOwnerDocument()->createElementNS(NULL,Path);
204             child->appendChild(path);
205             path->appendChild(e->getOwnerDocument()->createTextNode(e->getAttributeNS(NULL,_key)));
206             if (e->hasAttributeNS(NULL,password))
207                 child->setAttributeNS(NULL,password,e->getAttributeNS(NULL,password));
208             if (e->hasAttributeNS(NULL,keyName)) {
209                 path = e->getOwnerDocument()->createElementNS(NULL,Name);
210                 child->appendChild(path);
211                 path->appendChild(e->getOwnerDocument()->createTextNode(e->getAttributeNS(NULL,keyName)));
212             }
213         }
214         if (e->hasAttributeNS(NULL,_certificate)) {
215             child = e->getOwnerDocument()->createElementNS(NULL,Certificate);
216             dummy->appendChild(child);
217             path = e->getOwnerDocument()->createElementNS(NULL,Path);
218             child->appendChild(path);
219             path->appendChild(e->getOwnerDocument()->createTextNode(e->getAttributeNS(NULL,_certificate)));
220         }
221         e = dummy;  // reset "root" to the dummy config element
222     }
223
224     const DOMElement* root=e;
225     const XMLCh* usage = root->getAttributeNS(NULL,_use);
226
227     XSECCryptoKey* key=NULL;
228     vector<XSECCryptoX509*> xseccerts;
229     XSECCryptoX509CRL* crl=NULL;
230
231     format_t fformat;
232     const XMLCh* format_xml=NULL;
233     BIO* in = NULL;
234
235     // Move to Key
236     const DOMElement* keynode=XMLHelper::getFirstChildElement(root,Key);
237     if (keynode) {
238         // Get raw format attrib value, but defer processing til later since may need to
239         // determine format dynamically, and we need the Path for that.
240         format_xml=keynode->getAttributeNS(NULL,format);
241
242         const XMLCh* password_xml=keynode->getAttributeNS(NULL,password);
243         if (password_xml) {
244             auto_ptr_char kp(password_xml);
245             m_keypass=kp.get();
246         }
247
248         e=XMLHelper::getFirstChildElement(keynode,Path);
249         if (e && e->hasChildNodes()) {
250             const XMLCh* s=e->getFirstChild()->getNodeValue();
251             auto_ptr_char kpath(s);
252             m_keypath = kpath.get();
253             XMLToolingConfig::getConfig().getPathResolver()->resolve(m_keypath, PathResolver::XMLTOOLING_CFG_FILE);
254 #ifdef WIN32
255             struct _stat stat_buf;
256             if (_stat(m_keypath.c_str(), &stat_buf) != 0)
257 #else
258             struct stat stat_buf;
259             if (stat(m_keypath.c_str(), &stat_buf) != 0)
260 #endif
261             {
262                 log.error("key file (%s) can't be opened", m_keypath.c_str());
263                 throw XMLSecurityException("FilesystemCredentialResolver can't access key file ($1)",params(1,m_keypath.c_str()));
264             }
265         }
266         else {
267             log.error("Path element missing inside Key element");
268             throw XMLSecurityException("FilesystemCredentialResolver can't access key file, no Path element specified.");
269         }
270
271         // Determine the key encoding format dynamically, if not explicitly specified
272         if (format_xml && *format_xml) {
273             fformat = xmlFormatToFormat(format_xml);
274             if (fformat != UNKNOWN) {
275                 m_keyformat = fformat;
276             }
277             else {
278                 auto_ptr_char unknown(format_xml);
279                 log.error("configuration specifies unknown key encoding format (%s)", unknown.get());
280                 throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown key encoding format ($1)",params(1,unknown.get()));
281             }
282         }
283         else {
284             in=BIO_new(BIO_s_file_internal());
285             if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
286                 m_keyformat = getEncodingFormat(in);
287                 log.debug("key encoding format for (%s) dynamically resolved as (%s)", m_keypath.c_str(), formatToString(m_keyformat).c_str());
288             }
289             else {
290                 log.error("key file (%s) can't be read to determine encoding format", m_keypath.c_str());
291                 throw XMLSecurityException("FilesystemCredentialResolver can't read key file ($1) to determine encoding format",params(1,m_keypath.c_str()));
292             }
293             if (in)
294                 BIO_free(in);
295             in = NULL;
296         }
297
298         // Load the key.
299         key = loadKey();
300     }
301
302     // Check for CRL.
303     const DOMElement* crlnode=XMLHelper::getFirstChildElement(root,CRL);
304     if (crlnode) {
305         // Get raw format attrib value, but defer processing til later since may need to
306         // determine format dynamically, and we need the Path for that.
307         format_xml=crlnode->getAttributeNS(NULL,format);
308
309         e=XMLHelper::getFirstChildElement(crlnode,Path);
310         if (e && e->hasChildNodes()) {
311             const XMLCh* s=e->getFirstChild()->getNodeValue();
312             auto_ptr_char kpath(s);
313             m_crlpath=kpath.get();
314             XMLToolingConfig::getConfig().getPathResolver()->resolve(m_crlpath, PathResolver::XMLTOOLING_CFG_FILE);
315 #ifdef WIN32
316             struct _stat stat_buf;
317             if (_stat(m_crlpath.c_str(), &stat_buf) != 0)
318 #else
319             struct stat stat_buf;
320             if (stat(m_crlpath.c_str(), &stat_buf) != 0)
321 #endif
322             {
323                 log.error("CRL file (%s) can't be opened", m_crlpath.c_str());
324                 throw XMLSecurityException("FilesystemCredentialResolver can't access CRL file ($1)",params(1,m_crlpath.c_str()));
325             }
326         }
327         else {
328             log.error("Path element missing inside CRL element");
329             throw XMLSecurityException("FilesystemCredentialResolver can't access CRL file, no Path element specified.");
330         }
331
332         // Determine the CRL encoding format dynamically, if not explicitly specified
333         if (format_xml && *format_xml) {
334             fformat = xmlFormatToFormat(format_xml);
335             if (fformat != UNKNOWN) {
336                 m_crlformat = fformat;
337             }
338             else {
339                 auto_ptr_char unknown(format_xml);
340                 log.error("configuration specifies unknown CRL encoding format (%s)", unknown.get());
341                 throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown CRL encoding format ($1)",params(1,unknown.get()));
342             }
343         }
344         else {
345             in=BIO_new(BIO_s_file_internal());
346             if (in && BIO_read_filename(in,m_crlpath.c_str())>0) {
347                 m_crlformat = getEncodingFormat(in);
348                 log.debug("CRL encoding format for (%s) dynamically resolved as (%s)", m_crlpath.c_str(), formatToString(m_crlformat).c_str());
349             }
350             else {
351                 log.error("CRL file (%s) can't be read to determine encoding format", m_crlpath.c_str());
352                 throw XMLSecurityException("FilesystemCredentialResolver can't read CRL file ($1) to determine encoding format",params(1,m_crlpath.c_str()));
353             }
354             if (in)
355                 BIO_free(in);
356             in = NULL;
357         }
358
359         // Load the CRL.
360         crl = loadCRL();
361     }
362
363     // Check for Certificate
364     e=XMLHelper::getFirstChildElement(root,Certificate);
365     if (!e) {
366         m_credential = new FilesystemCredential(this,key,xseccerts,crl);
367         m_credential->addKeyNames(keynode);
368         m_credential->setUsage(usage);
369         m_credential->initKeyInfo(mask);
370         return;
371     }
372     auto_ptr_char certpass(e->getAttributeNS(NULL,password));
373
374     const DOMElement* ep=XMLHelper::getFirstChildElement(e,Path);
375     if (!ep || !ep->hasChildNodes()) {
376         log.error("Path element missing inside Certificate element or is empty");
377         delete key;
378         delete crl;
379         throw XMLSecurityException("FilesystemCredentialResolver can't access certificate file, missing or empty Path element.");
380     }
381
382     auto_ptr_char certpath2(ep->getFirstChild()->getNodeValue());
383     string certpath(certpath2.get());
384     XMLToolingConfig::getConfig().getPathResolver()->resolve(certpath, PathResolver::XMLTOOLING_CFG_FILE);
385
386     format_xml=e->getAttributeNS(NULL,format);
387     if (format_xml && *format_xml) {
388         fformat = xmlFormatToFormat(format_xml);
389         if (fformat == UNKNOWN) {
390             auto_ptr_char unknown(format_xml);
391             log.error("configuration specifies unknown certificate encoding format (%s)", unknown.get());
392             delete key;
393             delete crl;
394             throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown certificate encoding format ($1)",params(1,unknown.get()));
395         }
396     }
397
398     try {
399         X509* x=NULL;
400         PKCS12* p12=NULL;
401         in=BIO_new(BIO_s_file_internal());
402         if (in && BIO_read_filename(in,certpath.c_str())>0) {
403             if (!format_xml || !*format_xml) {
404                 // Determine the cert encoding format dynamically, if not explicitly specified
405                 fformat = getEncodingFormat(in);
406                 log.debug("certificate encoding format for (%s) dynamically resolved as (%s)", certpath.c_str(), formatToString(fformat).c_str());
407             }
408
409             Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver."FILESYSTEM_CREDENTIAL_RESOLVER).info(
410                 "loading certificate from file (%s)", certpath.c_str()
411                 );
412
413             switch(fformat) {
414                 case PEM:
415                     while (x=PEM_read_bio_X509(in,NULL,passwd_callback,const_cast<char*>(certpass.get())))
416                         m_certs.push_back(x);
417                     break;
418
419                 case DER:
420                     x=d2i_X509_bio(in,NULL);
421                     if (x)
422                         m_certs.push_back(x);
423                     else {
424                         log_openssl();
425                         BIO_free(in);
426                         throw XMLSecurityException("FilesystemCredentialResolver unable to load DER certificate from file ($1)",params(1,certpath.c_str()));
427                     }
428                     break;
429
430                 case _PKCS12:
431                     p12=d2i_PKCS12_bio(in,NULL);
432                     if (p12) {
433                         PKCS12_parse(p12, certpass.get(), NULL, &x, NULL);
434                         PKCS12_free(p12);
435                     }
436                     if (x) {
437                         m_certs.push_back(x);
438                         x=NULL;
439                     } else {
440                         log_openssl();
441                         BIO_free(in);
442                         throw XMLSecurityException("FilesystemCredentialResolver unable to load PKCS12 certificate from file ($1)",params(1,certpath.c_str()));
443                     }
444                     break;
445             } // end switch
446
447         } else {
448             log_openssl();
449             if (in) {
450                 BIO_free(in);
451                 in=NULL;
452             }
453             throw XMLSecurityException("FilesystemCredentialResolver unable to load certificate(s) from file ($1)",params(1,certpath.c_str()));
454         }
455         if (in) {
456             BIO_free(in);
457             in=NULL;
458         }
459
460         if (m_certs.empty())
461             throw XMLSecurityException("FilesystemCredentialResolver unable to load any certificate(s)");
462
463         // Load any extra CA files.
464         const DOMElement* extra=XMLHelper::getFirstChildElement(e,CAPath);
465         while (extra) {
466             if (!extra->hasChildNodes()) {
467                 log.warn("skipping empty CAPath element");
468                 extra = XMLHelper::getNextSiblingElement(extra,CAPath);
469                 continue;
470             }
471             auto_ptr_char capath2(extra->getFirstChild()->getNodeValue());
472             string capath(capath2.get());
473             XMLToolingConfig::getConfig().getPathResolver()->resolve(capath, PathResolver::XMLTOOLING_CFG_FILE);
474             x=NULL;
475             p12=NULL;
476             in=BIO_new(BIO_s_file_internal());
477             if (in && BIO_read_filename(in,capath.c_str())>0) {
478                 if (!format_xml || !*format_xml) {
479                     // Determine the cert encoding format dynamically, if not explicitly specified
480                     fformat = getEncodingFormat(in);
481                     log.debug("CA certificate encoding format for (%s) dynamically resolved as (%s)", capath.c_str(), formatToString(fformat).c_str());
482                 }
483
484                 Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver."FILESYSTEM_CREDENTIAL_RESOLVER).info(
485                     "loading CA certificate from file (%s)", capath.c_str()
486                     );
487
488                 switch (fformat) {
489                     case PEM:
490                         while (x=PEM_read_bio_X509(in,NULL,NULL,NULL))
491                             m_certs.push_back(x);
492                         break;
493
494                     case DER:
495                         x=d2i_X509_bio(in,NULL);
496                         if (x)
497                             m_certs.push_back(x);
498                         else {
499                             log_openssl();
500                             BIO_free(in);
501                             throw XMLSecurityException("FilesystemCredentialResolver unable to load DER CA certificate from file ($1)",params(1,capath.c_str()));
502                         }
503                         break;
504
505                     case _PKCS12:
506                         p12 = d2i_PKCS12_bio(in, NULL);
507                         if (p12) {
508                             PKCS12_parse(p12, NULL, NULL, &x, NULL);
509                             PKCS12_free(p12);
510                         }
511                         if (x) {
512                             m_certs.push_back(x);
513                             x=NULL;
514                         }
515                         else {
516                             log_openssl();
517                             BIO_free(in);
518                             throw XMLSecurityException("FilesystemCredentialResolver unable to load PKCS12 CA certificate from file ($1)",params(1,capath.c_str()));
519                         }
520                         break;
521                 } //end switch
522
523                 BIO_free(in);
524             }
525             else {
526                 if (in)
527                     BIO_free(in);
528                 log_openssl();
529                 log.error("CA certificate file (%s) can't be opened", capath.c_str());
530                 throw XMLSecurityException("FilesystemCredentialResolver can't open CA certificate file ($1)",params(1,capath.c_str()));
531             }
532
533             extra = XMLHelper::getNextSiblingElement(extra,CAPath);
534         }
535     }
536     catch (XMLToolingException&) {
537         delete key;
538         delete crl;
539         for_each(m_certs.begin(), m_certs.end(), X509_free);
540         throw;
541     }
542
543     // Reflect certs over to XSEC form and wrap with credential object.
544     for (vector<X509*>::iterator j=m_certs.begin(); j!=m_certs.end(); j++)
545         xseccerts.push_back(new OpenSSLCryptoX509(*j));
546     if (!key && !xseccerts.empty())
547         key = xseccerts.front()->clonePublicKey();
548     m_credential = new FilesystemCredential(this, key, xseccerts, crl);
549     m_credential->addKeyNames(keynode);
550     m_credential->setUsage(usage);
551     m_credential->initKeyInfo(mask);
552 }
553
554 XSECCryptoKey* FilesystemCredentialResolver::loadKey()
555 {
556 #ifdef _DEBUG
557     NDC ndc("loadKey");
558 #endif
559     Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver."FILESYSTEM_CREDENTIAL_RESOLVER).info(
560         "loading private key from file (%s)", m_keypath.c_str()
561         );
562
563     // Get a EVP_PKEY.
564     EVP_PKEY* pkey=NULL;
565     BIO* in=BIO_new(BIO_s_file_internal());
566     if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
567         switch (m_keyformat) {
568             case PEM:
569                 pkey=PEM_read_bio_PrivateKey(in, NULL, passwd_callback, const_cast<char*>(m_keypass.c_str()));
570                 break;
571
572             case DER:
573                 pkey=d2i_PrivateKey_bio(in, NULL);
574                 break;
575
576             default: {
577                 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);
578                 if (p12) {
579                     PKCS12_parse(p12, const_cast<char*>(m_keypass.c_str()), &pkey, NULL, NULL);
580                     PKCS12_free(p12);
581                 }
582             }
583         }
584     }
585     if (in)
586         BIO_free(in);
587
588     // Now map it to an XSEC wrapper.
589     if (pkey) {
590         XSECCryptoKey* ret=NULL;
591         switch (pkey->type) {
592             case EVP_PKEY_RSA:
593                 ret=new OpenSSLCryptoKeyRSA(pkey);
594                 break;
595
596             case EVP_PKEY_DSA:
597                 ret=new OpenSSLCryptoKeyDSA(pkey);
598                 break;
599
600             default:
601                 Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver."FILESYSTEM_CREDENTIAL_RESOLVER).error("unsupported private key type");
602         }
603         EVP_PKEY_free(pkey);
604         if (ret)
605             return ret;
606     }
607
608     log_openssl();
609     throw XMLSecurityException("FilesystemCredentialResolver unable to load private key from file.");
610 }
611
612 XSECCryptoX509CRL* FilesystemCredentialResolver::loadCRL()
613 {
614 #ifdef _DEBUG
615     NDC ndc("loadCRL");
616 #endif
617     Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver."FILESYSTEM_CREDENTIAL_RESOLVER).info(
618         "loading CRL from file (%s)", m_crlpath.c_str()
619         );
620
621     X509_CRL* crl=NULL;
622     BIO* in=BIO_new(BIO_s_file_internal());
623     if (in && BIO_read_filename(in,m_crlpath.c_str())>0) {
624         switch (m_crlformat) {
625             case PEM:
626                 crl=PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
627                 break;
628
629             case DER:
630                 crl=d2i_X509_CRL_bio(in, NULL);
631                 break;
632         }
633     }
634     if (in)
635         BIO_free(in);
636
637     // Now map it to an XSEC wrapper.
638     if (crl) {
639         XSECCryptoX509CRL* ret=new OpenSSLCryptoX509CRL(crl);
640         X509_CRL_free(crl);
641         return ret;
642     }
643
644     log_openssl();
645     throw XMLSecurityException("FilesystemCredentialResolver unable to load CRL from file.");
646 }
647
648 // Used to determine the encoding format of credentials files
649 // dynamically. Supports: PEM, DER, PKCS12.
650 FilesystemCredentialResolver::format_t FilesystemCredentialResolver::getEncodingFormat(BIO* in) const
651 {
652     PKCS12* p12 = NULL;
653     format_t format;
654
655     const int READSIZE = 1;
656     char buf[READSIZE];
657     char b1;
658     int mark;
659
660     try {
661         if ( (mark = BIO_tell(in)) < 0 )
662             throw XMLSecurityException("getEncodingFormat: BIO_tell() can't get the file position");
663         if ( BIO_read(in, buf, READSIZE) <= 0 )
664             throw XMLSecurityException("getEncodingFormat: BIO_read() can't read from the stream");
665         if ( BIO_seek(in, mark) < 0 )
666             throw XMLSecurityException("getEncodingFormat: BIO_seek() can't reset the file position");
667     }
668     catch (...) {
669         log_openssl();
670         throw;
671     }
672
673     b1 = buf[0];
674
675     // This is a slight variation of the Java code by Chad La Joie.
676     //
677     // Check the first byte of the file.  If it's some kind of
678     // DER-encoded structure (including PKCS12), it will begin with ASCII 048.
679     // Otherwise, assume it's PEM.
680     if (b1 !=  48) {
681         format = PEM;
682     } else {
683         // Here we know it's DER-encoded, now try to parse it as a PKCS12
684         // ASN.1 structure.  If it fails, must be another kind of DER-encoded
685         // key/cert structure.  A little inefficient...but it works.
686         if ( (p12=d2i_PKCS12_bio(in,NULL)) == NULL ) {
687             format = DER;
688         } else {
689             format = _PKCS12;
690         }
691         if (p12)
692             PKCS12_free(p12);
693         if ( BIO_seek(in, mark) < 0 ) {
694             log_openssl();
695             throw XMLSecurityException("getEncodingFormat: BIO_seek() can't reset the file position");
696         }
697     }
698
699     return format;
700 }
701
702 // Convert key/cert format_t types to a human-meaningful string for debug output
703 string FilesystemCredentialResolver::formatToString(format_t format) const
704 {
705     switch(format) {
706         case PEM:
707             return "PEM";
708         case DER:
709             return "DER";
710         case _PKCS12:
711             return "PKCS12";
712         default:
713             return "UNKNOWN";
714     }
715 }
716
717 // Convert key/cert raw XML format attribute (XMLCh[]) to format_t type
718 FilesystemCredentialResolver::format_t FilesystemCredentialResolver::xmlFormatToFormat(const XMLCh* format_xml) const
719 {
720     static const XMLCh cPEM[] = UNICODE_LITERAL_3(P,E,M);
721     static const XMLCh cDER[] = UNICODE_LITERAL_3(D,E,R);
722     static const XMLCh cPKCS12[] = { chLatin_P, chLatin_K, chLatin_C, chLatin_S, chDigit_1, chDigit_2, chNull };
723     format_t format;
724
725     if (!XMLString::compareString(format_xml,cPEM))
726         format=PEM;
727     else if (!XMLString::compareString(format_xml,cDER))
728         format=DER;
729     else if (!XMLString::compareString(format_xml,cPKCS12))
730         format=_PKCS12;
731     else
732         format=UNKNOWN;
733
734     return format;
735 }
736
737 void FilesystemCredentialResolver::attach(SSL_CTX* ctx) const
738 {
739 #ifdef _DEBUG
740     NDC ndc("attach");
741 #endif
742
743     if (m_keypath.empty())
744         throw XMLSecurityException("No key available, unable to attach private key to SSL context.");
745
746     // Attach key.
747     SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
748     SSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char*>(m_keypass.c_str()));
749
750     int ret=0;
751     switch (m_keyformat) {
752         case PEM:
753             ret=SSL_CTX_use_PrivateKey_file(ctx, m_keypath.c_str(), m_keyformat);
754             break;
755
756         case DER:
757             ret=SSL_CTX_use_RSAPrivateKey_file(ctx, m_keypath.c_str(), m_keyformat);
758             break;
759
760         default: {
761             BIO* in=BIO_new(BIO_s_file_internal());
762             if (in && BIO_read_filename(in,m_keypath.c_str())>0) {
763                 EVP_PKEY* pkey=NULL;
764                 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);
765                 if (p12) {
766                     PKCS12_parse(p12, const_cast<char*>(m_keypass.c_str()), &pkey, NULL, NULL);
767                     PKCS12_free(p12);
768                     if (pkey) {
769                         ret=SSL_CTX_use_PrivateKey(ctx, pkey);
770                         EVP_PKEY_free(pkey);
771                     }
772                 }
773             }
774             if (in)
775                 BIO_free(in);
776         }
777     }
778
779     if (ret!=1) {
780         log_openssl();
781         throw XMLSecurityException("Unable to attach private key to SSL context.");
782     }
783
784     // Attach certs.
785     for (vector<X509*>::const_iterator i=m_certs.begin(); i!=m_certs.end(); i++) {
786         if (i==m_certs.begin()) {
787             if (SSL_CTX_use_certificate(ctx, *i) != 1) {
788                 log_openssl();
789                 throw XMLSecurityException("Unable to attach client certificate to SSL context.");
790             }
791         }
792         else {
793             // When we add certs, they don't get ref counted, so we need to duplicate them.
794             X509* dup = X509_dup(*i);
795             if (SSL_CTX_add_extra_chain_cert(ctx, dup) != 1) {
796                 X509_free(dup);
797                 log_openssl();
798                 throw XMLSecurityException("Unable to attach CA certificate to SSL context.");
799             }
800         }
801     }
802 }
803
804 void FilesystemCredential::addKeyNames(const DOMElement* e)
805 {
806     e = e ? XMLHelper::getFirstChildElement(e, Name) : NULL;
807     while (e) {
808         if (e->hasChildNodes()) {
809             auto_ptr_char n(e->getFirstChild()->getNodeValue());
810             if (n.get() && *n.get())
811                 m_keyNames.insert(n.get());
812         }
813         e = XMLHelper::getNextSiblingElement(e, Name);
814     }
815 }
816
817 void FilesystemCredential::attach(SSL_CTX* ctx) const
818 {
819     return m_resolver->attach(ctx);
820 }