1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: seinitializer_nssimpl.cxx,v $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 // MARKER(update_precomp.py): autogen include statement, do not remove
32 #include "precompiled_xmlsecurity.hxx"
35 * Turn off DEBUG Assertions
38 #define _DEBUG_WAS_DEFINED _DEBUG
41 #undef _DEBUG_WAS_DEFINED
45 * and turn off the additional virtual methods which are part of some interfaces when compiled
49 #define DEBUG_WAS_DEFINED DEBUG
52 #undef DEBUG_WAS_DEFINED
56 #include <sal/types.h>
57 #include "rtl/instance.hxx"
58 #include "rtl/bootstrap.hxx"
59 #include "rtl/string.hxx"
60 #include "rtl/strbuf.hxx"
61 #include "osl/file.hxx"
62 #include "osl/thread.h"
63 #include <tools/debug.hxx>
64 #include <rtl/logfile.hxx>
66 #include "seinitializer_nssimpl.hxx"
68 #include "securityenvironment_nssimpl.hxx"
69 #include <com/sun/star/mozilla/XMozillaBootstrap.hpp>
78 namespace cssu
= com::sun::star::uno
;
79 namespace cssl
= com::sun::star::lang
;
80 namespace cssxc
= com::sun::star::xml::crypto
;
82 using namespace com::sun::star
;
83 using ::rtl::OUString
;
86 #define SERVICE_NAME "com.sun.star.xml.crypto.SEInitializer"
87 #define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.SEInitializer_NssImpl"
88 #define SECURITY_ENVIRONMENT "com.sun.star.xml.crypto.SecurityEnvironment"
89 #define SECURITY_CONTEXT "com.sun.star.xml.crypto.XMLSecurityContext"
92 #define ROOT_CERTS "Root Certs for OpenOffice.org"
95 extern "C" void nsscrypto_finalize();
101 bool nsscrypto_initialize( const char * sProfile
, bool & out_nss_init
);
103 struct InitNSSInitialize
105 //path to the database folder
106 const OString m_sProfile
;
107 InitNSSInitialize(const OString
& sProfile
): m_sProfile(sProfile
) {};
110 static bool bInitialized
= false;
111 bool bNSSInit
= false;
112 bInitialized
= nsscrypto_initialize(m_sProfile
.getStr(), bNSSInit
);
114 atexit(nsscrypto_finalize
);
115 return & bInitialized
;
120 bool * initNSS(const OString
& sProfile
)
122 return rtl_Instance
< bool, InitNSSInitialize
,
123 ::osl::MutexGuard
, ::osl::GetGlobalMutex
>::create(
124 InitNSSInitialize(sProfile
), ::osl::GetGlobalMutex());
127 void deleteRootsModule()
129 SECMODModule
*RootsModule
= 0;
130 SECMODModuleList
*list
= SECMOD_GetDefaultModuleList();
131 SECMODListLock
*lock
= SECMOD_GetDefaultModuleListLock();
132 SECMOD_GetReadLock(lock
);
134 while (!RootsModule
&& list
)
136 SECMODModule
*module
= list
->module
;
138 for (int i
=0; i
< module
->slotCount
; i
++)
140 PK11SlotInfo
*slot
= module
->slots
[i
];
141 if (PK11_IsPresent(slot
))
143 if (PK11_HasRootCerts(slot
))
145 OSL_TRACE("[xmlsecurity] The root certifificates module \"%s"
146 "\" is already loaded: \n%s",
147 module
->commonName
, module
->dllName
);
149 RootsModule
= SECMOD_ReferenceModule(module
);
156 SECMOD_ReleaseReadLock(lock
);
161 if (SECSuccess
== SECMOD_DeleteModule(RootsModule
->commonName
, &modType
))
163 OSL_TRACE("[xmlsecurity] Deleted module \"%s\".", RootsModule
->commonName
);
167 OSL_TRACE("[xmlsecurity] Failed to delete \"%s\" : \n%s",
168 RootsModule
->commonName
, RootsModule
->dllName
);
170 SECMOD_DestroyModule(RootsModule
);
175 //Older versions of Firefox (FF), for example FF2, and Thunderbird (TB) 2 write
176 //the roots certificate module (libnssckbi.so), which they use, into the
177 //profile. This module will then already be loaded during NSS_Init (and the
178 //other init functions). This fails in two cases. First, FF3 was used to create
179 //the profile, or possibly used that profile before, and second the profile was
180 //used on a different platform.
182 //Then one needs to add the roots module oneself. This should be done with
183 //SECMOD_LoadUserModule rather then SECMOD_AddNewModule. The latter would write
184 //the location of the roots module to the profile, which makes FF2 and TB2 use
185 //it instead of there own module.
187 //When using SYSTEM_MOZILLA then the libnss3.so lib is typically found in
188 ///usr/lib. This folder may, however, NOT contain the roots certificate
189 //module. That is, just providing the library name in SECMOD_LoadUserModule or
190 //SECMOD_AddNewModule will FAIL to load the mozilla unless the LD_LIBRARY_PATH
191 //contains an FF or TB installation.
192 //ATTENTION: DO NOT call this function directly instead use initNSS
193 //return true - whole initialization was successful
194 //param out_nss_init = true: at least the NSS initialization (NSS_InitReadWrite
195 //was successful and therefor NSS_Shutdown should be called when terminating.
196 bool nsscrypto_initialize( const char* token
, bool & out_nss_init
)
198 bool return_value
= true;
200 OSL_TRACE("[xmlsecurity] Using profile: %s", token
);
202 PR_Init( PR_USER_THREAD
, PR_PRIORITY_NORMAL
, 1 ) ;
204 if( NSS_InitReadWrite( token
) != SECSuccess
)
208 PR_GetErrorText(error
);
215 #if defined SYSTEM_MOZILLA
216 if (!SECMOD_HasRootCerts())
221 #if defined SYSTEM_MOZILLA
222 OUString
rootModule(RTL_CONSTASCII_USTRINGPARAM("libnssckbi"SAL_DLLEXTENSION
));
224 OUString
rootModule(RTL_CONSTASCII_USTRINGPARAM("${OOO_BASE_DIR}/program/libnssckbi"SAL_DLLEXTENSION
));
226 ::rtl::Bootstrap::expandMacros(rootModule
);
228 OUString rootModulePath
;
229 if (::osl::File::E_None
== ::osl::File::getSystemPathFromFileURL(rootModule
, rootModulePath
))
231 ::rtl::OString ospath
= ::rtl::OUStringToOString(rootModulePath
, osl_getThreadTextEncoding());
232 ::rtl::OStringBuffer pkcs11moduleSpec
;
233 pkcs11moduleSpec
.append("name=\"");
234 pkcs11moduleSpec
.append(ROOT_CERTS
);
235 pkcs11moduleSpec
.append("\" library=\"");
236 pkcs11moduleSpec
.append(ospath
.getStr());
237 pkcs11moduleSpec
.append("\"");
239 SECMODModule
* RootsModule
=
240 SECMOD_LoadUserModule(
241 const_cast<char*>(pkcs11moduleSpec
.makeStringAndClear().getStr()),
243 PR_FALSE
); // do not recurse
248 bool found
= RootsModule
->loaded
;
250 SECMOD_DestroyModule(RootsModule
);
253 OSL_TRACE("[xmlsecurity] Added new root certificate module "
254 "\""ROOT_CERTS
"\" contained in \n%s", ospath
.getStr());
257 OSL_TRACE("[xmlsecurity] FAILED to load the new root certificate module "
258 "\""ROOT_CERTS
"\" contained in \n%s", ospath
.getStr());
259 return_value
= false;
264 OSL_TRACE("[xmlsecurity] FAILED to add new root certifice module: "
265 "\""ROOT_CERTS
"\" contained in \n%s", ospath
.getStr());
266 return_value
= false;
272 OSL_TRACE("[xmlsecurity] Adding new root certificate module failed.");
273 return_value
= false;
283 // must be extern "C" because we pass the function pointer to atexit
284 extern "C" void nsscrypto_finalize()
286 SECMODModule
*RootsModule
= SECMOD_FindModule(ROOT_CERTS
);
291 if (SECSuccess
== SECMOD_UnloadUserModule(RootsModule
))
293 OSL_TRACE("[xmlsecurity] Unloaded module \""ROOT_CERTS
"\".");
297 OSL_TRACE("[xmlsecurity] Failed unloadeding module \""ROOT_CERTS
"\".");
299 SECMOD_DestroyModule(RootsModule
);
303 OSL_TRACE("[xmlsecurity] Unloading module \""ROOT_CERTS
304 "\" failed because it was not found.");
311 bool getMozillaCurrentProfile(
312 const com::sun::star::uno::Reference
< com::sun::star::lang::XMultiServiceFactory
> &rxMSF
,
313 rtl::OUString
& profilePath
)
316 * first, try to get the profile from "MOZILLA_CERTIFICATE_FOLDER"
318 char * env
= getenv("MOZILLA_CERTIFICATE_FOLDER");
321 profilePath
= rtl::OUString::createFromAscii( env
);
322 RTL_LOGFILE_PRODUCT_TRACE1( "XMLSEC: Using env MOZILLA_CERTIFICATE_FOLDER: %s", rtl::OUStringToOString( profilePath
, RTL_TEXTENCODING_ASCII_US
).getStr() );
327 RTL_LOGFILE_TRACE( "getMozillaCurrentProfile: Using MozillaBootstrap..." );
328 mozilla::MozillaProductType productTypes
[4] = {
329 mozilla::MozillaProductType_Thunderbird
,
330 mozilla::MozillaProductType_Mozilla
,
331 mozilla::MozillaProductType_Firefox
,
332 mozilla::MozillaProductType_Default
};
335 uno::Reference
<uno::XInterface
> xInstance
= rxMSF
->createInstance(
336 ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")) );
337 OSL_ENSURE( xInstance
.is(), "failed to create instance" );
339 uno::Reference
<mozilla::XMozillaBootstrap
> xMozillaBootstrap
340 = uno::Reference
<mozilla::XMozillaBootstrap
>(xInstance
,uno::UNO_QUERY
);
341 OSL_ENSURE( xMozillaBootstrap
.is(), "failed to create instance" );
343 if (xMozillaBootstrap
.is())
345 for (int i
=0; i
<nProduct
; i
++)
347 ::rtl::OUString profile
= xMozillaBootstrap
->getDefaultProfile(productTypes
[i
]);
349 RTL_LOGFILE_TRACE2( "getMozillaCurrentProfile: getDefaultProfile [%i] returns %s", i
, rtl::OUStringToOString( profile
, RTL_TEXTENCODING_ASCII_US
).getStr() );
351 if (profile
!= NULL
&& profile
.getLength()>0)
353 profilePath
= xMozillaBootstrap
->getProfilePath(productTypes
[i
],profile
);
354 RTL_LOGFILE_PRODUCT_TRACE1( "XMLSEC: Using Mozilla Profile: %s", rtl::OUStringToOString( profilePath
, RTL_TEXTENCODING_ASCII_US
).getStr() );
360 RTL_LOGFILE_PRODUCT_TRACE( "XMLSEC: No Mozilla Profile found!" );
367 SEInitializer_NssImpl::SEInitializer_NssImpl(
368 const com::sun::star::uno::Reference
< com::sun::star::lang::XMultiServiceFactory
> &rxMSF
)
373 SEInitializer_NssImpl::~SEInitializer_NssImpl()
378 cssu::Reference
< cssxc::XXMLSecurityContext
> SAL_CALL
379 SEInitializer_NssImpl::createSecurityContext(
380 const rtl::OUString
& sCertDB
)
381 throw (cssu::RuntimeException
)
383 CERTCertDBHandle
*pCertHandle
= NULL
;
385 rtl::OString sCertDir
;
386 if( sCertDB
.getLength() )
388 sCertDir
= rtl::OString(sCertDB
, sCertDB
.getLength(), RTL_TEXTENCODING_ASCII_US
);
392 static rtl::OString
* pDefaultCertDir
= NULL
;
393 if ( !pDefaultCertDir
)
395 pDefaultCertDir
= new rtl::OString
;
396 rtl::OUString ouCertDir
;
400 if ( getMozillaCurrentProfile(mxMSF
, ouCertDir
) )
401 *pDefaultCertDir
= rtl::OString(ouCertDir
, ouCertDir
.getLength(), RTL_TEXTENCODING_ASCII_US
);
403 sCertDir
= *pDefaultCertDir
;
407 if( !sCertDir
.getLength() )
409 RTL_LOGFILE_TRACE( "XMLSEC: Error - No certificate directory!" );
414 /* Initialize NSPR and NSS */
415 /* Replaced with new methods by AF. ----
416 //PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1 ) ;
417 PR_Init( PR_USER_THREAD, PR_PRIORITY_NORMAL, 1 ) ;
419 if (NSS_Init(sCertDir.getStr()) != SECSuccess )
425 if( ! *initNSS( sCertDir
.getStr() ) )
427 RTL_LOGFILE_TRACE( "XMLSEC: Error - nsscrypto_initialize() failed." );
428 if ( NSS_NoDB_Init(NULL
) != SECSuccess
)
430 RTL_LOGFILE_TRACE( "XMLSEC: NSS_NoDB_Init also failed, NSS Security not available!" );
435 RTL_LOGFILE_TRACE( "XMLSEC: NSS_NoDB_Init works, enough for verifying signatures..." );
439 pCertHandle
= CERT_GetDefaultCertDB() ;
443 /* Build XML Security Context */
444 const rtl::OUString
sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT
) );
445 cssu::Reference
< cssxc::XXMLSecurityContext
> xSecCtx( mxMSF
->createInstance ( sSecyrutyContext
), cssu::UNO_QUERY
);
449 const rtl::OUString
sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT
) );
450 cssu::Reference
< cssxc::XSecurityEnvironment
> xSecEnv( mxMSF
->createInstance ( sSecyrutyEnvironment
), cssu::UNO_QUERY
);
451 cssu::Reference
< cssl::XUnoTunnel
> xEnvTunnel( xSecEnv
, cssu::UNO_QUERY
) ;
452 if( !xEnvTunnel
.is() )
454 SecurityEnvironment_NssImpl
* pSecEnv
= reinterpret_cast<SecurityEnvironment_NssImpl
*>(
455 sal::static_int_cast
<sal_uIntPtr
>(
456 xEnvTunnel
->getSomething(SecurityEnvironment_NssImpl::getUnoTunnelId() ))) ;
457 pSecEnv
->setCertDb(pCertHandle
);
459 sal_Int32 n
= xSecCtx
->addSecurityEnvironment(xSecEnv
);
460 //originally the SecurityEnvironment with the internal slot was set as default
461 xSecCtx
->setDefaultSecurityEnvironmentIndex( n
);
464 catch( cssu::Exception
& )
472 void SAL_CALL
SEInitializer_NssImpl::freeSecurityContext( const cssu::Reference
< cssxc::XXMLSecurityContext
>& )
473 throw (cssu::RuntimeException
)
476 * because the security context will free all its content when it
477 * is destructed, so here no free process for the security context
484 rtl::OUString
SEInitializer_NssImpl_getImplementationName ()
485 throw (cssu::RuntimeException
)
488 return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME
) );
491 sal_Bool SAL_CALL
SEInitializer_NssImpl_supportsService( const rtl::OUString
& ServiceName
)
492 throw (cssu::RuntimeException
)
494 return ServiceName
.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME
));
497 cssu::Sequence
< rtl::OUString
> SAL_CALL
SEInitializer_NssImpl_getSupportedServiceNames( )
498 throw (cssu::RuntimeException
)
500 cssu::Sequence
< rtl::OUString
> aRet(1);
501 rtl::OUString
* pArray
= aRet
.getArray();
502 pArray
[0] = rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME
) );
507 cssu::Reference
< cssu::XInterface
> SAL_CALL
SEInitializer_NssImpl_createInstance( const cssu::Reference
< cssl::XMultiServiceFactory
> & rSMgr
)
508 throw( cssu::Exception
)
510 return (cppu::OWeakObject
*) new SEInitializer_NssImpl(rSMgr
);
514 rtl::OUString SAL_CALL
SEInitializer_NssImpl::getImplementationName( )
515 throw (cssu::RuntimeException
)
517 return SEInitializer_NssImpl_getImplementationName();
519 sal_Bool SAL_CALL
SEInitializer_NssImpl::supportsService( const rtl::OUString
& rServiceName
)
520 throw (cssu::RuntimeException
)
522 return SEInitializer_NssImpl_supportsService( rServiceName
);
524 cssu::Sequence
< rtl::OUString
> SAL_CALL
SEInitializer_NssImpl::getSupportedServiceNames( )
525 throw (cssu::RuntimeException
)
527 return SEInitializer_NssImpl_getSupportedServiceNames();