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