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