cid#1640468 Dereference after null check
[LibreOffice.git] / xmlsecurity / source / dialogs / certificatechooser.cxx
blobfae0bf2a86c44cd0b61110bd364c9ecc64f7577b
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 <config_gpgme.h>
21 #include <certificatechooser.hxx>
22 #include <certificateviewer.hxx>
23 #include <com/sun/star/lang/XServiceInfo.hpp>
24 #include <com/sun/star/xml/crypto/XSecurityEnvironment.hpp>
25 #include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
26 #include <comphelper/processfactory.hxx>
27 #include <comphelper/sequence.hxx>
28 #include <comphelper/xmlsechelper.hxx>
29 #include <comphelper/lok.hxx>
30 #include <sfx2/viewsh.hxx>
31 #include <svl/cryptosign.hxx>
33 #include <com/sun/star/security/NoPasswordException.hpp>
34 #include <com/sun/star/security/CertificateCharacters.hpp>
35 #include <com/sun/star/xml/crypto/NSSInitializer.hpp> // tdf#161909 - maybe not needed
37 #include <unotools/datetime.hxx>
38 #include <unotools/charclass.hxx>
39 #include <unotools/useroptions.hxx>
41 #include <resourcemanager.hxx>
42 #include <strings.hrc>
44 using namespace comphelper;
45 using namespace css;
47 CertificateChooser::CertificateChooser(weld::Window* _pParent,
48 SfxViewShell* pViewShell,
49 std::vector< css::uno::Reference< css::xml::crypto::XXMLSecurityContext > > && rxSecurityContexts,
50 CertificateChooserUserAction eAction)
51 : GenericDialogController(_pParent, u"xmlsec/ui/selectcertificatedialog.ui"_ustr, u"SelectCertificateDialog"_ustr)
52 , meAction(eAction)
53 , m_pViewShell(pViewShell)
54 , m_xFTSign(m_xBuilder->weld_label(u"sign"_ustr))
55 , m_xFTEncrypt(m_xBuilder->weld_label(u"encrypt"_ustr))
56 , m_xFTLoadedCerts(m_xBuilder->weld_label(u"loaded-certs"_ustr))
57 , m_xCertLB(m_xBuilder->weld_tree_view(u"signatures"_ustr))
58 , m_xViewBtn(m_xBuilder->weld_button(u"viewcert"_ustr))
59 , m_xOKBtn(m_xBuilder->weld_button(u"ok"_ustr))
60 , m_xFTDescription(m_xBuilder->weld_label(u"description-label"_ustr))
61 , m_xDescriptionED(m_xBuilder->weld_entry(u"description"_ustr))
62 , m_xSearchBox(m_xBuilder->weld_entry(u"searchbox"_ustr))
63 , m_xReloadBtn(m_xBuilder->weld_button(u"reloadcert"_ustr))
65 auto nControlWidth = m_xCertLB->get_approximate_digit_width() * 105;
66 m_xCertLB->set_size_request(nControlWidth, m_xCertLB->get_height_rows(12));
68 std::vector<int> aWidths
70 o3tl::narrowing<int>(30*nControlWidth/100),
71 o3tl::narrowing<int>(30*nControlWidth/100),
72 o3tl::narrowing<int>(10*nControlWidth/100),
73 o3tl::narrowing<int>(20*nControlWidth/100)
75 m_xCertLB->set_column_fixed_widths(aWidths);
76 m_xCertLB->connect_selection_changed(LINK(this, CertificateChooser, CertificateHighlightHdl));
77 m_xCertLB->connect_row_activated( LINK( this, CertificateChooser, CertificateSelectHdl ) );
78 m_xViewBtn->connect_clicked( LINK( this, CertificateChooser, ViewButtonHdl ) );
79 m_xSearchBox->connect_changed(LINK(this, CertificateChooser, SearchModifyHdl));
80 m_xReloadBtn->connect_clicked( LINK( this, CertificateChooser, ReloadButtonHdl ) );
82 mxSecurityContexts = std::move(rxSecurityContexts);
83 mbInitialized = false;
85 // disable buttons
86 CertificateHighlightHdl(*m_xCertLB);
88 if (comphelper::LibreOfficeKit::isActive())
90 // Single certificate doesn't change during the lifetime of a LOK view: no need to search or
91 // reload it.
92 m_xSearchBox->hide();
93 m_xReloadBtn->hide();
97 CertificateChooser::~CertificateChooser()
101 void CertificateChooser::BeforeRun()
103 // #i48432#
104 // We can't check for personal certificates before raising this dialog,
105 // because the mozilla implementation throws a NoPassword exception,
106 // if the user pressed cancel, and also if the database does not exist!
107 // But in the later case, the is no password query, and the user is confused
108 // that nothing happens when pressing "Add..." in the SignatureDialog.
110 // PostUserEvent( LINK( this, CertificateChooser, Initialize ) );
112 // PostUserLink behavior is too slow, so do it directly before Execute().
113 // Problem: This Dialog should be visible right now, and the parent should not be accessible.
114 // Show, Update, DisableInput...
116 m_xDialog->show();
117 ImplInitialize();
120 short CertificateChooser::run()
122 BeforeRun();
123 return GenericDialogController::run();
126 void CertificateChooser::HandleOneUsageBit(OUString& string, int& bits, int bit, TranslateId pResId)
128 if (bits & bit)
130 if (!string.isEmpty())
131 string += ", ";
132 string += XsResId(pResId);
133 bits &= ~bit;
137 OUString CertificateChooser::UsageInClearText(int bits)
139 OUString result;
141 HandleOneUsageBit(result, bits, 0x80, STR_DIGITAL_SIGNATURE);
142 HandleOneUsageBit(result, bits, 0x40, STR_NON_REPUDIATION);
143 HandleOneUsageBit(result, bits, 0x20, STR_KEY_ENCIPHERMENT);
144 HandleOneUsageBit(result, bits, 0x10, STR_DATA_ENCIPHERMENT);
145 HandleOneUsageBit(result, bits, 0x08, STR_KEY_AGREEMENT);
146 HandleOneUsageBit(result, bits, 0x04, STR_KEY_CERT_SIGN);
147 HandleOneUsageBit(result, bits, 0x02, STR_CRL_SIGN);
148 HandleOneUsageBit(result, bits, 0x01, STR_ENCIPHER_ONLY);
150 // Check for mystery leftover bits
151 if (bits != 0)
153 if (!result.isEmpty())
154 result += ", ";
155 result += "0x" + OUString::number(bits, 16);
158 return result;
161 void CertificateChooser::ImplInitialize(bool mbSearch)
163 if (mbInitialized && !mbSearch)
164 return;
166 m_xCertLB->clear();
167 m_xCertLB->make_unsorted();
168 m_xCertLB->freeze();
170 SvtUserOptions aUserOpts;
172 SvtSysLocale aSysLocale;
173 const CharClass& rCharClass = aSysLocale.GetCharClass();
174 const OUString aSearchStr(rCharClass.uppercase(m_xSearchBox->get_text()));
176 switch (meAction)
178 case CertificateChooserUserAction::Sign:
179 m_xFTSign->show();
180 m_xOKBtn->set_label(XsResId(STR_SIGN));
181 msPreferredKey = aUserOpts.GetSigningKey();
182 break;
184 case CertificateChooserUserAction::SelectSign:
185 m_xFTSign->show();
186 m_xOKBtn->set_label(XsResId(STR_SELECTSIGN));
187 msPreferredKey = aUserOpts.GetSigningKey();
188 break;
190 case CertificateChooserUserAction::Encrypt:
191 m_xFTEncrypt->show();
192 m_xFTDescription->hide();
193 m_xDescriptionED->hide();
194 m_xCertLB->set_selection_mode(SelectionMode::Multiple);
195 m_xOKBtn->set_label(XsResId(STR_ENCRYPT));
196 msPreferredKey = aUserOpts.GetEncryptionKey();
197 break;
201 bool has_x509 = false;
202 bool has_openpgp_gpg = false;
203 ::std::optional<int> oSelectRow;
204 uno::Sequence<uno::Reference< security::XCertificate>> xCerts;
205 for (auto& secContext : mxSecurityContexts)
207 if (!secContext.is())
208 continue;
209 auto secEnvironment = secContext->getSecurityEnvironment();
210 if (!secEnvironment.is())
211 continue;
213 uno::Reference<lang::XServiceInfo> secContextServiceInfo(secContext, uno::UNO_QUERY);
214 OUString secContextType = secContextServiceInfo->getImplementationName();
215 if (secContextType == "com.sun.star.xml.crypto.XMLSecurityContext") has_x509 = true;
216 else if (secContextType == "com.sun.star.xml.security.gpg.XMLSecurityContext_GpgImpl") has_openpgp_gpg = true;
220 if (xMemCerts.count(secContext))
222 xCerts = xMemCerts[secContext];
224 else
226 if (meAction == CertificateChooserUserAction::Sign || meAction == CertificateChooserUserAction::SelectSign)
228 if (comphelper::LibreOfficeKit::isActive())
230 // The LOK case takes the signing certificate from the view.
231 if (m_pViewShell && m_pViewShell->GetSigningCertificate().m_xCertificate.is())
233 xCerts = { m_pViewShell->GetSigningCertificate().m_xCertificate };
236 else
238 // Otherwise working from the system cert store is OK.
239 xCerts = secEnvironment->getPersonalCertificates();
242 else
243 // Currently (master 2024-07) all X.509 implementations (nss+mscrypt) give an empty list.
244 xCerts = secEnvironment->getAllCertificates();
246 for (sal_Int32 nCert = xCerts.getLength(); nCert;)
248 uno::Reference< security::XCertificate > xCert = xCerts[ --nCert ];
249 // Check if we have a private key for this...
250 tools::Long nCertificateCharacters = secEnvironment->getCertificateCharacters(xCert);
252 if (!(nCertificateCharacters & security::CertificateCharacters::HAS_PRIVATE_KEY))
254 ::comphelper::removeElementAt( xCerts, nCert );
257 xMemCerts[secContext] = xCerts;
260 catch (security::NoPasswordException&)
264 // fill list of certificates; the first entry will be selected
265 for (const auto& xCert : xCerts)
267 std::shared_ptr<CertificateChooserUserData> userData = std::make_shared<CertificateChooserUserData>();
268 userData->xCertificate = xCert;
269 userData->xSecurityContext = secContext;
270 userData->xSecurityEnvironment = secEnvironment;
272 // Needed to keep userData alive. (reference to shared_ptr prevents delete)
273 mvUserData.push_back(userData);
275 OUString sIssuer = xmlsec::GetContentPart( xCert->getIssuerName(), xCert->getCertificateKind());
277 // If we are searching and there is no match skip
278 if (mbSearch
279 && rCharClass.uppercase(sIssuer).indexOf(aSearchStr) < 0
280 && !aSearchStr.isEmpty())
281 continue;
283 m_xCertLB->append();
284 int nRow = m_xCertLB->n_children() - 1;
285 m_xCertLB->set_text(nRow, xmlsec::GetContentPart(xCert->getSubjectName(), xCert->getCertificateKind()), 0);
286 m_xCertLB->set_text(nRow, sIssuer, 1);
287 m_xCertLB->set_text(nRow, xmlsec::GetCertificateKind(xCert->getCertificateKind()), 2);
288 m_xCertLB->set_text(nRow, utl::GetDateString(xCert->getNotValidAfter()), 3);
289 m_xCertLB->set_text(nRow, UsageInClearText(xCert->getCertificateUsage()), 4);
290 OUString sId(weld::toId(userData.get()));
291 m_xCertLB->set_id(nRow, sId);
293 #if HAVE_FEATURE_GPGME
294 if ( !msPreferredKey.isEmpty() ) {
295 if ( xmlsec::GetHexString(xCert->getSHA1Thumbprint(), "") == msPreferredKey )
297 if ( meAction == CertificateChooserUserAction::Sign || meAction == CertificateChooserUserAction::SelectSign )
299 oSelectRow.emplace(nRow);
301 else if ( meAction == CertificateChooserUserAction::Encrypt &&
302 aUserOpts.GetEncryptToSelf() )
303 mxEncryptToSelf = xCert;
306 #endif
310 std::vector<OUString> seqLoadedCertsLabels;
311 if (has_openpgp_gpg)
312 seqLoadedCertsLabels.push_back(XsResId(STR_LOADED_CERTS_OPENPGP_GPG));
313 if (has_x509)
315 #ifdef _WIN32
316 seqLoadedCertsLabels.push_back(XsResId(STR_LOADED_CERTS_X509_MSCRYPT));
317 #else // _WIN32
318 // Should be the last one for optimal formatting, because of the appended path.
319 const uno::Reference< uno::XComponentContext >& xContext( ::comphelper::getProcessComponentContext() );
320 OUString nssPath = xml::crypto::NSSInitializer::create(xContext)->getNSSPath();
321 seqLoadedCertsLabels.push_back(XsResId(STR_LOADED_CERTS_X509_NSS_NEWLINE) + nssPath);
322 #endif // _WIN32
324 OUString loadedCertsLabel = XsResId(STR_LOADED_CERTS_BASE
326 for (size_t label_i=0; label_i<seqLoadedCertsLabels.size(); label_i++)
328 if (label_i > 0)
329 loadedCertsLabel += ", ";
330 loadedCertsLabel += seqLoadedCertsLabels[label_i];
332 m_xFTLoadedCerts->set_label(loadedCertsLabel);
333 m_xFTLoadedCerts->set_visible(true);
335 m_xCertLB->thaw();
336 m_xCertLB->unselect_all();
337 m_xCertLB->make_sorted();
339 if (oSelectRow)
341 m_xCertLB->select(*oSelectRow);
344 CertificateHighlightHdl(*m_xCertLB);
345 mbInitialized = true;
348 uno::Sequence<uno::Reference< css::security::XCertificate > > CertificateChooser::GetSelectedCertificates()
350 std::vector< uno::Reference< css::security::XCertificate > > aRet;
351 if (meAction == CertificateChooserUserAction::Encrypt)
353 // for encryption, multiselection is enabled
354 m_xCertLB->selected_foreach([this, &aRet](weld::TreeIter& rEntry){
355 CertificateChooserUserData* userData = weld::fromId<CertificateChooserUserData*>(m_xCertLB->get_id(rEntry));
356 aRet.push_back( userData->xCertificate );
357 return false;
360 else
362 uno::Reference< css::security::XCertificate > xCert;
363 int nSel = m_xCertLB->get_selected_index();
364 if (nSel != -1)
366 CertificateChooserUserData* userData = weld::fromId<CertificateChooserUserData*>(m_xCertLB->get_id(nSel));
367 xCert = userData->xCertificate;
369 aRet.push_back( xCert );
372 #if HAVE_FEATURE_GPGME
373 if ( mxEncryptToSelf.is())
374 aRet.push_back( mxEncryptToSelf );
375 #endif
377 return comphelper::containerToSequence(aRet);
380 uno::Reference<xml::crypto::XXMLSecurityContext> CertificateChooser::GetSelectedSecurityContext() const
382 int nSel = m_xCertLB->get_selected_index();
383 if (nSel == -1)
384 return uno::Reference<xml::crypto::XXMLSecurityContext>();
386 CertificateChooserUserData* userData = weld::fromId<CertificateChooserUserData*>(m_xCertLB->get_id(nSel));
387 uno::Reference<xml::crypto::XXMLSecurityContext> xCert = userData->xSecurityContext;
388 return xCert;
391 OUString CertificateChooser::GetDescription() const
393 return m_xDescriptionED->get_text();
396 OUString CertificateChooser::GetUsageText()
398 uno::Sequence< uno::Reference<css::security::XCertificate> > xCerts =
399 GetSelectedCertificates();
400 return (xCerts.hasElements() && xCerts[0].is()) ?
401 UsageInClearText(xCerts[0]->getCertificateUsage()) : OUString();
404 void CertificateChooser::ImplReloadCertificates()
406 xMemCerts.clear();
409 IMPL_LINK_NOARG(CertificateChooser, ReloadButtonHdl, weld::Button&, void)
411 ImplReloadCertificates();
412 mbInitialized = false;
413 ImplInitialize();
416 IMPL_LINK_NOARG(CertificateChooser, SearchModifyHdl, weld::Entry&, void)
418 ImplInitialize(true);
421 IMPL_LINK_NOARG(CertificateChooser, CertificateHighlightHdl, weld::TreeView&, void)
423 bool bEnable = m_xCertLB->get_selected_index() != -1;
424 m_xViewBtn->set_sensitive(bEnable);
425 m_xOKBtn->set_sensitive(bEnable);
426 m_xDescriptionED->set_sensitive(bEnable);
429 IMPL_LINK_NOARG(CertificateChooser, CertificateSelectHdl, weld::TreeView&, bool)
431 m_xDialog->response(RET_OK);
432 return true;
435 IMPL_LINK_NOARG(CertificateChooser, ViewButtonHdl, weld::Button&, void)
437 ImplShowCertificateDetails();
440 void CertificateChooser::ImplShowCertificateDetails()
442 int nSel = m_xCertLB->get_selected_index();
443 if (nSel == -1)
444 return;
446 CertificateChooserUserData* userData = weld::fromId<CertificateChooserUserData*>(m_xCertLB->get_id(nSel));
448 if (!userData->xSecurityEnvironment.is() || !userData->xCertificate.is())
449 return;
451 auto xViewer = std::make_shared<CertificateViewer>(m_xDialog.get(), userData->xSecurityEnvironment, userData->xCertificate, true, this);
452 weld::DialogController::runAsync(xViewer, [] (int) {});
455 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */