Debian Codegraph @

xmlsecurity/source/dialogs/digitalsignaturesdialog.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 <rtl/ustring.hxx>
21 #include <sal/config.h>
22
23 #include <string_view>
24
25 #include <digitalsignaturesdialog.hxx>
26 #include <certificatechooser.hxx>
27 #include <certificateviewer.hxx>
28 #include <biginteger.hxx>
29 #include <comphelper/diagnose_ex.hxx>
30 #include <comphelper/configuration.hxx>
31 #include <officecfg/Office/Common.hxx>
32
33 #include <com/sun/star/uno/SecurityException.hpp>
34 #include <com/sun/star/embed/XStorage.hpp>
35 #include <com/sun/star/container/XNameAccess.hpp>
36 #include <com/sun/star/security/CertificateValidity.hpp>
37 #include <com/sun/star/security/CertificateKind.hpp>
38 #include <com/sun/star/system/SystemShellExecute.hpp>
39 #include <com/sun/star/system/SystemShellExecuteFlags.hpp>
40
41 #include <osl/file.hxx>
42 #include <osl/process.h>
43 #include <sal/log.hxx>
44 #include <unotools/datetime.hxx>
45
46 #include <bitmaps.hlst>
47 #include <strings.hrc>
48 #include <resourcemanager.hxx>
49 #include <comphelper/lok.hxx>
50 #include <comphelper/xmlsechelper.hxx>
51 #include <comphelper/processfactory.hxx>
52
53 #include <utility>
54 #include <vcl/weld.hxx>
55 #include <vcl/svapp.hxx>
56 #include <sfx2/viewsh.hxx>
57 #include <svl/cryptosign.hxx>
58
59 #ifdef _WIN32
60 #include <o3tl/char16_t2wchar_t.hxx>
61 #include <systools/win32/comtools.hxx>
62 #include <Shlobj.h>
63 #endif
64
65 #if defined MACOSX
66 #include <sys/stat.h>
67 #endif
68
69 using namespace comphelper;
70 using namespace css::security;
71 using namespace css::uno;
72 using namespace css;
73
74 namespace
75 {
76
77 #ifdef _WIN32
78 constexpr std::u16string_view aGUIServers[]
79 = { u"Gpg4win\\kleopatra.exe",
80 u"Gpg4win\\bin\\kleopatra.exe",
81 u"GNU\\GnuPG\\kleopatra.exe",
82 u"GNU\\GnuPG\\launch-gpa.exe",
83 u"GNU\\GnuPG\\gpa.exe",
84 u"GnuPG\\bin\\gpa.exe",
85 u"GNU\\GnuPG\\bin\\kleopatra.exe",
86 u"GNU\\GnuPG\\bin\\launch-gpa.exe",
87 u"GNU\\GnuPG\\bin\\gpa.exe"};
88 #elif defined MACOSX
89 constexpr std::u16string_view aGUIServers[]
90 = { u"/Applications/GPG Keychain.app",
91 u"/Applications/Trusted Key Manager.app", // tdf#147291
92 u"/Applications/SCinterface/scManager.app", // tdf#147291
93 u"/System/Applications/Utilities/Keychain Access.app"};
94 #else
95 constexpr std::u16string_view aGUIServers[]
96 = { u"kleopatra", u"seahorse", u"gpa", u"kgpg"};
97 #endif
98
99 bool GetPathAllOS(OUString& aPath)
100 {
101 #ifdef _WIN32
102 sal::systools::CoTaskMemAllocated<wchar_t> sPath;
103 HRESULT hr
104 = SHGetKnownFolderPath(FOLDERID_ProgramFilesX86, KF_FLAG_DEFAULT, nullptr, &sPath);
105
106 if (FAILED(hr))
107 return false;
108 aPath = o3tl::toU(sPath);
109 #else
110 osl_getEnvironment(u"PATH"_ustr.pData, &aPath.pData);
111 #endif
112 return (!aPath.isEmpty());
113 }
114
115 void GetCertificateManager(OUString& sExecutable)
116 {
117 OUString aPath, aFoundGUIServer;
118 if (!GetPathAllOS(aPath))
119 return;
120
121 OUString aCetMgrConfig = officecfg::Office::Common::Security::Scripting::CertMgrPath::get();
122 if (!aCetMgrConfig.isEmpty())
123 {
124 if (aCetMgrConfig.indexOf('/') != -1
125 #ifdef _WIN32
126 || aCetMgrConfig.indexOf('\\') != -1
127 #endif
128 )
129 {
130 sExecutable = aCetMgrConfig;
131 return;
132 }
133 osl::FileBase::RC searchError = osl::File::searchFileURL(
134 aCetMgrConfig, aPath,
135 aFoundGUIServer);
136 if (searchError == osl::FileBase::E_None)
137 {
138 osl::File::getSystemPathFromFileURL(aFoundGUIServer, sExecutable);
139 return;
140 }
141 }
142
143 for (const auto& rServer: aGUIServers)
144 {
145 bool bSetCertMgrPath = false;
146
147 #ifdef MACOSX
148 // On macOS, the list of default certificate manager applications
149 // includes absolute paths so check if the path exists and is a
150 // directory
151 if (rServer.starts_with('/'))
152 {
153 OString aSysPath = OUString(rServer).toUtf8();
154 if (struct stat st; stat(aSysPath.getStr(), &st) == 0 && S_ISDIR(st.st_mode))
155 {
156 bSetCertMgrPath = true;
157 sExecutable = rServer;
158 }
159 }
160 #endif
161
162 if (!bSetCertMgrPath)
163 {
164 osl::FileBase::RC searchError = osl::File::searchFileURL(
165 OUString(rServer), aPath,
166 aFoundGUIServer);
167 if (searchError == osl::FileBase::E_None && osl::File::getSystemPathFromFileURL(aFoundGUIServer, sExecutable) == osl::FileBase::E_None)
168 bSetCertMgrPath = true;
169 }
170
171 if (bSetCertMgrPath)
172 {
173 std::shared_ptr<comphelper::ConfigurationChanges> pBatch(
174 comphelper::ConfigurationChanges::create());
175 officecfg::Office::Common::Security::Scripting::CertMgrPath::set(sExecutable,
176 pBatch);
177 pBatch->commit();
178
179 return;
180 }
181 }
182 }
183
184 bool IsThereCertificateMgr()
185 {
186 OUString sExecutable;
187 GetCertificateManager(sExecutable);
188 return (!sExecutable.isEmpty());
189 }
190 }//anonymous namespace
191
192 DigitalSignaturesDialog::DigitalSignaturesDialog(
193 weld::Window* pParent,
194 const uno::Reference< uno::XComponentContext >& rxCtx, DocumentSignatureMode eMode,
195 bool bReadOnly, OUString sODFVersion, bool bHasDocumentSignature,
196 SfxViewShell* pViewShell)
197 : GenericDialogController(pParent, u"xmlsec/ui/digitalsignaturesdialog.ui"_ustr, u"DigitalSignaturesDialog"_ustr)
198 , maSignatureManager(rxCtx, eMode)
199 , m_sODFVersion (std::move(sODFVersion))
200 , m_bHasDocumentSignature(bHasDocumentSignature)
201 , m_bWarningShowSignMacro(false)
202 , m_pViewShell(pViewShell)
203 , m_xHintDocFT(m_xBuilder->weld_label(u"dochint"_ustr))
204 , m_xHintBasicFT(m_xBuilder->weld_label(u"macrohint"_ustr))
205 , m_xSignaturesLB(m_xBuilder->weld_tree_view(u"signatures"_ustr))
206 , m_xSigsValidImg(m_xBuilder->weld_image(u"validimg"_ustr))
207 , m_xSigsValidFI(m_xBuilder->weld_label(u"validft"_ustr))
208 , m_xSigsInvalidImg(m_xBuilder->weld_image(u"invalidimg"_ustr))
209 , m_xSigsInvalidFI(m_xBuilder->weld_label(u"invalidft"_ustr))
210 , m_xSigsNotvalidatedImg(m_xBuilder->weld_image(u"notvalidatedimg"_ustr))
211 , m_xSigsNotvalidatedFI(m_xBuilder->weld_label(u"notvalidatedft"_ustr))
212 , m_xSigsOldSignatureImg(m_xBuilder->weld_image(u"oldsignatureimg"_ustr))
213 , m_xSigsOldSignatureFI(m_xBuilder->weld_label(u"oldsignatureft"_ustr))
214 , m_xViewBtn(m_xBuilder->weld_button(u"view"_ustr))
215 , m_xAddBtn(m_xBuilder->weld_button(u"sign"_ustr))
216 , m_xRemoveBtn(m_xBuilder->weld_button(u"remove"_ustr))
217 , m_xStartCertMgrBtn(m_xBuilder->weld_button(u"start_certmanager"_ustr))
218 , m_xCloseBtn(m_xBuilder->weld_button(u"close"_ustr))
219 {
220 auto nControlWidth = m_xSignaturesLB->get_approximate_digit_width() * 105;
221 m_xSignaturesLB->set_size_request(nControlWidth, m_xSignaturesLB->get_height_rows(10));
222
223 // Give the first column 6 percent, try to distribute the rest equally.
224 std::vector<int> aWidths;
225 aWidths.push_back(6*nControlWidth/100);
226 auto nColWidth = (nControlWidth - aWidths[0]) / 5;
227 aWidths.push_back(nColWidth);
228 aWidths.push_back(nColWidth);
229 aWidths.push_back(nColWidth);
230 aWidths.push_back(nColWidth);
231 m_xSignaturesLB->set_column_fixed_widths(aWidths);
232
233 mbVerifySignatures = true;
234 mbSignaturesChanged = false;
235
236 m_xSignaturesLB->connect_selection_changed(
237 LINK(this, DigitalSignaturesDialog, SignatureHighlightHdl));
238 m_xSignaturesLB->connect_row_activated( LINK( this, DigitalSignaturesDialog, SignatureSelectHdl ) );
239
240 m_xViewBtn->connect_clicked( LINK( this, DigitalSignaturesDialog, ViewButtonHdl ) );
241 m_xViewBtn->set_sensitive(false);
242
243 m_xAddBtn->connect_clicked( LINK( this, DigitalSignaturesDialog, AddButtonHdl ) );
244 if ( bReadOnly )
245 m_xAddBtn->set_sensitive(false);
246
247 m_xRemoveBtn->connect_clicked( LINK( this, DigitalSignaturesDialog, RemoveButtonHdl ) );
248 m_xRemoveBtn->set_sensitive(false);
249
250 m_xStartCertMgrBtn->connect_clicked( LINK( this, DigitalSignaturesDialog, CertMgrButtonHdl ) );
251
252 m_xCloseBtn->connect_clicked( LINK( this, DigitalSignaturesDialog, OKButtonHdl) );
253
254 switch( maSignatureManager.getSignatureMode() )
255 {
256 case DocumentSignatureMode::Content:
257 m_xHintDocFT->show();
258 break;
259 case DocumentSignatureMode::Macros:
260 m_xHintBasicFT->show();
261 break;
262 }
263
264 if (comphelper::LibreOfficeKit::isActive())
265 {
266 // If the view has a signing certificate, then allow adding a signature.
267 if (!pViewShell || !pViewShell->GetSigningCertificate().m_xCertificate.is())
268 {
269 m_xAddBtn->hide();
270 }
271 m_xStartCertMgrBtn->hide();
272 }
273
274 if (!IsThereCertificateMgr())
275 {
276 m_xStartCertMgrBtn->set_sensitive(false);
277 }
278 }
279
280 DigitalSignaturesDialog::~DigitalSignaturesDialog()
281 {
282 if (m_xViewer)
283 m_xViewer->response(RET_OK);
284
285 if (m_xInfoBox)
286 m_xInfoBox->response(RET_OK);
287 }
288
289 bool DigitalSignaturesDialog::Init()
290 {
291 bool bInit = maSignatureManager.init();
292
293 SAL_WARN_IF( !bInit, "xmlsecurity.dialogs", "Error initializing security context!" );
294
295 if ( bInit )
296 {
297 maSignatureManager.getSignatureHelper().SetStartVerifySignatureHdl( LINK( this, DigitalSignaturesDialog, StartVerifySignatureHdl ) );
298 }
299
300 return bInit;
301 }
302
303 void DigitalSignaturesDialog::SetStorage( const css::uno::Reference < css::embed::XStorage >& rxStore )
304 {
305 if (!rxStore.is())
306 {
307 // PDF supports AdES.
308 m_bAdESCompliant = true;
309 return;
310 }
311
312 // only ODF 1.1 wants to be non-XAdES (m_sODFVersion="1.0" for OOXML somehow?)
313 m_bAdESCompliant = !rxStore->hasByName(u"META-INF"_ustr) // it's a Zip storage
314 || !DocumentSignatureHelper::isODFPre_1_2(m_sODFVersion);
315
316 maSignatureManager.setStore(rxStore);
317 maSignatureManager.getSignatureHelper().SetStorage( maSignatureManager.getStore(), m_sODFVersion, {});
318 }
319
320 void DigitalSignaturesDialog::SetSignatureStream( const css::uno::Reference < css::io::XStream >& rxStream )
321 {
322 maSignatureManager.setSignatureStream(rxStream);
323 }
324
325 void DigitalSignaturesDialog::SetScriptingSignatureStream( const css::uno::Reference < css::io::XStream >& rxStream )
326 {
327 if (!rxStream.is())
328 {
329 return;
330 }
331
332 uno::Reference<uno::XComponentContext> xContext = comphelper::getProcessComponentContext();
333 moScriptSignatureManager.emplace(xContext, DocumentSignatureMode::Macros);
334 if (!moScriptSignatureManager->init())
335 {
336 return;
337 }
338 moScriptSignatureManager->setStore(maSignatureManager.getStore());
339 // This is the storage used by UriBindingHelper::getUriBinding().
340 moScriptSignatureManager->getSignatureHelper().SetStorage(maSignatureManager.getStore(), m_sODFVersion);
341 maSignatureManager.getSignatureHelper().SetStorage(maSignatureManager.getStore(), m_sODFVersion, rxStream);
342 moScriptSignatureManager->setSignatureStream(rxStream);
343 }
344
345 bool DigitalSignaturesDialog::canAddRemove()
346 {
347 //FIXME: this func needs some cleanup, such as real split between
348 //'canAdd' and 'canRemove' case
349 uno::Reference<container::XNameAccess> xNameAccess = maSignatureManager.getStore();
350 if (xNameAccess.is() && xNameAccess->hasByName(u"[Content_Types].xml"_ustr))
351 // It's always possible to append an OOXML signature.
352 return true;
353
354 if (!maSignatureManager.getStore().is())
355 // It's always possible to append a PDF signature.
356 return true;
357
358 OSL_ASSERT(maSignatureManager.getStore().is());
359 bool bDoc1_1 = DocumentSignatureHelper::isODFPre_1_2(m_sODFVersion);
360
361 // see specification
362 //cvs: specs/www/appwide/security/Electronic_Signatures_and_Security.sxw
363 //Paragraph 'Behavior with regard to ODF 1.2'
364 //For both, macro and document
365 if ( bDoc1_1 )
366 {
367 //#4
368 std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(m_xDialog.get(),
369 VclMessageType::Warning, VclButtonsType::Ok,
370 XsResId(STR_XMLSECDLG_OLD_ODF_FORMAT)));
371 xBox->run();
372 return false;
373 }
374
375 //As of OOo 3.2 the document signature includes in macrosignatures.xml. That is
376 //adding a macro signature will break an existing document signature.
377 //The sfx2 will remove the documentsignature when the user adds a macro signature
378 if (maSignatureManager.getSignatureMode() == DocumentSignatureMode::Macros)
379 {
380 if (m_bHasDocumentSignature && !m_bWarningShowSignMacro)
381 {
382 //The warning says that the document signatures will be removed if the user
383 //continues. He can then either press 'OK' or 'NO'
384 //It the user presses 'Add' or 'Remove' several times then, then the warning
385 //is shown every time until the user presses 'OK'. From then on, the warning
386 //is not displayed anymore as long as the signatures dialog is alive.
387 std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(
388 m_xDialog.get(), VclMessageType::Question, VclButtonsType::YesNo,
389 XsResId(STR_XMLSECDLG_QUERY_REMOVEDOCSIGNBEFORESIGN)));
390 if (xBox->run() == RET_NO)
391 return false;
392
393 m_bWarningShowSignMacro = true;
394 }
395 }
396 return true;
397 }
398
399 bool DigitalSignaturesDialog::canAdd() { return canAddRemove(); }
400
401 void DigitalSignaturesDialog::canRemove(const std::function<void(bool)>& rCallback)
402 {
403 auto onFinished = [this, rCallback](bool bRet) {
404 rCallback(bRet && canAddRemove());
405 };
406 bool bRet = true;
407
408 if ( maSignatureManager.getSignatureMode() == DocumentSignatureMode::Content )
409 {
410 std::shared_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(m_xDialog.get(),
411 VclMessageType::Question, VclButtonsType::YesNo,
412 XsResId(STR_XMLSECDLG_QUERY_REALLYREMOVE)));
413 xBox->runAsync(xBox, [onFinished=std::move(onFinished)](sal_Int32 nDlgRet) {
414 onFinished(nDlgRet == RET_YES);
415 });
416 return;
417 }
418
419 onFinished(bRet);
420 }
421
422 void DigitalSignaturesDialog::beforeRun()
423 {
424 // Verify Signatures and add certificates to ListBox...
425 mbVerifySignatures = true;
426 ImplGetSignatureInformations(/*bUseTempStream=*/false, /*bCacheLastSignature=*/true);
427 ImplFillSignaturesBox();
428
429 // FIXME: Disable the "Use XAdES compliant signatures" checkbox if it is irrelevant. If it is
430 // enabled, set its initial state based on existing signatures, if any.
431
432 // If it is OOXML, the checkbox is irrelevant.
433
434 // How to find out here whether it is OOXML? I don't want to create a SignatureStreamHelper and
435 // check its nStorageFormat as that seems overly complicated and seems to have weird indirect
436 // consequences, as I noticed when I tried to use DocumentSignatureManager::IsXAdESRelevant()
437 // (which now is in #if 0).
438
439 if (!maSignatureManager.getCurrentSignatureInformations().empty())
440 {
441 // If the document has only SHA-1 signatures we probably want it to stay that way?
442 }
443
444 // Only verify once, content will not change.
445 // But for refreshing signature information, StartVerifySignatureHdl will be called after each add/remove
446 mbVerifySignatures = false;
447 }
448
449 short DigitalSignaturesDialog::run()
450 {
451 beforeRun();
452 return GenericDialogController::run();
453 }
454
455 IMPL_LINK_NOARG(DigitalSignaturesDialog, SignatureHighlightHdl, weld::TreeView&, void)
456 {
457 bool bSel = m_xSignaturesLB->get_selected_index() != -1;
458 m_xViewBtn->set_sensitive( bSel );
459 if ( m_xAddBtn->get_sensitive() ) // not read only
460 m_xRemoveBtn->set_sensitive( bSel );
461 }
462
463 IMPL_LINK_NOARG(DigitalSignaturesDialog, OKButtonHdl, weld::Button&, void)
464 {
465 if (mbSignaturesChanged)
466 maSignatureManager.write(m_bAdESCompliant);
467
468 m_xDialog->response(RET_OK);
469 }
470
471 IMPL_LINK_NOARG(DigitalSignaturesDialog, SignatureSelectHdl, weld::TreeView&, bool)
472 {
473 ImplShowSignaturesDetails();
474 return true;
475 }
476
477 IMPL_LINK_NOARG(DigitalSignaturesDialog, ViewButtonHdl, weld::Button&, void)
478 {
479 ImplShowSignaturesDetails();
480 }
481
482 IMPL_LINK_NOARG(DigitalSignaturesDialog, AddButtonHdl, weld::Button&, void)
483 {
484 if( ! canAdd())
485 return;
486
487 // Separate function, so the function can call itself when the certificate choosing was
488 // successful, but the actual signing was not.
489 AddButtonHdlImpl();
490 }
491
492 void DigitalSignaturesDialog::AddButtonHdlImpl()
493 {
494 std::vector<uno::Reference<xml::crypto::XXMLSecurityContext>> xSecContexts
495 {
496 maSignatureManager.getSecurityContext()
497 };
498 // Gpg signing is only possible with ODF >= 1.2 documents
499 if (DocumentSignatureHelper::CanSignWithGPG(maSignatureManager.getStore(), m_sODFVersion))
500 xSecContexts.push_back(maSignatureManager.getGpgSecurityContext());
501
502 std::shared_ptr<CertificateChooser> aChooser = CertificateChooser::getInstance(m_xDialog.get(), m_pViewShell, std::move(xSecContexts), CertificateChooserUserAction::Sign);
503 aChooser->BeforeRun();
504 weld::DialogController::runAsync(aChooser, [this, aChooser](sal_Int32 nRet) {
505 if (nRet != RET_OK)
506 {
507 return;
508 }
509
510 try
511 {
512 sal_Int32 nSecurityId;
513
514 svl::crypto::SigningContext aSigningContext;
515 aSigningContext.m_xCertificate = aChooser->GetSelectedCertificates()[0];
516 if (moScriptSignatureManager)
517 {
518 if (!moScriptSignatureManager->add(aSigningContext,
519 aChooser->GetSelectedSecurityContext(),
520 aChooser->GetDescription(), nSecurityId,
521 m_bAdESCompliant))
522 {
523 return;
524 }
525
526 moScriptSignatureManager->read(/*bUseTempStream=*/true, /*bCacheLastSignature=*/false);
527 moScriptSignatureManager->write(m_bAdESCompliant);
528
529 maSignatureManager.setScriptingSignatureStream(moScriptSignatureManager->getSignatureStream());
530 }
531
532 if (!maSignatureManager.add(aSigningContext, aChooser->GetSelectedSecurityContext(),
533 aChooser->GetDescription(), nSecurityId, m_bAdESCompliant))
534 return;
535 mbSignaturesChanged = true;
536
537 xml::crypto::SecurityOperationStatus nStatus = xml::crypto::SecurityOperationStatus_OPERATION_SUCCEEDED;
538
539 if (maSignatureManager.getStore().is())
540 // In the PDF case the signature information is only available after parsing.
541 nStatus = maSignatureManager.getSignatureHelper().GetSignatureInformation( nSecurityId ).nStatus;
542
543 if ( nStatus == css::xml::crypto::SecurityOperationStatus_OPERATION_SUCCEEDED )
544 {
545 mbSignaturesChanged = true;
546
547 // Can't simply remember current information, need parsing for getting full information :(
548 // We need to verify the signatures again, otherwise the status in the signature information
549 // will not contain
550 // SecurityOperationStatus_OPERATION_SUCCEEDED
551 mbVerifySignatures = true;
552 ImplGetSignatureInformations(/*bUseTempStream=*/true, /*bCacheLastSignature=*/false);
553 ImplFillSignaturesBox();
554 }
555 else
556 {
557 AddButtonHdlImpl();
558 }
559 }
560 catch ( uno::Exception& )
561 {
562 TOOLS_WARN_EXCEPTION( "xmlsecurity.dialogs", "adding a signature!" );
563 std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(m_xDialog.get(),
564 VclMessageType::Error, VclButtonsType::Ok,
565 XsResId(STR_XMLSECDLG_SIGNING_FAILED)));
566 xBox->run();
567 // Don't keep invalid entries...
568 ImplGetSignatureInformations(/*bUseTempStream=*/true, /*bCacheLastSignature=*/false);
569 ImplFillSignaturesBox();
570 }
571 });
572 }
573
574 IMPL_LINK_NOARG(DigitalSignaturesDialog, RemoveButtonHdl, weld::Button&, void)
575 {
576 canRemove([this](bool bRet) {
577 if (!bRet)
578 return;
579
580 int nEntry = m_xSignaturesLB->get_selected_index();
581 if (nEntry == -1)
582 return;
583
584 try
585 {
586 sal_uInt16 nSelected = m_xSignaturesLB->get_id(nEntry).toUInt32();
587 maSignatureManager.remove(nSelected);
588
589 mbSignaturesChanged = true;
590
591 ImplFillSignaturesBox();
592 }
593 catch ( uno::Exception& )
594 {
595 TOOLS_WARN_EXCEPTION( "xmlsecurity.dialogs", "Exception while removing a signature!" );
596 // Don't keep invalid entries...
597 ImplGetSignatureInformations(/*bUseTempStream=*/true, /*bCacheLastSignature=*/true);
598 ImplFillSignaturesBox();
599 }
600 });
601 }
602
603
604 IMPL_LINK_NOARG(DigitalSignaturesDialog, CertMgrButtonHdl, weld::Button&, void)
605 {
606 OUString sExecutable;
607 GetCertificateManager(sExecutable);
608
609 if (!sExecutable.isEmpty())
610 {
611 const uno::Reference<uno::XComponentContext>& xContext
612 = ::comphelper::getProcessComponentContext();
613 uno::Reference<css::system::XSystemShellExecute> xSystemShell(
614 css::system::SystemShellExecute::create(xContext));
615
616 try
617 {
618 xSystemShell->execute(sExecutable, OUString(),
619 css::system::SystemShellExecuteFlags::DEFAULTS);
620 }
621 catch (...)
622 {
623 // Related tdf#159307 fix uncloseable windows due to uncaught exception
624 // XSystemShellExecute::execute() throws an exception for a variety
625 // of common error conditions such as files or directories that
626 // are non-existent or non-executable. Failure to catch such
627 // exceptions would cause the document window to be uncloseable
628 // and the application to be unquittable.
629 TOOLS_WARN_EXCEPTION( "xmlsecurity.dialogs", "executable failed!" );
630 sExecutable = OUString();
631 }
632 }
633
634 OUString sDialogText = (sExecutable.isEmpty() ?
635 XsResId(STR_XMLSECDLG_NO_CERT_MANAGER) : XsResId(STR_XMLSECDLG_OPENED_CRTMGR) + sExecutable);
636
637 std::unique_ptr<weld::MessageDialog> xInfoBox(Application::CreateMessageDialog(
638 m_xDialog.get(), VclMessageType::Info, VclButtonsType::Ok,
639 sDialogText));
640 xInfoBox->run();
641 }
642
643 IMPL_LINK_NOARG(DigitalSignaturesDialog, StartVerifySignatureHdl, LinkParamNone*, bool)
644 {
645 return mbVerifySignatures;
646 }
647
648 void DigitalSignaturesDialog::ImplFillSignaturesBox()
649 {
650 m_xSignaturesLB->clear();
651
652 size_t nInfos = maSignatureManager.getCurrentSignatureInformations().size();
653 size_t nValidSigs = 0, nValidCerts = 0;
654 bool bAllNewSignatures = true;
655 bool bSomePartial = false;
656
657 if( nInfos )
658 {
659 for( size_t n = 0; n < nInfos; ++n )
660 {
661 DocumentSignatureAlgorithm mode = DocumentSignatureHelper::getDocumentAlgorithm(
662 m_sODFVersion, maSignatureManager.getCurrentSignatureInformations()[n]);
663 std::vector< OUString > aElementsToBeVerified;
664 if (maSignatureManager.getStore().is())
665 aElementsToBeVerified = DocumentSignatureHelper::CreateElementList(maSignatureManager.getStore(), maSignatureManager.getSignatureMode(), mode);
666
667 const SignatureInformation& rInfo = maSignatureManager.getCurrentSignatureInformations()[n];
668 uno::Reference< css::security::XCertificate > xCert = getCertificate(rInfo);
669
670 OUString aSubject;
671 OUString aIssuer;
672 OUString aDateTimeStr;
673 OUString aDescription;
674 OUString aType;
675
676 bool bCertValid = false;
677 if( xCert.is() )
678 {
679 //check the validity of the cert
680 try {
681 sal_Int32 certResult = getSecurityEnvironmentForCertificate(xCert)->verifyCertificate(xCert,
682 Sequence<uno::Reference<security::XCertificate> >());
683
684 bCertValid = certResult == css::security::CertificateValidity::VALID;
685 if ( bCertValid )
686 nValidCerts++;
687
688 } catch (css::uno::SecurityException& ) {
689 OSL_FAIL("Verification of certificate failed");
690 bCertValid = false;
691 }
692
693 aSubject = xmlsec::GetContentPart( xCert->getSubjectName(), xCert->getCertificateKind() );
694 aIssuer = xmlsec::GetContentPart( xCert->getIssuerName(), xCert->getCertificateKind() );
695 }
696 else if (!rInfo.ouGpgCertificate.isEmpty())
697 {
698 // In case we don't have the gpg key locally, get some data from the document
699 aIssuer = rInfo.ouGpgOwner;
700 }
701
702 aDateTimeStr = utl::GetDateTimeString( rInfo.stDateTime );
703 aDescription = rInfo.ouDescription;
704
705 // Decide type string.
706 if (maSignatureManager.getStore().is())
707 {
708 // OpenPGP
709 if (!rInfo.ouGpgCertificate.isEmpty())
710 aType = "OpenPGP";
711 // XML based: XAdES or not.
712 else if (rInfo.GetSigningCertificate() && !rInfo.GetSigningCertificate()->CertDigest.isEmpty())
713 aType = "XAdES";
714 else
715 aType = "XML-DSig";
716 }
717 else
718 {
719 // Assume PDF: PAdES or not.
720 if (rInfo.bHasSigningCertificate)
721 aType = "PAdES";
722 else
723 aType = "PDF";
724 }
725
726 bool bSigValid = rInfo.nStatus == css::xml::crypto::SecurityOperationStatus_OPERATION_SUCCEEDED;
727
728 if ( bSigValid )
729 {
730 if (maSignatureManager.getStore().is())
731 {
732 // ZIP based.
733 bSigValid = DocumentSignatureHelper::checkIfAllFilesAreSigned(
734 aElementsToBeVerified, rInfo, mode);
735 }
736 else
737 {
738 // Assume PDF.
739 bSigValid = !rInfo.bPartialDocumentSignature;
740 }
741
742 if( bSigValid )
743 nValidSigs++;
744 else
745 {
746 bSomePartial = true;
747 }
748 }
749
750 OUString sImage;
751 if (!bSigValid)
752 {
753 sImage = BMP_SIG_INVALID;
754 }
755 else if (!bCertValid)
756 {
757 sImage = BMP_SIG_NOT_VALIDATED;
758 }
759 //Check if the signature is a "old" document signature, that is, which was created
760 //by a version of OOo previous to 3.2
761 // If there is no storage, then it's pointless to check storage
762 // stream references.
763 else if (maSignatureManager.getSignatureMode() == DocumentSignatureMode::Content
764 && (maSignatureManager.getStore().is() && !DocumentSignatureHelper::isOOo3_2_Signature(
765 maSignatureManager.getCurrentSignatureInformations()[n])))
766 {
767 sImage = BMP_SIG_NOT_VALIDATED;
768 bAllNewSignatures = false;
769 }
770 else if (maSignatureManager.getSignatureMode() == DocumentSignatureMode::Content
771 && DocumentSignatureHelper::isOOo3_2_Signature(
772 maSignatureManager.getCurrentSignatureInformations()[n]))
773 {
774 sImage = BMP_SIG_VALID;
775 }
776 else if (maSignatureManager.getSignatureMode() == DocumentSignatureMode::Macros)
777 {
778 sImage = BMP_SIG_VALID;
779 }
780
781 m_xSignaturesLB->insert(nullptr, n, nullptr, nullptr,
782 &sImage, nullptr, false, nullptr);
783 m_xSignaturesLB->set_text(n, aSubject, 1);
784 m_xSignaturesLB->set_text(n, aIssuer, 2);
785 m_xSignaturesLB->set_text(n, aDateTimeStr, 3);
786 m_xSignaturesLB->set_text(n, aDescription, 4);
787 m_xSignaturesLB->set_text(n, aType, 5);
788 m_xSignaturesLB->set_id(n, OUString::number(n)); // misuse user data as index
789 }
790 }
791
792 bool bAllSigsValid = (nValidSigs == nInfos);
793 bool bAllCertsValid = (nValidCerts == nInfos);
794 bool bShowValidState = nInfos && (bAllSigsValid && bAllCertsValid && bAllNewSignatures);
795
796 m_xSigsValidImg->set_visible( bShowValidState);
797 m_xSigsValidFI->set_visible( bShowValidState );
798
799 bool bShowInvalidState = nInfos && !bAllSigsValid;
800
801 m_xSigsInvalidImg->set_visible( bShowInvalidState && !bSomePartial);
802 m_xSigsInvalidFI->set_visible( bShowInvalidState && !bSomePartial);
803
804 bool bShowNotValidatedState = nInfos && bAllSigsValid && !bAllCertsValid;
805
806 m_xSigsNotvalidatedImg->set_visible(bShowNotValidatedState);
807 m_xSigsNotvalidatedFI->set_visible(bShowNotValidatedState);
808
809 //bAllNewSignatures is always true if we are not in document mode
810 bool bShowOldSignature = nInfos && bAllSigsValid && bAllCertsValid && !bAllNewSignatures;
811 m_xSigsOldSignatureImg->set_visible(bShowOldSignature || bSomePartial);
812 m_xSigsOldSignatureFI->set_visible(bShowOldSignature || bSomePartial);
813
814 SignatureHighlightHdl(*m_xSignaturesLB);
815 }
816
817 uno::Reference<security::XCertificate> DigitalSignaturesDialog::getCertificate(const SignatureInformation& rInfo)
818 {
819 uno::Reference<xml::crypto::XSecurityEnvironment> xSecEnv = maSignatureManager.getSecurityEnvironment();
820 uno::Reference<xml::crypto::XSecurityEnvironment> xGpgSecEnv = maSignatureManager.getGpgSecurityEnvironment();
821 uno::Reference<security::XCertificate> xCert;
822
823 //First we try to get the certificate which is embedded in the XML Signature
824 if (xSecEnv.is() && rInfo.GetSigningCertificate() && !rInfo.GetSigningCertificate()->X509Certificate.isEmpty())
825 xCert = xSecEnv->createCertificateFromAscii(rInfo.GetSigningCertificate()->X509Certificate);
826 else {
827 //There must be an embedded certificate because we use it to get the
828 //issuer name. We cannot use /Signature/KeyInfo/X509Data/X509IssuerName
829 //because it could be modified by an attacker. The issuer is displayed
830 //in the digital signature dialog.
831 //Comparing the X509IssuerName with the one from the X509Certificate in order
832 //to find out if the X509IssuerName was modified does not work. See #i62684
833 SAL_WARN( "xmlsecurity.dialogs", "Could not find embedded certificate!");
834 }
835
836 //In case there is no embedded certificate we try to get it from a local store
837 if (!xCert.is() && xSecEnv.is() && rInfo.GetSigningCertificate())
838 {
839 xCert = xSecEnv->getCertificate(rInfo.GetSigningCertificate()->X509IssuerName,
840 xmlsecurity::numericStringToBigInteger(rInfo.GetSigningCertificate()->X509SerialNumber));
841 }
842 if (!xCert.is() && xGpgSecEnv.is() && !rInfo.ouGpgKeyID.isEmpty())
843 xCert = xGpgSecEnv->getCertificate( rInfo.ouGpgKeyID, xmlsecurity::numericStringToBigInteger(u"") );
844
845 SAL_WARN_IF( !xCert.is(), "xmlsecurity.dialogs", "Certificate not found and can't be created!" );
846
847 return xCert;
848 }
849
850 uno::Reference<xml::crypto::XSecurityEnvironment> DigitalSignaturesDialog::getSecurityEnvironmentForCertificate(const uno::Reference<security::XCertificate>& xCert)
851 {
852 switch(xCert->getCertificateKind())
853 {
854 case CertificateKind_OPENPGP:
855 return maSignatureManager.getGpgSecurityEnvironment();
856 case CertificateKind_X509:
857 return maSignatureManager.getSecurityEnvironment();
858 default:
859 throw RuntimeException(u"Unknown certificate kind"_ustr);
860 }
861 }
862
863 //If bUseTempStream is true then the temporary signature stream is used.
864 //Otherwise the real signature stream is used.
865 void DigitalSignaturesDialog::ImplGetSignatureInformations(bool bUseTempStream, bool bCacheLastSignature)
866 {
867 maSignatureManager.read(bUseTempStream, bCacheLastSignature);
868 mbVerifySignatures = false;
869 }
870
871 void DigitalSignaturesDialog::ImplShowSignaturesDetails()
872 {
873 int nEntry = m_xSignaturesLB->get_selected_index();
874 if (nEntry == -1)
875 return;
876
877 sal_uInt16 nSelected = m_xSignaturesLB->get_id(nEntry).toUInt32();
878 const SignatureInformation& rInfo = maSignatureManager.getCurrentSignatureInformations()[ nSelected ];
879 uno::Reference<security::XCertificate> xCert = getCertificate(rInfo);
880
881 if ( xCert.is() )
882 {
883 if (m_xViewer)
884 m_xViewer->response(RET_OK);
885
886 uno::Reference<xml::crypto::XSecurityEnvironment> xSecEnv = getSecurityEnvironmentForCertificate(xCert);
887 m_xViewer = std::make_shared<CertificateViewer>(m_xDialog.get(), xSecEnv, xCert, false, nullptr);
888 weld::DialogController::runAsync(m_xViewer, [this] (sal_Int32) { m_xViewer = nullptr; });
889 }
890 else
891 {
892 if (m_xInfoBox)
893 m_xInfoBox->response(RET_OK);
894
895 m_xInfoBox = std::shared_ptr<weld::MessageDialog>(Application::CreateMessageDialog(m_xDialog.get(),
896 VclMessageType::Info, VclButtonsType::Ok,
897 XsResId(STR_XMLSECDLG_NO_CERT_FOUND)));
898 m_xInfoBox->runAsync(m_xInfoBox, [this] (sal_Int32) { m_xInfoBox = nullptr; });
899 }
900 }
901
902 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */