LibreOffice Module xmlsecurity (master) 1
x509certificate_nssimpl.cxx
Go to the documentation of this file.
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 <secder.h>
22
23#include <cert.h>
24#include <pk11pub.h>
25#include <hasht.h>
26
30#include <rtl/ref.hxx>
31#include <rtl/ustrbuf.hxx>
32#include <sal/log.hxx>
34
35#include <biginteger.hxx>
37
39#include <o3tl/string_view.hxx>
40#include <tools/time.hxx>
41#include <svl/sigstruct.hxx>
42
43using ::css::util::DateTime;
44
46 m_pCert(nullptr)
47{
48}
49
51 if( m_pCert != nullptr ) {
52 CERT_DestroyCertificate( m_pCert ) ;
53 }
54}
55
56//Methods from XCertificate
58 if( m_pCert != nullptr ) {
59 if( m_pCert->version.len > 0 ) {
60 return static_cast<char>(*( m_pCert->version.data )) ;
61 } else
62 return 0 ;
63 } else {
64 return -1 ;
65 }
66}
67
68css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getSerialNumber() {
69 if( m_pCert != nullptr && m_pCert->serialNumber.len > 0 ) {
70 return comphelper::arrayToSequence<sal_Int8>(m_pCert->serialNumber.data,
71 m_pCert->serialNumber.len) ;
72 } else {
73 return css::uno::Sequence< sal_Int8 >();
74 }
75}
76
78 if( m_pCert != nullptr ) {
79 return OUString(m_pCert->issuerName , PL_strlen(m_pCert->issuerName) , RTL_TEXTENCODING_UTF8) ;
80 } else {
81 return OUString() ;
82 }
83}
84
86 if( m_pCert != nullptr ) {
87 return OUString(m_pCert->subjectName , PL_strlen(m_pCert->subjectName) , RTL_TEXTENCODING_UTF8);
88 } else {
89 return OUString() ;
90 }
91}
92
93css::util::DateTime SAL_CALL X509Certificate_NssImpl::getNotValidBefore() {
94 if( m_pCert != nullptr ) {
95 SECStatus rv ;
96 PRTime notBefore ;
97 PRExplodedTime explTime ;
98 DateTime dateTime ;
99
100 rv = DER_DecodeTimeChoice( &notBefore, &m_pCert->validity.notBefore ) ;
101 if( rv != SECStatus::SECSuccess ) {
102 return DateTime() ;
103 }
104
105 //Convert the time to readable local time
106 PR_ExplodeTime( notBefore, PR_LocalTimeParameters, &explTime ) ;
107
108 dateTime.NanoSeconds = static_cast< sal_Int32 >( explTime.tm_usec * ::tools::Time::nanoPerMicro );
109 dateTime.Seconds = static_cast< sal_Int16 >( explTime.tm_sec );
110 dateTime.Minutes = static_cast< sal_Int16 >( explTime.tm_min );
111 dateTime.Hours = static_cast< sal_Int16 >( explTime.tm_hour );
112 dateTime.Day = static_cast< sal_Int16 >( explTime.tm_mday );
113 dateTime.Month = static_cast< sal_Int16 >( explTime.tm_month+1 );
114 dateTime.Year = static_cast< sal_Int16 >( explTime.tm_year );
115
116 return dateTime ;
117 } else {
118 return DateTime() ;
119 }
120}
121
122css::util::DateTime SAL_CALL X509Certificate_NssImpl::getNotValidAfter() {
123 if( m_pCert != nullptr ) {
124 SECStatus rv ;
125 PRTime notAfter ;
126 PRExplodedTime explTime ;
127 DateTime dateTime ;
128
129 rv = DER_DecodeTimeChoice( &notAfter, &m_pCert->validity.notAfter ) ;
130 if( rv != SECStatus::SECSuccess ) {
131 return DateTime() ;
132 }
133
134 //Convert the time to readable local time
135 PR_ExplodeTime( notAfter, PR_LocalTimeParameters, &explTime ) ;
136
137 dateTime.NanoSeconds = static_cast< sal_Int16 >( explTime.tm_usec * ::tools::Time::nanoPerMicro );
138 dateTime.Seconds = static_cast< sal_Int16 >( explTime.tm_sec );
139 dateTime.Minutes = static_cast< sal_Int16 >( explTime.tm_min );
140 dateTime.Hours = static_cast< sal_Int16 >( explTime.tm_hour );
141 dateTime.Day = static_cast< sal_Int16 >( explTime.tm_mday );
142 dateTime.Month = static_cast< sal_Int16 >( explTime.tm_month+1 );
143 dateTime.Year = static_cast< sal_Int16 >( explTime.tm_year );
144
145 return dateTime ;
146 } else {
147 return DateTime() ;
148 }
149}
150
151css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getIssuerUniqueID() {
152 if( m_pCert != nullptr && m_pCert->issuerID.len > 0 ) {
153 return comphelper::arrayToSequence<sal_Int8>(m_pCert->issuerID.data, m_pCert->issuerID.len) ;
154 } else {
155 return css::uno::Sequence< sal_Int8 >();
156 }
157}
158
159css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getSubjectUniqueID() {
160 if( m_pCert != nullptr && m_pCert->subjectID.len > 0 ) {
161 return comphelper::arrayToSequence<sal_Int8>(m_pCert->subjectID.data,
162 m_pCert->subjectID.len) ;
163 } else {
164 return css::uno::Sequence< sal_Int8 >();
165 }
166}
167
168css::uno::Sequence< css::uno::Reference< css::security::XCertificateExtension > > SAL_CALL X509Certificate_NssImpl::getExtensions() {
169 if( m_pCert != nullptr && m_pCert->extensions != nullptr ) {
170 CERTCertExtension** extns ;
171 int len ;
172
173 for( len = 0, extns = m_pCert->extensions; *extns != nullptr; len ++, extns ++ ) ;
174 css::uno::Sequence< css::uno::Reference< css::security::XCertificateExtension > > xExtns( len ) ;
175 auto xExtnsRange = asNonConstRange(xExtns);
176
177 for( extns = m_pCert->extensions, len = 0; *extns != nullptr; extns ++, len ++ ) {
178 const SECItem id = (*extns)->id;
179 OString oidString(CERT_GetOidString(&id));
180
181 bool crit;
182 if( (*extns)->critical.data == nullptr )
183 crit = false ;
184 else
185 crit = (*extns)->critical.data[0] == 0xFF;
186
187 // remove "OID." prefix if existing
188 OString objID;
189 constexpr std::string_view oid("OID.");
190 if (oidString.match(oid))
191 objID = oidString.copy(oid.size());
192 else
193 objID = oidString;
194
195 unsigned char* value = (*extns)->value.data;
196 unsigned int vlen = (*extns)->value.len;
197 unsigned char* objid = reinterpret_cast<unsigned char *>(const_cast<char *>(objID.getStr()));
198 unsigned int objidlen = objID.getLength();
199
200 if (objID == "2.5.29.17")
201 {
203 pExtn->setCertExtn(value, vlen, objid, objidlen, crit);
204 xExtnsRange[len] = pExtn ;
205 }
206 else
207 {
209 pExtn->setCertExtn(value, vlen, objid, objidlen, crit);
210 xExtnsRange[len] = pExtn;
211 }
212 }
213
214 return xExtns ;
215 } else {
216 return css::uno::Sequence< css::uno::Reference< css::security::XCertificateExtension > > ();
217 }
218}
219
220css::uno::Reference< css::security::XCertificateExtension > SAL_CALL X509Certificate_NssImpl::findCertificateExtension( const css::uno::Sequence< sal_Int8 >& oid ) {
221 if( m_pCert != nullptr && m_pCert->extensions != nullptr ) {
222 CERTCertExtension** extns ;
223 SECItem idItem ;
224
225 idItem.data = reinterpret_cast<unsigned char *>(const_cast<sal_Int8 *>(oid.getConstArray()));
226 idItem.len = oid.getLength() ;
227
228 css::uno::Reference<css::security::XCertificateExtension> xExtn;
229 for( extns = m_pCert->extensions; *extns != nullptr; extns ++ ) {
230 if( SECITEM_CompareItem( &idItem, &(*extns)->id ) == SECEqual ) {
231 const SECItem id = (*extns)->id;
232 OString objId(CERT_GetOidString(&id));
233
234 bool crit;
235 if( (*extns)->critical.data == nullptr )
236 crit = false ;
237 else
238 crit = (*extns)->critical.data[0] == 0xFF;
239
240 unsigned char* value = (*extns)->value.data;
241 unsigned int vlen = (*extns)->value.len;
242 unsigned char* objid = (*extns)->id.data;
243 unsigned int objidlen = (*extns)->id.len;
244
245 if ( objId == "OID.2.5.29.17" )
246 {
248 new SanExtensionImpl);
249 xSanImpl->setCertExtn(value, vlen, objid, objidlen, crit);
250 xExtn = xSanImpl.get();
251 }
252 else
253 {
256 xSecImpl->setCertExtn(value, vlen, objid, objidlen, crit);
257 xExtn = xSecImpl.get();
258 }
259 break;
260 }
261 }
262
263 return xExtn;
264 } else {
265 return nullptr ;
266 }
267}
268
269
270css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getEncoded() {
271 if( m_pCert != nullptr && m_pCert->derCert.len > 0 ) {
272 return comphelper::arrayToSequence<sal_Int8>(m_pCert->derCert.data, m_pCert->derCert.len) ;
273 } else {
274 return css::uno::Sequence< sal_Int8 >();
275 }
276}
277
278//Helper methods
279void X509Certificate_NssImpl::setCert( CERTCertificate* cert ) {
280 if( m_pCert != nullptr ) {
281 CERT_DestroyCertificate( m_pCert ) ;
282 m_pCert = nullptr ;
283 }
284
285 if( cert != nullptr ) {
286 m_pCert = CERT_DupCertificate( cert ) ;
287 }
288}
289
290const CERTCertificate* X509Certificate_NssImpl::getNssCert() const {
291 if( m_pCert != nullptr ) {
292 return m_pCert ;
293 } else {
294 return nullptr ;
295 }
296}
297
298void X509Certificate_NssImpl::setRawCert( const css::uno::Sequence< sal_Int8 >& rawCert ) {
299 CERTCertificate* cert ;
300 SECItem certItem ;
301
302 certItem.data = reinterpret_cast<unsigned char *>(const_cast<sal_Int8 *>(rawCert.getConstArray()));
303 certItem.len = rawCert.getLength() ;
304
305 cert = CERT_DecodeDERCertificate( &certItem, PR_TRUE, nullptr ) ;
306 if( cert == nullptr )
307 throw css::uno::RuntimeException() ;
308
309 if( m_pCert != nullptr ) {
310 CERT_DestroyCertificate( m_pCert ) ;
311 m_pCert = nullptr ;
312 }
313
314 m_pCert = cert ;
315}
316
318{
319 if (m_pCert && m_pCert->slot)
320 {
321 SECKEYPrivateKey* pPrivateKey = PK11_FindPrivateKeyFromCert(m_pCert->slot, m_pCert, nullptr);
322 if (pPrivateKey)
323 return pPrivateKey;
324 pPrivateKey = PK11_FindKeyByDERCert(m_pCert->slot, m_pCert, nullptr);
325 if (pPrivateKey)
326 {
327 SAL_INFO("xmlsecurity.xmlsec", "fallback from PK11_FindPrivateKeyFromCert to PK11_FindKeyByDERCert needed");
328 return pPrivateKey;
329 }
330 SAL_WARN("xmlsecurity.xmlsec", "X509Certificate_NssImpl::getPrivateKey() cannot find private key");
331 }
332 return nullptr;
333}
334
335static OUString getAlgorithmDescription(SECAlgorithmID const *aid)
336{
337 SECOidTag tag;
338 tag = SECOID_GetAlgorithmTag(aid);
339
340 const char *pDesc = SECOID_FindOIDTagDescription(tag);
341
342 return OUString::createFromAscii( pDesc ) ;
343}
344
345static css::uno::Sequence< sal_Int8 > getThumbprint(CERTCertificate const *pCert, SECOidTag id)
346{
347 if( pCert != nullptr )
348 {
349 SECStatus rv;
350 unsigned char fingerprint[32];
351 int length = 0;
352 switch (id)
353 {
354 case SEC_OID_MD5:
355 length = MD5_LENGTH;
356 break;
357 case SEC_OID_SHA1:
358 length = SHA1_LENGTH;
359 break;
360 case SEC_OID_SHA256:
361 length = SHA256_LENGTH;
362 break;
363 default:
364 break;
365 }
366
367 memset(fingerprint, 0, sizeof fingerprint);
368 rv = PK11_HashBuf(id, fingerprint, pCert->derCert.data, pCert->derCert.len);
369 if(rv == SECStatus::SECSuccess)
370 {
371 return comphelper::arrayToSequence<sal_Int8>(fingerprint, length);
372 }
373 }
374 return css::uno::Sequence< sal_Int8 >();
375}
376
378{
379 if( m_pCert != nullptr )
380 {
381 return getAlgorithmDescription(&(m_pCert->subjectPublicKeyInfo.algorithm));
382 }
383 else
384 {
385 return OUString() ;
386 }
387}
388
389css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getSubjectPublicKeyValue()
390{
391 if( m_pCert != nullptr )
392 {
393 SECItem spk = m_pCert->subjectPublicKeyInfo.subjectPublicKey;
394 DER_ConvertBitString(&spk);
395
396 if ( spk.len>0)
397 {
398 return comphelper::arrayToSequence<sal_Int8>(spk.data, spk.len) ;
399 }
400 }
401
402 return css::uno::Sequence< sal_Int8 >();
403}
404
406{
407 if( m_pCert != nullptr )
408 {
409 return getAlgorithmDescription(&(m_pCert->signature));
410 }
411 else
412 {
413 return OUString() ;
414 }
415}
416
418{
420
421 if (!m_pCert)
422 return nRet;
423
424 SECOidTag eTag = SECOID_GetAlgorithmTag(&m_pCert->subjectPublicKeyInfo.algorithm);
425 if (eTag == SEC_OID_ANSIX962_EC_PUBLIC_KEY)
427
428 return nRet;
429}
430
431css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getSHA1Thumbprint()
432{
433 return getThumbprint(m_pCert, SEC_OID_SHA1);
434}
435
437{
438 return getThumbprint(m_pCert, SEC_OID_SHA256);
439}
440
441css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getMD5Thumbprint()
442{
443 return getThumbprint(m_pCert, SEC_OID_MD5);
444}
445
446css::security::CertificateKind SAL_CALL X509Certificate_NssImpl::getCertificateKind()
447{
448 return css::security::CertificateKind_X509;
449}
450
452{
453 SECStatus rv;
454 SECItem tmpitem;
455 sal_Int32 usage;
456
457 rv = CERT_FindKeyUsageExtension(m_pCert, &tmpitem);
458 if ( rv == SECStatus::SECSuccess )
459 {
460 usage = tmpitem.data[0];
461 PORT_Free(tmpitem.data);
462 tmpitem.data = nullptr;
463 }
464 else
465 {
466 usage = KU_ALL;
467 }
468
469 /*
470 * to make the nss implementation compatible with MSCrypto,
471 * the following usage is ignored
472 *
473 *
474 if ( CERT_GovtApprovedBitSet(m_pCert) )
475 {
476 usage |= KU_NS_GOVT_APPROVED;
477 }
478 */
479
480 return usage;
481}
482
483/* XServiceInfo */
485{
486 return "com.sun.star.xml.security.gpg.XCertificate_NssImpl";
487}
488
489/* XServiceInfo */
490sal_Bool SAL_CALL X509Certificate_NssImpl::supportsService(const OUString& serviceName)
491{
492 return cppu::supportsService(this, serviceName);
493}
494
495/* XServiceInfo */
496css::uno::Sequence<OUString> SAL_CALL X509Certificate_NssImpl::getSupportedServiceNames() { return { OUString() }; }
497
498namespace xmlsecurity {
499
500// based on some guesswork and:
501// https://datatracker.ietf.org/doc/html/rfc1485
502// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certnametostra#CERT_X500_NAME_STR
503// the main problem appears to be that in values " is escaped as "" vs. \"
504static OUString CompatDNCryptoAPI(std::u16string_view rDN)
505{
506 OUStringBuffer buf(rDN.size());
507 enum { DEFAULT, INVALUE, INQUOTE } state(DEFAULT);
508 for (size_t i = 0; i < rDN.size(); ++i)
509 {
510 if (state == DEFAULT)
511 {
512 buf.append(rDN[i]);
513 if (rDN[i] == '=')
514 {
515 if (rDN.size() == i+1)
516 {
517 break; // invalid?
518 }
519 else if (rDN[i+1] == '"')
520 {
521 buf.append(rDN[i+1]);
522 ++i;
523 state = INQUOTE;
524 }
525 else
526 {
527 state = INVALUE;
528 }
529 }
530 }
531 else if (state == INVALUE)
532 {
533 if (rDN[i] == '+' || rDN[i] == ',' || rDN[i] == ';')
534 {
535 state = DEFAULT;
536 }
537 buf.append(rDN[i]);
538 }
539 else
540 {
541 assert(state == INQUOTE);
542 if (rDN[i] == '"')
543 {
544 if (rDN.size() != i+1 && rDN[i+1] == '"')
545 {
546 buf.append(OUString::Concat("\\") + OUStringChar(rDN[i+1]));
547 ++i;
548 }
549 else
550 {
551 buf.append(rDN[i]);
552 state = DEFAULT;
553 }
554 }
555 else
556 {
557 buf.append(rDN[i]);
558 }
559 }
560 }
561 return buf.makeStringAndClear();
562}
563
565 std::u16string_view const rName1, std::u16string_view const rName2,
566 EqualMode const eMode)
567{
568 if (eMode == COMPAT_BOTH && !rName1.empty() && rName1 == rName2)
569 { // handle case where both need to be converted
570 return true;
571 }
572 CERTName *const pName1(CERT_AsciiToName(OUStringToOString(rName1, RTL_TEXTENCODING_UTF8).getStr()));
573 if (pName1 == nullptr)
574 {
575 return false;
576 }
577 CERTName *const pName2(CERT_AsciiToName(OUStringToOString(rName2, RTL_TEXTENCODING_UTF8).getStr()));
578 bool ret(false);
579 if (pName2)
580 {
581 ret = (CERT_CompareName(pName1, pName2) == SECEqual);
582 CERT_DestroyName(pName2);
583 }
584 if (!ret && eMode == COMPAT_2ND)
585 {
586 CERTName *const pName2Compat(CERT_AsciiToName(OUStringToOString(
587 CompatDNCryptoAPI(rName2), RTL_TEXTENCODING_UTF8).getStr()));
588 if (pName2Compat == nullptr)
589 {
590 CERT_DestroyName(pName1);
591 return false;
592 }
593 ret = CERT_CompareName(pName1, pName2Compat) == SECEqual;
594 CERT_DestroyName(pName2Compat);
595 }
596 CERT_DestroyName(pName1);
597 return ret;
598}
599
600} // namespace xmlsecurity
601
602/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
virtual svl::crypto::SignatureMethodAlgorithm getSignatureMethodAlgorithm() override
void setRawCert(const css::uno::Sequence< sal_Int8 > &rawCert)
void setCert(CERTCertificate *cert)
virtual ~X509Certificate_NssImpl() override
SECKEYPrivateKey * getPrivateKey()
virtual css::uno::Sequence< css::uno::Reference< css::security::XCertificateExtension > > SAL_CALL getExtensions() override
virtual css::uno::Reference< css::security::XCertificateExtension > SAL_CALL findCertificateExtension(const css::uno::Sequence< sal_Int8 > &oid) override
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getMD5Thumbprint() override
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getSubjectUniqueID() override
virtual OUString SAL_CALL getImplementationName() override
const CERTCertificate * getNssCert() const
virtual sal_Int32 SAL_CALL getCertificateUsage() override
virtual css::uno::Sequence< sal_Int8 > getSHA256Thumbprint() override
virtual css::util::DateTime SAL_CALL getNotValidBefore() override
virtual css::util::DateTime SAL_CALL getNotValidAfter() override
virtual OUString SAL_CALL getSubjectPublicKeyAlgorithm() override
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getEncoded() override
virtual OUString SAL_CALL getSubjectName() override
virtual css::security::CertificateKind SAL_CALL getCertificateKind() override
virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override
virtual sal_Int16 SAL_CALL getVersion() override
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getIssuerUniqueID() override
virtual OUString SAL_CALL getSignatureAlgorithm() override
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getSubjectPublicKeyValue() override
virtual OUString SAL_CALL getIssuerName() override
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getSHA1Thumbprint() override
virtual sal_Bool SAL_CALL supportsService(const OUString &ServiceName) override
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getSerialNumber() override
static const sal_Int64 nanoPerMicro
Any value
#define SAL_WARN(area, stream)
#define SAL_INFO(area, stream)
bool CPPUHELPER_DLLPUBLIC supportsService(css::lang::XServiceInfo *implementation, rtl::OUString const &name)
int i
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
static OUString CompatDNCryptoAPI(std::u16string_view rDN)
bool EqualDistinguishedNames(std::u16string_view const rName1, std::u16string_view const rName2, EqualMode const eMode)
#define CERT_DecodeDERCertificate
Definition: nssrenam.h:39
unsigned char sal_Bool
signed char sal_Int8
static css::uno::Sequence< sal_Int8 > getThumbprint(CERTCertificate const *pCert, SECOidTag id)
static OUString getAlgorithmDescription(SECAlgorithmID const *aid)