Gtk-WARNING gtktreestore.c:1047: Invalid column number 1 added to iter
[LibreOffice.git] / xmlsecurity / source / xmlsec / nss / x509certificate_nssimpl.cxx
blobbed7772c5791e29b17acac1cb92677c66bc0b458
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
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/.
9 * This file incorporates work covered by the following license notice:
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 .
20 #include "nssrenam.h"
21 #include <secder.h>
23 #include <cert.h>
24 #include <pk11pub.h>
25 #include <hasht.h>
27 #include <comphelper/sequence.hxx>
28 #include <cppuhelper/supportsservice.hxx>
29 #include <rtl/ref.hxx>
30 #include <rtl/ustrbuf.hxx>
31 #include <sal/log.hxx>
32 #include "x509certificate_nssimpl.hxx"
34 #include <biginteger.hxx>
35 #include <certificateextension_xmlsecimpl.hxx>
37 #include "sanextension_nssimpl.hxx"
38 #include <tools/time.hxx>
39 #include <svl/sigstruct.hxx>
41 using ::css::util::DateTime;
43 X509Certificate_NssImpl::X509Certificate_NssImpl() :
44 m_pCert(nullptr)
48 X509Certificate_NssImpl::~X509Certificate_NssImpl() {
49 if( m_pCert != nullptr ) {
50 CERT_DestroyCertificate( m_pCert ) ;
54 //Methods from XCertificate
55 sal_Int16 SAL_CALL X509Certificate_NssImpl::getVersion() {
56 if( m_pCert != nullptr ) {
57 if( m_pCert->version.len > 0 ) {
58 return static_cast<char>(*( m_pCert->version.data )) ;
59 } else
60 return 0 ;
61 } else {
62 return -1 ;
66 css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getSerialNumber() {
67 if( m_pCert != nullptr && m_pCert->serialNumber.len > 0 ) {
68 return comphelper::arrayToSequence<sal_Int8>(m_pCert->serialNumber.data,
69 m_pCert->serialNumber.len) ;
70 } else {
71 return css::uno::Sequence< sal_Int8 >();
75 OUString SAL_CALL X509Certificate_NssImpl::getIssuerName() {
76 if( m_pCert != nullptr ) {
77 return OUString(m_pCert->issuerName , PL_strlen(m_pCert->issuerName) , RTL_TEXTENCODING_UTF8) ;
78 } else {
79 return OUString() ;
83 OUString SAL_CALL X509Certificate_NssImpl::getSubjectName() {
84 if( m_pCert != nullptr ) {
85 return OUString(m_pCert->subjectName , PL_strlen(m_pCert->subjectName) , RTL_TEXTENCODING_UTF8);
86 } else {
87 return OUString() ;
91 css::util::DateTime SAL_CALL X509Certificate_NssImpl::getNotValidBefore() {
92 if( m_pCert != nullptr ) {
93 SECStatus rv ;
94 PRTime notBefore ;
95 PRExplodedTime explTime ;
96 DateTime dateTime ;
98 rv = DER_DecodeTimeChoice( &notBefore, &m_pCert->validity.notBefore ) ;
99 if( rv != SECStatus::SECSuccess ) {
100 return DateTime() ;
103 //Convert the time to readable local time
104 PR_ExplodeTime( notBefore, PR_LocalTimeParameters, &explTime ) ;
106 dateTime.NanoSeconds = static_cast< sal_Int32 >( explTime.tm_usec * ::tools::Time::nanoPerMicro );
107 dateTime.Seconds = static_cast< sal_Int16 >( explTime.tm_sec );
108 dateTime.Minutes = static_cast< sal_Int16 >( explTime.tm_min );
109 dateTime.Hours = static_cast< sal_Int16 >( explTime.tm_hour );
110 dateTime.Day = static_cast< sal_Int16 >( explTime.tm_mday );
111 dateTime.Month = static_cast< sal_Int16 >( explTime.tm_month+1 );
112 dateTime.Year = static_cast< sal_Int16 >( explTime.tm_year );
114 return dateTime ;
115 } else {
116 return DateTime() ;
120 css::util::DateTime SAL_CALL X509Certificate_NssImpl::getNotValidAfter() {
121 if( m_pCert != nullptr ) {
122 SECStatus rv ;
123 PRTime notAfter ;
124 PRExplodedTime explTime ;
125 DateTime dateTime ;
127 rv = DER_DecodeTimeChoice( &notAfter, &m_pCert->validity.notAfter ) ;
128 if( rv != SECStatus::SECSuccess ) {
129 return DateTime() ;
132 //Convert the time to readable local time
133 PR_ExplodeTime( notAfter, PR_LocalTimeParameters, &explTime ) ;
135 dateTime.NanoSeconds = static_cast< sal_Int16 >( explTime.tm_usec * ::tools::Time::nanoPerMicro );
136 dateTime.Seconds = static_cast< sal_Int16 >( explTime.tm_sec );
137 dateTime.Minutes = static_cast< sal_Int16 >( explTime.tm_min );
138 dateTime.Hours = static_cast< sal_Int16 >( explTime.tm_hour );
139 dateTime.Day = static_cast< sal_Int16 >( explTime.tm_mday );
140 dateTime.Month = static_cast< sal_Int16 >( explTime.tm_month+1 );
141 dateTime.Year = static_cast< sal_Int16 >( explTime.tm_year );
143 return dateTime ;
144 } else {
145 return DateTime() ;
149 css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getIssuerUniqueID() {
150 if( m_pCert != nullptr && m_pCert->issuerID.len > 0 ) {
151 return comphelper::arrayToSequence<sal_Int8>(m_pCert->issuerID.data, m_pCert->issuerID.len) ;
152 } else {
153 return css::uno::Sequence< sal_Int8 >();
157 css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getSubjectUniqueID() {
158 if( m_pCert != nullptr && m_pCert->subjectID.len > 0 ) {
159 return comphelper::arrayToSequence<sal_Int8>(m_pCert->subjectID.data,
160 m_pCert->subjectID.len) ;
161 } else {
162 return css::uno::Sequence< sal_Int8 >();
166 css::uno::Sequence< css::uno::Reference< css::security::XCertificateExtension > > SAL_CALL X509Certificate_NssImpl::getExtensions() {
167 if( m_pCert != nullptr && m_pCert->extensions != nullptr ) {
168 CERTCertExtension** extns ;
169 int len ;
171 for( len = 0, extns = m_pCert->extensions; *extns != nullptr; len ++, extns ++ ) ;
172 css::uno::Sequence< css::uno::Reference< css::security::XCertificateExtension > > xExtns( len ) ;
173 auto xExtnsRange = asNonConstRange(xExtns);
175 for( extns = m_pCert->extensions, len = 0; *extns != nullptr; extns ++, len ++ ) {
176 const SECItem id = (*extns)->id;
177 OString oidString(CERT_GetOidString(&id));
179 bool crit;
180 if( (*extns)->critical.data == nullptr )
181 crit = false ;
182 else
183 crit = (*extns)->critical.data[0] == 0xFF;
185 // remove "OID." prefix if existing
186 OString objID;
187 static constexpr std::string_view oid("OID.");
188 if (oidString.match(oid))
189 objID = oidString.copy(oid.size());
190 else
191 objID = oidString;
193 unsigned char* value = (*extns)->value.data;
194 unsigned int vlen = (*extns)->value.len;
195 unsigned char* objid = reinterpret_cast<unsigned char *>(const_cast<char *>(objID.getStr()));
196 unsigned int objidlen = objID.getLength();
198 if (objID == "2.5.29.17")
200 rtl::Reference<SanExtensionImpl> pExtn = new SanExtensionImpl;
201 pExtn->setCertExtn(value, vlen, objid, objidlen, crit);
202 xExtnsRange[len] = pExtn ;
204 else
206 rtl::Reference<CertificateExtension_XmlSecImpl> pExtn = new CertificateExtension_XmlSecImpl;
207 pExtn->setCertExtn(value, vlen, objid, objidlen, crit);
208 xExtnsRange[len] = pExtn;
212 return xExtns ;
213 } else {
214 return css::uno::Sequence< css::uno::Reference< css::security::XCertificateExtension > > ();
218 css::uno::Reference< css::security::XCertificateExtension > SAL_CALL X509Certificate_NssImpl::findCertificateExtension( const css::uno::Sequence< sal_Int8 >& oid ) {
219 if( m_pCert != nullptr && m_pCert->extensions != nullptr ) {
220 CERTCertExtension** extns ;
221 SECItem idItem ;
223 idItem.data = reinterpret_cast<unsigned char *>(const_cast<sal_Int8 *>(oid.getConstArray()));
224 idItem.len = oid.getLength() ;
226 css::uno::Reference<css::security::XCertificateExtension> xExtn;
227 for( extns = m_pCert->extensions; *extns != nullptr; extns ++ ) {
228 if( SECITEM_CompareItem( &idItem, &(*extns)->id ) == SECEqual ) {
229 const SECItem id = (*extns)->id;
230 OString objId(CERT_GetOidString(&id));
232 bool crit;
233 if( (*extns)->critical.data == nullptr )
234 crit = false ;
235 else
236 crit = (*extns)->critical.data[0] == 0xFF;
238 unsigned char* value = (*extns)->value.data;
239 unsigned int vlen = (*extns)->value.len;
240 unsigned char* objid = (*extns)->id.data;
241 unsigned int objidlen = (*extns)->id.len;
243 if ( objId == "OID.2.5.29.17" )
245 rtl::Reference<SanExtensionImpl> xSanImpl(
246 new SanExtensionImpl);
247 xSanImpl->setCertExtn(value, vlen, objid, objidlen, crit);
248 xExtn = xSanImpl.get();
250 else
252 rtl::Reference<CertificateExtension_XmlSecImpl> xSecImpl(
253 new CertificateExtension_XmlSecImpl);
254 xSecImpl->setCertExtn(value, vlen, objid, objidlen, crit);
255 xExtn = xSecImpl.get();
257 break;
261 return xExtn;
262 } else {
263 return nullptr ;
268 css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getEncoded() {
269 if( m_pCert != nullptr && m_pCert->derCert.len > 0 ) {
270 return comphelper::arrayToSequence<sal_Int8>(m_pCert->derCert.data, m_pCert->derCert.len) ;
271 } else {
272 return css::uno::Sequence< sal_Int8 >();
276 //Helper methods
277 void X509Certificate_NssImpl::setCert( CERTCertificate* cert ) {
278 if( m_pCert != nullptr ) {
279 CERT_DestroyCertificate( m_pCert ) ;
280 m_pCert = nullptr ;
283 if( cert != nullptr ) {
284 m_pCert = CERT_DupCertificate( cert ) ;
288 const CERTCertificate* X509Certificate_NssImpl::getNssCert() const {
289 if( m_pCert != nullptr ) {
290 return m_pCert ;
291 } else {
292 return nullptr ;
296 void X509Certificate_NssImpl::setRawCert( const css::uno::Sequence< sal_Int8 >& rawCert ) {
297 CERTCertificate* cert ;
298 SECItem certItem ;
300 certItem.data = reinterpret_cast<unsigned char *>(const_cast<sal_Int8 *>(rawCert.getConstArray()));
301 certItem.len = rawCert.getLength() ;
303 cert = CERT_DecodeDERCertificate( &certItem, PR_TRUE, nullptr ) ;
304 if( cert == nullptr )
305 throw css::uno::RuntimeException() ;
307 if( m_pCert != nullptr ) {
308 CERT_DestroyCertificate( m_pCert ) ;
309 m_pCert = nullptr ;
312 m_pCert = cert ;
315 SECKEYPrivateKey* X509Certificate_NssImpl::getPrivateKey()
317 if (m_pCert && m_pCert->slot)
319 SECKEYPrivateKey* pPrivateKey = PK11_FindPrivateKeyFromCert(m_pCert->slot, m_pCert, nullptr);
320 if (pPrivateKey)
321 return pPrivateKey;
322 pPrivateKey = PK11_FindKeyByDERCert(m_pCert->slot, m_pCert, nullptr);
323 if (pPrivateKey)
325 SAL_INFO("xmlsecurity.xmlsec", "fallback from PK11_FindPrivateKeyFromCert to PK11_FindKeyByDERCert needed");
326 return pPrivateKey;
328 SAL_WARN("xmlsecurity.xmlsec", "X509Certificate_NssImpl::getPrivateKey() cannot find private key");
330 return nullptr;
333 static OUString getAlgorithmDescription(SECAlgorithmID const *aid)
335 SECOidTag tag;
336 tag = SECOID_GetAlgorithmTag(aid);
338 const char *pDesc = SECOID_FindOIDTagDescription(tag);
340 return OUString::createFromAscii( pDesc ) ;
343 static css::uno::Sequence< sal_Int8 > getThumbprint(CERTCertificate const *pCert, SECOidTag id)
345 if( pCert != nullptr )
347 SECStatus rv;
348 unsigned char fingerprint[32];
349 int length = 0;
350 switch (id)
352 case SEC_OID_MD5:
353 length = MD5_LENGTH;
354 break;
355 case SEC_OID_SHA1:
356 length = SHA1_LENGTH;
357 break;
358 case SEC_OID_SHA256:
359 length = SHA256_LENGTH;
360 break;
361 default:
362 break;
365 memset(fingerprint, 0, sizeof fingerprint);
366 rv = PK11_HashBuf(id, fingerprint, pCert->derCert.data, pCert->derCert.len);
367 if(rv == SECStatus::SECSuccess)
369 return comphelper::arrayToSequence<sal_Int8>(fingerprint, length);
372 return css::uno::Sequence< sal_Int8 >();
375 OUString SAL_CALL X509Certificate_NssImpl::getSubjectPublicKeyAlgorithm()
377 if( m_pCert != nullptr )
379 return getAlgorithmDescription(&(m_pCert->subjectPublicKeyInfo.algorithm));
381 else
383 return OUString() ;
387 css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getSubjectPublicKeyValue()
389 if( m_pCert != nullptr )
391 SECItem spk = m_pCert->subjectPublicKeyInfo.subjectPublicKey;
392 DER_ConvertBitString(&spk);
394 if ( spk.len>0)
396 return comphelper::arrayToSequence<sal_Int8>(spk.data, spk.len) ;
400 return css::uno::Sequence< sal_Int8 >();
403 OUString SAL_CALL X509Certificate_NssImpl::getSignatureAlgorithm()
405 if( m_pCert != nullptr )
407 return getAlgorithmDescription(&(m_pCert->signature));
409 else
411 return OUString() ;
415 svl::crypto::SignatureMethodAlgorithm X509Certificate_NssImpl::getSignatureMethodAlgorithm()
417 svl::crypto::SignatureMethodAlgorithm nRet = svl::crypto::SignatureMethodAlgorithm::RSA;
419 if (!m_pCert)
420 return nRet;
422 SECOidTag eTag = SECOID_GetAlgorithmTag(&m_pCert->subjectPublicKeyInfo.algorithm);
423 if (eTag == SEC_OID_ANSIX962_EC_PUBLIC_KEY)
424 nRet = svl::crypto::SignatureMethodAlgorithm::ECDSA;
426 return nRet;
429 css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getSHA1Thumbprint()
431 return getThumbprint(m_pCert, SEC_OID_SHA1);
434 css::uno::Sequence<sal_Int8> X509Certificate_NssImpl::getSHA256Thumbprint()
436 return getThumbprint(m_pCert, SEC_OID_SHA256);
439 css::uno::Sequence< sal_Int8 > SAL_CALL X509Certificate_NssImpl::getMD5Thumbprint()
441 return getThumbprint(m_pCert, SEC_OID_MD5);
444 css::security::CertificateKind SAL_CALL X509Certificate_NssImpl::getCertificateKind()
446 return css::security::CertificateKind_X509;
449 sal_Int32 SAL_CALL X509Certificate_NssImpl::getCertificateUsage( )
451 SECStatus rv;
452 SECItem tmpitem;
453 sal_Int32 usage;
455 rv = CERT_FindKeyUsageExtension(m_pCert, &tmpitem);
456 if ( rv == SECStatus::SECSuccess )
458 usage = tmpitem.data[0];
459 PORT_Free(tmpitem.data);
460 tmpitem.data = nullptr;
462 else
464 usage = KU_ALL;
468 * to make the nss implementation compatible with MSCrypto,
469 * the following usage is ignored
472 if ( CERT_GovtApprovedBitSet(m_pCert) )
474 usage |= KU_NS_GOVT_APPROVED;
478 return usage;
481 /* XServiceInfo */
482 OUString SAL_CALL X509Certificate_NssImpl::getImplementationName()
484 return u"com.sun.star.xml.security.gpg.XCertificate_NssImpl"_ustr;
487 /* XServiceInfo */
488 sal_Bool SAL_CALL X509Certificate_NssImpl::supportsService(const OUString& serviceName)
490 return cppu::supportsService(this, serviceName);
493 /* XServiceInfo */
494 css::uno::Sequence<OUString> SAL_CALL X509Certificate_NssImpl::getSupportedServiceNames() { return { OUString() }; }
496 namespace xmlsecurity {
498 // based on some guesswork and:
499 // https://datatracker.ietf.org/doc/html/rfc1485
500 // https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certnametostra#CERT_X500_NAME_STR
501 // the main problem appears to be that in values " is escaped as "" vs. \"
502 static OUString CompatDNCryptoAPI(std::u16string_view rDN)
504 OUStringBuffer buf(rDN.size());
505 enum { DEFAULT, INVALUE, INQUOTE } state(DEFAULT);
506 for (size_t i = 0; i < rDN.size(); ++i)
508 if (state == DEFAULT)
510 buf.append(rDN[i]);
511 if (rDN[i] == '=')
513 if (rDN.size() == i+1)
515 break; // invalid?
517 else if (rDN[i+1] == '"')
519 buf.append(rDN[i+1]);
520 ++i;
521 state = INQUOTE;
523 else
525 state = INVALUE;
529 else if (state == INVALUE)
531 if (rDN[i] == '+' || rDN[i] == ',' || rDN[i] == ';')
533 state = DEFAULT;
535 buf.append(rDN[i]);
537 else
539 assert(state == INQUOTE);
540 if (rDN[i] == '"')
542 if (rDN.size() != i+1 && rDN[i+1] == '"')
544 buf.append(OUString::Concat("\\") + OUStringChar(rDN[i+1]));
545 ++i;
547 else
549 buf.append(rDN[i]);
550 state = DEFAULT;
553 else
555 buf.append(rDN[i]);
559 return buf.makeStringAndClear();
562 bool EqualDistinguishedNames(
563 std::u16string_view const rName1, std::u16string_view const rName2,
564 EqualMode const eMode)
566 if (eMode == COMPAT_BOTH && !rName1.empty() && rName1 == rName2)
567 { // handle case where both need to be converted
568 return true;
570 CERTName *const pName1(CERT_AsciiToName(OUStringToOString(rName1, RTL_TEXTENCODING_UTF8).getStr()));
571 if (pName1 == nullptr)
573 return false;
575 CERTName *const pName2(CERT_AsciiToName(OUStringToOString(rName2, RTL_TEXTENCODING_UTF8).getStr()));
576 bool ret(false);
577 if (pName2)
579 ret = (CERT_CompareName(pName1, pName2) == SECEqual);
580 CERT_DestroyName(pName2);
582 if (!ret && eMode == COMPAT_2ND)
584 CERTName *const pName2Compat(CERT_AsciiToName(OUStringToOString(
585 CompatDNCryptoAPI(rName2), RTL_TEXTENCODING_UTF8).getStr()));
586 if (pName2Compat == nullptr)
588 CERT_DestroyName(pName1);
589 return false;
591 ret = CERT_CompareName(pName1, pName2Compat) == SECEqual;
592 CERT_DestroyName(pName2Compat);
594 CERT_DestroyName(pName1);
595 return ret;
598 } // namespace xmlsecurity
600 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */