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