Debian Codegraph @

xmlsecurity/source/xmlsec/nss/securityenvironment_nssimpl.cxx

raw
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19
20 #include "nssrenam.h"
21 #include <nss.h>
22 #include <cert.h>
23 #include <pk11pub.h>
24 #include <secerr.h>
25 #include <ocsp.h>
26
27 #include <sal/config.h>
28 #include <osl/diagnose.h>
29 #include "securityenvironment_nssimpl.hxx"
30 #include <cppuhelper/supportsservice.hxx>
31
32 #include <rtl/ustrbuf.hxx>
33 #include <comphelper/processfactory.hxx>
34 #include <comphelper/docpasswordrequest.hxx>
35 #include <sal/log.hxx>
36 #include <com/sun/star/task/InteractionHandler.hpp>
37 #include <com/sun/star/task/PasswordRequestMode.hpp>
38 #include <vector>
39 #include <memory>
40 #include <osl/thread.h>
41 #include <comphelper/sequence.hxx>
42
43 #include "x509certificate_nssimpl.hxx"
44 #include "secerror.hxx"
45 #include <prerror.h>
46 #include <keyhi.h>
47 #include <xmlsec/base64.h>
48 #include <xmlsec/keysmngr.h>
49 #include <xmlsec/nss/app.h>
50 #include <xmlsec/nss/pkikeys.h>
51
52 // added for password exception
53 #include <com/sun/star/security/NoPasswordException.hpp>
54 #include <com/sun/star/security/CertificateCharacters.hpp>
55 #include <com/sun/star/security/CertificateValidity.hpp>
56 #include <com/sun/star/xml/crypto/NSSInitializer.hpp>
57
58 namespace csss = ::com::sun::star::security;
59 using namespace ::com::sun::star::security;
60 using namespace com::sun::star;
61 using namespace ::com::sun::star::uno ;
62 using namespace ::com::sun::star::lang ;
63
64 using ::com::sun::star::security::XCertificate ;
65
66 namespace std
67 {
68 template <> struct default_delete<PRArenaPool>
69 {
70 void operator()(PRArenaPool* ptr) { PORT_FreeArena(ptr, PR_FALSE); }
71 };
72 }
73
74 static rtl::Reference<X509Certificate_NssImpl> NssCertToXCert( CERTCertificate* cert ) ;
75 static rtl::Reference<X509Certificate_NssImpl> NssPrivKeyToXCert( SECKEYPrivateKey* ) ;
76
77 namespace {
78
79 struct UsageDescription
80 {
81 SECCertificateUsage usage;
82 char const* description;
83
84 UsageDescription()
85 : usage( certificateUsageCheckAllUsages )
86 , description( nullptr )
87 {}
88
89 UsageDescription( SECCertificateUsage i_usage, char const* i_description )
90 : usage( i_usage )
91 , description( i_description )
92 {}
93 };
94
95 }
96
97 static char* GetPasswordFunction( PK11SlotInfo* pSlot, PRBool bRetry, void* /*arg*/ )
98 {
99 const uno::Reference< uno::XComponentContext >& xContext( ::comphelper::getProcessComponentContext() );
100 uno::Reference < task::XInteractionHandler2 > xInteractionHandler(
101 task::InteractionHandler::createWithParent(xContext, nullptr) );
102
103 task::PasswordRequestMode eMode = bRetry ? task::PasswordRequestMode_PASSWORD_REENTER : task::PasswordRequestMode_PASSWORD_ENTER;
104 OUString passwordLabel = xml::crypto::NSSInitializer::create(xContext)->getNSSPath();
105 if (!passwordLabel.isEmpty())
106 passwordLabel = ": " + passwordLabel;
107 passwordLabel = OUString::createFromAscii(PK11_GetTokenName(pSlot)) + passwordLabel;
108 rtl::Reference<::comphelper::DocPasswordRequest> pPasswordRequest = new ::comphelper::DocPasswordRequest(
109 ::comphelper::DocPasswordRequestType::Standard, eMode, passwordLabel);
110
111 xInteractionHandler->handle( pPasswordRequest );
112
113 if ( pPasswordRequest->isPassword() )
114 {
115 OString aPassword(OUStringToOString(
116 pPasswordRequest->getPassword(),
117 osl_getThreadTextEncoding()));
118 sal_Int32 nLen = aPassword.getLength();
119 char* pPassword = static_cast<char*>(PORT_Alloc( nLen+1 ) );
120 pPassword[nLen] = 0;
121 std::copy( aPassword.getStr(), aPassword.getStr() + nLen, pPassword );
122 return pPassword;
123 }
124 return nullptr;
125 }
126
127 SecurityEnvironment_NssImpl::SecurityEnvironment_NssImpl() :
128 m_pHandler( nullptr ) {
129 PK11_SetPasswordFunc( GetPasswordFunction ) ;
130 }
131
132 SecurityEnvironment_NssImpl::~SecurityEnvironment_NssImpl() {
133
134 PK11_SetPasswordFunc( nullptr ) ;
135
136 for (auto& slot : m_Slots)
137 {
138 PK11_FreeSlot(slot);
139 }
140
141 for( auto& symKey : m_tSymKeyList )
142 PK11_FreeSymKey( symKey ) ;
143 }
144
145 /* XServiceInfo */
146 OUString SAL_CALL SecurityEnvironment_NssImpl::getImplementationName() {
147 return u"com.sun.star.xml.crypto.SecurityEnvironment"_ustr;
148 }
149
150 /* XServiceInfo */
151 sal_Bool SAL_CALL SecurityEnvironment_NssImpl::supportsService( const OUString& serviceName) {
152 return cppu::supportsService(this, serviceName);
153 }
154
155 /* XServiceInfo */
156 Sequence< OUString > SAL_CALL SecurityEnvironment_NssImpl::getSupportedServiceNames() {
157 Sequence<OUString> seqServiceNames{ u"com.sun.star.xml.crypto.SecurityEnvironment"_ustr };
158 return seqServiceNames;
159 }
160
161 OUString SecurityEnvironment_NssImpl::getSecurityEnvironmentInformation()
162 {
163 OUStringBuffer buff;
164 for (auto& slot : m_Slots)
165 {
166 buff.appendAscii(PK11_GetTokenName(slot));
167 buff.append("\n");
168 }
169 return buff.makeStringAndClear();
170 }
171
172 void SecurityEnvironment_NssImpl::addCryptoSlot( PK11SlotInfo* aSlot)
173 {
174 PK11_ReferenceSlot(aSlot);
175 m_Slots.push_back(aSlot);
176 }
177
178 //Could we have multiple cert dbs?
179 void SecurityEnvironment_NssImpl::setCertDb( CERTCertDBHandle* aCertDb ) {
180 m_pHandler = aCertDb ;
181 }
182
183 void SecurityEnvironment_NssImpl::adoptSymKey( PK11SymKey* aSymKey ) {
184 if( aSymKey == nullptr ) return;
185
186 //First try to find the key in the list
187 if (std::find(m_tSymKeyList.begin(), m_tSymKeyList.end(), aSymKey) != m_tSymKeyList.end())
188 return;
189
190 //If we do not find the key in the list, add a new node
191 PK11SymKey* symkey = PK11_ReferenceSymKey( aSymKey ) ;
192 if( symkey == nullptr )
193 throw RuntimeException() ;
194
195 try {
196 m_tSymKeyList.push_back( symkey ) ;
197 } catch ( Exception& ) {
198 PK11_FreeSymKey( symkey ) ;
199 }
200 }
201
202 void SecurityEnvironment_NssImpl::updateSlots()
203 {
204 //In case new tokens are present then we can obtain the corresponding slot
205 std::scoped_lock guard(m_mutex);
206
207 m_Slots.clear();
208 m_tSymKeyList.clear();
209
210 PK11SlotList * slotList = PK11_GetAllTokens( CKM_INVALID_MECHANISM, PR_FALSE, PR_FALSE, nullptr ) ;
211 if( slotList == nullptr )
212 return;
213
214 for (PK11SlotListElement* slotEle = slotList->head ; slotEle != nullptr; slotEle = slotEle->next)
215 {
216 PK11SlotInfo * pSlot = slotEle->slot ;
217
218 if(pSlot != nullptr)
219 {
220 SAL_INFO(
221 "xmlsecurity.xmlsec",
222 "Found a slot: SlotName=" << PK11_GetSlotName(pSlot)
223 << ", TokenName=" << PK11_GetTokenName(pSlot));
224
225 //The following code which is commented out checks if a slot, that is a smart card for example, is
226 // able to generate a symmetric key of type CKM_DES3_CBC. If this fails then this token
227 // will not be used. This key is possibly used for the encryption service. However, all
228 // interfaces and services used for public key signature and encryption are not published
229 // and the encryption is not used in OOo. Therefore it does not do any harm to remove
230 // this code, hence allowing smart cards which cannot generate this type of key.
231 //
232 // By doing this, the encryption may fail if a smart card is being used which does not
233 // support this key generation.
234 //
235 PK11SymKey * pSymKey = PK11_KeyGen( pSlot , CKM_DES3_CBC, nullptr, 128, nullptr ) ;
236 // if( pSymKey == NULL )
237 // {
238 // PK11_FreeSlot( pSlot ) ;
239 // SAL_INFO( "xmlsecurity", "XMLSEC: Error - pSymKey is NULL" );
240 // continue;
241 // }
242 addCryptoSlot(pSlot);
243
244 if (pSymKey != nullptr)
245 {
246 adoptSymKey( pSymKey ) ;
247 PK11_FreeSymKey( pSymKey ) ;
248 pSymKey = nullptr;
249 }
250
251 }// end of if(pSlot != NULL)
252 }// end of for
253
254 PK11_FreeSlotList(slotList);
255 }
256
257 Sequence< Reference < XCertificate > >
258 SecurityEnvironment_NssImpl::getPersonalCertificates()
259 {
260 std::vector< rtl::Reference<X509Certificate_NssImpl> > certsList ;
261
262 updateSlots();
263 //firstly, we try to find private keys in slot
264 for (auto& slot : m_Slots)
265 {
266 SECKEYPrivateKeyList* priKeyList ;
267
268 if( PK11_NeedLogin(slot ) ) {
269 SECStatus nRet = PK11_Authenticate(slot, PR_TRUE, nullptr);
270 //PK11_Authenticate may fail in case the a slot has not been initialized.
271 //this is the case if the user has a new profile, so that they have never
272 //added a personal certificate.
273 if( nRet != SECSuccess && PORT_GetError() != SEC_ERROR_IO) {
274 throw NoPasswordException();
275 }
276 }
277
278 priKeyList = PK11_ListPrivateKeysInSlot(slot) ;
279 if( priKeyList != nullptr )
280 {
281 for (SECKEYPrivateKeyListNode* curPri = PRIVKEY_LIST_HEAD(priKeyList);
282 !PRIVKEY_LIST_END( curPri, priKeyList ) && curPri != nullptr;
283 curPri = PRIVKEY_LIST_NEXT(curPri))
284 {
285 rtl::Reference<X509Certificate_NssImpl> xcert = NssPrivKeyToXCert( curPri->key ) ;
286 if( xcert != nullptr )
287 certsList.push_back( xcert ) ;
288 }
289 SECKEY_DestroyPrivateKeyList( priKeyList ) ;
290 }
291
292
293 }
294
295 if( !certsList.empty() ) {
296 return comphelper::containerToSequence<Reference< XCertificate >>(certsList) ;
297 }
298
299 return Sequence< Reference < XCertificate > > ();
300 }
301
302 Reference< XCertificate > SecurityEnvironment_NssImpl::getCertificate( const OUString& issuerName, const Sequence< sal_Int8 >& serialNumber )
303 {
304 if( !m_pHandler )
305 return nullptr;
306
307 rtl::Reference<X509Certificate_NssImpl> xcert;
308 CERTIssuerAndSN issuerAndSN ;
309 CERTCertificate* cert ;
310 CERTName* nmIssuer ;
311 char* chIssuer ;
312 SECItem* derIssuer ;
313 std::unique_ptr<PRArenaPool> arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
314 if( arena == nullptr )
315 throw RuntimeException() ;
316
317 // Create cert info from issue and serial
318 OString ostr = OUStringToOString( issuerName , RTL_TEXTENCODING_UTF8 ) ;
319 chIssuer = PL_strndup( ostr.getStr(), static_cast<int>(ostr.getLength()) ) ;
320 nmIssuer = CERT_AsciiToName( chIssuer ) ;
321 if( nmIssuer == nullptr ) {
322 PL_strfree( chIssuer ) ;
323 return nullptr; // no need for exception cf. i40394
324 }
325
326 derIssuer = SEC_ASN1EncodeItem( arena.get(), nullptr, static_cast<void*>(nmIssuer), SEC_ASN1_GET( CERT_NameTemplate ) ) ;
327 if( derIssuer == nullptr ) {
328 PL_strfree( chIssuer ) ;
329 CERT_DestroyName( nmIssuer ) ;
330 throw RuntimeException() ;
331 }
332
333 memset( &issuerAndSN, 0, sizeof( issuerAndSN ) ) ;
334
335 issuerAndSN.derIssuer.data = derIssuer->data ;
336 issuerAndSN.derIssuer.len = derIssuer->len ;
337
338 issuerAndSN.serialNumber.data = reinterpret_cast<unsigned char *>(const_cast<sal_Int8 *>(serialNumber.getConstArray()));
339 issuerAndSN.serialNumber.len = serialNumber.getLength() ;
340
341 cert = CERT_FindCertByIssuerAndSN( m_pHandler, &issuerAndSN ) ;
342 if( cert != nullptr ) {
343 xcert = NssCertToXCert( cert ) ;
344 }
345
346 PL_strfree( chIssuer ) ;
347 CERT_DestroyName( nmIssuer ) ;
348 //SECITEM_FreeItem( derIssuer, PR_FALSE ) ;
349 CERT_DestroyCertificate( cert ) ;
350
351 return xcert ;
352 }
353
354 Sequence< Reference < XCertificate > > SecurityEnvironment_NssImpl::buildCertificatePath( const Reference< XCertificate >& begin ) {
355
356 X509Certificate_NssImpl* xcert = dynamic_cast<X509Certificate_NssImpl*>(begin.get());
357 if( xcert == nullptr ) {
358 throw RuntimeException() ;
359 }
360
361 // Remember the signing certificate.
362 m_xSigningCertificate = xcert;
363
364 const CERTCertificate* cert = xcert->getNssCert() ;
365 if (!cert)
366 return {};
367
368 //Get the system clock time
369 int64 timeboundary = PR_Now() ;
370 CERTCertList* certChain = CERT_GetCertChainFromCert( const_cast<CERTCertificate*>(cert), timeboundary, certUsageAnyCA ) ;
371
372 if( !certChain )
373 return {};
374
375 std::vector<uno::Reference<security::XCertificate>> aCertChain;
376
377 for (CERTCertListNode* node = CERT_LIST_HEAD(certChain); !CERT_LIST_END(node, certChain); node = CERT_LIST_NEXT(node)) {
378 rtl::Reference<X509Certificate_NssImpl> pCert = new X509Certificate_NssImpl();
379 if( pCert == nullptr ) {
380 CERT_DestroyCertList( certChain ) ;
381 throw RuntimeException() ;
382 }
383
384 pCert->setCert( node->cert ) ;
385
386 aCertChain.push_back(pCert);
387 }
388
389 CERT_DestroyCertList( certChain ) ;
390
391 return comphelper::containerToSequence(aCertChain);
392 }
393
394 rtl::Reference<X509Certificate_NssImpl> SecurityEnvironment_NssImpl::createAndAddCertificateFromPackage(
395 const css::uno::Sequence<sal_Int8>& raDERCertificate,
396 std::u16string_view raString)
397 {
398 auto pCertificateBytes = reinterpret_cast<char *>(const_cast<sal_Int8 *>(raDERCertificate.getConstArray()));
399 CERTCertificate* pCERTCertificate = CERT_DecodeCertFromPackage(pCertificateBytes, raDERCertificate.getLength());
400
401 if (!pCERTCertificate)
402 return nullptr;
403
404 SECStatus aStatus;
405
406 OString aTrustString = OUStringToOString(raString, RTL_TEXTENCODING_ASCII_US);
407 CERTCertTrust aTrust;
408
409 aStatus = CERT_DecodeTrustString(&aTrust, aTrustString.getStr());
410
411 if (aStatus != SECSuccess)
412 {
413 PRIntn err = PR_GetError();
414 SAL_WARN("xmlsecurity.xmlsec", "Error: " << err << ": " << getCertError(err));
415 return nullptr;
416 }
417
418 PK11SlotInfo* pSlot = PK11_GetInternalKeySlot();
419
420 if (!pSlot)
421 return nullptr;
422
423 aStatus = PK11_ImportCert(pSlot, pCERTCertificate, CK_INVALID_HANDLE, nullptr, PR_FALSE);
424
425 if (aStatus != SECSuccess)
426 {
427 PRIntn err = PR_GetError();
428 SAL_WARN("xmlsecurity.xmlsec", "Error: " << err << ": " << getCertError(err));
429 return nullptr;
430 }
431
432 aStatus = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), pCERTCertificate, &aTrust);
433
434 if (aStatus != SECSuccess)
435 {
436 PRIntn err = PR_GetError();
437 SAL_WARN("xmlsecurity.xmlsec", "Error: " << err << ": " << getCertError(err));
438 return nullptr;
439 }
440
441 PK11_FreeSlot(pSlot);
442
443 rtl::Reference<X509Certificate_NssImpl> pX509Certificate = new X509Certificate_NssImpl();
444 pX509Certificate->setCert(pCERTCertificate);
445 return pX509Certificate;
446 }
447
448 rtl::Reference<X509Certificate_NssImpl> SecurityEnvironment_NssImpl::createX509CertificateFromDER(const css::uno::Sequence<sal_Int8>& aDerCertificate)
449 {
450 rtl::Reference<X509Certificate_NssImpl> pX509Certificate;
451
452 if (aDerCertificate.hasElements())
453 {
454 pX509Certificate = new X509Certificate_NssImpl();
455 if (pX509Certificate == nullptr)
456 throw RuntimeException();
457 pX509Certificate->setRawCert(aDerCertificate);
458 }
459 return pX509Certificate;
460 }
461
462 Reference<XCertificate> SecurityEnvironment_NssImpl::createCertificateFromRaw(const Sequence< sal_Int8 >& rawCertificate)
463 {
464 return createX509CertificateFromDER(rawCertificate);
465 }
466
467 Reference< XCertificate > SecurityEnvironment_NssImpl::createCertificateFromAscii( const OUString& asciiCertificate )
468 {
469 OString oscert = OUStringToOString( asciiCertificate , RTL_TEXTENCODING_ASCII_US ) ;
470 xmlChar* chCert = xmlStrndup( reinterpret_cast<const xmlChar*>(oscert.getStr()), static_cast<int>(oscert.getLength()) ) ;
471 xmlSecSize certSize;
472 int nRet = xmlSecBase64Decode_ex( chCert, reinterpret_cast<xmlSecByte*>(chCert), xmlStrlen( chCert ), &certSize ) ;
473 if (nRet < 0 || certSize == 0)
474 {
475 xmlFree(chCert);
476 return nullptr;
477 }
478
479 Sequence< sal_Int8 > rawCert(comphelper::arrayToSequence<sal_Int8>(chCert, certSize)) ;
480
481 xmlFree( chCert ) ;
482
483 return createCertificateFromRaw( rawCert ) ;
484 }
485
486 sal_Int32 SecurityEnvironment_NssImpl ::
487 verifyCertificate( const Reference< csss::XCertificate >& aCert,
488 const Sequence< Reference< csss::XCertificate > >& intermediateCerts )
489 {
490 sal_Int32 validity = csss::CertificateValidity::INVALID;
491 const CERTCertificate* cert ;
492
493 SAL_INFO("xmlsecurity.xmlsec", "Start verification of certificate: " << aCert->getSubjectName());
494
495 const X509Certificate_NssImpl* xcert = dynamic_cast<X509Certificate_NssImpl*>(aCert.get());
496 if( xcert == nullptr ) {
497 throw RuntimeException() ;
498 }
499
500 //CERT_PKIXVerifyCert does not take a db as argument. It will therefore
501 //internally use CERT_GetDefaultCertDB
502 //Make sure m_pHandler is the default DB
503 OSL_ASSERT(m_pHandler == CERT_GetDefaultCertDB());
504 CERTCertDBHandle * certDb = m_pHandler != nullptr ? m_pHandler : CERT_GetDefaultCertDB();
505 cert = xcert->getNssCert() ;
506 if( !cert )
507 return css::security::CertificateValidity::INVALID;
508
509
510 ::std::vector<CERTCertificate*> vecTmpNSSCertificates;
511
512 //prepare the intermediate certificates
513 for (const auto& rIntermediateCert : intermediateCerts)
514 {
515 Sequence<sal_Int8> der = rIntermediateCert->getEncoded();
516 SECItem item;
517 item.type = siBuffer;
518 item.data = reinterpret_cast<unsigned char*>(der.getArray());
519 item.len = der.getLength();
520
521 CERTCertificate* certTmp = CERT_NewTempCertificate(certDb, &item,
522 nullptr /* nickname */,
523 PR_FALSE /* isPerm */,
524 PR_TRUE /* copyDER */);
525 if (!certTmp)
526 {
527 SAL_INFO("xmlsecurity.xmlsec", "Failed to add a temporary certificate: " << rIntermediateCert->getIssuerName());
528
529 }
530 else
531 {
532 SAL_INFO("xmlsecurity.xmlsec", "Added temporary certificate: " <<
533 (certTmp->subjectName ? certTmp->subjectName : ""));
534 vecTmpNSSCertificates.push_back(certTmp);
535 }
536 }
537
538
539 SECStatus status ;
540
541 CERTVerifyLog log;
542 log.arena = PORT_NewArena(512);
543 log.head = log.tail = nullptr;
544 log.count = 0;
545
546 CERT_EnableOCSPChecking(certDb);
547 CERT_DisableOCSPDefaultResponder(certDb);
548 CERTValOutParam cvout[5];
549 CERTValInParam cvin[3];
550 int ncvinCount=0;
551
552 #if ( NSS_VMAJOR > 3 ) || ( NSS_VMAJOR == 3 && NSS_VMINOR > 12 ) || ( NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH > 0 )
553 cvin[ncvinCount].type = cert_pi_useAIACertFetch;
554 cvin[ncvinCount].value.scalar.b = PR_TRUE;
555 ncvinCount++;
556 #endif
557
558 PRUint64 revFlagsLeaf[2];
559 PRUint64 revFlagsChain[2];
560 CERTRevocationFlags rev;
561 rev.leafTests.number_of_defined_methods = 2;
562 rev.leafTests.cert_rev_flags_per_method = revFlagsLeaf;
563 //the flags are defined in cert.h
564 //We check both leaf and chain.
565 //It is enough if one revocation method has fresh info,
566 //but at least one must have some. Otherwise validation fails.
567 //!!! using leaf test and CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE
568 // when validating a root certificate will result in "revoked". Usually
569 //there is no revocation information available for the root cert because
570 //it must be trusted anyway and it does itself issue revocation information.
571 //When we use the flag here and OOo shows the certification path then the root
572 //cert is invalid while all other can be valid. It would probably best if
573 //this interface method returned the whole chain.
574 //Otherwise we need to check if the certificate is self-signed and if it is
575 //then not use the flag when doing the leaf-test.
576 rev.leafTests.cert_rev_flags_per_method[cert_revocation_method_crl] =
577 CERT_REV_M_TEST_USING_THIS_METHOD
578 | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE;
579 rev.leafTests.cert_rev_flags_per_method[cert_revocation_method_ocsp] =
580 CERT_REV_M_TEST_USING_THIS_METHOD
581 | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE;
582 rev.leafTests.number_of_preferred_methods = 0;
583 rev.leafTests.preferred_methods = nullptr;
584 rev.leafTests.cert_rev_method_independent_flags =
585 CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST;
586
587 rev.chainTests.number_of_defined_methods = 2;
588 rev.chainTests.cert_rev_flags_per_method = revFlagsChain;
589 rev.chainTests.cert_rev_flags_per_method[cert_revocation_method_crl] =
590 CERT_REV_M_TEST_USING_THIS_METHOD
591 | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE;
592 rev.chainTests.cert_rev_flags_per_method[cert_revocation_method_ocsp] =
593 CERT_REV_M_TEST_USING_THIS_METHOD
594 | CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE;
595 rev.chainTests.number_of_preferred_methods = 0;
596 rev.chainTests.preferred_methods = nullptr;
597 rev.chainTests.cert_rev_method_independent_flags =
598 CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST;
599
600
601 cvin[ncvinCount].type = cert_pi_revocationFlags;
602 cvin[ncvinCount].value.pointer.revocation = &rev;
603 ncvinCount++;
604 // does not work, not implemented yet in 3.12.4
605 // cvin[ncvinCount].type = cert_pi_keyusage;
606 // cvin[ncvinCount].value.scalar.ui = KU_DIGITAL_SIGNATURE;
607 // ncvinCount++;
608 cvin[ncvinCount].type = cert_pi_end;
609
610 cvout[0].type = cert_po_trustAnchor;
611 cvout[0].value.pointer.cert = nullptr;
612 cvout[1].type = cert_po_errorLog;
613 cvout[1].value.pointer.log = &log;
614 cvout[2].type = cert_po_end;
615
616 // We check SSL server certificates, CA certificates and signing certificates.
617 //
618 // ToDo check keyusage, looking at CERT_KeyUsageAndTypeForCertUsage (
619 // mozilla/security/nss/lib/certdb/certdb.c indicates that
620 // certificateUsageSSLClient, certificateUsageSSLServer and certificateUsageSSLCA
621 // are sufficient. They cover the key usages for digital signature, key agreement
622 // and encipherment and certificate signature
623
624 //never use the following usages because they are not checked properly
625 // certificateUsageUserCertImport
626 // certificateUsageVerifyCA
627 // certificateUsageAnyCA
628 // certificateUsageProtectedObjectSigner
629
630 UsageDescription arUsages[5];
631 arUsages[0] = UsageDescription( certificateUsageSSLClient, "certificateUsageSSLClient" );
632 arUsages[1] = UsageDescription( certificateUsageSSLServer, "certificateUsageSSLServer" );
633 arUsages[2] = UsageDescription( certificateUsageSSLCA, "certificateUsageSSLCA" );
634 arUsages[3] = UsageDescription( certificateUsageEmailSigner, "certificateUsageEmailSigner" );
635 arUsages[4] = UsageDescription( certificateUsageEmailRecipient, "certificateUsageEmailRecipient" );
636
637 int numUsages = std::size(arUsages);
638 for (int i = 0; i < numUsages; i++)
639 {
640 SAL_INFO("xmlsecurity.xmlsec", "Testing usage " << i+1 <<
641 " of " << numUsages << ": " <<
642 arUsages[i].description <<
643 " (0x" << std::hex << static_cast<int>(arUsages[i].usage) << ")" << std::dec);
644
645 status = CERT_PKIXVerifyCert(const_cast<CERTCertificate *>(cert), arUsages[i].usage,
646 cvin, cvout, nullptr);
647 if( status == SECSuccess )
648 {
649 SAL_INFO("xmlsecurity.xmlsec", "CERT_PKIXVerifyCert returned SECSuccess.");
650 //When an intermediate or root certificate is checked then we expect the usage
651 //certificateUsageSSLCA. This, however, will be only set when in the trust settings dialog
652 //the button "This certificate can identify websites" is checked. If for example only
653 //"This certificate can identify mail users" is set then the end certificate can
654 //be validated and the returned usage will contain certificateUsageEmailRecipient.
655 //But checking directly the root or intermediate certificate will fail. In the
656 //certificate path view the end certificate will be shown as valid but the others
657 //will be displayed as invalid.
658
659 validity = csss::CertificateValidity::VALID;
660 SAL_INFO("xmlsecurity.xmlsec", "Certificate is valid.");
661 CERTCertificate * issuerCert = cvout[0].value.pointer.cert;
662 if (issuerCert)
663 {
664 SAL_INFO("xmlsecurity.xmlsec", "Root certificate: " << issuerCert->subjectName);
665 CERT_DestroyCertificate(issuerCert);
666 };
667
668 break;
669 }
670 else
671 {
672 PRIntn err = PR_GetError();
673 SAL_INFO("xmlsecurity.xmlsec", "Error: " << err << ": " << getCertError(err));
674
675 /* Display validation results */
676 if ( log.count > 0)
677 {
678 CERTVerifyLogNode *node = nullptr;
679 printChainFailure(&log);
680
681 for (node = log.head; node; node = node->next) {
682 if (node->cert)
683 CERT_DestroyCertificate(node->cert);
684 }
685 log.head = log.tail = nullptr;
686 log.count = 0;
687 }
688 SAL_INFO("xmlsecurity.xmlsec", "Certificate is invalid.");
689 }
690 }
691
692 //Destroying the temporary certificates
693 for (auto& tmpCert : vecTmpNSSCertificates)
694 {
695 SAL_INFO("xmlsecurity.xmlsec", "Destroying temporary certificate");
696 CERT_DestroyCertificate(tmpCert);
697 }
698 PORT_FreeArena(log.arena, true);
699 return validity ;
700 }
701
702 sal_Int32 SecurityEnvironment_NssImpl::getCertificateCharacters(
703 const css::uno::Reference< css::security::XCertificate >& aCert ) {
704 sal_Int32 characters ;
705 const CERTCertificate* cert ;
706
707 const X509Certificate_NssImpl* xcert = dynamic_cast<X509Certificate_NssImpl*>(aCert.get());
708 if( xcert == nullptr ) {
709 throw RuntimeException() ;
710 }
711
712 cert = xcert->getNssCert() ;
713
714 characters = 0x00000000 ;
715
716 //Firstly, find out whether or not the cert is self-signed.
717 if( SECITEM_CompareItem( &(cert->derIssuer), &(cert->derSubject) ) == SECEqual ) {
718 characters |= css::security::CertificateCharacters::SELF_SIGNED ;
719 } else {
720 characters &= ~ css::security::CertificateCharacters::SELF_SIGNED ;
721 }
722
723 //Secondly, find out whether or not the cert has a private key.
724
725 /*
726 * i40394
727 *
728 * mmi : need to check whether the cert's slot is valid first
729 */
730 SECKEYPrivateKey* priKey = nullptr;
731
732 if (cert->slot != nullptr)
733 {
734 priKey = PK11_FindPrivateKeyFromCert( cert->slot, const_cast<CERTCertificate*>(cert), nullptr ) ;
735 }
736 if(priKey == nullptr)
737 {
738 for (auto& slot : m_Slots)
739 {
740 priKey = PK11_FindPrivateKeyFromCert(slot, const_cast<CERTCertificate*>(cert), nullptr);
741 if (priKey)
742 break;
743 }
744 }
745 if( priKey != nullptr ) {
746 characters |= css::security::CertificateCharacters::HAS_PRIVATE_KEY ;
747
748 SECKEY_DestroyPrivateKey( priKey ) ;
749 } else {
750 characters &= ~ css::security::CertificateCharacters::HAS_PRIVATE_KEY ;
751 }
752
753 return characters ;
754 }
755
756 rtl::Reference<X509Certificate_NssImpl> NssCertToXCert( CERTCertificate* cert )
757 {
758 if( cert != nullptr ) {
759 rtl::Reference<X509Certificate_NssImpl> xcert = new X509Certificate_NssImpl() ;
760 xcert->setCert( cert ) ;
761 return xcert;
762 }
763
764 return nullptr;
765 }
766
767 rtl::Reference<X509Certificate_NssImpl> NssPrivKeyToXCert( SECKEYPrivateKey* priKey )
768 {
769 if( priKey != nullptr ) {
770 rtl::Reference<X509Certificate_NssImpl> xcert;
771 CERTCertificate* cert = PK11_GetCertFromPrivateKey( priKey ) ;
772
773 if( cert != nullptr ) {
774 xcert = NssCertToXCert( cert ) ;
775 }
776
777 CERT_DestroyCertificate( cert ) ;
778 return xcert;
779 }
780
781 return nullptr;
782 }
783
784 xmlSecKeysMngrPtr SecurityEnvironment_NssImpl::createKeysManager() {
785
786 /*-
787 * The following lines is based on the private version of xmlSec-NSS
788 * crypto engine
789 */
790 int cSlots = m_Slots.size();
791 std::unique_ptr<PK11SlotInfo*[]> sarSlots(new PK11SlotInfo*[cSlots]);
792 PK11SlotInfo** slots = sarSlots.get();
793 int count = 0;
794 for (const auto& slot : m_Slots)
795 {
796 slots[count] = slot;
797 ++count;
798 }
799
800 xmlSecKeysMngrPtr pKeysMngr = xmlSecKeysMngrCreate();
801 if (!pKeysMngr)
802 throw RuntimeException();
803
804 if (xmlSecNssAppDefaultKeysMngrInit(pKeysMngr) < 0)
805 throw RuntimeException();
806
807 // Adopt the private key of the signing certificate, if it has any.
808 if (m_xSigningCertificate)
809 {
810 SECKEYPrivateKey* pPrivateKey = SECKEY_CopyPrivateKey(m_xSigningCertificate->getPrivateKey());
811 if (pPrivateKey)
812 {
813 xmlSecKeyDataPtr pKeyData = xmlSecNssPKIAdoptKey(pPrivateKey, nullptr);
814 xmlSecKeyPtr pKey = xmlSecKeyCreate();
815 xmlSecKeySetValue(pKey, pKeyData);
816 xmlSecNssAppDefaultKeysMngrAdoptKey(pKeysMngr, pKey);
817 }
818 else
819 {
820 SAL_WARN("xmlsecurity.xmlsec", "Can't get the private key from the certificate.");
821 }
822 }
823
824 return pKeysMngr;
825 }
826
827 void SecurityEnvironment_NssImpl::destroyKeysManager(xmlSecKeysMngrPtr pKeysMngr) {
828 if( pKeysMngr != nullptr ) {
829 xmlSecKeysMngrDestroy( pKeysMngr ) ;
830 }
831 }
832
833 SECKEYPrivateKey* SecurityEnvironment_NssImpl::insertPrivateKey(css::uno::Sequence<sal_Int8> const & raPrivateKey)
834 {
835 PK11SlotInfo* pSlot = PK11_GetInternalKeySlot();
836
837 if (!pSlot)
838 return nullptr;
839
840 SECItem aDerPrivateKeyInfo;
841 aDerPrivateKeyInfo.data = reinterpret_cast<unsigned char *>(const_cast<sal_Int8 *>(raPrivateKey.getConstArray()));
842 aDerPrivateKeyInfo.len = raPrivateKey.getLength();
843
844 const unsigned int aKeyUsage = KU_ALL;
845 SECKEYPrivateKey* pPrivateKey = nullptr;
846
847 // If the import is not permanent, then later we won't be able to find the private key when
848 // searching for keys and signing will fail.
849 bool bPermanent = PR_TRUE;
850 bool bPrivate = PR_TRUE;
851
852 SECStatus nStatus = PK11_ImportDERPrivateKeyInfoAndReturnKey(
853 pSlot, &aDerPrivateKeyInfo, nullptr, nullptr, bPermanent, bPrivate,
854 aKeyUsage, &pPrivateKey, nullptr);
855
856 if (nStatus != SECSuccess)
857 return nullptr;
858
859 PK11_FreeSlot(pSlot);
860
861 return pPrivateKey;
862 }
863
864 uno::Reference<security::XCertificate> SecurityEnvironment_NssImpl::createDERCertificateWithPrivateKey(
865 Sequence<sal_Int8> const & raDERCertificate, Sequence<sal_Int8> const & raPrivateKey)
866 {
867 SECKEYPrivateKey* pPrivateKey = insertPrivateKey(raPrivateKey);
868
869 if (!pPrivateKey)
870 return uno::Reference<security::XCertificate>();
871
872 return createAndAddCertificateFromPackage(raDERCertificate, u"TCu,TCu,TCu");
873 }
874
875 uno::Reference<security::XCertificate> SecurityEnvironment_NssImpl::addDERCertificateToTheDatabase(
876 uno::Sequence<sal_Int8> const & raDERCertificate, OUString const & raTrustString)
877 {
878 return createAndAddCertificateFromPackage(raDERCertificate, raTrustString);
879 }
880
881 extern "C" SAL_DLLPUBLIC_EXPORT uno::XInterface*
882 com_sun_star_xml_crypto_SecurityEnvironment_get_implementation(
883 uno::XComponentContext* /*pCtx*/, uno::Sequence<uno::Any> const& /*rSeq*/)
884 {
885 return cppu::acquire(new SecurityEnvironment_NssImpl);
886 }
887
888 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */