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