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