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: securityenvironment_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 ************************************************************************/
32 // MARKER(update_precomp.py): autogen include statement, do not remove
33 #include "precompiled_xmlsecurity.hxx"
35 //todo before commit: nssrenam.h is not delivered!!!
40 #include <sal/config.h>
41 #include "securityenvironment_nssimpl.hxx"
42 #include "x509certificate_nssimpl.hxx"
46 #include <sal/types.h>
47 //For reasons that escape me, this is what xmlsec does when size_t is not 4
48 #if SAL_TYPES_SIZEOFPOINTER != 4
49 # define XMLSEC_NO_SIZE_T
51 #include <xmlsec/xmlsec.h>
52 #include <xmlsec/keysmngr.h>
53 #include <xmlsec/crypto.h>
54 #include <xmlsec/base64.h>
55 #include <xmlsec/strings.h>
57 #include <tools/string.hxx>
58 #include <rtl/ustrbuf.hxx>
59 #include <comphelper/processfactory.hxx>
60 #include <cppuhelper/servicefactory.hxx>
61 #include <comphelper/docpasswordrequest.hxx>
62 #include <xmlsecurity/biginteger.hxx>
63 #include <rtl/logfile.h>
64 #include <com/sun/star/task/XInteractionHandler.hpp>
66 #include "boost/scoped_array.hpp"
68 // MM : added for password exception
69 #include <com/sun/star/security/NoPasswordException.hpp>
70 namespace csss
= ::com::sun::star::security
;
71 using namespace ::com::sun::star::security
;
72 using namespace com::sun::star
;
73 using namespace ::com::sun::star::uno
;
74 using namespace ::com::sun::star::lang
;
75 using ::com::sun::star::lang::XMultiServiceFactory
;
76 using ::com::sun::star::lang::XSingleServiceFactory
;
77 using ::rtl::OUString
;
79 using ::com::sun::star::xml::crypto::XSecurityEnvironment
;
80 using ::com::sun::star::security::XCertificate
;
82 extern X509Certificate_NssImpl
* NssCertToXCert( CERTCertificate
* cert
) ;
83 extern X509Certificate_NssImpl
* NssPrivKeyToXCert( SECKEYPrivateKey
* ) ;
86 char* GetPasswordFunction( PK11SlotInfo
* pSlot
, PRBool bRetry
, void* /*arg*/ )
88 uno::Reference
< lang::XMultiServiceFactory
> xMSF( ::comphelper::getProcessServiceFactory() );
91 uno::Reference
< task::XInteractionHandler
> xInteractionHandler(
92 xMSF
->createInstance( rtl::OUString::createFromAscii("com.sun.star.task.InteractionHandler") ), uno::UNO_QUERY
);
94 if ( xInteractionHandler
.is() )
96 task::PasswordRequestMode eMode
= bRetry
? task::PasswordRequestMode_PASSWORD_REENTER
: task::PasswordRequestMode_PASSWORD_ENTER
;
97 ::comphelper::DocPasswordRequest
* pPasswordRequest
= new ::comphelper::DocPasswordRequest(
98 ::comphelper::DocPasswordRequestType_STANDARD
, eMode
, ::rtl::OUString::createFromAscii(PK11_GetTokenName(pSlot
)) );
100 uno::Reference
< task::XInteractionRequest
> xRequest( pPasswordRequest
);
101 xInteractionHandler
->handle( xRequest
);
103 if ( pPasswordRequest
->isPassword() )
105 ByteString aPassword
= ByteString( String( pPasswordRequest
->getPassword() ), gsl_getSystemTextEncoding() );
106 USHORT nLen
= aPassword
.Len();
107 char* pPassword
= (char*) PORT_Alloc( nLen
+1 ) ;
109 memcpy( pPassword
, aPassword
.GetBuffer(), nLen
);
117 SecurityEnvironment_NssImpl :: SecurityEnvironment_NssImpl( const Reference
< XMultiServiceFactory
>& ) :
118 m_pHandler( NULL
) , m_tSymKeyList() , m_tPubKeyList() , m_tPriKeyList() {
120 PK11_SetPasswordFunc( GetPasswordFunction
) ;
123 SecurityEnvironment_NssImpl :: ~SecurityEnvironment_NssImpl() {
125 PK11_SetPasswordFunc( NULL
) ;
127 for (CIT_SLOTS i
= m_Slots
.begin(); i
!= m_Slots
.end(); i
++)
132 if( !m_tSymKeyList
.empty() ) {
133 std::list
< PK11SymKey
* >::iterator symKeyIt
;
135 for( symKeyIt
= m_tSymKeyList
.begin() ; symKeyIt
!= m_tSymKeyList
.end() ; symKeyIt
++ )
136 PK11_FreeSymKey( *symKeyIt
) ;
139 if( !m_tPubKeyList
.empty() ) {
140 std::list
< SECKEYPublicKey
* >::iterator pubKeyIt
;
142 for( pubKeyIt
= m_tPubKeyList
.begin() ; pubKeyIt
!= m_tPubKeyList
.end() ; pubKeyIt
++ )
143 SECKEY_DestroyPublicKey( *pubKeyIt
) ;
146 if( !m_tPriKeyList
.empty() ) {
147 std::list
< SECKEYPrivateKey
* >::iterator priKeyIt
;
149 for( priKeyIt
= m_tPriKeyList
.begin() ; priKeyIt
!= m_tPriKeyList
.end() ; priKeyIt
++ )
150 SECKEY_DestroyPrivateKey( *priKeyIt
) ;
154 /* XInitialization */
155 void SAL_CALL
SecurityEnvironment_NssImpl :: initialize( const Sequence
< Any
>& ) throw( Exception
, RuntimeException
) {
160 OUString SAL_CALL
SecurityEnvironment_NssImpl :: getImplementationName() throw( RuntimeException
) {
161 return impl_getImplementationName() ;
165 sal_Bool SAL_CALL
SecurityEnvironment_NssImpl :: supportsService( const OUString
& serviceName
) throw( RuntimeException
) {
166 Sequence
< OUString
> seqServiceNames
= getSupportedServiceNames() ;
167 const OUString
* pArray
= seqServiceNames
.getConstArray() ;
168 for( sal_Int32 i
= 0 ; i
< seqServiceNames
.getLength() ; i
++ ) {
169 if( *( pArray
+ i
) == serviceName
)
176 Sequence
< OUString
> SAL_CALL
SecurityEnvironment_NssImpl :: getSupportedServiceNames() throw( RuntimeException
) {
177 return impl_getSupportedServiceNames() ;
180 //Helper for XServiceInfo
181 Sequence
< OUString
> SecurityEnvironment_NssImpl :: impl_getSupportedServiceNames() {
182 ::osl::Guard
< ::osl::Mutex
> aGuard( ::osl::Mutex::getGlobalMutex() ) ;
183 Sequence
< OUString
> seqServiceNames( 1 ) ;
184 seqServiceNames
.getArray()[0] = OUString::createFromAscii( "com.sun.star.xml.crypto.SecurityEnvironment" ) ;
185 return seqServiceNames
;
188 OUString
SecurityEnvironment_NssImpl :: impl_getImplementationName() throw( RuntimeException
) {
189 return OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.SecurityEnvironment_NssImpl" ) ;
192 //Helper for registry
193 Reference
< XInterface
> SAL_CALL
SecurityEnvironment_NssImpl :: impl_createInstance( const Reference
< XMultiServiceFactory
>& aServiceManager
) throw( RuntimeException
) {
194 return Reference
< XInterface
>( *new SecurityEnvironment_NssImpl( aServiceManager
) ) ;
197 Reference
< XSingleServiceFactory
> SecurityEnvironment_NssImpl :: impl_createFactory( const Reference
< XMultiServiceFactory
>& aServiceManager
) {
198 //Reference< XSingleServiceFactory > xFactory ;
199 //xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
201 return ::cppu::createSingleFactory( aServiceManager
, impl_getImplementationName() , impl_createInstance
, impl_getSupportedServiceNames() ) ;
205 sal_Int64 SAL_CALL
SecurityEnvironment_NssImpl :: getSomething( const Sequence
< sal_Int8
>& aIdentifier
)
206 throw( RuntimeException
)
208 if( aIdentifier
.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(), aIdentifier
.getConstArray(), 16 ) ) {
209 return sal::static_int_cast
<sal_Int64
>(reinterpret_cast<sal_uIntPtr
>(this));
214 /* XUnoTunnel extension */
215 const Sequence
< sal_Int8
>& SecurityEnvironment_NssImpl :: getUnoTunnelId() {
216 static Sequence
< sal_Int8
>* pSeq
= 0 ;
218 ::osl::Guard
< ::osl::Mutex
> aGuard( ::osl::Mutex::getGlobalMutex() ) ;
220 static Sequence
< sal_Int8
> aSeq( 16 ) ;
221 rtl_createUuid( ( sal_uInt8
* )aSeq
.getArray() , 0 , sal_True
) ;
228 /* XUnoTunnel extension */
229 SecurityEnvironment_NssImpl
* SecurityEnvironment_NssImpl :: getImplementation( const Reference
< XInterface
> xObj
) {
230 Reference
< XUnoTunnel
> xUT( xObj
, UNO_QUERY
) ;
232 return reinterpret_cast<SecurityEnvironment_NssImpl
*>(
233 sal::static_int_cast
<sal_uIntPtr
>(xUT
->getSomething( getUnoTunnelId() ))) ;
239 ::rtl::OUString
SecurityEnvironment_NssImpl::getSecurityEnvironmentInformation() throw( ::com::sun::star::uno::RuntimeException
)
241 rtl::OUString result
;
242 ::rtl::OUStringBuffer buff
;
243 for (CIT_SLOTS is
= m_Slots
.begin(); is
!= m_Slots
.end(); is
++)
245 buff
.append(rtl::OUString::createFromAscii(PK11_GetTokenName(*is
)));
246 buff
.appendAscii("\n");
248 return buff
.makeStringAndClear();
251 void SecurityEnvironment_NssImpl::addCryptoSlot( PK11SlotInfo
* aSlot
) throw( Exception
, RuntimeException
)
253 PK11_ReferenceSlot(aSlot
);
254 m_Slots
.push_back(aSlot
);
257 CERTCertDBHandle
* SecurityEnvironment_NssImpl :: getCertDb() throw( Exception
, RuntimeException
) {
261 //Could we have multiple cert dbs?
262 void SecurityEnvironment_NssImpl :: setCertDb( CERTCertDBHandle
* aCertDb
) throw( Exception
, RuntimeException
) {
263 m_pHandler
= aCertDb
;
266 void SecurityEnvironment_NssImpl :: adoptSymKey( PK11SymKey
* aSymKey
) throw( Exception
, RuntimeException
) {
268 std::list
< PK11SymKey
* >::iterator keyIt
;
270 if( aSymKey
!= NULL
) {
271 //First try to find the key in the list
272 for( keyIt
= m_tSymKeyList
.begin() ; keyIt
!= m_tSymKeyList
.end() ; keyIt
++ ) {
273 if( *keyIt
== aSymKey
)
277 //If we do not find the key in the list, add a new node
278 symkey
= PK11_ReferenceSymKey( aSymKey
) ;
280 throw RuntimeException() ;
283 m_tSymKeyList
.push_back( symkey
) ;
284 } catch ( Exception
& ) {
285 PK11_FreeSymKey( symkey
) ;
290 void SecurityEnvironment_NssImpl :: rejectSymKey( PK11SymKey
* aSymKey
) throw( Exception
, RuntimeException
) {
292 std::list
< PK11SymKey
* >::iterator keyIt
;
294 if( aSymKey
!= NULL
) {
295 for( keyIt
= m_tSymKeyList
.begin() ; keyIt
!= m_tSymKeyList
.end() ; keyIt
++ ) {
296 if( *keyIt
== aSymKey
) {
298 PK11_FreeSymKey( symkey
) ;
299 m_tSymKeyList
.erase( keyIt
) ;
306 PK11SymKey
* SecurityEnvironment_NssImpl :: getSymKey( unsigned int position
) throw( Exception
, RuntimeException
) {
308 std::list
< PK11SymKey
* >::iterator keyIt
;
312 for( pos
= 0, keyIt
= m_tSymKeyList
.begin() ; pos
< position
&& keyIt
!= m_tSymKeyList
.end() ; pos
++ , keyIt
++ ) ;
314 if( pos
== position
&& keyIt
!= m_tSymKeyList
.end() )
320 void SecurityEnvironment_NssImpl :: adoptPubKey( SECKEYPublicKey
* aPubKey
) throw( Exception
, RuntimeException
) {
321 SECKEYPublicKey
* pubkey
;
322 std::list
< SECKEYPublicKey
* >::iterator keyIt
;
324 if( aPubKey
!= NULL
) {
325 //First try to find the key in the list
326 for( keyIt
= m_tPubKeyList
.begin() ; keyIt
!= m_tPubKeyList
.end() ; keyIt
++ ) {
327 if( *keyIt
== aPubKey
)
331 //If we do not find the key in the list, add a new node
332 pubkey
= SECKEY_CopyPublicKey( aPubKey
) ;
334 throw RuntimeException() ;
337 m_tPubKeyList
.push_back( pubkey
) ;
338 } catch ( Exception
& ) {
339 SECKEY_DestroyPublicKey( pubkey
) ;
344 void SecurityEnvironment_NssImpl :: rejectPubKey( SECKEYPublicKey
* aPubKey
) throw( Exception
, RuntimeException
) {
345 SECKEYPublicKey
* pubkey
;
346 std::list
< SECKEYPublicKey
* >::iterator keyIt
;
348 if( aPubKey
!= NULL
) {
349 for( keyIt
= m_tPubKeyList
.begin() ; keyIt
!= m_tPubKeyList
.end() ; keyIt
++ ) {
350 if( *keyIt
== aPubKey
) {
352 SECKEY_DestroyPublicKey( pubkey
) ;
353 m_tPubKeyList
.erase( keyIt
) ;
360 SECKEYPublicKey
* SecurityEnvironment_NssImpl :: getPubKey( unsigned int position
) throw( Exception
, RuntimeException
) {
361 SECKEYPublicKey
* pubkey
;
362 std::list
< SECKEYPublicKey
* >::iterator keyIt
;
366 for( pos
= 0, keyIt
= m_tPubKeyList
.begin() ; pos
< position
&& keyIt
!= m_tPubKeyList
.end() ; pos
++ , keyIt
++ ) ;
368 if( pos
== position
&& keyIt
!= m_tPubKeyList
.end() )
374 void SecurityEnvironment_NssImpl :: adoptPriKey( SECKEYPrivateKey
* aPriKey
) throw( Exception
, RuntimeException
) {
375 SECKEYPrivateKey
* prikey
;
376 std::list
< SECKEYPrivateKey
* >::iterator keyIt
;
378 if( aPriKey
!= NULL
) {
379 //First try to find the key in the list
380 for( keyIt
= m_tPriKeyList
.begin() ; keyIt
!= m_tPriKeyList
.end() ; keyIt
++ ) {
381 if( *keyIt
== aPriKey
)
385 //If we do not find the key in the list, add a new node
386 prikey
= SECKEY_CopyPrivateKey( aPriKey
) ;
388 throw RuntimeException() ;
391 m_tPriKeyList
.push_back( prikey
) ;
392 } catch ( Exception
& ) {
393 SECKEY_DestroyPrivateKey( prikey
) ;
398 void SecurityEnvironment_NssImpl :: rejectPriKey( SECKEYPrivateKey
* aPriKey
) throw( Exception
, RuntimeException
) {
399 SECKEYPrivateKey
* prikey
;
400 std::list
< SECKEYPrivateKey
* >::iterator keyIt
;
402 if( aPriKey
!= NULL
) {
403 for( keyIt
= m_tPriKeyList
.begin() ; keyIt
!= m_tPriKeyList
.end() ; keyIt
++ ) {
404 if( *keyIt
== aPriKey
) {
406 SECKEY_DestroyPrivateKey( prikey
) ;
407 m_tPriKeyList
.erase( keyIt
) ;
414 SECKEYPrivateKey
* SecurityEnvironment_NssImpl :: getPriKey( unsigned int position
) throw( ::com::sun::star::uno::Exception
, ::com::sun::star::uno::RuntimeException
) {
415 SECKEYPrivateKey
* prikey
;
416 std::list
< SECKEYPrivateKey
* >::iterator keyIt
;
420 for( pos
= 0, keyIt
= m_tPriKeyList
.begin() ; pos
< position
&& keyIt
!= m_tPriKeyList
.end() ; pos
++ , keyIt
++ ) ;
422 if( pos
== position
&& keyIt
!= m_tPriKeyList
.end() )
428 void SecurityEnvironment_NssImpl::updateSlots()
430 //In case new tokens are present then we can obtain the corresponding slot
431 PK11SlotList
* soltList
= NULL
;
432 PK11SlotListElement
* soltEle
= NULL
;
433 PK11SlotInfo
* pSlot
= NULL
;
434 PK11SymKey
* pSymKey
= NULL
;
436 osl::MutexGuard
guard(m_mutex
);
439 m_tSymKeyList
.clear();
441 soltList
= PK11_GetAllTokens( CKM_INVALID_MECHANISM
, PR_FALSE
, PR_FALSE
, NULL
) ;
442 if( soltList
!= NULL
)
444 for( soltEle
= soltList
->head
; soltEle
!= NULL
; soltEle
= soltEle
->next
)
446 pSlot
= soltEle
->slot
;
450 RTL_LOGFILE_TRACE2( "XMLSEC: Found a slot: SlotName=%s, TokenName=%s", PK11_GetSlotName(pSlot
), PK11_GetTokenName(pSlot
) );
452 //The following code which is commented out checks if a slot, that is a smart card for example, is
453 // able to generate a symmetric key of type CKM_DES3_CBC. If this fails then this token
454 // will not be used. This key is possibly used for the encryption service. However, all
455 // interfaces and services used for public key signature and encryption are not published
456 // and the encryption is not used in OOo. Therefore it does not do any harm to remove
457 // this code, hence allowing smart cards which cannot generate this type of key.
459 // By doing this, the encryption may fail if a smart card is being used which does not
460 // support this key generation.
462 pSymKey
= PK11_KeyGen( pSlot
, CKM_DES3_CBC
, NULL
, 128, NULL
) ;
463 // if( pSymKey == NULL )
465 // PK11_FreeSlot( pSlot ) ;
466 // RTL_LOGFILE_TRACE( "XMLSEC: Error - pSymKey is NULL" );
469 addCryptoSlot(pSlot
);
470 PK11_FreeSlot( pSlot
) ;
475 adoptSymKey( pSymKey
) ;
476 PK11_FreeSymKey( pSymKey
) ;
480 }// end of if(pSlot != NULL)
482 }// end of if( soltList != NULL )
487 Sequence
< Reference
< XCertificate
> >
488 SecurityEnvironment_NssImpl::getPersonalCertificates() throw( SecurityException
, RuntimeException
)
491 X509Certificate_NssImpl
* xcert
;
492 std::list
< X509Certificate_NssImpl
* > certsList
;
495 //firstly, we try to find private keys in slot
496 for (CIT_SLOTS is
= m_Slots
.begin(); is
!= m_Slots
.end(); is
++)
498 PK11SlotInfo
*slot
= *is
;
499 SECKEYPrivateKeyList
* priKeyList
;
500 SECKEYPrivateKeyListNode
* curPri
;
502 if( PK11_NeedLogin(slot
) ) {
503 SECStatus nRet
= PK11_Authenticate(slot
, PR_TRUE
, NULL
);
504 //PK11_Authenticate may fail in case the a slot has not been initialized.
505 //this is the case if the user has a new profile, so that they have never
506 //added a personal certificate.
507 if( nRet
!= SECSuccess
&& PORT_GetError() != SEC_ERROR_IO
) {
508 throw NoPasswordException();
512 priKeyList
= PK11_ListPrivateKeysInSlot(slot
) ;
513 if( priKeyList
!= NULL
) {
514 for( curPri
= PRIVKEY_LIST_HEAD( priKeyList
);
515 !PRIVKEY_LIST_END( curPri
, priKeyList
) && curPri
!= NULL
;
516 curPri
= PRIVKEY_LIST_NEXT( curPri
) ) {
517 xcert
= NssPrivKeyToXCert( curPri
->key
) ;
519 certsList
.push_back( xcert
) ;
523 SECKEY_DestroyPrivateKeyList( priKeyList
) ;
526 //secondly, we try to find certificate from registered private keys.
527 if( !m_tPriKeyList
.empty() ) {
528 std::list
< SECKEYPrivateKey
* >::iterator priKeyIt
;
530 for( priKeyIt
= m_tPriKeyList
.begin() ; priKeyIt
!= m_tPriKeyList
.end() ; priKeyIt
++ ) {
531 xcert
= NssPrivKeyToXCert( *priKeyIt
) ;
533 certsList
.push_back( xcert
) ;
537 length
= certsList
.size() ;
540 std::list
< X509Certificate_NssImpl
* >::iterator xcertIt
;
541 Sequence
< Reference
< XCertificate
> > certSeq( length
) ;
543 for( i
= 0, xcertIt
= certsList
.begin(); xcertIt
!= certsList
.end(); xcertIt
++, i
++ ) {
544 certSeq
[i
] = *xcertIt
;
550 return Sequence
< Reference
< XCertificate
> > ();
553 Reference
< XCertificate
> SecurityEnvironment_NssImpl :: getCertificate( const OUString
& issuerName
, const Sequence
< sal_Int8
>& serialNumber
) throw( SecurityException
, RuntimeException
)
555 X509Certificate_NssImpl
* xcert
= NULL
;
557 if( m_pHandler
!= NULL
) {
558 CERTIssuerAndSN issuerAndSN
;
559 CERTCertificate
* cert
;
565 arena
= PORT_NewArena( DER_DEFAULT_CHUNKSIZE
) ;
567 throw RuntimeException() ;
570 * mmi : because MS Crypto use the 'S' tag (equal to the 'ST' tag in NSS), but the NSS can't recognise
571 * it, so the 'S' tag should be changed to 'ST' tag
573 * PS : it can work, but inside libxmlsec, the 'S' tag is till used to find cert in NSS engine, so it
574 * is not useful at all. (comment out now)
578 sal_Int32 nIndex = 0;
579 OUString newIssuerName;
582 OUString aToken = issuerName.getToken( 0, ',', nIndex ).trim();
583 if (aToken.compareToAscii("S=",2) == 0)
585 newIssuerName+=OUString::createFromAscii("ST=");
586 newIssuerName+=aToken.copy(2);
590 newIssuerName+=aToken;
595 newIssuerName+=OUString::createFromAscii(",");
597 } while ( nIndex >= 0 );
602 //Create cert info from issue and serial
603 rtl::OString ostr
= rtl::OUStringToOString( issuerName
, RTL_TEXTENCODING_UTF8
) ;
604 chIssuer
= PL_strndup( ( char* )ostr
.getStr(), ( int )ostr
.getLength() ) ;
605 nmIssuer
= CERT_AsciiToName( chIssuer
) ;
606 if( nmIssuer
== NULL
) {
607 PL_strfree( chIssuer
) ;
608 PORT_FreeArena( arena
, PR_FALSE
) ;
613 * mmi : no need to throw exception
614 * just return "no found"
616 //throw RuntimeException() ;
620 derIssuer
= SEC_ASN1EncodeItem( arena
, NULL
, ( void* )nmIssuer
, SEC_ASN1_GET( CERT_NameTemplate
) ) ;
621 if( derIssuer
== NULL
) {
622 PL_strfree( chIssuer
) ;
623 CERT_DestroyName( nmIssuer
) ;
624 PORT_FreeArena( arena
, PR_FALSE
) ;
625 throw RuntimeException() ;
628 memset( &issuerAndSN
, 0, sizeof( issuerAndSN
) ) ;
630 issuerAndSN
.derIssuer
.data
= derIssuer
->data
;
631 issuerAndSN
.derIssuer
.len
= derIssuer
->len
;
633 issuerAndSN
.serialNumber
.data
= ( unsigned char* )&serialNumber
[0] ;
634 issuerAndSN
.serialNumber
.len
= serialNumber
.getLength() ;
636 cert
= CERT_FindCertByIssuerAndSN( m_pHandler
, &issuerAndSN
) ;
638 xcert
= NssCertToXCert( cert
) ;
643 PL_strfree( chIssuer
) ;
644 CERT_DestroyName( nmIssuer
) ;
645 //SECITEM_FreeItem( derIssuer, PR_FALSE ) ;
646 CERT_DestroyCertificate( cert
) ;
647 PORT_FreeArena( arena
, PR_FALSE
) ;
655 Reference
< XCertificate
> SecurityEnvironment_NssImpl :: getCertificate( const OUString
& issuerName
, const OUString
& serialNumber
) throw( SecurityException
, RuntimeException
) {
656 Sequence
< sal_Int8
> serial
= numericStringToBigInteger( serialNumber
) ;
657 return getCertificate( issuerName
, serial
) ;
660 Sequence
< Reference
< XCertificate
> > SecurityEnvironment_NssImpl :: buildCertificatePath( const Reference
< XCertificate
>& begin
) throw( SecurityException
, RuntimeException
) {
661 const X509Certificate_NssImpl
* xcert
;
662 const CERTCertificate
* cert
;
663 CERTCertList
* certChain
;
665 Reference
< XUnoTunnel
> xCertTunnel( begin
, UNO_QUERY
) ;
666 if( !xCertTunnel
.is() ) {
667 throw RuntimeException() ;
670 xcert
= reinterpret_cast<X509Certificate_NssImpl
*>(
671 sal::static_int_cast
<sal_uIntPtr
>(xCertTunnel
->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
672 if( xcert
== NULL
) {
673 throw RuntimeException() ;
676 cert
= xcert
->getNssCert() ;
680 //Get the system clock time
681 timeboundary
= PR_Now() ;
683 certChain
= CERT_GetCertChainFromCert( ( CERTCertificate
* )cert
, timeboundary
, certUsageAnyCA
) ;
688 if( certChain
!= NULL
) {
689 X509Certificate_NssImpl
* pCert
;
690 CERTCertListNode
* node
;
693 for( len
= 0, node
= CERT_LIST_HEAD( certChain
); !CERT_LIST_END( node
, certChain
); node
= CERT_LIST_NEXT( node
), len
++ ) ;
694 Sequence
< Reference
< XCertificate
> > xCertChain( len
) ;
696 for( len
= 0, node
= CERT_LIST_HEAD( certChain
); !CERT_LIST_END( node
, certChain
); node
= CERT_LIST_NEXT( node
), len
++ ) {
697 pCert
= new X509Certificate_NssImpl() ;
698 if( pCert
== NULL
) {
699 CERT_DestroyCertList( certChain
) ;
700 throw RuntimeException() ;
703 pCert
->setCert( node
->cert
) ;
705 xCertChain
[len
] = pCert
;
708 CERT_DestroyCertList( certChain
) ;
713 return Sequence
< Reference
< XCertificate
> >();
716 Reference
< XCertificate
> SecurityEnvironment_NssImpl :: createCertificateFromRaw( const Sequence
< sal_Int8
>& rawCertificate
) throw( SecurityException
, RuntimeException
) {
717 X509Certificate_NssImpl
* xcert
;
719 if( rawCertificate
.getLength() > 0 ) {
720 xcert
= new X509Certificate_NssImpl() ;
722 throw RuntimeException() ;
724 xcert
->setRawCert( rawCertificate
) ;
732 Reference
< XCertificate
> SecurityEnvironment_NssImpl :: createCertificateFromAscii( const OUString
& asciiCertificate
) throw( SecurityException
, RuntimeException
) {
734 xmlSecSize certSize
;
736 rtl::OString oscert
= rtl::OUStringToOString( asciiCertificate
, RTL_TEXTENCODING_ASCII_US
) ;
738 chCert
= xmlStrndup( ( const xmlChar
* )oscert
.getStr(), ( int )oscert
.getLength() ) ;
740 certSize
= xmlSecBase64Decode( chCert
, ( xmlSecByte
* )chCert
, xmlStrlen( chCert
) ) ;
742 Sequence
< sal_Int8
> rawCert( certSize
) ;
743 for( unsigned int i
= 0 ; i
< certSize
; i
++ )
744 rawCert
[i
] = *( chCert
+ i
) ;
748 return createCertificateFromRaw( rawCert
) ;
751 sal_Int32
SecurityEnvironment_NssImpl ::
752 verifyCertificate( const Reference
< csss::XCertificate
>& aCert
,
753 const Sequence
< Reference
< csss::XCertificate
> >& intermediateCerts
)
754 throw( ::com::sun::star::uno::SecurityException
, ::com::sun::star::uno::RuntimeException
)
756 sal_Int32 validity
= 0;
757 const X509Certificate_NssImpl
* xcert
;
758 const CERTCertificate
* cert
;
759 ::std::vector
<CERTCertificate
*> vecTmpNSSCertificates
;
760 Reference
< XUnoTunnel
> xCertTunnel( aCert
, UNO_QUERY
) ;
761 if( !xCertTunnel
.is() ) {
762 throw RuntimeException() ;
765 OSL_TRACE("[xmlsecurity] Start verification of certificate: %s",
767 aCert
->getIssuerName(), osl_getThreadTextEncoding()).getStr());
770 xcert
= reinterpret_cast<X509Certificate_NssImpl
*>(
771 sal::static_int_cast
<sal_uIntPtr
>(xCertTunnel
->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
772 if( xcert
== NULL
) {
773 throw RuntimeException() ;
776 cert
= xcert
->getNssCert() ;
780 //prepare the intermediate certificates
781 CERTCertDBHandle
* certDb
= m_pHandler
!= NULL
? m_pHandler
: CERT_GetDefaultCertDB();
782 for (sal_Int32 i
= 0; i
< intermediateCerts
.getLength(); i
++)
784 Sequence
<sal_Int8
> der
= intermediateCerts
[i
]->getEncoded();
786 item
.type
= siBuffer
;
787 item
.data
= (unsigned char*)der
.getArray();
788 item
.len
= der
.getLength();
790 CERTCertificate
* certTmp
= CERT_NewTempCertificate(certDb
, &item
,
792 PR_FALSE
/* isPerm */,
793 PR_TRUE
/* copyDER */);
796 OSL_TRACE("[xmlsecurity] Failed to add a temporary certificate: %s",
797 OUStringToOString(intermediateCerts
[i
]->getIssuerName(),
798 osl_getThreadTextEncoding()).getStr());
803 OSL_TRACE("[xmlsecurity] Added temporary certificate: %s",
804 certTmp
->subjectName
? certTmp
->subjectName
: "");
805 vecTmpNSSCertificates
.push_back(certTmp
);
813 //Get the system clock time
814 timeboundary
= PR_Now() ;
815 SECCertificateUsage usage
= 0;
819 CERTVerifyLog realLog
;
828 log
->arena
= PORT_NewArena( DER_DEFAULT_CHUNKSIZE
);
830 //CERTVerifyLog *log;
831 //PRArenaPool *arena;
833 //arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE );
834 //log = PORT_ArenaZNew( arena, CERTVerifyLog );
835 //log->arena = arena;
836 validity
= csss::CertificateValidity::INVALID
;
838 if( m_pHandler
!= NULL
)
840 //JL: We must not pass a particular usage in the requiredUsages argument (the 4th) because,
841 //then ONLY these are verified. For example, we pass
842 //certificateUsageSSLClient | certificateUsageSSLServer. Then checking a certificate which
843 // is a valid certificateUsageEmailSigner but no certificateUsageSSLClient | certificateUsageSSLServer
844 //will result in CertificateValidity::INVALID.
845 //Only if the argument "requiredUsages" has a value (other than zero)
846 //then the function will return SECFailure in case
847 //the certificate is not suitable for the provided usage. That is, in the previous
848 //example the function returns SECFailure.
849 status
= CERT_VerifyCertificate(
850 m_pHandler
, ( CERTCertificate
* )cert
, PR_TRUE
,
851 (SECCertificateUsage
)0, timeboundary
, NULL
, log
, &usage
);
855 status
= CERT_VerifyCertificate(
856 CERT_GetDefaultCertDB(), ( CERTCertificate
* )cert
,
857 PR_TRUE
, (SECCertificateUsage
)0, timeboundary
,NULL
, log
, &usage
);
860 if( status
== SECSuccess
)
862 // JL & TKR : certificateUsageUserCertImport,
863 // certificateUsageVerifyCA and certificateUsageAnyCA dont check the chain
865 //When an intermediate or root certificate is checked then we expect the usage
866 //certificateUsageSSLCA. This, however, will be only set when in the trust settings dialog
867 //the button "This certificate can identify websites" is checked. If for example only
868 //"This certificate can identify mail users" is set then the end certificate can
869 //be validated and the returned usage will conain certificateUsageEmailRecipient.
870 //But checking directly the root or intermediate certificate will fail. In the
871 //certificate path view the end certificate will be shown as valid but the others
872 //will be displayed as invalid.
874 if (usage
& certificateUsageEmailSigner
875 || usage
& certificateUsageEmailRecipient
876 || usage
& certificateUsageSSLCA
877 || usage
& certificateUsageSSLServer
878 || usage
& certificateUsageSSLClient
879 || usage
& certificateUsageProtectedObjectSigner
880 || usage
& certificateUsageObjectSigner
881 // || usage & certificateUsageUserCertImport
882 // || usage & certificateUsageVerifyCA
883 || usage
& certificateUsageStatusResponder
)
884 // || usage & certificateUsageAnyCA )
885 validity
= csss::CertificateValidity::VALID
;
887 validity
= csss::CertificateValidity::INVALID
;
890 // always check what kind of error occured, even SECStatus says Success
891 //JL: When we call CERT_VerifyCertificate whit the parameter requiredUsages == 0 then all
892 //possible usages are checked. Then there are certainly usages for which the certificate
893 //is not intended. For these usages there will be NO flag set in the argument returnedUsages
894 // (the last arg) and there will be error codes set in the log. Therefore we cannot
895 //set the CertificateValidity to INVALID because there is a log entry.
896 // CERTVerifyLogNode *logNode = 0;
898 // logNode = log->head;
899 // while ( logNode != NULL )
901 // sal_Int32 errorCode = 0;
902 // errorCode = logNode->error;
904 // switch ( errorCode )
906 // // JL & TKR: Any error are treated as invalid because we cannot say that we get all occurred errors from NSS
908 // case ( SEC_ERROR_REVOKED_CERTIFICATE ):
909 // validity |= csss::CertificateValidity::REVOKED;
911 // case ( SEC_ERROR_EXPIRED_CERTIFICATE ):
912 // validity |= csss::CertificateValidity::TIME_INVALID;
914 // case ( SEC_ERROR_CERT_USAGES_INVALID):
915 // validity |= csss::CertificateValidity::INVALID;
917 // case ( SEC_ERROR_UNTRUSTED_ISSUER ):
918 // case ( SEC_ERROR_UNTRUSTED_CERT ):
919 // validity |= csss::CertificateValidity::UNTRUSTED;
923 // validity |= csss::CertificateValidity::INVALID;
926 // logNode = logNode->next;
932 validity
= ::com::sun::star::security::CertificateValidity::INVALID
;
935 //Destroying the temporary certificates
936 std::vector
<CERTCertificate
*>::const_iterator cert_i
;
937 for (cert_i
= vecTmpNSSCertificates
.begin(); cert_i
!= vecTmpNSSCertificates
.end(); cert_i
++)
939 OSL_TRACE("[xmlsecurity] Destroying temporary certificate");
940 CERT_DestroyCertificate(*cert_i
);
942 #if OSL_DEBUG_LEVEL > 1
943 if (validity
== ::com::sun::star::security::CertificateValidity::VALID
)
944 OSL_TRACE("[xmlsecurity] Certificate is valid.");
946 OSL_TRACE("[xmlsecurity] Certificate is invalid.");
951 sal_Int32
SecurityEnvironment_NssImpl::getCertificateCharacters(
952 const ::com::sun::star::uno::Reference
< ::com::sun::star::security::XCertificate
>& aCert
) throw( ::com::sun::star::uno::SecurityException
, ::com::sun::star::uno::RuntimeException
) {
953 sal_Int32 characters
;
954 const X509Certificate_NssImpl
* xcert
;
955 const CERTCertificate
* cert
;
957 Reference
< XUnoTunnel
> xCertTunnel( aCert
, UNO_QUERY
) ;
958 if( !xCertTunnel
.is() ) {
959 throw RuntimeException() ;
962 xcert
= reinterpret_cast<X509Certificate_NssImpl
*>(
963 sal::static_int_cast
<sal_uIntPtr
>(xCertTunnel
->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
964 if( xcert
== NULL
) {
965 throw RuntimeException() ;
968 cert
= xcert
->getNssCert() ;
970 characters
= 0x00000000 ;
972 //Firstly, find out whether or not the cert is self-signed.
973 if( SECITEM_CompareItem( &(cert
->derIssuer
), &(cert
->derSubject
) ) == SECEqual
) {
974 characters
|= ::com::sun::star::security::CertificateCharacters::SELF_SIGNED
;
976 characters
&= ~ ::com::sun::star::security::CertificateCharacters::SELF_SIGNED
;
979 //Secondly, find out whether or not the cert has a private key.
984 * mmi : need to check whether the cert's slot is valid first
986 SECKEYPrivateKey
* priKey
= NULL
;
988 if (cert
->slot
!= NULL
)
990 priKey
= PK11_FindPrivateKeyFromCert( cert
->slot
, ( CERTCertificate
* )cert
, NULL
) ;
994 for (CIT_SLOTS is
= m_Slots
.begin(); is
!= m_Slots
.end(); is
++)
996 priKey
= PK11_FindPrivateKeyFromCert(*is
, (CERTCertificate
*)cert
, NULL
);
1001 if( priKey
!= NULL
) {
1002 characters
|= ::com::sun::star::security::CertificateCharacters::HAS_PRIVATE_KEY
;
1004 SECKEY_DestroyPrivateKey( priKey
) ;
1006 characters
&= ~ ::com::sun::star::security::CertificateCharacters::HAS_PRIVATE_KEY
;
1012 X509Certificate_NssImpl
* NssCertToXCert( CERTCertificate
* cert
)
1014 X509Certificate_NssImpl
* xcert
;
1016 if( cert
!= NULL
) {
1017 xcert
= new X509Certificate_NssImpl() ;
1018 if( xcert
== NULL
) {
1021 xcert
->setCert( cert
) ;
1030 X509Certificate_NssImpl
* NssPrivKeyToXCert( SECKEYPrivateKey
* priKey
)
1032 CERTCertificate
* cert
;
1033 X509Certificate_NssImpl
* xcert
;
1035 if( priKey
!= NULL
) {
1036 cert
= PK11_GetCertFromPrivateKey( priKey
) ;
1038 if( cert
!= NULL
) {
1039 xcert
= NssCertToXCert( cert
) ;
1044 CERT_DestroyCertificate( cert
) ;
1053 /* Native methods */
1054 xmlSecKeysMngrPtr
SecurityEnvironment_NssImpl::createKeysManager() throw( Exception
, RuntimeException
) {
1057 CERTCertDBHandle
* handler
= NULL
;
1058 PK11SymKey
* symKey
= NULL
;
1059 SECKEYPublicKey
* pubKey
= NULL
;
1060 SECKEYPrivateKey
* priKey
= NULL
;
1061 xmlSecKeysMngrPtr pKeysMngr
= NULL
;
1063 handler
= this->getCertDb() ;
1066 * The following lines is based on the private version of xmlSec-NSS
1069 int cSlots
= m_Slots
.size();
1070 boost::scoped_array
<PK11SlotInfo
*> sarSlots(new PK11SlotInfo
*[cSlots
]);
1071 PK11SlotInfo
** slots
= sarSlots
.get();
1073 for (CIT_SLOTS islots
= m_Slots
.begin();islots
!= m_Slots
.end(); islots
++, count
++)
1074 slots
[count
] = *islots
;
1076 pKeysMngr
= xmlSecNssAppliedKeysMngrCreate(slots
, cSlots
, handler
) ;
1077 if( pKeysMngr
== NULL
)
1078 throw RuntimeException() ;
1081 * Adopt symmetric key into keys manager
1083 for( i
= 0 ; ( symKey
= this->getSymKey( i
) ) != NULL
; i
++ ) {
1084 if( xmlSecNssAppliedKeysMngrSymKeyLoad( pKeysMngr
, symKey
) < 0 ) {
1085 throw RuntimeException() ;
1090 * Adopt asymmetric public key into keys manager
1092 for( i
= 0 ; ( pubKey
= this->getPubKey( i
) ) != NULL
; i
++ ) {
1093 if( xmlSecNssAppliedKeysMngrPubKeyLoad( pKeysMngr
, pubKey
) < 0 ) {
1094 throw RuntimeException() ;
1099 * Adopt asymmetric private key into keys manager
1101 for( i
= 0 ; ( priKey
= this->getPriKey( i
) ) != NULL
; i
++ ) {
1102 if( xmlSecNssAppliedKeysMngrPriKeyLoad( pKeysMngr
, priKey
) < 0 ) {
1103 throw RuntimeException() ;
1108 void SecurityEnvironment_NssImpl::destroyKeysManager(xmlSecKeysMngrPtr pKeysMngr
) throw( Exception
, RuntimeException
) {
1109 if( pKeysMngr
!= NULL
) {
1110 xmlSecKeysMngrDestroy( pKeysMngr
) ;