merged tag ooo/OOO330_m14
[LibreOffice.git] / xmlsecurity / source / xmlsec / nss / seinitializer_nssimpl.cxx
blob127d7fa43fe6fd299488243087b3b438aff43f25
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * Copyright 2000, 2010 Oracle and/or its affiliates.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * This file is part of OpenOffice.org.
11 * OpenOffice.org is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License version 3
13 * only, as published by the Free Software Foundation.
15 * OpenOffice.org is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License version 3 for more details
19 * (a copy is included in the LICENSE file that accompanied this code).
21 * You should have received a copy of the GNU Lesser General Public License
22 * version 3 along with OpenOffice.org. If not, see
23 * <http://www.openoffice.org/license.html>
24 * for a copy of the LGPLv3 License.
26 ************************************************************************/
28 // MARKER(update_precomp.py): autogen include statement, do not remove
29 #include "precompiled_xmlsecurity.hxx"
32 * Turn off DEBUG Assertions
34 #ifdef _DEBUG
35 #define _DEBUG_WAS_DEFINED _DEBUG
36 #undef _DEBUG
37 #else
38 #undef _DEBUG_WAS_DEFINED
39 #endif
42 * and turn off the additional virtual methods which are part of some interfaces when compiled
43 * with debug
45 #ifdef DEBUG
46 #define DEBUG_WAS_DEFINED DEBUG
47 #undef DEBUG
48 #else
49 #undef DEBUG_WAS_DEFINED
50 #endif
53 #include <sal/types.h>
54 #include "rtl/instance.hxx"
55 #include "rtl/bootstrap.hxx"
56 #include "rtl/string.hxx"
57 #include "rtl/strbuf.hxx"
58 #include "osl/file.hxx"
59 #include "osl/thread.h"
60 #include <tools/debug.hxx>
61 #include <rtl/logfile.hxx>
63 #include "seinitializer_nssimpl.hxx"
64 #include "../diagnose.hxx"
66 #include "securityenvironment_nssimpl.hxx"
67 #include <com/sun/star/mozilla/XMozillaBootstrap.hpp>
69 #include "nspr.h"
70 #include "cert.h"
71 #include "nss.h"
72 #include "secmod.h"
73 #include "nssckbi.h"
76 namespace cssu = com::sun::star::uno;
77 namespace cssl = com::sun::star::lang;
78 namespace cssxc = com::sun::star::xml::crypto;
80 using namespace xmlsecurity;
81 using namespace com::sun::star;
82 using ::rtl::OUString;
83 using ::rtl::OString;
85 #define SERVICE_NAME "com.sun.star.xml.crypto.SEInitializer"
86 #define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.SEInitializer_NssImpl"
87 #define SECURITY_ENVIRONMENT "com.sun.star.xml.crypto.SecurityEnvironment"
88 #define SECURITY_CONTEXT "com.sun.star.xml.crypto.XMLSecurityContext"
91 #define ROOT_CERTS "Root Certs for OpenOffice.org"
94 extern "C" void nsscrypto_finalize();
97 namespace
100 bool nsscrypto_initialize( const char * sProfile, bool & out_nss_init);
102 struct InitNSSInitialize
104 //path to the database folder
105 const OString m_sProfile;
106 InitNSSInitialize(const OString & sProfile): m_sProfile(sProfile) {};
107 bool * operator()()
109 static bool bInitialized = false;
110 bool bNSSInit = false;
111 bInitialized = nsscrypto_initialize(m_sProfile.getStr(), bNSSInit);
112 if (bNSSInit)
113 atexit(nsscrypto_finalize );
114 return & bInitialized;
119 bool * initNSS(const OString & sProfile)
121 return rtl_Instance< bool, InitNSSInitialize,
122 ::osl::MutexGuard, ::osl::GetGlobalMutex >::create(
123 InitNSSInitialize(sProfile), ::osl::GetGlobalMutex());
126 void deleteRootsModule()
128 SECMODModule *RootsModule = 0;
129 SECMODModuleList *list = SECMOD_GetDefaultModuleList();
130 SECMODListLock *lock = SECMOD_GetDefaultModuleListLock();
131 SECMOD_GetReadLock(lock);
133 while (!RootsModule && list)
135 SECMODModule *module = list->module;
137 for (int i=0; i < module->slotCount; i++)
139 PK11SlotInfo *slot = module->slots[i];
140 if (PK11_IsPresent(slot))
142 if (PK11_HasRootCerts(slot))
144 xmlsec_trace("The root certifificates module \"%s"
145 "\" is already loaded: \n%s",
146 module->commonName, module->dllName);
148 RootsModule = SECMOD_ReferenceModule(module);
149 break;
153 list = list->next;
155 SECMOD_ReleaseReadLock(lock);
157 if (RootsModule)
159 PRInt32 modType;
160 if (SECSuccess == SECMOD_DeleteModule(RootsModule->commonName, &modType))
162 xmlsec_trace("Deleted module \"%s\".", RootsModule->commonName);
164 else
166 xmlsec_trace("Failed to delete \"%s\" : \n%s",
167 RootsModule->commonName, RootsModule->dllName);
169 SECMOD_DestroyModule(RootsModule);
170 RootsModule = 0;
174 //Older versions of Firefox (FF), for example FF2, and Thunderbird (TB) 2 write
175 //the roots certificate module (libnssckbi.so), which they use, into the
176 //profile. This module will then already be loaded during NSS_Init (and the
177 //other init functions). This fails in two cases. First, FF3 was used to create
178 //the profile, or possibly used that profile before, and second the profile was
179 //used on a different platform.
181 //Then one needs to add the roots module oneself. This should be done with
182 //SECMOD_LoadUserModule rather then SECMOD_AddNewModule. The latter would write
183 //the location of the roots module to the profile, which makes FF2 and TB2 use
184 //it instead of there own module.
186 //When using SYSTEM_MOZILLA then the libnss3.so lib is typically found in
187 ///usr/lib. This folder may, however, NOT contain the roots certificate
188 //module. That is, just providing the library name in SECMOD_LoadUserModule or
189 //SECMOD_AddNewModule will FAIL to load the mozilla unless the LD_LIBRARY_PATH
190 //contains an FF or TB installation.
191 //ATTENTION: DO NOT call this function directly instead use initNSS
192 //return true - whole initialization was successful
193 //param out_nss_init = true: at least the NSS initialization (NSS_InitReadWrite
194 //was successful and therefor NSS_Shutdown should be called when terminating.
195 bool nsscrypto_initialize( const char* token, bool & out_nss_init )
197 bool return_value = true;
199 xmlsec_trace("Using profile: %s", token);
201 PR_Init( PR_USER_THREAD, PR_PRIORITY_NORMAL, 1 ) ;
203 //token may be an empty string
204 if (token != NULL && strlen(token) > 0)
206 if( NSS_InitReadWrite( token ) != SECSuccess )
208 xmlsec_trace("Initializing NSS with profile failed.");
209 char * error = NULL;
211 PR_GetErrorText(error);
212 if (error)
213 xmlsec_trace("%s",error);
214 return false ;
217 else
219 xmlsec_trace("Initializing NSS without profile.");
220 if ( NSS_NoDB_Init(NULL) != SECSuccess )
222 xmlsec_trace("Initializing NSS without profile failed.");
223 char * error = NULL;
224 PR_GetErrorText(error);
225 if (error)
226 xmlsec_trace("%s",error);
227 return false ;
230 out_nss_init = true;
232 #if defined SYSTEM_MOZILLA
233 if (!SECMOD_HasRootCerts())
235 #endif
236 deleteRootsModule();
238 #if defined SYSTEM_MOZILLA
239 OUString rootModule(RTL_CONSTASCII_USTRINGPARAM("libnssckbi"SAL_DLLEXTENSION));
240 #else
241 OUString rootModule(RTL_CONSTASCII_USTRINGPARAM("${OOO_BASE_DIR}/program/libnssckbi"SAL_DLLEXTENSION));
242 #endif
243 ::rtl::Bootstrap::expandMacros(rootModule);
245 OUString rootModulePath;
246 if (::osl::File::E_None == ::osl::File::getSystemPathFromFileURL(rootModule, rootModulePath))
248 ::rtl::OString ospath = ::rtl::OUStringToOString(rootModulePath, osl_getThreadTextEncoding());
249 ::rtl::OStringBuffer pkcs11moduleSpec;
250 pkcs11moduleSpec.append("name=\"");
251 pkcs11moduleSpec.append(ROOT_CERTS);
252 pkcs11moduleSpec.append("\" library=\"");
253 pkcs11moduleSpec.append(ospath.getStr());
254 pkcs11moduleSpec.append("\"");
256 SECMODModule * RootsModule =
257 SECMOD_LoadUserModule(
258 const_cast<char*>(pkcs11moduleSpec.makeStringAndClear().getStr()),
259 0, // no parent
260 PR_FALSE); // do not recurse
262 if (RootsModule)
265 bool found = RootsModule->loaded;
267 SECMOD_DestroyModule(RootsModule);
268 RootsModule = 0;
269 if (found)
270 xmlsec_trace("Added new root certificate module "
271 "\""ROOT_CERTS"\" contained in \n%s", ospath.getStr());
272 else
274 xmlsec_trace("FAILED to load the new root certificate module "
275 "\""ROOT_CERTS"\" contained in \n%s", ospath.getStr());
276 return_value = false;
279 else
281 xmlsec_trace("FAILED to add new root certifice module: "
282 "\""ROOT_CERTS"\" contained in \n%s", ospath.getStr());
283 return_value = false;
287 else
289 xmlsec_trace("Adding new root certificate module failed.");
290 return_value = false;
292 #if SYSTEM_MOZILLA
294 #endif
296 return return_value;
300 // must be extern "C" because we pass the function pointer to atexit
301 extern "C" void nsscrypto_finalize()
303 SECMODModule *RootsModule = SECMOD_FindModule(ROOT_CERTS);
305 if (RootsModule)
308 if (SECSuccess == SECMOD_UnloadUserModule(RootsModule))
310 xmlsec_trace("Unloaded module \""ROOT_CERTS"\".");
312 else
314 xmlsec_trace("Failed unloadeding module \""ROOT_CERTS"\".");
316 SECMOD_DestroyModule(RootsModule);
318 else
320 xmlsec_trace("Unloading module \""ROOT_CERTS
321 "\" failed because it was not found.");
323 PK11_LogoutAll();
324 NSS_Shutdown();
328 bool getMozillaCurrentProfile(
329 const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF,
330 rtl::OUString& profilePath)
333 * first, try to get the profile from "MOZILLA_CERTIFICATE_FOLDER"
335 char * env = getenv("MOZILLA_CERTIFICATE_FOLDER");
336 if (env)
338 profilePath = rtl::OUString::createFromAscii( env );
339 RTL_LOGFILE_PRODUCT_TRACE1( "XMLSEC: Using env MOZILLA_CERTIFICATE_FOLDER: %s", rtl::OUStringToOString( profilePath, RTL_TEXTENCODING_ASCII_US ).getStr() );
340 return true;
342 else
344 mozilla::MozillaProductType productTypes[4] = {
345 mozilla::MozillaProductType_Thunderbird,
346 mozilla::MozillaProductType_Mozilla,
347 mozilla::MozillaProductType_Firefox,
348 mozilla::MozillaProductType_Default };
349 int nProduct = 4;
351 uno::Reference<uno::XInterface> xInstance = rxMSF->createInstance(
352 ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")) );
353 OSL_ENSURE( xInstance.is(), "failed to create instance" );
355 uno::Reference<mozilla::XMozillaBootstrap> xMozillaBootstrap
356 = uno::Reference<mozilla::XMozillaBootstrap>(xInstance,uno::UNO_QUERY);
357 OSL_ENSURE( xMozillaBootstrap.is(), "failed to create instance" );
359 if (xMozillaBootstrap.is())
361 for (int i=0; i<nProduct; i++)
363 ::rtl::OUString profile = xMozillaBootstrap->getDefaultProfile(productTypes[i]);
365 if (profile != NULL && profile.getLength()>0)
367 profilePath = xMozillaBootstrap->getProfilePath(productTypes[i],profile);
368 RTL_LOGFILE_PRODUCT_TRACE1( "XMLSEC: Using Mozilla Profile: %s", rtl::OUStringToOString( profilePath, RTL_TEXTENCODING_ASCII_US ).getStr() );
369 return true;
374 RTL_LOGFILE_PRODUCT_TRACE( "XMLSEC: No Mozilla Profile found!" );
375 return false;
379 } // namespace
381 SEInitializer_NssImpl::SEInitializer_NssImpl(
382 const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF)
383 :mxMSF( rxMSF )
387 SEInitializer_NssImpl::~SEInitializer_NssImpl()
391 /* XSEInitializer */
392 cssu::Reference< cssxc::XXMLSecurityContext > SAL_CALL
393 SEInitializer_NssImpl::createSecurityContext(
394 const rtl::OUString& sCertDB )
395 throw (cssu::RuntimeException)
397 CERTCertDBHandle *pCertHandle = NULL ;
399 rtl::OString sCertDir;
400 if( sCertDB.getLength() )
402 sCertDir = rtl::OString(sCertDB, sCertDB.getLength(), RTL_TEXTENCODING_ASCII_US);
404 else
406 static rtl::OString* pDefaultCertDir = NULL;
407 if ( !pDefaultCertDir )
409 pDefaultCertDir = new rtl::OString;
410 rtl::OUString ouCertDir;
414 if ( getMozillaCurrentProfile(mxMSF, ouCertDir) )
415 *pDefaultCertDir = rtl::OString(ouCertDir, ouCertDir.getLength(), RTL_TEXTENCODING_ASCII_US);
417 sCertDir = *pDefaultCertDir;
421 if( ! *initNSS( sCertDir.getStr() ) )
423 return NULL;
426 pCertHandle = CERT_GetDefaultCertDB() ;
430 /* Build XML Security Context */
431 const rtl::OUString sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT ) );
432 cssu::Reference< cssxc::XXMLSecurityContext > xSecCtx( mxMSF->createInstance ( sSecyrutyContext ), cssu::UNO_QUERY );
433 if( !xSecCtx.is() )
434 return NULL;
436 const rtl::OUString sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT ) );
437 cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv( mxMSF->createInstance ( sSecyrutyEnvironment ), cssu::UNO_QUERY );
438 cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;
439 if( !xEnvTunnel.is() )
440 return NULL;
441 SecurityEnvironment_NssImpl* pSecEnv = reinterpret_cast<SecurityEnvironment_NssImpl*>(
442 sal::static_int_cast<sal_uIntPtr>(
443 xEnvTunnel->getSomething(SecurityEnvironment_NssImpl::getUnoTunnelId() ))) ;
444 pSecEnv->setCertDb(pCertHandle);
446 sal_Int32 n = xSecCtx->addSecurityEnvironment(xSecEnv);
447 //originally the SecurityEnvironment with the internal slot was set as default
448 xSecCtx->setDefaultSecurityEnvironmentIndex( n );
449 return xSecCtx;
451 catch( cssu::Exception& )
453 //PK11_LogoutAll();
454 //NSS_Shutdown();
455 return NULL;
459 void SAL_CALL SEInitializer_NssImpl::freeSecurityContext( const cssu::Reference< cssxc::XXMLSecurityContext >& )
460 throw (cssu::RuntimeException)
463 * because the security context will free all its content when it
464 * is destructed, so here no free process for the security context
465 * is needed.
467 //PK11_LogoutAll();
468 //NSS_Shutdown();
471 rtl::OUString SEInitializer_NssImpl_getImplementationName ()
472 throw (cssu::RuntimeException)
475 return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
478 sal_Bool SAL_CALL SEInitializer_NssImpl_supportsService( const rtl::OUString& ServiceName )
479 throw (cssu::RuntimeException)
481 return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
484 cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl_getSupportedServiceNames( )
485 throw (cssu::RuntimeException)
487 cssu::Sequence < rtl::OUString > aRet(1);
488 rtl::OUString* pArray = aRet.getArray();
489 pArray[0] = rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
490 return aRet;
492 #undef SERVICE_NAME
494 cssu::Reference< cssu::XInterface > SAL_CALL SEInitializer_NssImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)
495 throw( cssu::Exception )
497 return (cppu::OWeakObject*) new SEInitializer_NssImpl(rSMgr);
500 /* XServiceInfo */
501 rtl::OUString SAL_CALL SEInitializer_NssImpl::getImplementationName( )
502 throw (cssu::RuntimeException)
504 return SEInitializer_NssImpl_getImplementationName();
506 sal_Bool SAL_CALL SEInitializer_NssImpl::supportsService( const rtl::OUString& rServiceName )
507 throw (cssu::RuntimeException)
509 return SEInitializer_NssImpl_supportsService( rServiceName );
511 cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl::getSupportedServiceNames( )
512 throw (cssu::RuntimeException)
514 return SEInitializer_NssImpl_getSupportedServiceNames();