Algorithm and key size criteria, incoming signature algorithm extraction.
[shibboleth/cpp-xmltooling.git] / xmltooling / XMLToolingConfig.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  * XMLToolingConfig.cpp
19  * 
20  * Library configuration 
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "XMLToolingConfig.h"
26 #include "encryption/Encrypter.h"
27 #include "impl/UnknownElement.h"
28 #include "security/TrustEngine.h"
29 #include "security/OpenSSLCryptoX509CRL.h"
30 #include "security/CredentialResolver.h"
31 #include "security/KeyInfoResolver.h"
32 #include "signature/Signature.h"
33 #include "soap/SOAP.h"
34 #include "soap/SOAPTransport.h"
35 #include "util/NDC.h"
36 #include "util/ReplayCache.h"
37 #include "util/StorageService.h"
38 #include "util/TemplateEngine.h"
39 #include "util/URLEncoder.h"
40 #include "util/XMLConstants.h"
41 #include "validation/ValidatorSuite.h"
42
43 #ifdef HAVE_DLFCN_H
44 # include <dlfcn.h>
45 #endif
46
47 #include <stdexcept>
48 #include <curl/curl.h>
49 #include <log4cpp/Category.hh>
50 #include <log4cpp/PropertyConfigurator.hh>
51 #include <log4cpp/OstreamAppender.hh>
52 #include <xercesc/util/PlatformUtils.hpp>
53 #ifndef XMLTOOLING_NO_XMLSEC
54     #include <xsec/framework/XSECProvider.hpp>
55     #include <openssl/err.h>
56 #endif
57
58 using namespace soap11;
59 using namespace xmlencryption;
60 using namespace xmlsignature;
61 using namespace xmltooling;
62 using namespace log4cpp;
63 using namespace std;
64
65 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
66 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
67 DECL_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
68 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
69 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
70 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
71 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
72 DECL_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
73 DECL_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
74
75 #ifndef XMLTOOLING_NO_XMLSEC
76     DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
77     DECL_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
78     DECL_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
79 #endif
80
81 namespace xmltooling {
82     static XMLToolingInternalConfig g_config;
83     static vector<Mutex*> g_openssl_locks;
84
85     extern "C" void openssl_locking_callback(int mode,int n,const char *file,int line)
86     {
87         if (mode & CRYPTO_LOCK)
88             g_openssl_locks[n]->lock();
89         else
90             g_openssl_locks[n]->unlock();
91     }
92     
93     #ifndef WIN32
94     extern "C" unsigned long openssl_thread_id(void)
95     {
96         return (unsigned long)(pthread_self());
97     }
98     #endif
99 }
100
101 XMLToolingConfig& XMLToolingConfig::getConfig()
102 {
103     return g_config;
104 }
105
106 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
107 {
108     return g_config;
109 }
110
111 bool XMLToolingInternalConfig::log_config(const char* config)
112 {
113     try {
114         if (!config || !*config)
115             config=getenv("XMLTOOLING_LOG_CONFIG");
116         if (!config || !*config)
117             config="WARN";
118         
119         bool level=false;
120         Category& root = Category::getRoot();
121         if (!strcmp(config,"DEBUG")) {
122             root.setPriority(Priority::DEBUG);
123             level=true;
124         }
125         else if (!strcmp(config,"INFO")) {
126             root.setPriority(Priority::INFO);
127             level=true;
128         }
129         else if (!strcmp(config,"NOTICE")) {
130             root.setPriority(Priority::NOTICE);
131             level=true;
132         }
133         else if (!strcmp(config,"WARN")) {
134             root.setPriority(Priority::WARN);
135             level=true;
136         }
137         else if (!strcmp(config,"ERROR")) {
138             root.setPriority(Priority::ERROR);
139             level=true;
140         }
141         else if (!strcmp(config,"CRIT")) {
142             root.setPriority(Priority::CRIT);
143             level=true;
144         }
145         else if (!strcmp(config,"ALERT")) {
146             root.setPriority(Priority::ALERT);
147             level=true;
148         }
149         else if (!strcmp(config,"EMERG")) {
150             root.setPriority(Priority::EMERG);
151             level=true;
152         }
153         else if (!strcmp(config,"FATAL")) {
154             root.setPriority(Priority::FATAL);
155             level=true;
156         }
157         if (level)
158             root.setAppender(new OstreamAppender("default",&cerr));
159         else
160             PropertyConfigurator::configure(config);
161     }
162     catch (const ConfigureFailure& e) {
163         Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
164         return false;
165     }
166     
167     return true;
168 }
169
170 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
171 {
172     delete m_replayCache;
173     m_replayCache = replayCache;
174 }
175
176 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
177 {
178     delete m_templateEngine;
179     m_templateEngine = templateEngine;
180 }
181
182 void XMLToolingConfig::setURLEncoder(URLEncoder* urlEncoder)
183 {
184     delete m_urlEncoder;
185     m_urlEncoder = urlEncoder;
186 }
187
188 bool XMLToolingInternalConfig::init()
189 {
190 #ifdef _DEBUG
191     xmltooling::NDC ndc("init");
192 #endif
193     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
194     try {
195         log.debug("library initialization started");
196
197         if (curl_global_init(CURL_GLOBAL_ALL)) {
198             log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
199             return false;
200         }
201         log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
202
203         xercesc::XMLPlatformUtils::Initialize();
204         log.debug("Xerces initialization complete");
205
206 #ifndef XMLTOOLING_NO_XMLSEC
207         XSECPlatformUtils::Initialise();
208         m_xsecProvider=new XSECProvider();
209         log.debug("XMLSec initialization complete");
210 #endif
211
212         m_parserPool=new ParserPool();
213         m_validatingPool=new ParserPool(true,true);
214         m_lock=xercesc::XMLPlatformUtils::makeMutex();
215         
216         // Load catalogs from path.
217         if (!catalog_path.empty()) {
218             char* catpath=strdup(catalog_path.c_str());
219             char* sep=NULL;
220             char* start=catpath;
221             while (start && *start) {
222                 sep=strchr(start,PATH_SEPARATOR_CHAR);
223                 if (sep)
224                     *sep=0;
225                 auto_ptr_XMLCh temp(start);
226                 m_validatingPool->loadCatalog(temp.get());
227                 start = sep ? sep + 1 : NULL;
228             }
229             free(catpath);
230         }
231
232         // default registrations
233         XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
234
235         registerKeyInfoClasses();
236         registerEncryptionClasses();
237         registerSOAPClasses();
238
239         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
240         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
241         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
242         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
243         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
244         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
245         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
246         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
247         
248 #ifndef XMLTOOLING_NO_XMLSEC
249         XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
250         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
251         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
252         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
253         registerKeyInfoResolvers();
254         registerCredentialResolvers();
255         registerTrustEngines();
256 #endif
257         registerSOAPTransports();
258         initSOAPTransports();
259         registerStorageServices();
260
261         m_urlEncoder = new URLEncoder();
262         m_keyInfoResolver = KeyInfoResolverManager.newPlugin(INLINE_KEYINFO_RESOLVER,NULL);
263         
264         // Register xml:id as an ID attribute.        
265         static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
266         AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid)); 
267     }
268     catch (const xercesc::XMLException&) {
269         log.fatal("caught exception while initializing Xerces");
270         curl_global_cleanup();
271         return false;
272     }
273
274     // Set up OpenSSL locking.
275     for (int i=0; i<CRYPTO_num_locks(); i++)
276         g_openssl_locks.push_back(Mutex::create());
277     CRYPTO_set_locking_callback(openssl_locking_callback);
278 #ifndef WIN32
279     CRYPTO_set_id_callback(openssl_thread_id);
280 #endif
281
282     log.info("library initialization complete");
283     return true;
284 }
285
286 void XMLToolingInternalConfig::term()
287 {
288     CRYPTO_set_locking_callback(NULL);
289     for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
290     g_openssl_locks.clear();
291
292     SchemaValidators.destroyValidators();
293     XMLObjectBuilder::destroyBuilders();
294     XMLToolingException::deregisterFactories();
295     AttributeExtensibleXMLObject::deregisterIDAttributes();
296
297     StorageServiceManager.deregisterFactories();
298     termSOAPTransports();
299     SOAPTransportManager.deregisterFactories();
300 #ifndef XMLTOOLING_NO_XMLSEC
301     TrustEngineManager.deregisterFactories();
302     CredentialResolverManager.deregisterFactories();
303     KeyInfoResolverManager.deregisterFactories();
304     registerXMLAlgorithms();
305 #endif
306
307     delete m_keyInfoResolver;
308     m_keyInfoResolver = NULL;
309
310     delete m_replayCache;
311     m_replayCache = NULL;
312     
313     delete m_templateEngine;
314     m_templateEngine = NULL;
315
316     delete m_urlEncoder;
317     m_urlEncoder = NULL;
318
319     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
320 #if defined(WIN32)
321         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
322         if (fn)
323             fn();
324         FreeLibrary(static_cast<HMODULE>(*i));
325 #elif defined(HAVE_DLFCN_H)
326         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
327         if (fn)
328             fn();
329         dlclose(*i);
330 #else
331 # error "Don't know about dynamic loading on this platform!"
332 #endif
333     }
334     m_libhandles.clear();
335     
336     delete m_parserPool;
337     m_parserPool=NULL;
338     delete m_validatingPool;
339     m_validatingPool=NULL;
340
341 #ifndef XMLTOOLING_NO_XMLSEC
342     delete m_xsecProvider;
343     m_xsecProvider=NULL;
344     XSECPlatformUtils::Terminate();
345 #endif
346
347     xercesc::XMLPlatformUtils::closeMutex(m_lock);
348     m_lock=NULL;
349     xercesc::XMLPlatformUtils::Terminate();
350
351     curl_global_cleanup();
352     
353  #ifdef _DEBUG
354     xmltooling::NDC ndc("term");
355 #endif
356    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
357 }
358
359 Lockable* XMLToolingInternalConfig::lock()
360 {
361     xercesc::XMLPlatformUtils::lockMutex(m_lock);
362     return this;
363 }
364
365 void XMLToolingInternalConfig::unlock()
366 {
367     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
368 }
369
370 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
371 {
372 #ifdef _DEBUG
373     xmltooling::NDC ndc("LoadLibrary");
374 #endif
375     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
376     log.info("loading extension: %s", path);
377
378     Locker locker(this);
379
380 #if defined(WIN32)
381     HMODULE handle=NULL;
382     char* fixed=const_cast<char*>(path);
383     if (strchr(fixed,'/')) {
384         fixed=strdup(path);
385         char* p=fixed;
386         while (p=strchr(p,'/'))
387             *p='\\';
388     }
389
390     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
391     try {
392         handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
393         if (!handle)
394              handle=LoadLibraryEx(fixed,NULL,0);
395         if (!handle)
396             throw runtime_error(string("unable to load extension library: ") + fixed);
397         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
398         if (!fn)
399             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
400         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
401             throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
402         if (fixed!=path)
403             free(fixed);
404         SetErrorMode(em);
405     }
406     catch(runtime_error& e) {
407         log.error(e.what());
408         if (handle)
409             FreeLibrary(handle);
410         SetErrorMode(em);
411         if (fixed!=path)
412             free(fixed);
413         return false;
414     }
415
416 #elif defined(HAVE_DLFCN_H)
417     void* handle=dlopen(path,RTLD_LAZY);
418     if (!handle)
419         throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
420     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
421     if (!fn) {
422         dlclose(handle);
423         throw runtime_error(
424             string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
425                 (dlerror() ? dlerror() : "unknown error")
426             );
427     }
428     try {
429         if (fn(context)!=0)
430             throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
431     }
432     catch(runtime_error& e) {
433         log.error(e.what());
434         if (handle)
435             dlclose(handle);
436         return false;
437     }
438 #else
439 # error "Don't know about dynamic loading on this platform!"
440 #endif
441     m_libhandles.push_back(handle);
442     log.info("loaded extension: %s", path);
443     return true;
444 }
445
446 #ifndef XMLTOOLING_NO_XMLSEC
447 void xmltooling::log_openssl()
448 {
449     const char* file;
450     const char* data;
451     int flags,line;
452
453     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
454     while (code) {
455         Category& log=Category::getInstance("OpenSSL");
456         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
457         if (data && (flags & ERR_TXT_STRING))
458             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
459         code=ERR_get_error_line_data(&file,&line,&data,&flags);
460     }
461 }
462
463 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
464 {
465     return new OpenSSLCryptoX509CRL();
466 }
467
468 void XMLToolingInternalConfig::registerXMLAlgorithms()
469 {
470     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_MD5, "RSA", 0);
471     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA1, "RSA", 0);
472     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA224, "RSA", 0);
473     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA256, "RSA", 0);
474     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA384, "RSA", 0);
475     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA512, "RSA", 0);
476
477     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_1_5, "RSA", 0);
478     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_OAEP_MGFP1, "RSA", 0);
479
480     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIDSA_SHA1, "DSA", 0);
481
482     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA1, "HMAC", 0);
483     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA224, "HMAC", 0);
484     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA256, "HMAC", 0);
485     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA384, "HMAC", 0);
486     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA512, "HMAC", 0);
487
488     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURI3DES_CBC, "DESede", 192);
489     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_3DES, "DESede", 192);
490
491     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES128_CBC, "AES", 128);
492     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES128, "AES", 128);
493
494     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES192_CBC, "AES", 192);
495     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES192, "AES", 192);
496
497     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES256_CBC, "AES", 256);
498     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES256, "AES", 256);
499 }
500 #endif