Line data Source code
1 : /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 : /*
3 : * This file is part of the LibreOffice project.
4 : *
5 : * This Source Code Form is subject to the terms of the Mozilla Public
6 : * License, v. 2.0. If a copy of the MPL was not distributed with this
7 : * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 : *
9 : * This file incorporates work covered by the following license notice:
10 : *
11 : * Licensed to the Apache Software Foundation (ASF) under one or more
12 : * contributor license agreements. See the NOTICE file distributed
13 : * with this work for additional information regarding copyright
14 : * ownership. The ASF licenses this file to you under the Apache
15 : * License, Version 2.0 (the "License"); you may not use this file
16 : * except in compliance with the License. You may obtain a copy of
17 : * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 : */
19 :
20 :
21 : /*
22 : * Turn off DEBUG Assertions
23 : */
24 : #ifdef _DEBUG
25 : #define _DEBUG_WAS_DEFINED _DEBUG
26 : #undef _DEBUG
27 : #else
28 : #undef _DEBUG_WAS_DEFINED
29 : #endif
30 :
31 : /*
32 : * and turn off the additional virtual methods which are part of some interfaces when compiled
33 : * with debug
34 : */
35 : #ifdef DEBUG
36 : #define DEBUG_WAS_DEFINED DEBUG
37 : #undef DEBUG
38 : #else
39 : #undef DEBUG_WAS_DEFINED
40 : #endif
41 :
42 :
43 : #include <com/sun/star/mozilla/XMozillaBootstrap.hpp>
44 : #include <com/sun/star/xml/crypto/DigestID.hpp>
45 : #include <com/sun/star/xml/crypto/CipherID.hpp>
46 :
47 : #include <officecfg/Office/Common.hxx>
48 :
49 : #include <sal/types.h>
50 : #include <rtl/instance.hxx>
51 : #include <rtl/bootstrap.hxx>
52 : #include <rtl/string.hxx>
53 : #include <rtl/strbuf.hxx>
54 : #include <osl/file.hxx>
55 : #include <osl/thread.h>
56 : #include <sal/log.hxx>
57 :
58 : #include "seinitializer_nssimpl.hxx"
59 : #include "../diagnose.hxx"
60 :
61 : #include "securityenvironment_nssimpl.hxx"
62 : #include "digestcontext.hxx"
63 : #include "ciphercontext.hxx"
64 :
65 : #include <nspr.h>
66 : #include <cert.h>
67 : #include <nss.h>
68 : #include <pk11pub.h>
69 : #include <secmod.h>
70 : #include <nssckbi.h>
71 :
72 : namespace cssu = css::uno;
73 : namespace cssl = css::lang;
74 :
75 : using namespace xmlsecurity;
76 : using namespace com::sun::star;
77 : using ::rtl::OUString;
78 : using ::rtl::OString;
79 :
80 : #define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.NSSInitializer_NssImpl"
81 :
82 : #define ROOT_CERTS "Root Certs for OpenOffice.org"
83 :
84 : extern "C" void nsscrypto_finalize();
85 :
86 :
87 : namespace
88 : {
89 :
90 : bool nsscrypto_initialize( const css::uno::Reference< css::uno::XComponentContext > &rxContext, bool & out_nss_init );
91 :
92 36 : struct InitNSSInitialize
93 : {
94 : css::uno::Reference< css::uno::XComponentContext > m_xContext;
95 :
96 36 : InitNSSInitialize( const css::uno::Reference< css::uno::XComponentContext > &rxContext )
97 36 : : m_xContext( rxContext )
98 : {
99 36 : }
100 :
101 2 : bool * operator()()
102 : {
103 : static bool bInitialized = false;
104 2 : bool bNSSInit = false;
105 2 : bInitialized = nsscrypto_initialize( m_xContext, bNSSInit );
106 2 : if (bNSSInit)
107 2 : atexit(nsscrypto_finalize );
108 2 : return & bInitialized;
109 : }
110 : };
111 :
112 : struct GetNSSInitStaticMutex
113 : {
114 2 : ::osl::Mutex* operator()()
115 : {
116 2 : static ::osl::Mutex aNSSInitMutex;
117 2 : return &aNSSInitMutex;
118 : }
119 : };
120 :
121 2 : void deleteRootsModule()
122 : {
123 2 : SECMODModule *RootsModule = 0;
124 2 : SECMODModuleList *list = SECMOD_GetDefaultModuleList();
125 2 : SECMODListLock *lock = SECMOD_GetDefaultModuleListLock();
126 2 : SECMOD_GetReadLock(lock);
127 :
128 6 : while (!RootsModule && list)
129 : {
130 2 : SECMODModule *module = list->module;
131 :
132 6 : for (int i=0; i < module->slotCount; i++)
133 : {
134 4 : PK11SlotInfo *slot = module->slots[i];
135 4 : if (PK11_IsPresent(slot))
136 : {
137 4 : if (PK11_HasRootCerts(slot))
138 : {
139 : xmlsec_trace("The root certifificates module \"%s"
140 : "\" is already loaded: \n%s",
141 0 : module->commonName, module->dllName);
142 :
143 0 : RootsModule = SECMOD_ReferenceModule(module);
144 0 : break;
145 : }
146 : }
147 : }
148 2 : list = list->next;
149 : }
150 2 : SECMOD_ReleaseReadLock(lock);
151 :
152 2 : if (RootsModule)
153 : {
154 : PRInt32 modType;
155 0 : if (SECSuccess == SECMOD_DeleteModule(RootsModule->commonName, &modType))
156 : {
157 0 : xmlsec_trace("Deleted module \"%s\".", RootsModule->commonName);
158 : }
159 : else
160 : {
161 : xmlsec_trace("Failed to delete \"%s\" : \n%s",
162 0 : RootsModule->commonName, RootsModule->dllName);
163 : }
164 0 : SECMOD_DestroyModule(RootsModule);
165 0 : RootsModule = 0;
166 : }
167 2 : }
168 :
169 2 : ::rtl::OString getMozillaCurrentProfile( const css::uno::Reference< css::uno::XComponentContext > &rxContext )
170 : {
171 : // first, try to get the profile from "MOZILLA_CERTIFICATE_FOLDER"
172 2 : const char* pEnv = getenv("MOZILLA_CERTIFICATE_FOLDER");
173 2 : if (pEnv)
174 : {
175 : SAL_INFO(
176 : "xmlsecurity.xmlsec",
177 : "Using Mozilla profile from MOZILLA_CERTIFICATE_FOLDER=" << pEnv);
178 0 : return rtl::OString(pEnv);
179 : }
180 :
181 : // second, try to get saved user-preference
182 : try
183 : {
184 : rtl::OUString sUserSetCertPath =
185 2 : officecfg::Office::Common::Security::Scripting::CertDir::get().get_value_or(rtl::OUString());
186 :
187 2 : if (!sUserSetCertPath.isEmpty())
188 : {
189 : SAL_INFO(
190 : "xmlsecurity.xmlsec",
191 : "Using Mozilla profile from /org.openoffice.Office.Common/"
192 : "Security/Scripting/CertDir: " << sUserSetCertPath);
193 0 : return rtl::OUStringToOString(sUserSetCertPath, osl_getThreadTextEncoding());
194 2 : }
195 : }
196 0 : catch (const uno::Exception &e)
197 : {
198 : SAL_WARN(
199 : "xmlsecurity.xmlsec",
200 : "getMozillaCurrentProfile: caught exception " << e.Message);
201 : }
202 :
203 : // third, dig around to see if there's one available
204 : mozilla::MozillaProductType productTypes[3] = {
205 : mozilla::MozillaProductType_Thunderbird,
206 : mozilla::MozillaProductType_Firefox,
207 2 : mozilla::MozillaProductType_Mozilla };
208 2 : int nProduct = SAL_N_ELEMENTS(productTypes);
209 :
210 2 : uno::Reference<uno::XInterface> xInstance = rxContext->getServiceManager()->createInstanceWithContext("com.sun.star.mozilla.MozillaBootstrap", rxContext);
211 : OSL_ENSURE( xInstance.is(), "failed to create instance" );
212 :
213 : uno::Reference<mozilla::XMozillaBootstrap> xMozillaBootstrap
214 2 : = uno::Reference<mozilla::XMozillaBootstrap>(xInstance,uno::UNO_QUERY);
215 : OSL_ENSURE( xMozillaBootstrap.is(), "failed to create instance" );
216 :
217 2 : if (xMozillaBootstrap.is())
218 : {
219 0 : for (int i=0; i<nProduct; ++i)
220 : {
221 0 : rtl::OUString profile = xMozillaBootstrap->getDefaultProfile(productTypes[i]);
222 :
223 0 : if (!profile.isEmpty())
224 : {
225 0 : rtl::OUString sProfilePath = xMozillaBootstrap->getProfilePath( productTypes[i], profile );
226 : SAL_INFO(
227 : "xmlsecurity.xmlsec",
228 : "Using Mozilla profile " << sProfilePath);
229 0 : return rtl::OUStringToOString(sProfilePath, osl_getThreadTextEncoding());
230 : }
231 0 : }
232 : }
233 :
234 : SAL_INFO("xmlsecurity.xmlsec", "No Mozilla profile found");
235 2 : return rtl::OString();
236 : }
237 :
238 : //Older versions of Firefox (FF), for example FF2, and Thunderbird (TB) 2 write
239 : //the roots certificate module (libnssckbi.so), which they use, into the
240 : //profile. This module will then already be loaded during NSS_Init (and the
241 : //other init functions). This fails in two cases. First, FF3 was used to create
242 : //the profile, or possibly used that profile before, and second the profile was
243 : //used on a different platform.
244 : //
245 : //Then one needs to add the roots module oneself. This should be done with
246 : //SECMOD_LoadUserModule rather then SECMOD_AddNewModule. The latter would write
247 : //the location of the roots module to the profile, which makes FF2 and TB2 use
248 : //it instead of there own module.
249 : //
250 : //When using SYSTEM_NSS then the libnss3.so lib is typically found in /usr/lib.
251 : //This folder may, however, NOT contain the roots certificate module. That is,
252 : //just providing the library name in SECMOD_LoadUserModule or
253 : //SECMOD_AddNewModule will FAIL to load the mozilla unless the LD_LIBRARY_PATH
254 : //contains an FF or TB installation.
255 : //ATTENTION: DO NOT call this function directly instead use initNSS
256 : //return true - whole initialization was successful
257 : //param out_nss_init = true: at least the NSS initialization (NSS_InitReadWrite
258 : //was successful and therefor NSS_Shutdown should be called when terminating.
259 2 : bool nsscrypto_initialize( const css::uno::Reference< css::uno::XComponentContext > &rxContext, bool & out_nss_init )
260 : {
261 2 : bool return_value = true;
262 :
263 : // this method must be called only once, no need for additional lock
264 2 : rtl::OString sCertDir;
265 :
266 : #ifdef XMLSEC_CRYPTO_NSS
267 2 : sCertDir = getMozillaCurrentProfile(rxContext);
268 : #else
269 : (void) rxContext;
270 : #endif
271 2 : xmlsec_trace( "Using profile: %s", sCertDir.getStr() );
272 :
273 2 : PR_Init( PR_USER_THREAD, PR_PRIORITY_NORMAL, 1 ) ;
274 :
275 2 : bool bSuccess = true;
276 : // there might be no profile
277 2 : if ( !sCertDir.isEmpty() )
278 : {
279 0 : if( NSS_InitReadWrite( sCertDir.getStr() ) != SECSuccess )
280 : {
281 0 : xmlsec_trace("Initializing NSS with profile failed.");
282 0 : char * error = NULL;
283 :
284 0 : PR_GetErrorText(error);
285 0 : if (error)
286 0 : xmlsec_trace("%s",error);
287 0 : bSuccess = false;
288 : }
289 : }
290 :
291 2 : if( sCertDir.isEmpty() || !bSuccess )
292 : {
293 2 : xmlsec_trace("Initializing NSS without profile.");
294 2 : if ( NSS_NoDB_Init(NULL) != SECSuccess )
295 : {
296 0 : xmlsec_trace("Initializing NSS without profile failed.");
297 0 : char * error = NULL;
298 0 : PR_GetErrorText(error);
299 0 : if (error)
300 0 : xmlsec_trace("%s",error);
301 0 : return false ;
302 : }
303 : }
304 2 : out_nss_init = true;
305 :
306 : #ifdef XMLSEC_CRYPTO_NSS
307 : #if defined SYSTEM_NSS
308 2 : if (!SECMOD_HasRootCerts())
309 : #endif
310 : {
311 2 : deleteRootsModule();
312 :
313 : #if defined SYSTEM_NSS
314 2 : OUString rootModule(RTL_CONSTASCII_USTRINGPARAM("libnssckbi" SAL_DLLEXTENSION));
315 : #else
316 : OUString rootModule(RTL_CONSTASCII_USTRINGPARAM("${LO_LIB_DIR}/libnssckbi" SAL_DLLEXTENSION));
317 : #endif
318 2 : ::rtl::Bootstrap::expandMacros(rootModule);
319 :
320 2 : OUString rootModulePath;
321 2 : if (::osl::File::E_None == ::osl::File::getSystemPathFromFileURL(rootModule, rootModulePath))
322 : {
323 2 : ::rtl::OString ospath = ::rtl::OUStringToOString(rootModulePath, osl_getThreadTextEncoding());
324 2 : ::rtl::OStringBuffer pkcs11moduleSpec;
325 2 : pkcs11moduleSpec.append("name=\"");
326 2 : pkcs11moduleSpec.append(ROOT_CERTS);
327 2 : pkcs11moduleSpec.append("\" library=\"");
328 2 : pkcs11moduleSpec.append(ospath.getStr());
329 2 : pkcs11moduleSpec.append("\"");
330 :
331 : SECMODModule * RootsModule =
332 : SECMOD_LoadUserModule(
333 4 : const_cast<char*>(pkcs11moduleSpec.makeStringAndClear().getStr()),
334 : 0, // no parent
335 2 : PR_FALSE); // do not recurse
336 :
337 2 : if (RootsModule)
338 : {
339 :
340 2 : bool found = RootsModule->loaded;
341 :
342 2 : SECMOD_DestroyModule(RootsModule);
343 2 : RootsModule = 0;
344 2 : if (found)
345 : xmlsec_trace("Added new root certificate module "
346 2 : "\"" ROOT_CERTS "\" contained in \n%s", ospath.getStr());
347 : else
348 : {
349 : xmlsec_trace("FAILED to load the new root certificate module "
350 0 : "\"" ROOT_CERTS "\" contained in \n%s", ospath.getStr());
351 0 : return_value = false;
352 : }
353 : }
354 : else
355 : {
356 : xmlsec_trace("FAILED to add new root certifice module: "
357 0 : "\"" ROOT_CERTS "\" contained in \n%s", ospath.getStr());
358 0 : return_value = false;
359 :
360 2 : }
361 : }
362 : else
363 : {
364 0 : xmlsec_trace("Adding new root certificate module failed.");
365 0 : return_value = false;
366 2 : }
367 : }
368 : #endif
369 :
370 2 : return return_value;
371 : }
372 :
373 :
374 : // must be extern "C" because we pass the function pointer to atexit
375 2 : extern "C" void nsscrypto_finalize()
376 : {
377 2 : SECMODModule *RootsModule = SECMOD_FindModule(ROOT_CERTS);
378 :
379 2 : if (RootsModule)
380 : {
381 :
382 2 : if (SECSuccess == SECMOD_UnloadUserModule(RootsModule))
383 : {
384 2 : xmlsec_trace("Unloaded module \"" ROOT_CERTS "\".");
385 : }
386 : else
387 : {
388 0 : xmlsec_trace("Failed unloading module \"" ROOT_CERTS "\".");
389 : }
390 2 : SECMOD_DestroyModule(RootsModule);
391 : }
392 : else
393 : {
394 : xmlsec_trace("Unloading module \"" ROOT_CERTS
395 0 : "\" failed because it was not found.");
396 : }
397 2 : PK11_LogoutAll();
398 2 : NSS_Shutdown();
399 2 : }
400 : } // namespace
401 :
402 0 : ONSSInitializer::ONSSInitializer(
403 : const css::uno::Reference< css::uno::XComponentContext > &rxContext)
404 0 : :m_xContext( rxContext )
405 : {
406 0 : }
407 :
408 36 : ONSSInitializer::~ONSSInitializer()
409 : {
410 36 : }
411 :
412 36 : bool ONSSInitializer::initNSS( const css::uno::Reference< css::uno::XComponentContext > &rxContext )
413 : {
414 : return *rtl_Instance< bool, InitNSSInitialize, ::osl::MutexGuard, GetNSSInitStaticMutex >
415 36 : ::create( InitNSSInitialize( rxContext ), GetNSSInitStaticMutex() );
416 : }
417 :
418 16 : css::uno::Reference< css::xml::crypto::XDigestContext > SAL_CALL ONSSInitializer::getDigestContext( ::sal_Int32 nDigestID, const css::uno::Sequence< css::beans::NamedValue >& aParams )
419 : throw (css::lang::IllegalArgumentException, css::uno::RuntimeException)
420 : {
421 16 : SECOidTag nNSSDigestID = SEC_OID_UNKNOWN;
422 16 : sal_Int32 nDigestLength = 0;
423 16 : bool b1KData = false;
424 16 : if ( nDigestID == css::xml::crypto::DigestID::SHA256
425 : || nDigestID == css::xml::crypto::DigestID::SHA256_1K )
426 : {
427 16 : nNSSDigestID = SEC_OID_SHA256;
428 16 : nDigestLength = 32;
429 16 : b1KData = ( nDigestID == css::xml::crypto::DigestID::SHA256_1K );
430 : }
431 0 : else if ( nDigestID == css::xml::crypto::DigestID::SHA1
432 : || nDigestID == css::xml::crypto::DigestID::SHA1_1K )
433 : {
434 0 : nNSSDigestID = SEC_OID_SHA1;
435 0 : nDigestLength = 20;
436 0 : b1KData = ( nDigestID == css::xml::crypto::DigestID::SHA1_1K );
437 : }
438 : else
439 0 : throw css::lang::IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Unexpected digest requested." ) ), css::uno::Reference< css::uno::XInterface >(), 1 );
440 :
441 16 : if ( aParams.getLength() )
442 0 : throw css::lang::IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Unexpected arguments provided for digest creation." ) ), css::uno::Reference< css::uno::XInterface >(), 2 );
443 :
444 16 : css::uno::Reference< css::xml::crypto::XDigestContext > xResult;
445 16 : if( initNSS( m_xContext ) )
446 : {
447 16 : PK11Context* pContext = PK11_CreateDigestContext( nNSSDigestID );
448 16 : if ( pContext && PK11_DigestBegin( pContext ) == SECSuccess )
449 16 : xResult = new ODigestContext( pContext, nDigestLength, b1KData );
450 : }
451 :
452 16 : return xResult;
453 : }
454 :
455 20 : css::uno::Reference< css::xml::crypto::XCipherContext > SAL_CALL ONSSInitializer::getCipherContext( ::sal_Int32 nCipherID, const css::uno::Sequence< ::sal_Int8 >& aKey, const css::uno::Sequence< ::sal_Int8 >& aInitializationVector, ::sal_Bool bEncryption, const css::uno::Sequence< css::beans::NamedValue >& aParams )
456 : throw (css::lang::IllegalArgumentException, css::uno::RuntimeException)
457 : {
458 20 : CK_MECHANISM_TYPE nNSSCipherID = 0;
459 20 : bool bW3CPadding = false;
460 20 : if ( nCipherID == css::xml::crypto::CipherID::AES_CBC_W3C_PADDING )
461 : {
462 20 : nNSSCipherID = CKM_AES_CBC;
463 20 : bW3CPadding = true;
464 :
465 20 : if ( aKey.getLength() != 16 && aKey.getLength() != 24 && aKey.getLength() != 32 )
466 0 : throw css::lang::IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Unexpected key length." ) ), css::uno::Reference< css::uno::XInterface >(), 2 );
467 :
468 20 : if ( aParams.getLength() )
469 0 : throw css::lang::IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Unexpected arguments provided for cipher creation." ) ), css::uno::Reference< css::uno::XInterface >(), 5 );
470 : }
471 : else
472 0 : throw css::lang::IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Unexpected cipher requested." ) ), css::uno::Reference< css::uno::XInterface >(), 1 );
473 :
474 20 : css::uno::Reference< css::xml::crypto::XCipherContext > xResult;
475 20 : if( initNSS( m_xContext ) )
476 : {
477 20 : if ( aInitializationVector.getLength() != PK11_GetIVLength( nNSSCipherID ) )
478 0 : throw css::lang::IllegalArgumentException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Unexpected length of initialization vector." ) ), css::uno::Reference< css::uno::XInterface >(), 3 );
479 :
480 20 : xResult = OCipherContext::Create( nNSSCipherID, aKey, aInitializationVector, bEncryption, bW3CPadding );
481 : }
482 :
483 20 : return xResult;
484 : }
485 :
486 0 : rtl::OUString ONSSInitializer_getImplementationName ()
487 : throw (cssu::RuntimeException)
488 : {
489 :
490 0 : return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
491 : }
492 :
493 0 : sal_Bool SAL_CALL ONSSInitializer_supportsService( const rtl::OUString& ServiceName )
494 : throw (cssu::RuntimeException)
495 : {
496 0 : return ServiceName == NSS_SERVICE_NAME;
497 : }
498 :
499 0 : cssu::Sequence< rtl::OUString > SAL_CALL ONSSInitializer_getSupportedServiceNames( )
500 : throw (cssu::RuntimeException)
501 : {
502 0 : cssu::Sequence < rtl::OUString > aRet(1);
503 0 : rtl::OUString* pArray = aRet.getArray();
504 0 : pArray[0] = rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( NSS_SERVICE_NAME ) );
505 0 : return aRet;
506 : }
507 :
508 0 : cssu::Reference< cssu::XInterface > SAL_CALL ONSSInitializer_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)
509 : throw( cssu::Exception )
510 : {
511 0 : return (cppu::OWeakObject*) new ONSSInitializer( comphelper::getComponentContext(rSMgr) );
512 : }
513 :
514 : /* XServiceInfo */
515 0 : rtl::OUString SAL_CALL ONSSInitializer::getImplementationName()
516 : throw (cssu::RuntimeException)
517 : {
518 0 : return ONSSInitializer_getImplementationName();
519 : }
520 0 : sal_Bool SAL_CALL ONSSInitializer::supportsService( const rtl::OUString& rServiceName )
521 : throw (cssu::RuntimeException)
522 : {
523 0 : return ONSSInitializer_supportsService( rServiceName );
524 : }
525 0 : cssu::Sequence< rtl::OUString > SAL_CALL ONSSInitializer::getSupportedServiceNames( )
526 : throw (cssu::RuntimeException)
527 : {
528 0 : return ONSSInitializer_getSupportedServiceNames();
529 : }
530 :
531 : /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|