Debian Codegraph @

xmlsecurity/source/dialogs/certificatechooser.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 <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 <rtl/ustrbuf.hxx>
31 #include <sfx2/viewsh.hxx>
32 #include <svl/cryptosign.hxx>
33
34 #include <com/sun/star/security/NoPasswordException.hpp>
35 #include <com/sun/star/security/CertificateCharacters.hpp>
36 #include <com/sun/star/xml/crypto/NSSInitializer.hpp> // tdf#161909 - maybe not needed
37
38 #include <unotools/datetime.hxx>
39 #include <unotools/charclass.hxx>
40 #include <unotools/useroptions.hxx>
41
42 #include <resourcemanager.hxx>
43 #include <strings.hrc>
44
45 using namespace comphelper;
46 using namespace css;
47
48 CertificateChooser::CertificateChooser(weld::Window* _pParent,
49 SfxViewShell* pViewShell,
50 std::vector< css::uno::Reference< css::xml::crypto::XXMLSecurityContext > > && rxSecurityContexts,
51 CertificateChooserUserAction eAction)
52 : GenericDialogController(_pParent, u"xmlsec/ui/selectcertificatedialog.ui"_ustr, u"SelectCertificateDialog"_ustr)
53 , meAction(eAction)
54 , m_pViewShell(pViewShell)
55 , m_xFTSign(m_xBuilder->weld_label(u"sign"_ustr))
56 , m_xFTEncrypt(m_xBuilder->weld_label(u"encrypt"_ustr))
57 , m_xFTLoadedCerts(m_xBuilder->weld_label(u"loaded-certs"_ustr))
58 , m_xCertLB(m_xBuilder->weld_tree_view(u"signatures"_ustr))
59 , m_xViewBtn(m_xBuilder->weld_button(u"viewcert"_ustr))
60 , m_xOKBtn(m_xBuilder->weld_button(u"ok"_ustr))
61 , m_xFTDescription(m_xBuilder->weld_label(u"description-label"_ustr))
62 , m_xDescriptionED(m_xBuilder->weld_entry(u"description"_ustr))
63 , m_xSearchBox(m_xBuilder->weld_entry(u"searchbox"_ustr))
64 , m_xReloadBtn(m_xBuilder->weld_button(u"reloadcert"_ustr))
65 {
66 auto nControlWidth = m_xCertLB->get_approximate_digit_width() * 105;
67 m_xCertLB->set_size_request(nControlWidth, m_xCertLB->get_height_rows(12));
68
69 std::vector<int> aWidths
70 {
71 o3tl::narrowing<int>(30*nControlWidth/100),
72 o3tl::narrowing<int>(30*nControlWidth/100),
73 o3tl::narrowing<int>(10*nControlWidth/100),
74 o3tl::narrowing<int>(20*nControlWidth/100)
75 };
76 m_xCertLB->set_column_fixed_widths(aWidths);
77 m_xCertLB->connect_selection_changed(LINK(this, CertificateChooser, CertificateHighlightHdl));
78 m_xCertLB->connect_row_activated( LINK( this, CertificateChooser, CertificateSelectHdl ) );
79 m_xViewBtn->connect_clicked( LINK( this, CertificateChooser, ViewButtonHdl ) );
80 m_xSearchBox->connect_changed(LINK(this, CertificateChooser, SearchModifyHdl));
81 m_xReloadBtn->connect_clicked( LINK( this, CertificateChooser, ReloadButtonHdl ) );
82
83 mxSecurityContexts = std::move(rxSecurityContexts);
84 mbInitialized = false;
85
86 // disable buttons
87 CertificateHighlightHdl(*m_xCertLB);
88
89 if (comphelper::LibreOfficeKit::isActive())
90 {
91 // Single certificate doesn't change during the lifetime of a LOK view: no need to search or
92 // reload it.
93 m_xSearchBox->hide();
94 m_xReloadBtn->hide();
95 }
96 }
97
98 CertificateChooser::~CertificateChooser()
99 {
100 }
101
102 void CertificateChooser::BeforeRun()
103 {
104 // #i48432#
105 // We can't check for personal certificates before raising this dialog,
106 // because the mozilla implementation throws a NoPassword exception,
107 // if the user pressed cancel, and also if the database does not exist!
108 // But in the later case, the is no password query, and the user is confused
109 // that nothing happens when pressing "Add..." in the SignatureDialog.
110
111 // PostUserEvent( LINK( this, CertificateChooser, Initialize ) );
112
113 // PostUserLink behavior is too slow, so do it directly before Execute().
114 // Problem: This Dialog should be visible right now, and the parent should not be accessible.
115 // Show, Update, DisableInput...
116
117 m_xDialog->show();
118 ImplInitialize();
119 }
120
121 short CertificateChooser::run()
122 {
123 BeforeRun();
124 return GenericDialogController::run();
125 }
126
127 void CertificateChooser::HandleOneUsageBit(OUString& string, int& bits, int bit, TranslateId pResId)
128 {
129 if (bits & bit)
130 {
131 if (!string.isEmpty())
132 string += ", ";
133 string += XsResId(pResId);
134 bits &= ~bit;
135 }
136 }
137
138 OUString CertificateChooser::UsageInClearText(int bits)
139 {
140 OUString result;
141
142 HandleOneUsageBit(result, bits, 0x80, STR_DIGITAL_SIGNATURE);
143 HandleOneUsageBit(result, bits, 0x40, STR_NON_REPUDIATION);
144 HandleOneUsageBit(result, bits, 0x20, STR_KEY_ENCIPHERMENT);
145 HandleOneUsageBit(result, bits, 0x10, STR_DATA_ENCIPHERMENT);
146 HandleOneUsageBit(result, bits, 0x08, STR_KEY_AGREEMENT);
147 HandleOneUsageBit(result, bits, 0x04, STR_KEY_CERT_SIGN);
148 HandleOneUsageBit(result, bits, 0x02, STR_CRL_SIGN);
149 HandleOneUsageBit(result, bits, 0x01, STR_ENCIPHER_ONLY);
150
151 // Check for mystery leftover bits
152 if (bits != 0)
153 {
154 if (!result.isEmpty())
155 result += ", ";
156 result += "0x" + OUString::number(bits, 16);
157 }
158
159 return result;
160 }
161
162 void CertificateChooser::ImplInitialize(bool mbSearch)
163 {
164 if (mbInitialized && !mbSearch)
165 return;
166
167 m_xCertLB->clear();
168 m_xCertLB->make_unsorted();
169 m_xCertLB->freeze();
170
171 SvtUserOptions aUserOpts;
172
173 SvtSysLocale aSysLocale;
174 const CharClass& rCharClass = aSysLocale.GetCharClass();
175 const OUString aSearchStr(rCharClass.uppercase(m_xSearchBox->get_text()));
176
177 switch (meAction)
178 {
179 case CertificateChooserUserAction::Sign:
180 m_xFTSign->show();
181 m_xOKBtn->set_label(XsResId(STR_SIGN));
182 msPreferredKey = aUserOpts.GetSigningKey();
183 break;
184
185 case CertificateChooserUserAction::SelectSign:
186 m_xFTSign->show();
187 m_xOKBtn->set_label(XsResId(STR_SELECTSIGN));
188 msPreferredKey = aUserOpts.GetSigningKey();
189 break;
190
191 case CertificateChooserUserAction::Encrypt:
192 m_xFTEncrypt->show();
193 m_xFTDescription->hide();
194 m_xDescriptionED->hide();
195 m_xCertLB->set_selection_mode(SelectionMode::Multiple);
196 m_xOKBtn->set_label(XsResId(STR_ENCRYPT));
197 msPreferredKey = aUserOpts.GetEncryptionKey();
198 break;
199
200 }
201
202 bool has_x509 = false;
203 bool has_openpgp_gpg = false;
204 ::std::optional<int> oSelectRow;
205 uno::Sequence<uno::Reference< security::XCertificate>> xCerts;
206 for (auto& secContext : mxSecurityContexts)
207 {
208 if (!secContext.is())
209 continue;
210 auto secEnvironment = secContext->getSecurityEnvironment();
211 if (!secEnvironment.is())
212 continue;
213
214 uno::Reference<lang::XServiceInfo> secContextServiceInfo(secContext, uno::UNO_QUERY);
215 OUString secContextType = secContextServiceInfo->getImplementationName();
216 if (secContextType == "com.sun.star.xml.crypto.XMLSecurityContext") has_x509 = true;
217 else if (secContextType == "com.sun.star.xml.security.gpg.XMLSecurityContext_GpgImpl") has_openpgp_gpg = true;
218
219 try
220 {
221 if (xMemCerts.count(secContext))
222 {
223 xCerts = xMemCerts[secContext];
224 }
225 else
226 {
227 if (meAction == CertificateChooserUserAction::Sign || meAction == CertificateChooserUserAction::SelectSign)
228 {
229 if (comphelper::LibreOfficeKit::isActive())
230 {
231 // The LOK case takes the signing certificate from the view.
232 if (m_pViewShell && m_pViewShell->GetSigningCertificate().m_xCertificate.is())
233 {
234 xCerts = { m_pViewShell->GetSigningCertificate().m_xCertificate };
235 }
236 }
237 else
238 {
239 // Otherwise working from the system cert store is OK.
240 xCerts = secEnvironment->getPersonalCertificates();
241 }
242 }
243 else
244 // Currently (master 2024-07) all X.509 implementations (nss+mscrypt) give an empty list.
245 xCerts = secEnvironment->getAllCertificates();
246
247 for (sal_Int32 nCert = xCerts.getLength(); nCert;)
248 {
249 uno::Reference< security::XCertificate > xCert = xCerts[ --nCert ];
250 // Check if we have a private key for this...
251 tools::Long nCertificateCharacters = secEnvironment->getCertificateCharacters(xCert);
252
253 if (!(nCertificateCharacters & security::CertificateCharacters::HAS_PRIVATE_KEY))
254 {
255 ::comphelper::removeElementAt( xCerts, nCert );
256 }
257 }
258 xMemCerts[secContext] = xCerts;
259 }
260 }
261 catch (security::NoPasswordException&)
262 {
263 }
264
265 // fill list of certificates; the first entry will be selected
266 for (const auto& xCert : xCerts)
267 {
268 std::shared_ptr<CertificateChooserUserData> userData = std::make_shared<CertificateChooserUserData>();
269 userData->xCertificate = xCert;
270 userData->xSecurityContext = secContext;
271 userData->xSecurityEnvironment = secEnvironment;
272
273 // Needed to keep userData alive. (reference to shared_ptr prevents delete)
274 mvUserData.push_back(userData);
275
276 OUString sIssuer = xmlsec::GetContentPart( xCert->getIssuerName(), xCert->getCertificateKind());
277
278 // If we are searching and there is no match skip
279 if (mbSearch
280 && rCharClass.uppercase(sIssuer).indexOf(aSearchStr) < 0
281 && !aSearchStr.isEmpty())
282 continue;
283
284 m_xCertLB->append();
285 int nRow = m_xCertLB->n_children() - 1;
286 m_xCertLB->set_text(nRow, xmlsec::GetContentPart(xCert->getSubjectName(), xCert->getCertificateKind()), 0);
287 m_xCertLB->set_text(nRow, sIssuer, 1);
288 m_xCertLB->set_text(nRow, xmlsec::GetCertificateKind(xCert->getCertificateKind()), 2);
289 m_xCertLB->set_text(nRow, utl::GetDateString(xCert->getNotValidAfter()), 3);
290 m_xCertLB->set_text(nRow, UsageInClearText(xCert->getCertificateUsage()), 4);
291 OUString sId(weld::toId(userData.get()));
292 m_xCertLB->set_id(nRow, sId);
293
294 #if HAVE_FEATURE_GPGME
295 if ( !msPreferredKey.isEmpty() ) {
296 if ( xmlsec::GetHexString(xCert->getSHA1Thumbprint(), "") == msPreferredKey )
297 {
298 if ( meAction == CertificateChooserUserAction::Sign || meAction == CertificateChooserUserAction::SelectSign )
299 {
300 oSelectRow.emplace(nRow);
301 }
302 else if ( meAction == CertificateChooserUserAction::Encrypt &&
303 aUserOpts.GetEncryptToSelf() )
304 mxEncryptToSelf = xCert;
305 }
306 }
307 #endif
308 }
309 }
310
311 std::vector<OUString> seqLoadedCertsLabels;
312 if (has_openpgp_gpg)
313 seqLoadedCertsLabels.push_back(XsResId(STR_LOADED_CERTS_OPENPGP_GPG));
314 if (has_x509)
315 {
316 #ifdef _WIN32
317 seqLoadedCertsLabels.push_back(XsResId(STR_LOADED_CERTS_X509_MSCRYPT));
318 #else // _WIN32
319 // Should be the last one for optimal formatting, because of the appended path.
320 const uno::Reference< uno::XComponentContext >& xContext( ::comphelper::getProcessComponentContext() );
321 OUString nssPath = xml::crypto::NSSInitializer::create(xContext)->getNSSPath();
322 seqLoadedCertsLabels.push_back(XsResId(STR_LOADED_CERTS_X509_NSS_NEWLINE) + nssPath);
323 #endif // _WIN32
324 }
325 OUStringBuffer loadedCertsLabel(XsResId(STR_LOADED_CERTS_BASE));
326 for (size_t label_i=0; label_i<seqLoadedCertsLabels.size(); label_i++)
327 {
328 if (label_i > 0)
329 loadedCertsLabel.append(", ");
330 loadedCertsLabel.append(seqLoadedCertsLabels[label_i]);
331 }
332 m_xFTLoadedCerts->set_label(loadedCertsLabel.toString());
333 m_xFTLoadedCerts->set_visible(true);
334
335 m_xCertLB->thaw();
336 m_xCertLB->unselect_all();
337 m_xCertLB->make_sorted();
338
339 if (oSelectRow)
340 {
341 m_xCertLB->select(*oSelectRow);
342 }
343
344 CertificateHighlightHdl(*m_xCertLB);
345 mbInitialized = true;
346 }
347
348 uno::Sequence<uno::Reference< css::security::XCertificate > > CertificateChooser::GetSelectedCertificates()
349 {
350 std::vector< uno::Reference< css::security::XCertificate > > aRet;
351 if (meAction == CertificateChooserUserAction::Encrypt)
352 {
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;
358 });
359 }
360 else
361 {
362 uno::Reference< css::security::XCertificate > xCert;
363 int nSel = m_xCertLB->get_selected_index();
364 if (nSel != -1)
365 {
366 CertificateChooserUserData* userData = weld::fromId<CertificateChooserUserData*>(m_xCertLB->get_id(nSel));
367 xCert = userData->xCertificate;
368 }
369 aRet.push_back( xCert );
370 }
371
372 #if HAVE_FEATURE_GPGME
373 if ( mxEncryptToSelf.is())
374 aRet.push_back( mxEncryptToSelf );
375 #endif
376
377 return comphelper::containerToSequence(aRet);
378 }
379
380 uno::Reference<xml::crypto::XXMLSecurityContext> CertificateChooser::GetSelectedSecurityContext() const
381 {
382 int nSel = m_xCertLB->get_selected_index();
383 if (nSel == -1)
384 return uno::Reference<xml::crypto::XXMLSecurityContext>();
385
386 CertificateChooserUserData* userData = weld::fromId<CertificateChooserUserData*>(m_xCertLB->get_id(nSel));
387 uno::Reference<xml::crypto::XXMLSecurityContext> xCert = userData->xSecurityContext;
388 return xCert;
389 }
390
391 OUString CertificateChooser::GetDescription() const
392 {
393 return m_xDescriptionED->get_text();
394 }
395
396 OUString CertificateChooser::GetUsageText()
397 {
398 uno::Sequence< uno::Reference<css::security::XCertificate> > xCerts =
399 GetSelectedCertificates();
400 return (xCerts.hasElements() && xCerts[0].is()) ?
401 UsageInClearText(xCerts[0]->getCertificateUsage()) : OUString();
402 }
403
404 void CertificateChooser::ImplReloadCertificates()
405 {
406 xMemCerts.clear();
407 }
408
409 IMPL_LINK_NOARG(CertificateChooser, ReloadButtonHdl, weld::Button&, void)
410 {
411 ImplReloadCertificates();
412 mbInitialized = false;
413 ImplInitialize();
414 }
415
416 IMPL_LINK_NOARG(CertificateChooser, SearchModifyHdl, weld::Entry&, void)
417 {
418 ImplInitialize(true);
419 }
420
421 IMPL_LINK_NOARG(CertificateChooser, CertificateHighlightHdl, weld::TreeView&, void)
422 {
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);
427 }
428
429 IMPL_LINK_NOARG(CertificateChooser, CertificateSelectHdl, weld::TreeView&, bool)
430 {
431 m_xDialog->response(RET_OK);
432 return true;
433 }
434
435 IMPL_LINK_NOARG(CertificateChooser, ViewButtonHdl, weld::Button&, void)
436 {
437 ImplShowCertificateDetails();
438 }
439
440 void CertificateChooser::ImplShowCertificateDetails()
441 {
442 int nSel = m_xCertLB->get_selected_index();
443 if (nSel == -1)
444 return;
445
446 CertificateChooserUserData* userData = weld::fromId<CertificateChooserUserData*>(m_xCertLB->get_id(nSel));
447
448 if (!userData->xSecurityEnvironment.is() || !userData->xCertificate.is())
449 return;
450
451 auto xViewer = std::make_shared<CertificateViewer>(m_xDialog.get(), userData->xSecurityEnvironment, userData->xCertificate, true, this);
452 weld::DialogController::runAsync(xViewer, [] (int) {});
453 }
454
455 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */