Credential resolver plugin
[shibboleth/cpp-xmltooling.git] / xmltooling / signature / impl / FilesystemCredentialResolver.cpp
1 /*\r
2  *  Copyright 2001-2005 Internet2\r
3  * \r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * FilesystemCredentialResolver.cpp\r
19  * \r
20  * Supplies credentials from local files\r
21  */\r
22 \r
23 #include "internal.h"\r
24 #include "signature/OpenSSLCredentialResolver.h"\r
25 #include "util/NDC.h"\r
26 #include "util/XMLHelper.h"\r
27 \r
28 using namespace xmlsignature;\r
29 using namespace xmltooling;\r
30 \r
31 #include <sys/types.h>\r
32 #include <sys/stat.h>\r
33 #include <algorithm>\r
34 #include <openssl/pkcs12.h>\r
35 #include <log4cpp/Category.hh>\r
36 #include <xercesc/util/XMLUniDefs.hpp>\r
37 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>\r
38 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyRSA.hpp>\r
39 #include <xsec/enc/OpenSSL/OpenSSLCryptoKeyDSA.hpp>\r
40 \r
41 using namespace xmlsignature;\r
42 using namespace xmltooling;\r
43 using namespace log4cpp;\r
44 using namespace std;\r
45 \r
46 // OpenSSL password callback...\r
47 static int passwd_callback(char* buf, int len, int verify, void* passwd)\r
48 {\r
49     if(!verify)\r
50     {\r
51         if(passwd && len > strlen(reinterpret_cast<char*>(passwd)))\r
52         {\r
53             strcpy(buf,reinterpret_cast<char*>(passwd));\r
54             return strlen(buf);\r
55         }\r
56     }  \r
57     return 0;\r
58 }\r
59 \r
60 namespace xmlsignature {\r
61     class FilesystemCredentialResolver : public CredentialResolver\r
62     {\r
63     public:\r
64         FilesystemCredentialResolver(const DOMElement* e);\r
65         ~FilesystemCredentialResolver();\r
66 \r
67         Lockable* lock() { return this; }\r
68         void unlock() {}\r
69         \r
70         XSECCryptoKey* loadKey();\r
71         \r
72         void attach(SSL_CTX* ctx) const;\r
73         XSECCryptoKey* getKey() const { return m_key->clone(); }\r
74         const vector<XSECCryptoX509*>& getCertificates() const { return m_xseccerts; }\r
75         \r
76     private:\r
77         enum format_t { PEM=SSL_FILETYPE_PEM, DER=SSL_FILETYPE_ASN1, _PKCS12, UNKNOWN };\r
78     \r
79         format_t getEncodingFormat(BIO* in) const;\r
80         string formatToString(format_t format) const;\r
81         format_t xmlFormatToFormat(const XMLCh* format_xml) const;\r
82     \r
83         format_t m_keyformat;\r
84         string m_keypath,m_keypass;\r
85         vector<X509*> m_certs;\r
86         vector<XSECCryptoX509*> m_xseccerts;\r
87         XSECCryptoKey* m_key;\r
88     };\r
89 \r
90     CredentialResolver* XMLTOOL_DLLLOCAL FilesystemCredentialResolverFactory(const DOMElement* const & e)\r
91     {\r
92         return new FilesystemCredentialResolver(e);\r
93     }\r
94 };\r
95 \r
96 static const XMLCh CAPath[] =           UNICODE_LITERAL_6(C,A,P,a,t,h);\r
97 static const XMLCh Certificate[] =      UNICODE_LITERAL_11(C,e,r,t,i,f,i,c,a,t,e);\r
98 static const XMLCh format[] =           UNICODE_LITERAL_6(f,o,r,m,a,t);\r
99 static const XMLCh Key[] =              UNICODE_LITERAL_3(K,e,y);\r
100 static const XMLCh password[] =         UNICODE_LITERAL_8(p,a,s,s,w,o,r,d);\r
101 static const XMLCh Path[] =             UNICODE_LITERAL_4(P,a,t,h);\r
102 \r
103 FilesystemCredentialResolver::FilesystemCredentialResolver(const DOMElement* e)\r
104 {\r
105 #ifdef _DEBUG\r
106     NDC ndc("FilesystemCredentialResolver");\r
107 #endif\r
108     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver");\r
109 \r
110     format_t fformat;\r
111     const XMLCh* format_xml=NULL;\r
112     BIO* in = NULL;\r
113     \r
114     // Move to Key\r
115     const DOMElement* root=e;\r
116     e=XMLHelper::getFirstChildElement(root,Key);\r
117     if (e) {\r
118 \r
119         // Get raw format attrib value, but defer processing til later since may need to \r
120         // determine format dynamically, and we need the Path for that.\r
121         format_xml=e->getAttributeNS(NULL,format);\r
122             \r
123         const XMLCh* password_xml=e->getAttributeNS(NULL,password);\r
124         if (password_xml) {\r
125             auto_ptr_char kp(password_xml);\r
126             m_keypass=kp.get();\r
127         }\r
128         \r
129         e=XMLHelper::getFirstChildElement(e,Path);\r
130         if (e && e->hasChildNodes()) {\r
131             const XMLCh* s=e->getFirstChild()->getNodeValue();\r
132             auto_ptr_char kpath(s);\r
133 #ifdef WIN32\r
134             struct _stat stat_buf;\r
135             if (_stat(kpath.get(), &stat_buf) != 0)\r
136 #else\r
137             struct stat stat_buf;\r
138             if (stat(kpath.get(), &stat_buf) != 0)\r
139 #endif\r
140             {\r
141                 log.error("key file (%s) can't be opened", kpath.get());\r
142                 throw XMLSecurityException("FilesystemCredentialResolver can't access key file ($1)",params(1,kpath.get()));\r
143             }\r
144             m_keypath=kpath.get();\r
145         }\r
146         else {\r
147             log.error("Path element missing inside Key element");\r
148             throw XMLSecurityException("FilesystemCredentialResolver can't access key file, no Path element specified.");\r
149         }\r
150 \r
151         // Determine the key encoding format dynamically, if not explicitly specified\r
152         if (format_xml && *format_xml) {\r
153             fformat = xmlFormatToFormat(format_xml);\r
154             if (fformat != UNKNOWN) {\r
155                 m_keyformat = fformat;\r
156             }\r
157             else {\r
158                 auto_ptr_char unknown(format_xml);\r
159                 log.error("configuration specifies unknown key encoding format (%s)", unknown.get());\r
160                 throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown key encoding format ($1)",params(1,unknown.get()));\r
161             }\r
162         }\r
163         else {\r
164             in=BIO_new(BIO_s_file_internal());\r
165             if (in && BIO_read_filename(in,m_keypath.c_str())>0) {\r
166                 m_keyformat = getEncodingFormat(in);\r
167                 log.debug("key encoding format for (%s) dynamically resolved as (%s)", m_keypath.c_str(), formatToString(m_keyformat).c_str());\r
168             }\r
169             else {\r
170                 log.error("key file (%s) can't be read to determine encoding format", m_keypath.c_str());\r
171                 throw XMLSecurityException("FilesystemCredentialResolver can't read key file ($1) to determine encoding format",params(1,m_keypath.c_str()));\r
172             }\r
173             if (in)\r
174                 BIO_free(in);\r
175             in = NULL;    \r
176         }\r
177         \r
178         // Load the key.\r
179         m_key = loadKey();\r
180     }\r
181         \r
182     // Check for Certificate\r
183     e=XMLHelper::getFirstChildElement(root,Certificate);\r
184     if (!e)\r
185         return;\r
186     auto_ptr_char certpass(e->getAttributeNS(NULL,password));\r
187     \r
188     DOMElement* ep=XMLHelper::getFirstChildElement(e,Path);\r
189     if (!ep || !ep->hasChildNodes()) {\r
190         log.error("Path element missing inside Certificate element or is empty");\r
191         throw XMLSecurityException("FilesystemCredentialResolver can't access certificate file, missing or empty Path element.");\r
192     }\r
193     \r
194     auto_ptr_char certpath(ep->getFirstChild()->getNodeValue());\r
195     format_xml=e->getAttributeNS(NULL,format);\r
196     if (format_xml && *format_xml) {\r
197         fformat = xmlFormatToFormat(format_xml);\r
198         if (fformat == UNKNOWN) {\r
199             auto_ptr_char unknown(format_xml);\r
200             log.error("configuration specifies unknown certificate encoding format (%s)", unknown.get());\r
201             throw XMLSecurityException("FilesystemCredentialResolver configuration contains unknown certificate encoding format ($1)",params(1,unknown.get()));\r
202         }\r
203     }\r
204     \r
205     try {\r
206         X509* x=NULL;\r
207         PKCS12* p12=NULL;\r
208         in=BIO_new(BIO_s_file_internal());\r
209         if (in && BIO_read_filename(in,certpath.get())>0) {\r
210             if (!format_xml || !*format_xml) {\r
211                 // Determine the cert encoding format dynamically, if not explicitly specified\r
212                 fformat = getEncodingFormat(in);\r
213                 log.debug("certificate encoding format for (%s) dynamically resolved as (%s)", certpath.get(), formatToString(fformat).c_str());\r
214             }\r
215 \r
216             switch(fformat) {\r
217                 case PEM:\r
218                     while (x=PEM_read_bio_X509(in,NULL,passwd_callback,const_cast<char*>(certpass.get())))\r
219                         m_certs.push_back(x);\r
220                     break;\r
221                                 \r
222                 case DER:\r
223                     x=d2i_X509_bio(in,NULL);\r
224                     if (x)\r
225                         m_certs.push_back(x);\r
226                     else {\r
227                         log_openssl();\r
228                         BIO_free(in);\r
229                         throw XMLSecurityException("FilesystemCredentialResolver unable to load DER certificate from file ($1)",params(1,certpath.get()));\r
230                     }\r
231                     break;\r
232 \r
233                 case _PKCS12:\r
234                     p12=d2i_PKCS12_bio(in,NULL);\r
235                     if (p12) {\r
236                         PKCS12_parse(p12, certpass.get(), NULL, &x, NULL);\r
237                         PKCS12_free(p12);\r
238                     }\r
239                     if (x) {\r
240                         m_certs.push_back(x);\r
241                         x=NULL;\r
242                     } else {\r
243                         log_openssl();\r
244                         BIO_free(in);\r
245                         throw XMLSecurityException("FilesystemCredentialResolver unable to load PKCS12 certificate from file ($1)",params(1,certpath.get()));\r
246                     }\r
247                     break;\r
248             } // end switch\r
249 \r
250         } else {\r
251             log_openssl();\r
252             if (in) {\r
253                 BIO_free(in);\r
254                 in=NULL;\r
255             }\r
256             throw XMLSecurityException("FilesystemCredentialResolver unable to load certificate(s) from file ($1)",params(1,certpath.get()));\r
257         }\r
258         if (in) {\r
259             BIO_free(in);\r
260             in=NULL;\r
261         }\r
262 \r
263         if (m_certs.empty()) {\r
264             throw XMLSecurityException("FilesystemCredentialResolver unable to load any certificate(s)");\r
265         }\r
266 \r
267         // Load any extra CA files.\r
268         DOMElement* extra=XMLHelper::getFirstChildElement(e,CAPath);\r
269         while (extra) {\r
270             if (!extra->hasChildNodes()) {\r
271                 log.warn("skipping empty CAPath element");\r
272                 extra = XMLHelper::getNextSiblingElement(extra,CAPath);\r
273                 continue;\r
274             }\r
275             auto_ptr_char capath(extra->getFirstChild()->getNodeValue());\r
276             x=NULL;\r
277             p12=NULL;\r
278             in=BIO_new(BIO_s_file_internal());\r
279             if (in && BIO_read_filename(in,capath.get())>0) {\r
280                 if (!format_xml || !*format_xml) {\r
281                     // Determine the cert encoding format dynamically, if not explicitly specified\r
282                     fformat = getEncodingFormat(in);\r
283                     log.debug("CA certificate encoding format for (%s) dynamically resolved as (%s)", certpath.get(), formatToString(fformat).c_str());\r
284                 }\r
285 \r
286                 switch (fformat) {\r
287                     case PEM:\r
288                         while (x=PEM_read_bio_X509(in,NULL,passwd_callback,const_cast<char*>(certpass.get())))\r
289                             m_certs.push_back(x);\r
290                         break;\r
291 \r
292                     case DER:\r
293                         x=d2i_X509_bio(in,NULL);\r
294                         if (x)\r
295                             m_certs.push_back(x);\r
296                         else {\r
297                             log_openssl();\r
298                             BIO_free(in);\r
299                             throw XMLSecurityException("FilesystemCredentialResolver unable to load DER CA certificate from file ($1)",params(1,capath.get()));\r
300                         }\r
301                         break;\r
302 \r
303                     case _PKCS12:\r
304                         p12 = d2i_PKCS12_bio(in, NULL);\r
305                         if (p12) {\r
306                             PKCS12_parse(p12, certpass.get(), NULL, &x, NULL);\r
307                             PKCS12_free(p12);\r
308                         }\r
309                         if (x) {\r
310                             m_certs.push_back(x);\r
311                             x=NULL;\r
312                         }\r
313                         else {\r
314                             log_openssl();\r
315                             BIO_free(in);\r
316                             throw XMLSecurityException("FilesystemCredentialResolver unable to load PKCS12 CA certificate from file ($1)",params(1,capath.get()));\r
317                         }\r
318                         break;\r
319                 } //end switch\r
320 \r
321                 BIO_free(in);\r
322             }\r
323             else {\r
324                 if (in)\r
325                     BIO_free(in);\r
326                 log_openssl();\r
327                 log.error("CA file (%s) can't be opened", capath.get());\r
328                 throw XMLSecurityException("FilesystemCredentialResolver can't open CA file ($1)",params(1,capath.get()));\r
329             }\r
330             \r
331             extra = XMLHelper::getNextSiblingElement(extra,CAPath);\r
332         }\r
333     }\r
334     catch (XMLToolingException&) {\r
335         for (vector<X509*>::iterator j=m_certs.begin(); j!=m_certs.end(); j++)\r
336             X509_free(*j);\r
337         throw;\r
338     }\r
339 \r
340     // Reflect certs over to XSEC form.\r
341     for (vector<X509*>::iterator j=m_certs.begin(); j!=m_certs.end(); j++)\r
342         m_xseccerts.push_back(new OpenSSLCryptoX509(*j));\r
343 }\r
344 \r
345 XSECCryptoKey* FilesystemCredentialResolver::loadKey()\r
346 {\r
347 #ifdef _DEBUG\r
348     NDC ndc("loadKey");\r
349 #endif\r
350 \r
351     // Get a EVP_PKEY.\r
352     EVP_PKEY* pkey=NULL;\r
353     BIO* in=BIO_new(BIO_s_file_internal());\r
354     if (in && BIO_read_filename(in,m_keypath.c_str())>0) {\r
355         switch (m_keyformat) {\r
356             case PEM:\r
357                 pkey=PEM_read_bio_PrivateKey(in, NULL, passwd_callback, const_cast<char*>(m_keypass.c_str()));\r
358                 break;\r
359             \r
360             case DER:\r
361                 pkey=d2i_PrivateKey_bio(in, NULL);\r
362                 break;\r
363                 \r
364             default: {\r
365                 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);\r
366                 if (p12) {\r
367                     PKCS12_parse(p12, const_cast<char*>(m_keypass.c_str()), &pkey, NULL, NULL);\r
368                     PKCS12_free(p12);\r
369                 }\r
370             }\r
371         }\r
372     }\r
373     if (in)\r
374         BIO_free(in);\r
375     \r
376     // Now map it to an XSEC wrapper.\r
377     if (pkey) {\r
378         XSECCryptoKey* ret=NULL;\r
379         switch (pkey->type) {\r
380             case EVP_PKEY_RSA:\r
381                 ret=new OpenSSLCryptoKeyRSA(pkey);\r
382                 break;\r
383                 \r
384             case EVP_PKEY_DSA:\r
385                 ret=new OpenSSLCryptoKeyDSA(pkey);\r
386                 break;\r
387             \r
388             default:\r
389                 Category::getInstance(XMLTOOLING_LOGCAT".CredentialResolver").error("unsupported private key type");\r
390         }\r
391         EVP_PKEY_free(pkey);\r
392         if (ret)\r
393             return ret;\r
394     }\r
395 \r
396     log_openssl();\r
397     throw XMLSecurityException("FilesystemCredentialResolver unable to load private key from file."); \r
398 }\r
399 \r
400 FilesystemCredentialResolver::~FilesystemCredentialResolver()\r
401 {\r
402     for_each(m_certs.begin(),m_certs.end(),X509_free);\r
403     for_each(m_xseccerts.begin(),m_xseccerts.end(),xmltooling::cleanup<XSECCryptoX509>());\r
404 }\r
405 \r
406 void FilesystemCredentialResolver::attach(SSL_CTX* ctx) const\r
407 {\r
408 #ifdef _DEBUG\r
409     NDC ndc("attach");\r
410 #endif\r
411     \r
412     // Attach key.\r
413     SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);\r
414     SSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char*>(m_keypass.c_str()));\r
415 \r
416     int ret=0;\r
417     switch (m_keyformat) {\r
418         case PEM:\r
419             ret=SSL_CTX_use_PrivateKey_file(ctx, m_keypath.c_str(), m_keyformat);\r
420             break;\r
421             \r
422         case DER:\r
423             ret=SSL_CTX_use_RSAPrivateKey_file(ctx, m_keypath.c_str(), m_keyformat);\r
424             break;\r
425             \r
426         default: {\r
427             BIO* in=BIO_new(BIO_s_file_internal());\r
428             if (in && BIO_read_filename(in,m_keypath.c_str())>0) {\r
429                 EVP_PKEY* pkey=NULL;\r
430                 PKCS12* p12 = d2i_PKCS12_bio(in, NULL);\r
431                 if (p12) {\r
432                     PKCS12_parse(p12, const_cast<char*>(m_keypass.c_str()), &pkey, NULL, NULL);\r
433                     PKCS12_free(p12);\r
434                     if (pkey) {\r
435                         ret=SSL_CTX_use_PrivateKey(ctx, pkey);\r
436                         EVP_PKEY_free(pkey);\r
437                     }\r
438                 }\r
439             }\r
440             if (in)\r
441                 BIO_free(in);\r
442         }\r
443     }\r
444     \r
445     if (ret!=1) {\r
446         log_openssl();\r
447         throw XMLSecurityException("Unable to attach private key to SSL context.");\r
448     }\r
449 \r
450     // Attach certs.\r
451     for (vector<X509*>::const_iterator i=m_certs.begin(); i!=m_certs.end(); i++) {\r
452         if (i==m_certs.begin()) {\r
453             if (SSL_CTX_use_certificate(ctx, *i) != 1) {\r
454                 log_openssl();\r
455                 throw XMLSecurityException("Unable to attach client certificate to SSL context.");\r
456             }\r
457         }\r
458         else {\r
459             // When we add certs, they don't get ref counted, so we need to duplicate them.\r
460             X509* dup = X509_dup(*i);\r
461             if (SSL_CTX_add_extra_chain_cert(ctx, dup) != 1) {\r
462                 X509_free(dup);\r
463                 log_openssl();\r
464                 throw XMLSecurityException("Unable to attach CA certificate to SSL context.");\r
465             }\r
466         }\r
467     }\r
468 }\r
469 \r
470 // Used to determine the encoding format of credentials files\r
471 // dynamically. Supports: PEM, DER, PKCS12.\r
472 FilesystemCredentialResolver::format_t FilesystemCredentialResolver::getEncodingFormat(BIO* in) const\r
473 {\r
474     PKCS12* p12 = NULL;\r
475     format_t format;\r
476 \r
477     const int READSIZE = 1;\r
478     char buf[READSIZE];\r
479     char b1;\r
480     int mark;\r
481 \r
482     try {\r
483         if ( (mark = BIO_tell(in)) < 0 ) \r
484             throw XMLSecurityException("getEncodingFormat: BIO_tell() can't get the file position");\r
485         if ( BIO_read(in, buf, READSIZE) <= 0 ) \r
486             throw XMLSecurityException("getEncodingFormat: BIO_read() can't read from the stream");\r
487         if ( BIO_seek(in, mark) < 0 ) \r
488             throw XMLSecurityException("getEncodingFormat: BIO_seek() can't reset the file position");\r
489     }\r
490     catch (...) {\r
491         log_openssl();\r
492         throw;\r
493     }\r
494 \r
495     b1 = buf[0];\r
496 \r
497     // This is a slight variation of the Java code by Chad La Joie.\r
498     //\r
499     // Check the first byte of the file.  If it's some kind of\r
500     // DER-encoded structure (including PKCS12), it will begin with ASCII 048.\r
501     // Otherwise, assume it's PEM.\r
502     if (b1 !=  48) {\r
503         format = PEM;\r
504     } else {\r
505         // Here we know it's DER-encoded, now try to parse it as a PKCS12\r
506         // ASN.1 structure.  If it fails, must be another kind of DER-encoded\r
507         // key/cert structure.  A little inefficient...but it works.\r
508         if ( (p12=d2i_PKCS12_bio(in,NULL)) == NULL ) {\r
509             format = DER;\r
510         } else {\r
511             format = _PKCS12;\r
512         }\r
513         if (p12)\r
514             PKCS12_free(p12);    \r
515         if ( BIO_seek(in, mark) < 0 ) {\r
516             log_openssl();\r
517             throw XMLSecurityException("getEncodingFormat: BIO_seek() can't reset the file position");\r
518         }\r
519     }\r
520 \r
521     return format;\r
522 }\r
523 \r
524 // Convert key/cert format_t types to a human-meaningful string for debug output\r
525 string FilesystemCredentialResolver::formatToString(format_t format) const\r
526 {\r
527     switch(format) {\r
528         case PEM:\r
529             return "PEM";\r
530         case DER:\r
531             return "DER";\r
532         case _PKCS12:\r
533             return "PKCS12";\r
534         default:\r
535             return "UNKNOWN";\r
536     }\r
537 }\r
538 \r
539 // Convert key/cert raw XML format attribute (XMLCh[]) to format_t type\r
540 FilesystemCredentialResolver::format_t FilesystemCredentialResolver::xmlFormatToFormat(const XMLCh* format_xml) const\r
541 {\r
542     static const XMLCh cPEM[] = UNICODE_LITERAL_3(P,E,M);\r
543     static const XMLCh cDER[] = UNICODE_LITERAL_3(D,E,R);\r
544     static const XMLCh cPKCS12[] = { chLatin_P, chLatin_K, chLatin_C, chLatin_S, chDigit_1, chDigit_2, chNull };\r
545     format_t format;\r
546 \r
547     if (!XMLString::compareString(format_xml,cPEM))\r
548         format=PEM;\r
549     else if (!XMLString::compareString(format_xml,cDER))\r
550         format=DER;\r
551     else if (!XMLString::compareString(format_xml,cPKCS12))\r
552         format=_PKCS12;\r
553     else\r
554         format=UNKNOWN;\r
555 \r
556     return format;\r
557 }\r