xref: /trunk/main/xmlsecurity/source/xmlsec/nss/securityenvironment_nssimpl.cxx (revision 91144cd0085a7583d2099b982122deb2184ab956)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 
25 // MARKER(update_precomp.py): autogen include statement, do not remove
26 #include "precompiled_xmlsecurity.hxx"
27 
28 //todo before commit:  nssrenam.h is not delivered!!!
29 #ifndef __nssrenam_h_
30 #define CERT_NewTempCertificate __CERT_NewTempCertificate
31 #endif /* __nssrenam_h_ */
32 
33 #include "cert.h"
34 #include "secerr.h"
35 #include "ocsp.h"
36 
37 #include <sal/config.h>
38 #include "securityenvironment_nssimpl.hxx"
39 #include "x509certificate_nssimpl.hxx"
40 #include <rtl/uuid.h>
41 #include "../diagnose.hxx"
42 
43 #include <sal/types.h>
44 //For reasons that escape me, this is what xmlsec does when size_t is not 4
45 #if SAL_TYPES_SIZEOFPOINTER != 4
46 #    define XMLSEC_NO_SIZE_T
47 #endif
48 #include <xmlsec/xmlsec.h>
49 #include <xmlsec/keysmngr.h>
50 #include <xmlsec/crypto.h>
51 #include <xmlsec/base64.h>
52 #include <xmlsec/strings.h>
53 
54 #include <tools/string.hxx>
55 #include <rtl/ustrbuf.hxx>
56 #include <comphelper/processfactory.hxx>
57 #include <cppuhelper/servicefactory.hxx>
58 #include <comphelper/docpasswordrequest.hxx>
59 #include <xmlsecurity/biginteger.hxx>
60 #include <rtl/logfile.h>
61 #include <com/sun/star/task/XInteractionHandler.hpp>
62 #include <vector>
63 #include "boost/scoped_array.hpp"
64 
65 #include "secerror.hxx"
66 
67 // MM : added for password exception
68 #include <com/sun/star/security/NoPasswordException.hpp>
69 namespace csss = ::com::sun::star::security;
70 using namespace xmlsecurity;
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 ;
78 
79 using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
80 using ::com::sun::star::security::XCertificate ;
81 
82 extern X509Certificate_NssImpl* NssCertToXCert( CERTCertificate* cert ) ;
83 extern X509Certificate_NssImpl* NssPrivKeyToXCert( SECKEYPrivateKey* ) ;
84 
85 
86 struct UsageDescription
87 {
88     SECCertificateUsage usage;
89     char const* description;
90 
UsageDescriptionUsageDescription91     UsageDescription()
92     : usage( certificateUsageCheckAllUsages )
93     , description( NULL )
94     {}
95 
UsageDescriptionUsageDescription96     UsageDescription( SECCertificateUsage i_usage, char const* i_description )
97     : usage( i_usage )
98     , description( i_description )
99     {}
100 
UsageDescriptionUsageDescription101     UsageDescription( const UsageDescription& aDescription )
102     : usage( aDescription.usage )
103     , description( aDescription.description )
104     {}
105 
operator =UsageDescription106     UsageDescription& operator =( const UsageDescription& aDescription )
107     {
108         usage = aDescription.usage;
109         description = aDescription.description;
110         return *this;
111     }
112 };
113 
114 
115 
GetPasswordFunction(PK11SlotInfo * pSlot,PRBool bRetry,void *)116 char* GetPasswordFunction( PK11SlotInfo* pSlot, PRBool bRetry, void* /*arg*/ )
117 {
118     uno::Reference< lang::XMultiServiceFactory > xMSF( ::comphelper::getProcessServiceFactory() );
119     if ( xMSF.is() )
120     {
121         uno::Reference < task::XInteractionHandler > xInteractionHandler(
122             xMSF->createInstance( rtl::OUString::createFromAscii("com.sun.star.task.InteractionHandler") ), uno::UNO_QUERY );
123 
124         if ( xInteractionHandler.is() )
125         {
126             task::PasswordRequestMode eMode = bRetry ? task::PasswordRequestMode_PASSWORD_REENTER : task::PasswordRequestMode_PASSWORD_ENTER;
127             ::comphelper::DocPasswordRequest* pPasswordRequest = new ::comphelper::DocPasswordRequest(
128                 ::comphelper::DocPasswordRequestType_STANDARD, eMode, ::rtl::OUString::createFromAscii(PK11_GetTokenName(pSlot)) );
129 
130             uno::Reference< task::XInteractionRequest > xRequest( pPasswordRequest );
131             xInteractionHandler->handle( xRequest );
132 
133             if ( pPasswordRequest->isPassword() )
134             {
135                 ByteString aPassword = ByteString( String( pPasswordRequest->getPassword() ), gsl_getSystemTextEncoding() );
136                 sal_uInt16 nLen = aPassword.Len();
137                 char* pPassword = (char*) PORT_Alloc( nLen+1 ) ;
138                 pPassword[nLen] = 0;
139                 memcpy( pPassword, aPassword.GetBuffer(), nLen );
140                 return pPassword;
141             }
142         }
143     }
144     return NULL;
145 }
146 
SecurityEnvironment_NssImpl(const Reference<XMultiServiceFactory> &)147 SecurityEnvironment_NssImpl :: SecurityEnvironment_NssImpl( const Reference< XMultiServiceFactory >& ) :
148 m_pHandler( NULL ) , m_tSymKeyList() , m_tPubKeyList() , m_tPriKeyList() {
149 
150     PK11_SetPasswordFunc( GetPasswordFunction ) ;
151 }
152 
~SecurityEnvironment_NssImpl()153 SecurityEnvironment_NssImpl :: ~SecurityEnvironment_NssImpl() {
154 
155     PK11_SetPasswordFunc( NULL ) ;
156 
157     for (CIT_SLOTS i = m_Slots.begin(); i != m_Slots.end(); i++)
158     {
159         PK11_FreeSlot(*i);
160     }
161 
162     if( !m_tSymKeyList.empty()  ) {
163         std::list< PK11SymKey* >::iterator symKeyIt ;
164 
165         for( symKeyIt = m_tSymKeyList.begin() ; symKeyIt != m_tSymKeyList.end() ; symKeyIt ++ )
166             PK11_FreeSymKey( *symKeyIt ) ;
167     }
168 
169     if( !m_tPubKeyList.empty()  ) {
170         std::list< SECKEYPublicKey* >::iterator pubKeyIt ;
171 
172         for( pubKeyIt = m_tPubKeyList.begin() ; pubKeyIt != m_tPubKeyList.end() ; pubKeyIt ++ )
173             SECKEY_DestroyPublicKey( *pubKeyIt ) ;
174     }
175 
176     if( !m_tPriKeyList.empty()  ) {
177         std::list< SECKEYPrivateKey* >::iterator priKeyIt ;
178 
179         for( priKeyIt = m_tPriKeyList.begin() ; priKeyIt != m_tPriKeyList.end() ; priKeyIt ++ )
180             SECKEY_DestroyPrivateKey( *priKeyIt ) ;
181     }
182 }
183 
184 /* XInitialization */
initialize(const Sequence<Any> &)185 void SAL_CALL SecurityEnvironment_NssImpl :: initialize( const Sequence< Any >& ) {
186     // TBD
187 } ;
188 
189 /* XServiceInfo */
getImplementationName()190 OUString SAL_CALL SecurityEnvironment_NssImpl :: getImplementationName() {
191     return impl_getImplementationName() ;
192 }
193 
194 /* XServiceInfo */
supportsService(const OUString & serviceName)195 sal_Bool SAL_CALL SecurityEnvironment_NssImpl :: supportsService( const OUString& serviceName) {
196     Sequence< OUString > seqServiceNames = getSupportedServiceNames() ;
197     const OUString* pArray = seqServiceNames.getConstArray() ;
198     for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) {
199         if( *( pArray + i ) == serviceName )
200             return sal_True ;
201     }
202     return sal_False ;
203 }
204 
205 /* XServiceInfo */
getSupportedServiceNames()206 Sequence< OUString > SAL_CALL SecurityEnvironment_NssImpl :: getSupportedServiceNames() {
207     return impl_getSupportedServiceNames() ;
208 }
209 
210 //Helper for XServiceInfo
impl_getSupportedServiceNames()211 Sequence< OUString > SecurityEnvironment_NssImpl :: impl_getSupportedServiceNames() {
212     ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
213     Sequence< OUString > seqServiceNames( 1 ) ;
214     seqServiceNames.getArray()[0] = OUString::createFromAscii( "com.sun.star.xml.crypto.SecurityEnvironment" ) ;
215     return seqServiceNames ;
216 }
217 
impl_getImplementationName()218 OUString SecurityEnvironment_NssImpl :: impl_getImplementationName() {
219     return OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.SecurityEnvironment_NssImpl" ) ;
220 }
221 
222 //Helper for registry
impl_createInstance(const Reference<XMultiServiceFactory> & aServiceManager)223 Reference< XInterface > SAL_CALL SecurityEnvironment_NssImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) {
224     return Reference< XInterface >( *new SecurityEnvironment_NssImpl( aServiceManager ) ) ;
225 }
226 
impl_createFactory(const Reference<XMultiServiceFactory> & aServiceManager)227 Reference< XSingleServiceFactory > SecurityEnvironment_NssImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) {
228     //Reference< XSingleServiceFactory > xFactory ;
229     //xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
230     //return xFactory ;
231     return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ;
232 }
233 
234 /* XUnoTunnel */
getSomething(const Sequence<sal_Int8> & aIdentifier)235 sal_Int64 SAL_CALL SecurityEnvironment_NssImpl :: getSomething( const Sequence< sal_Int8 >& aIdentifier )
236 {
237     if( aIdentifier.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(), aIdentifier.getConstArray(), 16 ) ) {
238         return sal::static_int_cast<sal_Int64>(reinterpret_cast<sal_uIntPtr>(this));
239     }
240     return 0 ;
241 }
242 
243 /* XUnoTunnel extension */
getUnoTunnelId()244 const Sequence< sal_Int8>& SecurityEnvironment_NssImpl :: getUnoTunnelId() {
245     static Sequence< sal_Int8 >* pSeq = 0 ;
246     if( !pSeq ) {
247         ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
248         if( !pSeq ) {
249             static Sequence< sal_Int8> aSeq( 16 ) ;
250             rtl_createUuid( ( sal_uInt8* )aSeq.getArray() , 0 , sal_True ) ;
251             pSeq = &aSeq ;
252         }
253     }
254     return *pSeq ;
255 }
256 
257 /* XUnoTunnel extension */
getImplementation(const Reference<XInterface> xObj)258 SecurityEnvironment_NssImpl* SecurityEnvironment_NssImpl :: getImplementation( const Reference< XInterface > xObj ) {
259     Reference< XUnoTunnel > xUT( xObj , UNO_QUERY ) ;
260     if( xUT.is() ) {
261         return reinterpret_cast<SecurityEnvironment_NssImpl*>(
262             sal::static_int_cast<sal_uIntPtr>(xUT->getSomething( getUnoTunnelId() ))) ;
263     } else
264         return NULL ;
265 }
266 
267 
getSecurityEnvironmentInformation()268 ::rtl::OUString SecurityEnvironment_NssImpl::getSecurityEnvironmentInformation()
269 {
270     rtl::OUString result;
271     ::rtl::OUStringBuffer buff;
272     for (CIT_SLOTS is = m_Slots.begin(); is != m_Slots.end(); is++)
273     {
274         buff.append(rtl::OUString::createFromAscii(PK11_GetTokenName(*is)));
275         buff.appendAscii("\n");
276     }
277     return buff.makeStringAndClear();
278 }
279 
addCryptoSlot(PK11SlotInfo * aSlot)280 void SecurityEnvironment_NssImpl::addCryptoSlot( PK11SlotInfo* aSlot)
281 {
282     PK11_ReferenceSlot(aSlot);
283     m_Slots.push_back(aSlot);
284 }
285 
getCertDb()286 CERTCertDBHandle* SecurityEnvironment_NssImpl :: getCertDb() {
287     return m_pHandler ;
288 }
289 
290 //Could we have multiple cert dbs?
setCertDb(CERTCertDBHandle * aCertDb)291 void SecurityEnvironment_NssImpl :: setCertDb( CERTCertDBHandle* aCertDb ) {
292     m_pHandler = aCertDb ;
293 }
294 
adoptSymKey(PK11SymKey * aSymKey)295 void SecurityEnvironment_NssImpl :: adoptSymKey( PK11SymKey* aSymKey ) {
296     PK11SymKey* symkey ;
297     std::list< PK11SymKey* >::iterator keyIt ;
298 
299     if( aSymKey != NULL ) {
300         //First try to find the key in the list
301         for( keyIt = m_tSymKeyList.begin() ; keyIt != m_tSymKeyList.end() ; keyIt ++ ) {
302             if( *keyIt == aSymKey )
303                 return ;
304         }
305 
306         //If we do not find the key in the list, add a new node
307         symkey = PK11_ReferenceSymKey( aSymKey ) ;
308         if( symkey == NULL )
309             throw RuntimeException() ;
310 
311         try {
312             m_tSymKeyList.push_back( symkey ) ;
313         } catch ( Exception& ) {
314             PK11_FreeSymKey( symkey ) ;
315         }
316     }
317 }
318 
rejectSymKey(PK11SymKey * aSymKey)319 void SecurityEnvironment_NssImpl :: rejectSymKey( PK11SymKey* aSymKey ) {
320     PK11SymKey* symkey ;
321     std::list< PK11SymKey* >::iterator keyIt ;
322 
323     if( aSymKey != NULL ) {
324         for( keyIt = m_tSymKeyList.begin() ; keyIt != m_tSymKeyList.end() ; keyIt ++ ) {
325             if( *keyIt == aSymKey ) {
326                 symkey = *keyIt ;
327                 PK11_FreeSymKey( symkey ) ;
328                 m_tSymKeyList.erase( keyIt ) ;
329                 break ;
330             }
331         }
332     }
333 }
334 
getSymKey(unsigned int position)335 PK11SymKey* SecurityEnvironment_NssImpl :: getSymKey( unsigned int position ) {
336     PK11SymKey* symkey ;
337     std::list< PK11SymKey* >::iterator keyIt ;
338     unsigned int pos ;
339 
340     symkey = NULL ;
341     for( pos = 0, keyIt = m_tSymKeyList.begin() ; pos < position && keyIt != m_tSymKeyList.end() ; pos ++ , keyIt ++ ) ;
342 
343     if( pos == position && keyIt != m_tSymKeyList.end() )
344         symkey = *keyIt ;
345 
346     return symkey ;
347 }
348 
adoptPubKey(SECKEYPublicKey * aPubKey)349 void SecurityEnvironment_NssImpl :: adoptPubKey( SECKEYPublicKey* aPubKey ) {
350     SECKEYPublicKey*    pubkey ;
351     std::list< SECKEYPublicKey* >::iterator keyIt ;
352 
353     if( aPubKey != NULL ) {
354         //First try to find the key in the list
355         for( keyIt = m_tPubKeyList.begin() ; keyIt != m_tPubKeyList.end() ; keyIt ++ ) {
356             if( *keyIt == aPubKey )
357                 return ;
358         }
359 
360         //If we do not find the key in the list, add a new node
361         pubkey = SECKEY_CopyPublicKey( aPubKey ) ;
362         if( pubkey == NULL )
363             throw RuntimeException() ;
364 
365         try {
366             m_tPubKeyList.push_back( pubkey ) ;
367         } catch ( Exception& ) {
368             SECKEY_DestroyPublicKey( pubkey ) ;
369         }
370     }
371 }
372 
rejectPubKey(SECKEYPublicKey * aPubKey)373 void SecurityEnvironment_NssImpl :: rejectPubKey( SECKEYPublicKey* aPubKey ) {
374     SECKEYPublicKey*    pubkey ;
375     std::list< SECKEYPublicKey* >::iterator keyIt ;
376 
377     if( aPubKey != NULL ) {
378         for( keyIt = m_tPubKeyList.begin() ; keyIt != m_tPubKeyList.end() ; keyIt ++ ) {
379             if( *keyIt == aPubKey ) {
380                 pubkey = *keyIt ;
381                 SECKEY_DestroyPublicKey( pubkey ) ;
382                 m_tPubKeyList.erase( keyIt ) ;
383                 break ;
384             }
385         }
386     }
387 }
388 
getPubKey(unsigned int position)389 SECKEYPublicKey* SecurityEnvironment_NssImpl :: getPubKey( unsigned int position ) {
390     SECKEYPublicKey* pubkey ;
391     std::list< SECKEYPublicKey* >::iterator keyIt ;
392     unsigned int pos ;
393 
394     pubkey = NULL ;
395     for( pos = 0, keyIt = m_tPubKeyList.begin() ; pos < position && keyIt != m_tPubKeyList.end() ; pos ++ , keyIt ++ ) ;
396 
397     if( pos == position && keyIt != m_tPubKeyList.end() )
398         pubkey = *keyIt ;
399 
400     return pubkey ;
401 }
402 
adoptPriKey(SECKEYPrivateKey * aPriKey)403 void SecurityEnvironment_NssImpl :: adoptPriKey( SECKEYPrivateKey* aPriKey ) {
404     SECKEYPrivateKey*   prikey ;
405     std::list< SECKEYPrivateKey* >::iterator keyIt ;
406 
407     if( aPriKey != NULL ) {
408         //First try to find the key in the list
409         for( keyIt = m_tPriKeyList.begin() ; keyIt != m_tPriKeyList.end() ; keyIt ++ ) {
410             if( *keyIt == aPriKey )
411                 return ;
412         }
413 
414         //If we do not find the key in the list, add a new node
415         prikey = SECKEY_CopyPrivateKey( aPriKey ) ;
416         if( prikey == NULL )
417             throw RuntimeException() ;
418 
419         try {
420             m_tPriKeyList.push_back( prikey ) ;
421         } catch ( Exception& ) {
422             SECKEY_DestroyPrivateKey( prikey ) ;
423         }
424     }
425 }
426 
rejectPriKey(SECKEYPrivateKey * aPriKey)427 void SecurityEnvironment_NssImpl :: rejectPriKey( SECKEYPrivateKey* aPriKey ) {
428     SECKEYPrivateKey*   prikey ;
429     std::list< SECKEYPrivateKey* >::iterator keyIt ;
430 
431     if( aPriKey != NULL ) {
432         for( keyIt = m_tPriKeyList.begin() ; keyIt != m_tPriKeyList.end() ; keyIt ++ ) {
433             if( *keyIt == aPriKey ) {
434                 prikey = *keyIt ;
435                 SECKEY_DestroyPrivateKey( prikey ) ;
436                 m_tPriKeyList.erase( keyIt ) ;
437                 break ;
438             }
439         }
440     }
441 }
442 
getPriKey(unsigned int position)443 SECKEYPrivateKey* SecurityEnvironment_NssImpl :: getPriKey( unsigned int position )  {
444     SECKEYPrivateKey* prikey ;
445     std::list< SECKEYPrivateKey* >::iterator keyIt ;
446     unsigned int pos ;
447 
448     prikey = NULL ;
449     for( pos = 0, keyIt = m_tPriKeyList.begin() ; pos < position && keyIt != m_tPriKeyList.end() ; pos ++ , keyIt ++ ) ;
450 
451     if( pos == position && keyIt != m_tPriKeyList.end() )
452         prikey = *keyIt ;
453 
454     return prikey ;
455 }
456 
updateSlots()457 void SecurityEnvironment_NssImpl::updateSlots()
458 {
459     //In case new tokens are present then we can obtain the corresponding slot
460     PK11SlotList * soltList = NULL;
461     PK11SlotListElement * soltEle = NULL;
462     PK11SlotInfo * pSlot = NULL;
463     PK11SymKey * pSymKey = NULL;
464 
465     osl::MutexGuard guard(m_mutex);
466 
467     m_Slots.clear();
468     m_tSymKeyList.clear();
469 
470     soltList = PK11_GetAllTokens( CKM_INVALID_MECHANISM, PR_FALSE, PR_FALSE, NULL ) ;
471     if( soltList != NULL )
472     {
473         for( soltEle = soltList->head ; soltEle != NULL; soltEle = soltEle->next )
474         {
475             pSlot = soltEle->slot ;
476 
477             if(pSlot != NULL)
478             {
479                 RTL_LOGFILE_TRACE2( "XMLSEC: Found a slot: SlotName=%s, TokenName=%s", PK11_GetSlotName(pSlot), PK11_GetTokenName(pSlot) );
480 
481 //The following code which is commented out checks if a slot, that is a smart card for example, is
482 //              able to generate a symmetric key of type CKM_DES3_CBC. If this fails then this token
483 //              will not be used. This key is possibly used for the encryption service. However, all
484 //              interfaces and services used for public key signature and encryption are not published
485 //              and the encryption is not used in OOo. Therefore it does not do any harm to remove
486 //              this code, hence allowing smart cards which cannot generate this type of key.
487 //
488 //              By doing this, the encryption may fail if a smart card is being used which does not
489 //              support this key generation.
490 //
491                 pSymKey = PK11_KeyGen( pSlot , CKM_DES3_CBC, NULL, 128, NULL ) ;
492 //              if( pSymKey == NULL )
493 //              {
494 //                  PK11_FreeSlot( pSlot ) ;
495 //                  RTL_LOGFILE_TRACE( "XMLSEC: Error - pSymKey is NULL" );
496 //                  continue;
497 //              }
498                 addCryptoSlot(pSlot);
499                 PK11_FreeSlot( pSlot ) ;
500                 pSlot = NULL;
501 
502                 if (pSymKey != NULL)
503                 {
504                     adoptSymKey( pSymKey ) ;
505                     PK11_FreeSymKey( pSymKey ) ;
506                     pSymKey = NULL;
507                 }
508 
509             }// end of if(pSlot != NULL)
510         }// end of for
511     }// end of if( soltList != NULL )
512 
513 }
514 
515 
516 Sequence< Reference < XCertificate > >
getPersonalCertificates()517 SecurityEnvironment_NssImpl::getPersonalCertificates()
518 {
519     sal_Int32 length ;
520     X509Certificate_NssImpl* xcert ;
521     std::list< X509Certificate_NssImpl* > certsList ;
522 
523     updateSlots();
524     //firstly, we try to find private keys in slot
525     for (CIT_SLOTS is = m_Slots.begin(); is != m_Slots.end(); is++)
526     {
527         PK11SlotInfo *slot = *is;
528         SECKEYPrivateKeyList* priKeyList ;
529         SECKEYPrivateKeyListNode* curPri ;
530 
531         if( PK11_NeedLogin(slot ) ) {
532             SECStatus nRet = PK11_Authenticate(slot, PR_TRUE, NULL);
533             //PK11_Authenticate may fail in case the a slot has not been initialized.
534             //this is the case if the user has a new profile, so that they have never
535             //added a personal certificate.
536             if( nRet != SECSuccess && PORT_GetError() != SEC_ERROR_IO) {
537                 throw NoPasswordException();
538             }
539         }
540 
541         priKeyList = PK11_ListPrivateKeysInSlot(slot) ;
542         if( priKeyList != NULL ) {
543             for( curPri = PRIVKEY_LIST_HEAD( priKeyList );
544                 !PRIVKEY_LIST_END( curPri, priKeyList ) && curPri != NULL ;
545                 curPri = PRIVKEY_LIST_NEXT( curPri ) ) {
546                 xcert = NssPrivKeyToXCert( curPri->key ) ;
547                 if( xcert != NULL )
548                     certsList.push_back( xcert ) ;
549             }
550             SECKEY_DestroyPrivateKeyList( priKeyList ) ;
551         }
552 
553     }
554 
555     //secondly, we try to find certificate from registered private keys.
556     if( !m_tPriKeyList.empty()  ) {
557         std::list< SECKEYPrivateKey* >::iterator priKeyIt ;
558 
559         for( priKeyIt = m_tPriKeyList.begin() ; priKeyIt != m_tPriKeyList.end() ; priKeyIt ++ ) {
560             xcert = NssPrivKeyToXCert( *priKeyIt ) ;
561             if( xcert != NULL )
562                 certsList.push_back( xcert ) ;
563         }
564     }
565 
566     length = certsList.size() ;
567     if( length != 0 ) {
568         int i ;
569         std::list< X509Certificate_NssImpl* >::iterator xcertIt ;
570         Sequence< Reference< XCertificate > > certSeq( length ) ;
571 
572         for( i = 0, xcertIt = certsList.begin(); xcertIt != certsList.end(); xcertIt ++, i++ ) {
573             certSeq[i] = *xcertIt ;
574         }
575 
576         return certSeq ;
577     }
578 
579     return Sequence< Reference < XCertificate > > ();
580 }
581 
getCertificate(const OUString & issuerName,const Sequence<sal_Int8> & serialNumber)582 Reference< XCertificate > SecurityEnvironment_NssImpl :: getCertificate( const OUString& issuerName, const Sequence< sal_Int8 >& serialNumber )
583 {
584     X509Certificate_NssImpl* xcert = NULL;
585 
586     if( m_pHandler != NULL ) {
587         CERTIssuerAndSN issuerAndSN ;
588         CERTCertificate* cert ;
589         CERTName* nmIssuer ;
590         char* chIssuer ;
591         SECItem* derIssuer ;
592         PRArenaPool* arena ;
593 
594         arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE ) ;
595         if( arena == NULL )
596             throw RuntimeException() ;
597 
598                 /*
599                  * mmi : because MS Crypto use the 'S' tag (equal to the 'ST' tag in NSS), but the NSS can't recognise
600                  *      it, so the 'S' tag should be changed to 'ST' tag
601                  *
602                  * PS  : it can work, but inside libxmlsec, the 'S' tag is till used to find cert in NSS engine, so it
603                  *       is not useful at all. (comment out now)
604                  */
605 
606                 /*
607                 sal_Int32 nIndex = 0;
608                 OUString newIssuerName;
609                 do
610                 {
611                     OUString aToken = issuerName.getToken( 0, ',', nIndex ).trim();
612                     if (aToken.compareToAscii("S=",2) == 0)
613                     {
614                         newIssuerName+=OUString::createFromAscii("ST=");
615                         newIssuerName+=aToken.copy(2);
616                     }
617                     else
618                     {
619                         newIssuerName+=aToken;
620                     }
621 
622                     if (nIndex >= 0)
623                     {
624                         newIssuerName+=OUString::createFromAscii(",");
625                     }
626                 } while ( nIndex >= 0 );
627                 */
628 
629                 /* end */
630 
631         //Create cert info from issue and serial
632         rtl::OString ostr = rtl::OUStringToOString( issuerName , RTL_TEXTENCODING_UTF8 ) ;
633         chIssuer = PL_strndup( ( char* )ostr.getStr(), ( int )ostr.getLength() ) ;
634         nmIssuer = CERT_AsciiToName( chIssuer ) ;
635         if( nmIssuer == NULL ) {
636             PL_strfree( chIssuer ) ;
637             PORT_FreeArena( arena, PR_FALSE ) ;
638 
639             /*
640              * i40394
641              *
642              * mmi : no need to throw exception
643              *       just return "no found"
644              */
645             //throw RuntimeException() ;
646             return NULL;
647         }
648 
649         derIssuer = SEC_ASN1EncodeItem( arena, NULL, ( void* )nmIssuer, SEC_ASN1_GET( CERT_NameTemplate ) ) ;
650         if( derIssuer == NULL ) {
651             PL_strfree( chIssuer ) ;
652             CERT_DestroyName( nmIssuer ) ;
653             PORT_FreeArena( arena, PR_FALSE ) ;
654             throw RuntimeException() ;
655         }
656 
657         memset( &issuerAndSN, 0, sizeof( issuerAndSN ) ) ;
658 
659         issuerAndSN.derIssuer.data = derIssuer->data ;
660         issuerAndSN.derIssuer.len = derIssuer->len ;
661 
662         issuerAndSN.serialNumber.data = ( unsigned char* )&serialNumber[0] ;
663         issuerAndSN.serialNumber.len = serialNumber.getLength() ;
664 
665         cert = CERT_FindCertByIssuerAndSN( m_pHandler, &issuerAndSN ) ;
666         if( cert != NULL ) {
667             xcert = NssCertToXCert( cert ) ;
668         } else {
669             xcert = NULL ;
670         }
671 
672         PL_strfree( chIssuer ) ;
673         CERT_DestroyName( nmIssuer ) ;
674         //SECITEM_FreeItem( derIssuer, PR_FALSE ) ;
675         CERT_DestroyCertificate( cert ) ;
676         PORT_FreeArena( arena, PR_FALSE ) ;
677     } else {
678         xcert = NULL ;
679     }
680 
681     return xcert ;
682 }
683 
getCertificate(const OUString & issuerName,const OUString & serialNumber)684 Reference< XCertificate > SecurityEnvironment_NssImpl :: getCertificate( const OUString& issuerName, const OUString& serialNumber ) {
685     Sequence< sal_Int8 > serial = numericStringToBigInteger( serialNumber ) ;
686     return getCertificate( issuerName, serial ) ;
687 }
688 
buildCertificatePath(const Reference<XCertificate> & begin)689 Sequence< Reference < XCertificate > > SecurityEnvironment_NssImpl :: buildCertificatePath( const Reference< XCertificate >& begin ) {
690     const X509Certificate_NssImpl* xcert ;
691     const CERTCertificate* cert ;
692     CERTCertList* certChain ;
693 
694     Reference< XUnoTunnel > xCertTunnel( begin, UNO_QUERY ) ;
695     if( !xCertTunnel.is() ) {
696         throw RuntimeException() ;
697     }
698 
699     xcert = reinterpret_cast<X509Certificate_NssImpl*>(
700         sal::static_int_cast<sal_uIntPtr>(xCertTunnel->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
701     if( xcert == NULL ) {
702         throw RuntimeException() ;
703     }
704 
705     cert = xcert->getNssCert() ;
706     if( cert != NULL ) {
707         int64 timeboundary ;
708 
709         //Get the system clock time
710         timeboundary = PR_Now() ;
711 
712         certChain = CERT_GetCertChainFromCert( ( CERTCertificate* )cert, timeboundary, certUsageAnyCA ) ;
713     } else {
714         certChain = NULL ;
715     }
716 
717     if( certChain != NULL ) {
718         X509Certificate_NssImpl* pCert ;
719         CERTCertListNode* node ;
720         int len ;
721 
722         for( len = 0, node = CERT_LIST_HEAD( certChain ); !CERT_LIST_END( node, certChain ); node = CERT_LIST_NEXT( node ), len ++ ) ;
723         Sequence< Reference< XCertificate > > xCertChain( len ) ;
724 
725         for( len = 0, node = CERT_LIST_HEAD( certChain ); !CERT_LIST_END( node, certChain ); node = CERT_LIST_NEXT( node ), len ++ ) {
726             pCert = new X509Certificate_NssImpl() ;
727             if( pCert == NULL ) {
728                 CERT_DestroyCertList( certChain ) ;
729                 throw RuntimeException() ;
730             }
731 
732             pCert->setCert( node->cert ) ;
733 
734             xCertChain[len] = pCert ;
735         }
736 
737         CERT_DestroyCertList( certChain ) ;
738 
739         return xCertChain ;
740     }
741 
742     return Sequence< Reference < XCertificate > >();
743 }
744 
createCertificateFromRaw(const Sequence<sal_Int8> & rawCertificate)745 Reference< XCertificate > SecurityEnvironment_NssImpl :: createCertificateFromRaw( const Sequence< sal_Int8 >& rawCertificate ) {
746     X509Certificate_NssImpl* xcert ;
747 
748     if( rawCertificate.getLength() > 0 ) {
749         xcert = new X509Certificate_NssImpl() ;
750         if( xcert == NULL )
751             throw RuntimeException() ;
752 
753         xcert->setRawCert( rawCertificate ) ;
754     } else {
755         xcert = NULL ;
756     }
757 
758     return xcert ;
759 }
760 
createCertificateFromAscii(const OUString & asciiCertificate)761 Reference< XCertificate > SecurityEnvironment_NssImpl :: createCertificateFromAscii( const OUString& asciiCertificate ) {
762     xmlChar* chCert ;
763     xmlSecSize certSize ;
764 
765     rtl::OString oscert = rtl::OUStringToOString( asciiCertificate , RTL_TEXTENCODING_ASCII_US ) ;
766 
767     chCert = xmlStrndup( ( const xmlChar* )oscert.getStr(), ( int )oscert.getLength() ) ;
768 
769     certSize = xmlSecBase64Decode( chCert, ( xmlSecByte* )chCert, xmlStrlen( chCert ) ) ;
770 
771     Sequence< sal_Int8 > rawCert( certSize ) ;
772     for( unsigned int i = 0 ; i < certSize ; i ++ )
773         rawCert[i] = *( chCert + i ) ;
774 
775     xmlFree( chCert ) ;
776 
777     return createCertificateFromRaw( rawCert ) ;
778 }
779 
780 sal_Int32 SecurityEnvironment_NssImpl ::
verifyCertificate(const Reference<csss::XCertificate> & aCert,const Sequence<Reference<csss::XCertificate>> & intermediateCerts)781 verifyCertificate( const Reference< csss::XCertificate >& aCert,
782                    const Sequence< Reference< csss::XCertificate > >&  intermediateCerts )
783 {
784     sal_Int32 validity = csss::CertificateValidity::INVALID;
785     const X509Certificate_NssImpl* xcert ;
786     const CERTCertificate* cert ;
787     ::std::vector<CERTCertificate*> vecTmpNSSCertificates;
788     Reference< XUnoTunnel > xCertTunnel( aCert, UNO_QUERY ) ;
789     if( !xCertTunnel.is() ) {
790         throw RuntimeException() ;
791     }
792 
793     xmlsec_trace("Start verification of certificate: \n %s \n",
794               OUStringToOString(
795                   aCert->getSubjectName(), osl_getThreadTextEncoding()).getStr());
796 
797     xcert = reinterpret_cast<X509Certificate_NssImpl*>(
798        sal::static_int_cast<sal_uIntPtr>(xCertTunnel->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
799     if( xcert == NULL ) {
800         throw RuntimeException() ;
801     }
802 
803     //CERT_PKIXVerifyCert does not take a db as argument. It will therefore
804     //internally use CERT_GetDefaultCertDB
805     //Make sure m_pHandler is the default DB
806     OSL_ASSERT(m_pHandler == CERT_GetDefaultCertDB());
807     CERTCertDBHandle * certDb = m_pHandler != NULL ? m_pHandler : CERT_GetDefaultCertDB();
808     cert = xcert->getNssCert() ;
809     if( cert != NULL )
810     {
811 
812         //prepare the intermediate certificates
813         for (sal_Int32 i = 0; i < intermediateCerts.getLength(); i++)
814         {
815             Sequence<sal_Int8> der = intermediateCerts[i]->getEncoded();
816             SECItem item;
817             item.type = siBuffer;
818             item.data = (unsigned char*)der.getArray();
819             item.len = der.getLength();
820 
821             CERTCertificate* certTmp = CERT_NewTempCertificate(certDb, &item,
822                                            NULL     /* nickname */,
823                                            PR_FALSE /* isPerm */,
824                                            PR_TRUE  /* copyDER */);
825              if (!certTmp)
826              {
827                  xmlsec_trace("Failed to add a temporary certificate: %s",
828                            OUStringToOString(intermediateCerts[i]->getIssuerName(),
829                                              osl_getThreadTextEncoding()).getStr());
830 
831              }
832              else
833              {
834                  xmlsec_trace("Added temporary certificate: %s",
835                            certTmp->subjectName ? certTmp->subjectName : "");
836                  vecTmpNSSCertificates.push_back(certTmp);
837              }
838         }
839 
840 
841         SECStatus status ;
842 
843         CERTVerifyLog log;
844         log.arena = PORT_NewArena(512);
845         log.head = log.tail = NULL;
846         log.count = 0;
847 
848         CERT_EnableOCSPChecking(certDb);
849         CERT_DisableOCSPDefaultResponder(certDb);
850         CERTValOutParam cvout[5];
851         CERTValInParam cvin[3];
852 
853         cvin[0].type = cert_pi_useAIACertFetch;
854         cvin[0].value.scalar.b = PR_TRUE;
855 
856         PRUint64 revFlagsLeaf[2];
857         PRUint64 revFlagsChain[2];
858         CERTRevocationFlags rev;
859         rev.leafTests.number_of_defined_methods = 2;
860         rev.leafTests.cert_rev_flags_per_method = revFlagsLeaf;
861         //the flags are defined in cert.h
862         //We check both leaf and chain.
863         //It is enough if one revocation method has fresh info,
864         //but at least one must have some. Otherwise validation fails.
865         //!!! using leaf test and CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE
866         // when validating a root certificate will result in "revoked". Usually
867         //there is no revocation information available for the root cert because
868         //it must be trusted anyway and it does itself issue revocation information.
869         //When we use the flag here and OOo shows the certification path then the root
870         //cert is invalid while all other can be valid. It would probably best if
871         //this interface method returned the whole chain.
872         //Otherwise we need to check if the certificate is self-signed and if it is
873         //then not use the flag when doing the leaf-test.
874         rev.leafTests.cert_rev_flags_per_method[cert_revocation_method_crl] =
875             CERT_REV_M_TEST_USING_THIS_METHOD
876             | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE;
877         rev.leafTests.cert_rev_flags_per_method[cert_revocation_method_ocsp] =
878             CERT_REV_M_TEST_USING_THIS_METHOD
879             | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE;
880         rev.leafTests.number_of_preferred_methods = 0;
881         rev.leafTests.preferred_methods = NULL;
882         rev.leafTests.cert_rev_method_independent_flags =
883             CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST;
884 //            | CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
885 
886         rev.chainTests.number_of_defined_methods = 2;
887         rev.chainTests.cert_rev_flags_per_method = revFlagsChain;
888         rev.chainTests.cert_rev_flags_per_method[cert_revocation_method_crl] =
889             CERT_REV_M_TEST_USING_THIS_METHOD
890             | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE;
891         rev.chainTests.cert_rev_flags_per_method[cert_revocation_method_ocsp] =
892             CERT_REV_M_TEST_USING_THIS_METHOD
893             | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE;
894         rev.chainTests.number_of_preferred_methods = 0;
895         rev.chainTests.preferred_methods = NULL;
896         rev.chainTests.cert_rev_method_independent_flags =
897             CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST;
898 //            | CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE;
899 
900 
901         cvin[1].type = cert_pi_revocationFlags;
902         cvin[1].value.pointer.revocation = &rev;
903         // does not work, not implemented yet in 3.12.4
904 //         cvin[2].type = cert_pi_keyusage;
905 //         cvin[2].value.scalar.ui = KU_DIGITAL_SIGNATURE;
906         cvin[2].type = cert_pi_end;
907 
908         cvout[0].type = cert_po_trustAnchor;
909         cvout[0].value.pointer.cert = NULL;
910         cvout[1].type = cert_po_errorLog;
911         cvout[1].value.pointer.log = &log;
912         cvout[2].type = cert_po_end;
913 
914         // We check SSL server certificates, CA certificates and signing sertificates.
915         //
916         // ToDo check keyusage, looking at CERT_KeyUsageAndTypeForCertUsage (
917         // mozilla/security/nss/lib/certdb/certdb.c indicates that
918         // certificateUsageSSLClient, certificateUsageSSLServer and certificateUsageSSLCA
919         // are sufficient. They cover the key usages for digital signature, key agreement
920         // and encipherment and certificate signature
921 
922         //never use the following usages because they are not checked properly
923         // certificateUsageUserCertImport
924         // certificateUsageVerifyCA
925         // certificateUsageAnyCA
926         // certificateUsageProtectedObjectSigner
927 
928         UsageDescription arUsages[5];
929         arUsages[0] = UsageDescription( certificateUsageSSLClient, "certificateUsageSSLClient"  );
930         arUsages[1] = UsageDescription( certificateUsageSSLServer, "certificateUsageSSLServer"  );
931         arUsages[2] = UsageDescription( certificateUsageSSLCA, "certificateUsageSSLCA"  );
932         arUsages[3] = UsageDescription( certificateUsageEmailSigner, "certificateUsageEmailSigner" );
933         arUsages[4] = UsageDescription( certificateUsageEmailRecipient, "certificateUsageEmailRecipient" );
934 
935         int numUsages = sizeof(arUsages) / sizeof(UsageDescription);
936         for (int i = 0; i < numUsages; i++)
937         {
938             xmlsec_trace("Testing usage %d of %d: %s (0x%x)", i + 1,
939                       numUsages, arUsages[i].description, (int) arUsages[i].usage);
940 
941             status = CERT_PKIXVerifyCert(const_cast<CERTCertificate *>(cert), arUsages[i].usage,
942                                          cvin, cvout, NULL);
943             if( status == SECSuccess )
944             {
945                 xmlsec_trace("CERT_PKIXVerifyCert returned SECSuccess.");
946                 //When an intermediate or root certificate is checked then we expect the usage
947                 //certificateUsageSSLCA. This, however, will be only set when in the trust settings dialog
948                 //the button "This certificate can identify websites" is checked. If for example only
949                 //"This certificate can identify mail users" is set then the end certificate can
950                 //be validated and the returned usage will conain certificateUsageEmailRecipient.
951                 //But checking directly the root or intermediate certificate will fail. In the
952                 //certificate path view the end certificate will be shown as valid but the others
953                 //will be displayed as invalid.
954 
955                 validity = csss::CertificateValidity::VALID;
956                 xmlsec_trace("Certificate is valid.\n");
957                 CERTCertificate * issuerCert = cvout[0].value.pointer.cert;
958                 if (issuerCert)
959                 {
960                     xmlsec_trace("Root certificate: %s", issuerCert->subjectName);
961                     CERT_DestroyCertificate(issuerCert);
962                 };
963 
964                 break;
965             }
966             else
967             {
968                 PRIntn err = PR_GetError();
969                 xmlsec_trace("Error: , %d = %s", err, getCertError(err));
970 
971                 /* Display validation results */
972                 if ( log.count > 0)
973                 {
974                     CERTVerifyLogNode *node = NULL;
975                     printChainFailure(&log);
976 
977                     for (node = log.head; node; node = node->next) {
978                         if (node->cert)
979                             CERT_DestroyCertificate(node->cert);
980                     }
981                     log.head = log.tail = NULL;
982                     log.count = 0;
983                 }
984                 xmlsec_trace("Certificate is invalid.\n");
985             }
986         }
987 
988     }
989     else
990     {
991         validity = ::com::sun::star::security::CertificateValidity::INVALID ;
992     }
993 
994     //Destroying the temporary certificates
995     std::vector<CERTCertificate*>::const_iterator cert_i;
996     for (cert_i = vecTmpNSSCertificates.begin(); cert_i != vecTmpNSSCertificates.end(); cert_i++)
997     {
998         xmlsec_trace("Destroying temporary certificate");
999         CERT_DestroyCertificate(*cert_i);
1000     }
1001     return validity ;
1002 }
1003 
getCertificateCharacters(const::com::sun::star::uno::Reference<::com::sun::star::security::XCertificate> & aCert)1004 sal_Int32 SecurityEnvironment_NssImpl::getCertificateCharacters(
1005     const ::com::sun::star::uno::Reference< ::com::sun::star::security::XCertificate >& aCert ) {
1006     sal_Int32 characters ;
1007     const X509Certificate_NssImpl* xcert ;
1008     const CERTCertificate* cert ;
1009 
1010     Reference< XUnoTunnel > xCertTunnel( aCert, UNO_QUERY ) ;
1011     if( !xCertTunnel.is() ) {
1012         throw RuntimeException() ;
1013     }
1014 
1015     xcert = reinterpret_cast<X509Certificate_NssImpl*>(
1016         sal::static_int_cast<sal_uIntPtr>(xCertTunnel->getSomething( X509Certificate_NssImpl::getUnoTunnelId() ))) ;
1017     if( xcert == NULL ) {
1018         throw RuntimeException() ;
1019     }
1020 
1021     cert = xcert->getNssCert() ;
1022 
1023     characters = 0x00000000 ;
1024 
1025     //Firstly, find out whether or not the cert is self-signed.
1026     if( SECITEM_CompareItem( &(cert->derIssuer), &(cert->derSubject) ) == SECEqual ) {
1027         characters |= ::com::sun::star::security::CertificateCharacters::SELF_SIGNED ;
1028     } else {
1029         characters &= ~ ::com::sun::star::security::CertificateCharacters::SELF_SIGNED ;
1030     }
1031 
1032     //Secondly, find out whether or not the cert has a private key.
1033 
1034     /*
1035      * i40394
1036      *
1037      * mmi : need to check whether the cert's slot is valid first
1038      */
1039     SECKEYPrivateKey* priKey = NULL;
1040 
1041     if (cert->slot != NULL)
1042     {
1043         priKey = PK11_FindPrivateKeyFromCert( cert->slot, ( CERTCertificate* )cert, NULL ) ;
1044     }
1045     if(priKey == NULL)
1046     {
1047         for (CIT_SLOTS is = m_Slots.begin(); is != m_Slots.end(); is++)
1048         {
1049             priKey = PK11_FindPrivateKeyFromCert(*is, (CERTCertificate*)cert, NULL);
1050             if (priKey)
1051                 break;
1052         }
1053     }
1054     if( priKey != NULL ) {
1055         characters |=  ::com::sun::star::security::CertificateCharacters::HAS_PRIVATE_KEY ;
1056 
1057         SECKEY_DestroyPrivateKey( priKey ) ;
1058     } else {
1059         characters &= ~ ::com::sun::star::security::CertificateCharacters::HAS_PRIVATE_KEY ;
1060     }
1061 
1062     return characters ;
1063 }
1064 
NssCertToXCert(CERTCertificate * cert)1065 X509Certificate_NssImpl* NssCertToXCert( CERTCertificate* cert )
1066 {
1067     X509Certificate_NssImpl* xcert ;
1068 
1069     if( cert != NULL ) {
1070         xcert = new X509Certificate_NssImpl() ;
1071         if( xcert == NULL ) {
1072             xcert = NULL ;
1073         } else {
1074             xcert->setCert( cert ) ;
1075         }
1076     } else {
1077         xcert = NULL ;
1078     }
1079 
1080     return xcert ;
1081 }
1082 
NssPrivKeyToXCert(SECKEYPrivateKey * priKey)1083 X509Certificate_NssImpl* NssPrivKeyToXCert( SECKEYPrivateKey* priKey )
1084 {
1085     CERTCertificate* cert ;
1086     X509Certificate_NssImpl* xcert ;
1087 
1088     if( priKey != NULL ) {
1089         cert = PK11_GetCertFromPrivateKey( priKey ) ;
1090 
1091         if( cert != NULL ) {
1092             xcert = NssCertToXCert( cert ) ;
1093         } else {
1094             xcert = NULL ;
1095         }
1096 
1097         CERT_DestroyCertificate( cert ) ;
1098     } else {
1099         xcert = NULL ;
1100     }
1101 
1102     return xcert ;
1103 }
1104 
1105 
1106 /* Native methods */
createKeysManager()1107 xmlSecKeysMngrPtr SecurityEnvironment_NssImpl::createKeysManager() {
1108 
1109     unsigned int i ;
1110     CERTCertDBHandle* handler = NULL ;
1111     PK11SymKey* symKey = NULL ;
1112     SECKEYPublicKey* pubKey = NULL ;
1113     SECKEYPrivateKey* priKey = NULL ;
1114     xmlSecKeysMngrPtr pKeysMngr = NULL ;
1115 
1116     handler = this->getCertDb() ;
1117 
1118     /*-
1119      * The following lines is based on the private version of xmlSec-NSS
1120      * crypto engine
1121      */
1122     int cSlots = m_Slots.size();
1123     boost::scoped_array<PK11SlotInfo*> sarSlots(new PK11SlotInfo*[cSlots]);
1124     PK11SlotInfo**  slots = sarSlots.get();
1125     int count = 0;
1126     for (CIT_SLOTS islots = m_Slots.begin();islots != m_Slots.end(); islots++, count++)
1127         slots[count] = *islots;
1128 
1129     pKeysMngr = xmlSecNssAppliedKeysMngrCreate(slots, cSlots, handler ) ;
1130     if( pKeysMngr == NULL )
1131         throw RuntimeException() ;
1132 
1133     /*-
1134      * Adopt symmetric key into keys manager
1135      */
1136     for( i = 0 ; ( symKey = this->getSymKey( i ) ) != NULL ; i ++ ) {
1137         if( xmlSecNssAppliedKeysMngrSymKeyLoad( pKeysMngr, symKey ) < 0 ) {
1138             throw RuntimeException() ;
1139         }
1140     }
1141 
1142     /*-
1143      * Adopt asymmetric public key into keys manager
1144      */
1145     for( i = 0 ; ( pubKey = this->getPubKey( i ) ) != NULL ; i ++ ) {
1146         if( xmlSecNssAppliedKeysMngrPubKeyLoad( pKeysMngr, pubKey ) < 0 ) {
1147             throw RuntimeException() ;
1148         }
1149     }
1150 
1151     /*-
1152      * Adopt asymmetric private key into keys manager
1153      */
1154     for( i = 0 ; ( priKey = this->getPriKey( i ) ) != NULL ; i ++ ) {
1155         if( xmlSecNssAppliedKeysMngrPriKeyLoad( pKeysMngr, priKey ) < 0 ) {
1156             throw RuntimeException() ;
1157         }
1158     }
1159     return pKeysMngr ;
1160 }
destroyKeysManager(xmlSecKeysMngrPtr pKeysMngr)1161 void SecurityEnvironment_NssImpl::destroyKeysManager(xmlSecKeysMngrPtr pKeysMngr) {
1162     if( pKeysMngr != NULL ) {
1163         xmlSecKeysMngrDestroy( pKeysMngr ) ;
1164     }
1165 }
1166