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