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