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 ************************************************************************/
29 // MARKER(update_precomp.py): autogen include statement, do not remove
30 #include "precompiled_xmlsecurity.hxx"
32 //todo before commit: nssrenam.h is not delivered!!!
38 #include <sal/config.h>
39 #include "securityenvironment_nssimpl.hxx"
40 #include "x509certificate_nssimpl.hxx"
42 #include "../diagnose.hxx"
44 #include <sal/types.h>
45 //For reasons that escape me, this is what xmlsec does when size_t is not 4
46 #if SAL_TYPES_SIZEOFPOINTER != 4
47 # define XMLSEC_NO_SIZE_T
49 #include <xmlsec/xmlsec.h>
50 #include <xmlsec/keysmngr.h>
51 #include <xmlsec/crypto.h>
52 #include <xmlsec/base64.h>
53 #include <xmlsec/strings.h>
55 #include <tools/string.hxx>
56 #include <rtl/ustrbuf.hxx>
57 #include <comphelper/processfactory.hxx>
58 #include <cppuhelper/servicefactory.hxx>
59 #include <comphelper/docpasswordrequest.hxx>
60 #include <xmlsecurity/biginteger.hxx>
61 #include <rtl/logfile.h>
62 #include <com/sun/star/task/XInteractionHandler.hpp>
64 #include "boost/scoped_array.hpp"
66 #include "secerror.hxx"
68 // MM : added for password exception
69 #include <com/sun/star/security/NoPasswordException.hpp>
70 namespace csss
= ::com::sun::star::security
;
71 using namespace xmlsecurity
;
72 using namespace ::com::sun::star::security
;
73 using namespace com::sun::star
;
74 using namespace ::com::sun::star::uno
;
75 using namespace ::com::sun::star::lang
;
76 using ::com::sun::star::lang::XMultiServiceFactory
;
77 using ::com::sun::star::lang::XSingleServiceFactory
;
78 using ::rtl::OUString
;
80 using ::com::sun::star::xml::crypto::XSecurityEnvironment
;
81 using ::com::sun::star::security::XCertificate
;
83 extern X509Certificate_NssImpl
* NssCertToXCert( CERTCertificate
* cert
) ;
84 extern X509Certificate_NssImpl
* NssPrivKeyToXCert( SECKEYPrivateKey
* ) ;
87 struct UsageDescription
89 SECCertificateUsage usage
;
90 char const * const description
;
95 char* GetPasswordFunction( PK11SlotInfo
* pSlot
, PRBool bRetry
, void* /*arg*/ )
97 uno::Reference
< lang::XMultiServiceFactory
> xMSF( ::comphelper::getProcessServiceFactory() );
100 uno::Reference
< task::XInteractionHandler
> xInteractionHandler(
101 xMSF
->createInstance( rtl::OUString::createFromAscii("com.sun.star.task.InteractionHandler") ), uno::UNO_QUERY
);
103 if ( xInteractionHandler
.is() )
105 task::PasswordRequestMode eMode
= bRetry
? task::PasswordRequestMode_PASSWORD_REENTER
: task::PasswordRequestMode_PASSWORD_ENTER
;
106 ::comphelper::DocPasswordRequest
* pPasswordRequest
= new ::comphelper::DocPasswordRequest(
107 ::comphelper::DocPasswordRequestType_STANDARD
, eMode
, ::rtl::OUString::createFromAscii(PK11_GetTokenName(pSlot
)) );
109 uno::Reference
< task::XInteractionRequest
> xRequest( pPasswordRequest
);
110 xInteractionHandler
->handle( xRequest
);
112 if ( pPasswordRequest
->isPassword() )
114 ByteString aPassword
= ByteString( String( pPasswordRequest
->getPassword() ), gsl_getSystemTextEncoding() );
115 USHORT nLen
= aPassword
.Len();
116 char* pPassword
= (char*) PORT_Alloc( nLen
+1 ) ;
118 memcpy( pPassword
, aPassword
.GetBuffer(), nLen
);
126 SecurityEnvironment_NssImpl :: SecurityEnvironment_NssImpl( const Reference
< XMultiServiceFactory
>& ) :
127 m_pHandler( NULL
) , m_tSymKeyList() , m_tPubKeyList() , m_tPriKeyList() {
129 PK11_SetPasswordFunc( GetPasswordFunction
) ;
132 SecurityEnvironment_NssImpl :: ~SecurityEnvironment_NssImpl() {
134 PK11_SetPasswordFunc( NULL
) ;
136 for (CIT_SLOTS i
= m_Slots
.begin(); i
!= m_Slots
.end(); i
++)
141 if( !m_tSymKeyList
.empty() ) {
142 std::list
< PK11SymKey
* >::iterator symKeyIt
;
144 for( symKeyIt
= m_tSymKeyList
.begin() ; symKeyIt
!= m_tSymKeyList
.end() ; symKeyIt
++ )
145 PK11_FreeSymKey( *symKeyIt
) ;
148 if( !m_tPubKeyList
.empty() ) {
149 std::list
< SECKEYPublicKey
* >::iterator pubKeyIt
;
151 for( pubKeyIt
= m_tPubKeyList
.begin() ; pubKeyIt
!= m_tPubKeyList
.end() ; pubKeyIt
++ )
152 SECKEY_DestroyPublicKey( *pubKeyIt
) ;
155 if( !m_tPriKeyList
.empty() ) {
156 std::list
< SECKEYPrivateKey
* >::iterator priKeyIt
;
158 for( priKeyIt
= m_tPriKeyList
.begin() ; priKeyIt
!= m_tPriKeyList
.end() ; priKeyIt
++ )
159 SECKEY_DestroyPrivateKey( *priKeyIt
) ;
163 /* XInitialization */
164 void SAL_CALL
SecurityEnvironment_NssImpl :: initialize( const Sequence
< Any
>& ) throw( Exception
, RuntimeException
) {
169 OUString SAL_CALL
SecurityEnvironment_NssImpl :: getImplementationName() throw( RuntimeException
) {
170 return impl_getImplementationName() ;
174 sal_Bool SAL_CALL
SecurityEnvironment_NssImpl :: supportsService( const OUString
& serviceName
) throw( RuntimeException
) {
175 Sequence
< OUString
> seqServiceNames
= getSupportedServiceNames() ;
176 const OUString
* pArray
= seqServiceNames
.getConstArray() ;
177 for( sal_Int32 i
= 0 ; i
< seqServiceNames
.getLength() ; i
++ ) {
178 if( *( pArray
+ i
) == serviceName
)
185 Sequence
< OUString
> SAL_CALL
SecurityEnvironment_NssImpl :: getSupportedServiceNames() throw( RuntimeException
) {
186 return impl_getSupportedServiceNames() ;
189 //Helper for XServiceInfo
190 Sequence
< OUString
> SecurityEnvironment_NssImpl :: impl_getSupportedServiceNames() {
191 ::osl::Guard
< ::osl::Mutex
> aGuard( ::osl::Mutex::getGlobalMutex() ) ;
192 Sequence
< OUString
> seqServiceNames( 1 ) ;
193 seqServiceNames
.getArray()[0] = OUString::createFromAscii( "com.sun.star.xml.crypto.SecurityEnvironment" ) ;
194 return seqServiceNames
;
197 OUString
SecurityEnvironment_NssImpl :: impl_getImplementationName() throw( RuntimeException
) {
198 return OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.SecurityEnvironment_NssImpl" ) ;
201 //Helper for registry
202 Reference
< XInterface
> SAL_CALL
SecurityEnvironment_NssImpl :: impl_createInstance( const Reference
< XMultiServiceFactory
>& aServiceManager
) throw( RuntimeException
) {
203 return Reference
< XInterface
>( *new SecurityEnvironment_NssImpl( aServiceManager
) ) ;
206 Reference
< XSingleServiceFactory
> SecurityEnvironment_NssImpl :: impl_createFactory( const Reference
< XMultiServiceFactory
>& aServiceManager
) {
207 //Reference< XSingleServiceFactory > xFactory ;
208 //xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
210 return ::cppu::createSingleFactory( aServiceManager
, impl_getImplementationName() , impl_createInstance
, impl_getSupportedServiceNames() ) ;
214 sal_Int64 SAL_CALL
SecurityEnvironment_NssImpl :: getSomething( const Sequence
< sal_Int8
>& aIdentifier
)
215 throw( RuntimeException
)
217 if( aIdentifier
.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(), aIdentifier
.getConstArray(), 16 ) ) {
218 return sal::static_int_cast
<sal_Int64
>(reinterpret_cast<sal_uIntPtr
>(this));
223 /* XUnoTunnel extension */
224 const Sequence
< sal_Int8
>& SecurityEnvironment_NssImpl :: getUnoTunnelId() {
225 static Sequence
< sal_Int8
>* pSeq
= 0 ;
227 ::osl::Guard
< ::osl::Mutex
> aGuard( ::osl::Mutex::getGlobalMutex() ) ;
229 static Sequence
< sal_Int8
> aSeq( 16 ) ;
230 rtl_createUuid( ( sal_uInt8
* )aSeq
.getArray() , 0 , sal_True
) ;
237 /* XUnoTunnel extension */
238 SecurityEnvironment_NssImpl
* SecurityEnvironment_NssImpl :: getImplementation( const Reference
< XInterface
> xObj
) {
239 Reference
< XUnoTunnel
> xUT( xObj
, UNO_QUERY
) ;
241 return reinterpret_cast<SecurityEnvironment_NssImpl
*>(
242 sal::static_int_cast
<sal_uIntPtr
>(xUT
->getSomething( getUnoTunnelId() ))) ;
248 ::rtl::OUString
SecurityEnvironment_NssImpl::getSecurityEnvironmentInformation() throw( ::com::sun::star::uno::RuntimeException
)
250 rtl::OUString result
;
251 ::rtl::OUStringBuffer buff
;
252 for (CIT_SLOTS is
= m_Slots
.begin(); is
!= m_Slots
.end(); is
++)
254 buff
.append(rtl::OUString::createFromAscii(PK11_GetTokenName(*is
)));
255 buff
.appendAscii("\n");
257 return buff
.makeStringAndClear();
260 void SecurityEnvironment_NssImpl::addCryptoSlot( PK11SlotInfo
* aSlot
) throw( Exception
, RuntimeException
)
262 PK11_ReferenceSlot(aSlot
);
263 m_Slots
.push_back(aSlot
);
266 CERTCertDBHandle
* SecurityEnvironment_NssImpl :: getCertDb() throw( Exception
, RuntimeException
) {
270 //Could we have multiple cert dbs?
271 void SecurityEnvironment_NssImpl :: setCertDb( CERTCertDBHandle
* aCertDb
) throw( Exception
, RuntimeException
) {
272 m_pHandler
= aCertDb
;
275 void SecurityEnvironment_NssImpl :: adoptSymKey( PK11SymKey
* aSymKey
) throw( Exception
, RuntimeException
) {
277 std::list
< PK11SymKey
* >::iterator keyIt
;
279 if( aSymKey
!= NULL
) {
280 //First try to find the key in the list
281 for( keyIt
= m_tSymKeyList
.begin() ; keyIt
!= m_tSymKeyList
.end() ; keyIt
++ ) {
282 if( *keyIt
== aSymKey
)
286 //If we do not find the key in the list, add a new node
287 symkey
= PK11_ReferenceSymKey( aSymKey
) ;
289 throw RuntimeException() ;
292 m_tSymKeyList
.push_back( symkey
) ;
293 } catch ( Exception
& ) {
294 PK11_FreeSymKey( symkey
) ;
299 void SecurityEnvironment_NssImpl :: rejectSymKey( PK11SymKey
* aSymKey
) throw( Exception
, RuntimeException
) {
301 std::list
< PK11SymKey
* >::iterator keyIt
;
303 if( aSymKey
!= NULL
) {
304 for( keyIt
= m_tSymKeyList
.begin() ; keyIt
!= m_tSymKeyList
.end() ; keyIt
++ ) {
305 if( *keyIt
== aSymKey
) {
307 PK11_FreeSymKey( symkey
) ;
308 m_tSymKeyList
.erase( keyIt
) ;
315 PK11SymKey
* SecurityEnvironment_NssImpl :: getSymKey( unsigned int position
) throw( Exception
, RuntimeException
) {
317 std::list
< PK11SymKey
* >::iterator keyIt
;
321 for( pos
= 0, keyIt
= m_tSymKeyList
.begin() ; pos
< position
&& keyIt
!= m_tSymKeyList
.end() ; pos
++ , keyIt
++ ) ;
323 if( pos
== position
&& keyIt
!= m_tSymKeyList
.end() )
329 void SecurityEnvironment_NssImpl :: adoptPubKey( SECKEYPublicKey
* aPubKey
) throw( Exception
, RuntimeException
) {
330 SECKEYPublicKey
* pubkey
;
331 std::list
< SECKEYPublicKey
* >::iterator keyIt
;
333 if( aPubKey
!= NULL
) {
334 //First try to find the key in the list
335 for( keyIt
= m_tPubKeyList
.begin() ; keyIt
!= m_tPubKeyList
.end() ; keyIt
++ ) {
336 if( *keyIt
== aPubKey
)
340 //If we do not find the key in the list, add a new node
341 pubkey
= SECKEY_CopyPublicKey( aPubKey
) ;
343 throw RuntimeException() ;
346 m_tPubKeyList
.push_back( pubkey
) ;
347 } catch ( Exception
& ) {
348 SECKEY_DestroyPublicKey( pubkey
) ;
353 void SecurityEnvironment_NssImpl :: rejectPubKey( SECKEYPublicKey
* aPubKey
) throw( Exception
, RuntimeException
) {
354 SECKEYPublicKey
* pubkey
;
355 std::list
< SECKEYPublicKey
* >::iterator keyIt
;
357 if( aPubKey
!= NULL
) {
358 for( keyIt
= m_tPubKeyList
.begin() ; keyIt
!= m_tPubKeyList
.end() ; keyIt
++ ) {
359 if( *keyIt
== aPubKey
) {
361 SECKEY_DestroyPublicKey( pubkey
) ;
362 m_tPubKeyList
.erase( keyIt
) ;
369 SECKEYPublicKey
* SecurityEnvironment_NssImpl :: getPubKey( unsigned int position
) throw( Exception
, RuntimeException
) {
370 SECKEYPublicKey
* pubkey
;
371 std::list
< SECKEYPublicKey
* >::iterator keyIt
;
375 for( pos
= 0, keyIt
= m_tPubKeyList
.begin() ; pos
< position
&& keyIt
!= m_tPubKeyList
.end() ; pos
++ , keyIt
++ ) ;
377 if( pos
== position
&& keyIt
!= m_tPubKeyList
.end() )
383 void SecurityEnvironment_NssImpl :: adoptPriKey( SECKEYPrivateKey
* aPriKey
) throw( Exception
, RuntimeException
) {
384 SECKEYPrivateKey
* prikey
;
385 std::list
< SECKEYPrivateKey
* >::iterator keyIt
;
387 if( aPriKey
!= NULL
) {
388 //First try to find the key in the list
389 for( keyIt
= m_tPriKeyList
.begin() ; keyIt
!= m_tPriKeyList
.end() ; keyIt
++ ) {
390 if( *keyIt
== aPriKey
)
394 //If we do not find the key in the list, add a new node
395 prikey
= SECKEY_CopyPrivateKey( aPriKey
) ;
397 throw RuntimeException() ;
400 m_tPriKeyList
.push_back( prikey
) ;
401 } catch ( Exception
& ) {
402 SECKEY_DestroyPrivateKey( prikey
) ;
407 void SecurityEnvironment_NssImpl :: rejectPriKey( SECKEYPrivateKey
* aPriKey
) throw( Exception
, RuntimeException
) {
408 SECKEYPrivateKey
* prikey
;
409 std::list
< SECKEYPrivateKey
* >::iterator keyIt
;
411 if( aPriKey
!= NULL
) {
412 for( keyIt
= m_tPriKeyList
.begin() ; keyIt
!= m_tPriKeyList
.end() ; keyIt
++ ) {
413 if( *keyIt
== aPriKey
) {
415 SECKEY_DestroyPrivateKey( prikey
) ;
416 m_tPriKeyList
.erase( keyIt
) ;
423 SECKEYPrivateKey
* SecurityEnvironment_NssImpl :: getPriKey( unsigned int position
) throw( ::com::sun::star::uno::Exception
, ::com::sun::star::uno::RuntimeException
) {
424 SECKEYPrivateKey
* prikey
;
425 std::list
< SECKEYPrivateKey
* >::iterator keyIt
;
429 for( pos
= 0, keyIt
= m_tPriKeyList
.begin() ; pos
< position
&& keyIt
!= m_tPriKeyList
.end() ; pos
++ , keyIt
++ ) ;
431 if( pos
== position
&& keyIt
!= m_tPriKeyList
.end() )
437 void SecurityEnvironment_NssImpl::updateSlots()
439 //In case new tokens are present then we can obtain the corresponding slot
440 PK11SlotList
* soltList
= NULL
;
441 PK11SlotListElement
* soltEle
= NULL
;
442 PK11SlotInfo
* pSlot
= NULL
;
443 PK11SymKey
* pSymKey
= NULL
;
445 osl::MutexGuard
guard(m_mutex
);
448 m_tSymKeyList
.clear();
450 soltList
= PK11_GetAllTokens( CKM_INVALID_MECHANISM
, PR_FALSE
, PR_FALSE
, NULL
) ;
451 if( soltList
!= NULL
)
453 for( soltEle
= soltList
->head
; soltEle
!= NULL
; soltEle
= soltEle
->next
)
455 pSlot
= soltEle
->slot
;
459 RTL_LOGFILE_TRACE2( "XMLSEC: Found a slot: SlotName=%s, TokenName=%s", PK11_GetSlotName(pSlot
), PK11_GetTokenName(pSlot
) );
461 //The following code which is commented out checks if a slot, that is a smart card for example, is
462 // able to generate a symmetric key of type CKM_DES3_CBC. If this fails then this token
463 // will not be used. This key is possibly used for the encryption service. However, all
464 // interfaces and services used for public key signature and encryption are not published
465 // and the encryption is not used in OOo. Therefore it does not do any harm to remove
466 // this code, hence allowing smart cards which cannot generate this type of key.
468 // By doing this, the encryption may fail if a smart card is being used which does not
469 // support this key generation.
471 pSymKey
= PK11_KeyGen( pSlot
, CKM_DES3_CBC
, NULL
, 128, NULL
) ;
472 // if( pSymKey == NULL )
474 // PK11_FreeSlot( pSlot ) ;
475 // RTL_LOGFILE_TRACE( "XMLSEC: Error - pSymKey is NULL" );
478 addCryptoSlot(pSlot
);
479 PK11_FreeSlot( pSlot
) ;
484 adoptSymKey( pSymKey
) ;
485 PK11_FreeSymKey( pSymKey
) ;
489 }// end of if(pSlot != NULL)
491 }// end of if( soltList != NULL )
496 Sequence
< Reference
< XCertificate
> >
497 SecurityEnvironment_NssImpl::getPersonalCertificates() throw( SecurityException
, RuntimeException
)
500 X509Certificate_NssImpl
* xcert
;
501 std::list
< X509Certificate_NssImpl
* > certsList
;
504 //firstly, we try to find private keys in slot
505 for (CIT_SLOTS is
= m_Slots
.begin(); is
!= m_Slots
.end(); is
++)
507 PK11SlotInfo
*slot
= *is
;
508 SECKEYPrivateKeyList
* priKeyList
;
509 SECKEYPrivateKeyListNode
* curPri
;
511 if( PK11_NeedLogin(slot
) ) {
512 SECStatus nRet
= PK11_Authenticate(slot
, PR_TRUE
, NULL
);
513 //PK11_Authenticate may fail in case the a slot has not been initialized.
514 //this is the case if the user has a new profile, so that they have never
515 //added a personal certificate.
516 if( nRet
!= SECSuccess
&& PORT_GetError() != SEC_ERROR_IO
) {
517 throw NoPasswordException();
521 priKeyList
= PK11_ListPrivateKeysInSlot(slot
) ;
522 if( priKeyList
!= NULL
) {
523 for( curPri
= PRIVKEY_LIST_HEAD( priKeyList
);
524 !PRIVKEY_LIST_END( curPri
, priKeyList
) && curPri
!= NULL
;
525 curPri
= PRIVKEY_LIST_NEXT( curPri
) ) {
526 xcert
= NssPrivKeyToXCert( curPri
->key
) ;
528 certsList
.push_back( xcert
) ;
532 SECKEY_DestroyPrivateKeyList( priKeyList
) ;
535 //secondly, we try to find certificate from registered private keys.
536 if( !m_tPriKeyList
.empty() ) {
537 std::list
< SECKEYPrivateKey
* >::iterator priKeyIt
;
539 for( priKeyIt
= m_tPriKeyList
.begin() ; priKeyIt
!= m_tPriKeyList
.end() ; priKeyIt
++ ) {
540 xcert
= NssPrivKeyToXCert( *priKeyIt
) ;
542 certsList
.push_back( xcert
) ;
546 length
= certsList
.size() ;
549 std::list
< X509Certificate_NssImpl
* >::iterator xcertIt
;
550 Sequence
< Reference
< XCertificate
> > certSeq( length
) ;
552 for( i
= 0, xcertIt
= certsList
.begin(); xcertIt
!= certsList
.end(); xcertIt
++, i
++ ) {
553 certSeq
[i
] = *xcertIt
;
559 return Sequence
< Reference
< XCertificate
> > ();
562 Reference
< XCertificate
> SecurityEnvironment_NssImpl :: getCertificate( const OUString
& issuerName
, const Sequence
< sal_Int8
>& serialNumber
) throw( SecurityException
, RuntimeException
)
564 X509Certificate_NssImpl
* xcert
= NULL
;
566 if( m_pHandler
!= NULL
) {
567 CERTIssuerAndSN issuerAndSN
;
568 CERTCertificate
* cert
;
574 arena
= PORT_NewArena( DER_DEFAULT_CHUNKSIZE
) ;
576 throw RuntimeException() ;
579 * mmi : because MS Crypto use the 'S' tag (equal to the 'ST' tag in NSS), but the NSS can't recognise
580 * it, so the 'S' tag should be changed to 'ST' tag
582 * PS : it can work, but inside libxmlsec, the 'S' tag is till used to find cert in NSS engine, so it
583 * is not useful at all. (comment out now)
587 sal_Int32 nIndex = 0;
588 OUString newIssuerName;
591 OUString aToken = issuerName.getToken( 0, ',', nIndex ).trim();
592 if (aToken.compareToAscii("S=",2) == 0)
594 newIssuerName+=OUString::createFromAscii("ST=");
595 newIssuerName+=aToken.copy(2);
599 newIssuerName+=aToken;
604 newIssuerName+=OUString::createFromAscii(",");
606 } while ( nIndex >= 0 );
611 //Create cert info from issue and serial
612 rtl::OString ostr
= rtl::OUStringToOString( issuerName
, RTL_TEXTENCODING_UTF8
) ;
613 chIssuer
= PL_strndup( ( char* )ostr
.getStr(), ( int )ostr
.getLength() ) ;
614 nmIssuer
= CERT_AsciiToName( chIssuer
) ;
615 if( nmIssuer
== NULL
) {
616 PL_strfree( chIssuer
) ;
617 PORT_FreeArena( arena
, PR_FALSE
) ;
622 * mmi : no need to throw exception
623 * just return "no found"
625 //throw RuntimeException() ;
629 derIssuer
= SEC_ASN1EncodeItem( arena
, NULL
, ( void* )nmIssuer
, SEC_ASN1_GET( CERT_NameTemplate
) ) ;
630 if( derIssuer
== NULL
) {
631 PL_strfree( chIssuer
) ;
632 CERT_DestroyName( nmIssuer
) ;
633 PORT_FreeArena( arena
, PR_FALSE
) ;
634 throw RuntimeException() ;
637 memset( &issuerAndSN
, 0, sizeof( issuerAndSN
) ) ;
639 issuerAndSN
.derIssuer
.data
= derIssuer
->data
;
640 issuerAndSN
.derIssuer
.len
= derIssuer
->len
;
642 issuerAndSN
.serialNumber
.data
= ( unsigned char* )&serialNumber
[0] ;
643 issuerAndSN
.serialNumber
.len
= serialNumber
.getLength() ;
645 cert
= CERT_FindCertByIssuerAndSN( m_pHandler
, &issuerAndSN
) ;
647 xcert
= NssCertToXCert( cert
) ;
652 PL_strfree( chIssuer
) ;
653 CERT_DestroyName( nmIssuer
) ;
654 //SECITEM_FreeItem( derIssuer, PR_FALSE ) ;
655 CERT_DestroyCertificate( cert
) ;
656 PORT_FreeArena( arena
, PR_FALSE
) ;
664 Reference
< XCertificate
> SecurityEnvironment_NssImpl :: getCertificate( const OUString
& issuerName
, const OUString
& serialNumber
) throw( SecurityException
, RuntimeException
) {
665 Sequence
< sal_Int8
> serial
= numericStringToBigInteger( serialNumber
) ;
666 return getCertificate( issuerName
, serial
) ;
669 Sequence
< Reference
< XCertificate
> > SecurityEnvironment_NssImpl :: buildCertificatePath( const Reference
< XCertificate
>& begin
) throw( SecurityException
, RuntimeException
) {
670 const X509Certificate_NssImpl
* xcert
;
671 const CERTCertificate
* cert
;
672 CERTCertList
* certChain
;
674 Reference
< XUnoTunnel
> xCertTunnel( begin
, UNO_QUERY
) ;
675 if( !xCertTunnel
.is() ) {
676 throw RuntimeException() ;
679 xcert
= reinterpret_cast<X509Certificate_NssImpl
*>(
680 sal::static_int_cast
<sal_uIntPtr
>(xCertTunnel
->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
681 if( xcert
== NULL
) {
682 throw RuntimeException() ;
685 cert
= xcert
->getNssCert() ;
689 //Get the system clock time
690 timeboundary
= PR_Now() ;
692 certChain
= CERT_GetCertChainFromCert( ( CERTCertificate
* )cert
, timeboundary
, certUsageAnyCA
) ;
697 if( certChain
!= NULL
) {
698 X509Certificate_NssImpl
* pCert
;
699 CERTCertListNode
* node
;
702 for( len
= 0, node
= CERT_LIST_HEAD( certChain
); !CERT_LIST_END( node
, certChain
); node
= CERT_LIST_NEXT( node
), len
++ ) ;
703 Sequence
< Reference
< XCertificate
> > xCertChain( len
) ;
705 for( len
= 0, node
= CERT_LIST_HEAD( certChain
); !CERT_LIST_END( node
, certChain
); node
= CERT_LIST_NEXT( node
), len
++ ) {
706 pCert
= new X509Certificate_NssImpl() ;
707 if( pCert
== NULL
) {
708 CERT_DestroyCertList( certChain
) ;
709 throw RuntimeException() ;
712 pCert
->setCert( node
->cert
) ;
714 xCertChain
[len
] = pCert
;
717 CERT_DestroyCertList( certChain
) ;
722 return Sequence
< Reference
< XCertificate
> >();
725 Reference
< XCertificate
> SecurityEnvironment_NssImpl :: createCertificateFromRaw( const Sequence
< sal_Int8
>& rawCertificate
) throw( SecurityException
, RuntimeException
) {
726 X509Certificate_NssImpl
* xcert
;
728 if( rawCertificate
.getLength() > 0 ) {
729 xcert
= new X509Certificate_NssImpl() ;
731 throw RuntimeException() ;
733 xcert
->setRawCert( rawCertificate
) ;
741 Reference
< XCertificate
> SecurityEnvironment_NssImpl :: createCertificateFromAscii( const OUString
& asciiCertificate
) throw( SecurityException
, RuntimeException
) {
743 xmlSecSize certSize
;
745 rtl::OString oscert
= rtl::OUStringToOString( asciiCertificate
, RTL_TEXTENCODING_ASCII_US
) ;
747 chCert
= xmlStrndup( ( const xmlChar
* )oscert
.getStr(), ( int )oscert
.getLength() ) ;
749 certSize
= xmlSecBase64Decode( chCert
, ( xmlSecByte
* )chCert
, xmlStrlen( chCert
) ) ;
751 Sequence
< sal_Int8
> rawCert( certSize
) ;
752 for( unsigned int i
= 0 ; i
< certSize
; i
++ )
753 rawCert
[i
] = *( chCert
+ i
) ;
757 return createCertificateFromRaw( rawCert
) ;
760 sal_Int32
SecurityEnvironment_NssImpl ::
761 verifyCertificate( const Reference
< csss::XCertificate
>& aCert
,
762 const Sequence
< Reference
< csss::XCertificate
> >& intermediateCerts
)
763 throw( ::com::sun::star::uno::SecurityException
, ::com::sun::star::uno::RuntimeException
)
765 sal_Int32 validity
= csss::CertificateValidity::INVALID
;
766 const X509Certificate_NssImpl
* xcert
;
767 const CERTCertificate
* cert
;
768 ::std::vector
<CERTCertificate
*> vecTmpNSSCertificates
;
769 Reference
< XUnoTunnel
> xCertTunnel( aCert
, UNO_QUERY
) ;
770 if( !xCertTunnel
.is() ) {
771 throw RuntimeException() ;
774 xmlsec_trace("Start verification of certificate: \n %s \n",
776 aCert
->getSubjectName(), osl_getThreadTextEncoding()).getStr());
778 xcert
= reinterpret_cast<X509Certificate_NssImpl
*>(
779 sal::static_int_cast
<sal_uIntPtr
>(xCertTunnel
->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
780 if( xcert
== NULL
) {
781 throw RuntimeException() ;
784 //CERT_PKIXVerifyCert does not take a db as argument. It will therefore
785 //internally use CERT_GetDefaultCertDB
786 //Make sure m_pHandler is the default DB
787 OSL_ASSERT(m_pHandler
== CERT_GetDefaultCertDB());
788 CERTCertDBHandle
* certDb
= m_pHandler
!= NULL
? m_pHandler
: CERT_GetDefaultCertDB();
789 cert
= xcert
->getNssCert() ;
793 //prepare the intermediate certificates
794 for (sal_Int32 i
= 0; i
< intermediateCerts
.getLength(); i
++)
796 Sequence
<sal_Int8
> der
= intermediateCerts
[i
]->getEncoded();
798 item
.type
= siBuffer
;
799 item
.data
= (unsigned char*)der
.getArray();
800 item
.len
= der
.getLength();
802 CERTCertificate
* certTmp
= CERT_NewTempCertificate(certDb
, &item
,
804 PR_FALSE
/* isPerm */,
805 PR_TRUE
/* copyDER */);
808 xmlsec_trace("Failed to add a temporary certificate: %s",
809 OUStringToOString(intermediateCerts
[i
]->getIssuerName(),
810 osl_getThreadTextEncoding()).getStr());
815 xmlsec_trace("Added temporary certificate: %s",
816 certTmp
->subjectName
? certTmp
->subjectName
: "");
817 vecTmpNSSCertificates
.push_back(certTmp
);
825 log
.arena
= PORT_NewArena(512);
826 log
.head
= log
.tail
= NULL
;
829 CERT_EnableOCSPChecking(certDb
);
830 CERT_DisableOCSPDefaultResponder(certDb
);
831 CERTValOutParam cvout
[5];
832 CERTValInParam cvin
[3];
834 cvin
[0].type
= cert_pi_useAIACertFetch
;
835 cvin
[0].value
.scalar
.b
= PR_TRUE
;
837 PRUint64 revFlagsLeaf
[2];
838 PRUint64 revFlagsChain
[2];
839 CERTRevocationFlags rev
;
840 rev
.leafTests
.number_of_defined_methods
= 2;
841 rev
.leafTests
.cert_rev_flags_per_method
= revFlagsLeaf
;
842 //the flags are defined in cert.h
843 //We check both leaf and chain.
844 //It is enough if one revocation method has fresh info,
845 //but at least one must have some. Otherwise validation fails.
846 //!!! using leaf test and CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE
847 // when validating a root certificate will result in "revoked". Usually
848 //there is no revocation information available for the root cert because
849 //it must be trusted anyway and it does itself issue revocation information.
850 //When we use the flag here and OOo shows the certification path then the root
851 //cert is invalid while all other can be valid. It would probably best if
852 //this interface method returned the whole chain.
853 //Otherwise we need to check if the certificate is self-signed and if it is
854 //then not use the flag when doing the leaf-test.
855 rev
.leafTests
.cert_rev_flags_per_method
[cert_revocation_method_crl
] =
856 CERT_REV_M_TEST_USING_THIS_METHOD
857 | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE
;
858 rev
.leafTests
.cert_rev_flags_per_method
[cert_revocation_method_ocsp
] =
859 CERT_REV_M_TEST_USING_THIS_METHOD
860 | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE
;
861 rev
.leafTests
.number_of_preferred_methods
= 0;
862 rev
.leafTests
.preferred_methods
= NULL
;
863 rev
.leafTests
.cert_rev_method_independent_flags
=
864 CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST
;
865 // | CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
867 rev
.chainTests
.number_of_defined_methods
= 2;
868 rev
.chainTests
.cert_rev_flags_per_method
= revFlagsChain
;
869 rev
.chainTests
.cert_rev_flags_per_method
[cert_revocation_method_crl
] =
870 CERT_REV_M_TEST_USING_THIS_METHOD
871 | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE
;
872 rev
.chainTests
.cert_rev_flags_per_method
[cert_revocation_method_ocsp
] =
873 CERT_REV_M_TEST_USING_THIS_METHOD
874 | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE
;
875 rev
.chainTests
.number_of_preferred_methods
= 0;
876 rev
.chainTests
.preferred_methods
= NULL
;
877 rev
.chainTests
.cert_rev_method_independent_flags
=
878 CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST
;
879 // | CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
882 cvin
[1].type
= cert_pi_revocationFlags
;
883 cvin
[1].value
.pointer
.revocation
= &rev
;
884 // does not work, not implemented yet in 3.12.4
885 // cvin[2].type = cert_pi_keyusage;
886 // cvin[2].value.scalar.ui = KU_DIGITAL_SIGNATURE;
887 cvin
[2].type
= cert_pi_end
;
889 cvout
[0].type
= cert_po_trustAnchor
;
890 cvout
[0].value
.pointer
.cert
= NULL
;
891 cvout
[1].type
= cert_po_errorLog
;
892 cvout
[1].value
.pointer
.log
= &log
;
893 cvout
[2].type
= cert_po_end
;
895 // We check SSL server certificates, CA certificates and signing sertificates.
897 // ToDo check keyusage, looking at CERT_KeyUsageAndTypeForCertUsage (
898 // mozilla/security/nss/lib/certdb/certdb.c indicates that
899 // certificateUsageSSLClient, certificateUsageSSLServer and certificateUsageSSLCA
900 // are sufficient. They cover the key usages for digital signature, key agreement
901 // and encipherment and certificate signature
903 //never use the following usages because they are not checked properly
904 // certificateUsageUserCertImport
905 // certificateUsageVerifyCA
906 // certificateUsageAnyCA
907 // certificateUsageProtectedObjectSigner
909 UsageDescription arUsages
[] =
911 {certificateUsageSSLClient
, "certificateUsageSSLClient" },
912 {certificateUsageSSLServer
, "certificateUsageSSLServer" },
913 {certificateUsageSSLCA
, "certificateUsageSSLCA" },
914 {certificateUsageEmailSigner
, "certificateUsageEmailSigner"}, //only usable for end certs
915 {certificateUsageEmailRecipient
, "certificateUsageEmailRecipient"}
918 int numUsages
= sizeof(arUsages
) / sizeof(UsageDescription
);
919 for (int i
= 0; i
< numUsages
; i
++)
921 xmlsec_trace("Testing usage %d of %d: %s (0x%x)", i
+ 1,
922 numUsages
, arUsages
[i
].description
, (int) arUsages
[i
].usage
);
924 status
= CERT_PKIXVerifyCert(const_cast<CERTCertificate
*>(cert
), arUsages
[i
].usage
,
926 if( status
== SECSuccess
)
928 xmlsec_trace("CERT_PKIXVerifyCert returned SECSuccess.");
929 //When an intermediate or root certificate is checked then we expect the usage
930 //certificateUsageSSLCA. This, however, will be only set when in the trust settings dialog
931 //the button "This certificate can identify websites" is checked. If for example only
932 //"This certificate can identify mail users" is set then the end certificate can
933 //be validated and the returned usage will conain certificateUsageEmailRecipient.
934 //But checking directly the root or intermediate certificate will fail. In the
935 //certificate path view the end certificate will be shown as valid but the others
936 //will be displayed as invalid.
938 validity
= csss::CertificateValidity::VALID
;
939 xmlsec_trace("Certificate is valid.\n");
940 CERTCertificate
* issuerCert
= cvout
[0].value
.pointer
.cert
;
943 xmlsec_trace("Root certificate: %s", issuerCert
->subjectName
);
944 CERT_DestroyCertificate(issuerCert
);
951 PRIntn err
= PR_GetError();
952 xmlsec_trace("Error: , %d = %s", err
, getCertError(err
));
954 /* Display validation results */
957 CERTVerifyLogNode
*node
= NULL
;
958 printChainFailure(&log
);
960 for (node
= log
.head
; node
; node
= node
->next
) {
962 CERT_DestroyCertificate(node
->cert
);
964 log
.head
= log
.tail
= NULL
;
967 xmlsec_trace("Certificate is invalid.\n");
974 validity
= ::com::sun::star::security::CertificateValidity::INVALID
;
977 //Destroying the temporary certificates
978 std::vector
<CERTCertificate
*>::const_iterator cert_i
;
979 for (cert_i
= vecTmpNSSCertificates
.begin(); cert_i
!= vecTmpNSSCertificates
.end(); cert_i
++)
981 xmlsec_trace("Destroying temporary certificate");
982 CERT_DestroyCertificate(*cert_i
);
987 sal_Int32
SecurityEnvironment_NssImpl::getCertificateCharacters(
988 const ::com::sun::star::uno::Reference
< ::com::sun::star::security::XCertificate
>& aCert
) throw( ::com::sun::star::uno::SecurityException
, ::com::sun::star::uno::RuntimeException
) {
989 sal_Int32 characters
;
990 const X509Certificate_NssImpl
* xcert
;
991 const CERTCertificate
* cert
;
993 Reference
< XUnoTunnel
> xCertTunnel( aCert
, UNO_QUERY
) ;
994 if( !xCertTunnel
.is() ) {
995 throw RuntimeException() ;
998 xcert
= reinterpret_cast<X509Certificate_NssImpl
*>(
999 sal::static_int_cast
<sal_uIntPtr
>(xCertTunnel
->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
1000 if( xcert
== NULL
) {
1001 throw RuntimeException() ;
1004 cert
= xcert
->getNssCert() ;
1006 characters
= 0x00000000 ;
1008 //Firstly, find out whether or not the cert is self-signed.
1009 if( SECITEM_CompareItem( &(cert
->derIssuer
), &(cert
->derSubject
) ) == SECEqual
) {
1010 characters
|= ::com::sun::star::security::CertificateCharacters::SELF_SIGNED
;
1012 characters
&= ~ ::com::sun::star::security::CertificateCharacters::SELF_SIGNED
;
1015 //Secondly, find out whether or not the cert has a private key.
1020 * mmi : need to check whether the cert's slot is valid first
1022 SECKEYPrivateKey
* priKey
= NULL
;
1024 if (cert
->slot
!= NULL
)
1026 priKey
= PK11_FindPrivateKeyFromCert( cert
->slot
, ( CERTCertificate
* )cert
, NULL
) ;
1030 for (CIT_SLOTS is
= m_Slots
.begin(); is
!= m_Slots
.end(); is
++)
1032 priKey
= PK11_FindPrivateKeyFromCert(*is
, (CERTCertificate
*)cert
, NULL
);
1037 if( priKey
!= NULL
) {
1038 characters
|= ::com::sun::star::security::CertificateCharacters::HAS_PRIVATE_KEY
;
1040 SECKEY_DestroyPrivateKey( priKey
) ;
1042 characters
&= ~ ::com::sun::star::security::CertificateCharacters::HAS_PRIVATE_KEY
;
1048 X509Certificate_NssImpl
* NssCertToXCert( CERTCertificate
* cert
)
1050 X509Certificate_NssImpl
* xcert
;
1052 if( cert
!= NULL
) {
1053 xcert
= new X509Certificate_NssImpl() ;
1054 if( xcert
== NULL
) {
1057 xcert
->setCert( cert
) ;
1066 X509Certificate_NssImpl
* NssPrivKeyToXCert( SECKEYPrivateKey
* priKey
)
1068 CERTCertificate
* cert
;
1069 X509Certificate_NssImpl
* xcert
;
1071 if( priKey
!= NULL
) {
1072 cert
= PK11_GetCertFromPrivateKey( priKey
) ;
1074 if( cert
!= NULL
) {
1075 xcert
= NssCertToXCert( cert
) ;
1080 CERT_DestroyCertificate( cert
) ;
1089 /* Native methods */
1090 xmlSecKeysMngrPtr
SecurityEnvironment_NssImpl::createKeysManager() throw( Exception
, RuntimeException
) {
1093 CERTCertDBHandle
* handler
= NULL
;
1094 PK11SymKey
* symKey
= NULL
;
1095 SECKEYPublicKey
* pubKey
= NULL
;
1096 SECKEYPrivateKey
* priKey
= NULL
;
1097 xmlSecKeysMngrPtr pKeysMngr
= NULL
;
1099 handler
= this->getCertDb() ;
1102 * The following lines is based on the private version of xmlSec-NSS
1105 int cSlots
= m_Slots
.size();
1106 boost::scoped_array
<PK11SlotInfo
*> sarSlots(new PK11SlotInfo
*[cSlots
]);
1107 PK11SlotInfo
** slots
= sarSlots
.get();
1109 for (CIT_SLOTS islots
= m_Slots
.begin();islots
!= m_Slots
.end(); islots
++, count
++)
1110 slots
[count
] = *islots
;
1112 pKeysMngr
= xmlSecNssAppliedKeysMngrCreate(slots
, cSlots
, handler
) ;
1113 if( pKeysMngr
== NULL
)
1114 throw RuntimeException() ;
1117 * Adopt symmetric key into keys manager
1119 for( i
= 0 ; ( symKey
= this->getSymKey( i
) ) != NULL
; i
++ ) {
1120 if( xmlSecNssAppliedKeysMngrSymKeyLoad( pKeysMngr
, symKey
) < 0 ) {
1121 throw RuntimeException() ;
1126 * Adopt asymmetric public key into keys manager
1128 for( i
= 0 ; ( pubKey
= this->getPubKey( i
) ) != NULL
; i
++ ) {
1129 if( xmlSecNssAppliedKeysMngrPubKeyLoad( pKeysMngr
, pubKey
) < 0 ) {
1130 throw RuntimeException() ;
1135 * Adopt asymmetric private key into keys manager
1137 for( i
= 0 ; ( priKey
= this->getPriKey( i
) ) != NULL
; i
++ ) {
1138 if( xmlSecNssAppliedKeysMngrPriKeyLoad( pKeysMngr
, priKey
) < 0 ) {
1139 throw RuntimeException() ;
1144 void SecurityEnvironment_NssImpl::destroyKeysManager(xmlSecKeysMngrPtr pKeysMngr
) throw( Exception
, RuntimeException
) {
1145 if( pKeysMngr
!= NULL
) {
1146 xmlSecKeysMngrDestroy( pKeysMngr
) ;