diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e11dde5fd..3bbec7c2f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,623 +1,625 @@ # SPDX-FileCopyrightText: none # SPDX-License-Identifier: BSD-3-Clause add_subdirectory(icons) add_subdirectory(mimetypes) include_directories(${CMAKE_CURRENT_BINARY_DIR}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) if (NOT DISABLE_KWATCHGNUPG) add_subdirectory(kwatchgnupg) endif() add_subdirectory(libkleopatraclient) add_subdirectory(conf) add_subdirectory(kconf_update) if(WIN32) set(_kleopatra_extra_uiserver_SRCS uiserver/uiserver_win.cpp) set(_kleopatra_extra_SRCS selftest/registrycheck.cpp utils/gnupg-registry.c utils/userinfo_win.cpp utils/windowsprocessdevice.cpp ) else() set(_kleopatra_extra_uiserver_SRCS uiserver/uiserver_unix.cpp) set(_kleopatra_extra_SRCS) endif() set(_kleopatra_uiserver_SRCS ${_kleopatra_extra_uiserver_SRCS} selftest/uiservercheck.cpp uiserver/assuanserverconnection.cpp uiserver/createchecksumscommand.cpp uiserver/decryptverifycommandemailbase.cpp uiserver/decryptverifycommandfilesbase.cpp uiserver/echocommand.cpp uiserver/encryptcommand.cpp uiserver/importfilescommand.cpp uiserver/prepencryptcommand.cpp uiserver/prepsigncommand.cpp uiserver/selectcertificatecommand.cpp uiserver/sessiondata.cpp uiserver/signcommand.cpp uiserver/signencryptfilescommand.cpp uiserver/uiserver.cpp uiserver/verifychecksumscommand.cpp ) if(ASSUAN2_FOUND) include_directories(${ASSUAN2_INCLUDES}) set(_kleopatra_uiserver_extra_libs ${ASSUAN2_LIBRARIES}) else() include_directories(${ASSUAN_INCLUDES}) if(WIN32) set(_kleopatra_uiserver_extra_libs ${ASSUAN_VANILLA_LIBRARIES}) else() set(_kleopatra_uiserver_extra_libs ${ASSUAN_PTHREAD_LIBRARIES}) endif() endif() if(HAVE_GPG_ERR_SOURCE_KLEO) add_definitions(-DGPG_ERR_SOURCE_DEFAULT=GPG_ERR_SOURCE_KLEO) add_definitions(-DGPGMEPP_ERR_SOURCE_DEFAULT=GPG_ERR_SOURCE_KLEO) else() add_definitions(-DGPG_ERR_SOURCE_DEFAULT=GPG_ERR_SOURCE_USER_1) add_definitions(-DGPGMEPP_ERR_SOURCE_DEFAULT=GPG_ERR_SOURCE_USER_1) endif() if(KF5IdentityManagement_FOUND AND KF5MailTransport_FOUND AND KF5MailTransportAkonadi_FOUND) set(_kleopatra_mail_libs KF5::IdentityManagement # Export OpenPGP keys using WKS KF5::MailTransport KF5::MailTransportAkonadi ) add_definitions(-DMAILAKONADI_ENABLED) endif() ki18n_wrap_ui(_kleopatra_uiserver_SRCS crypto/gui/signingcertificateselectionwidget.ui) set(_kleopatra_SRCS ${_kleopatra_extra_SRCS} accessibility/accessiblelink.cpp accessibility/accessiblelink_p.h accessibility/accessiblerichtextlabel.cpp accessibility/accessiblerichtextlabel_p.h accessibility/accessiblevaluelabel.cpp accessibility/accessiblevaluelabel_p.h accessibility/accessiblewidgetfactory.cpp accessibility/accessiblewidgetfactory.h commands/adduseridcommand.cpp commands/adduseridcommand.h commands/authenticatepivcardapplicationcommand.cpp commands/authenticatepivcardapplicationcommand.h commands/cardcommand.cpp commands/cardcommand.h commands/certificatetopivcardcommand.cpp commands/certificatetopivcardcommand.h commands/certifycertificatecommand.cpp commands/certifycertificatecommand.h commands/changeexpirycommand.cpp commands/changeexpirycommand.h commands/changeownertrustcommand.cpp commands/changeownertrustcommand.h commands/changepassphrasecommand.cpp commands/changepassphrasecommand.h commands/changepincommand.cpp commands/changepincommand.h commands/changeroottrustcommand.cpp commands/changeroottrustcommand.h commands/checksumcreatefilescommand.cpp commands/checksumcreatefilescommand.h commands/checksumverifyfilescommand.cpp commands/checksumverifyfilescommand.h commands/clearcrlcachecommand.cpp commands/clearcrlcachecommand.h commands/command.cpp commands/command.h commands/createcsrforcardkeycommand.cpp commands/createcsrforcardkeycommand.h commands/createopenpgpkeyfromcardkeyscommand.cpp commands/createopenpgpkeyfromcardkeyscommand.h commands/decryptverifyclipboardcommand.cpp commands/decryptverifyclipboardcommand.h commands/decryptverifyfilescommand.cpp commands/decryptverifyfilescommand.h commands/deletecertificatescommand.cpp commands/deletecertificatescommand.h commands/detailscommand.cpp commands/detailscommand.h commands/dumpcertificatecommand.cpp commands/dumpcertificatecommand.h commands/dumpcrlcachecommand.cpp commands/dumpcrlcachecommand.h commands/encryptclipboardcommand.cpp commands/encryptclipboardcommand.h commands/exportcertificatecommand.cpp commands/exportcertificatecommand.h commands/exportgroupscommand.cpp commands/exportgroupscommand.h commands/exportopenpgpcertstoservercommand.cpp commands/exportopenpgpcertstoservercommand.h commands/exportopenpgpcerttoprovidercommand.cpp commands/exportopenpgpcerttoprovidercommand.h commands/exportpaperkeycommand.cpp commands/exportpaperkeycommand.h commands/exportsecretkeycommand.cpp commands/exportsecretkeycommand.h commands/exportsecretkeycommand_old.cpp commands/exportsecretkeycommand_old.h commands/exportsecretsubkeycommand.cpp commands/exportsecretsubkeycommand.h commands/genrevokecommand.cpp commands/genrevokecommand.h commands/gnupgprocesscommand.cpp commands/gnupgprocesscommand.h commands/importcertificatefromclipboardcommand.cpp commands/importcertificatefromclipboardcommand.h commands/importcertificatefromdatacommand.cpp commands/importcertificatefromdatacommand.h commands/importcertificatefromfilecommand.cpp commands/importcertificatefromfilecommand.h commands/importcertificatefromkeyservercommand.cpp commands/importcertificatefromkeyservercommand.h commands/importcertificatefrompivcardcommand.cpp commands/importcertificatefrompivcardcommand.h commands/importcertificatescommand.cpp commands/importcertificatescommand.h commands/importcrlcommand.cpp commands/importcrlcommand.h commands/importpaperkeycommand.cpp commands/importpaperkeycommand.h commands/keytocardcommand.cpp commands/keytocardcommand.h commands/learncardkeyscommand.cpp commands/learncardkeyscommand.h commands/lookupcertificatescommand.cpp commands/lookupcertificatescommand.h commands/newcertificatesigningrequestcommand.cpp commands/newcertificatesigningrequestcommand.h commands/newopenpgpcertificatecommand.cpp commands/newopenpgpcertificatecommand.h + commands/openpgpgeneratecardkeycommand.cpp + commands/openpgpgeneratecardkeycommand.h commands/pivgeneratecardkeycommand.cpp commands/pivgeneratecardkeycommand.h commands/refreshcertificatecommand.cpp commands/refreshcertificatecommand.h commands/refreshopenpgpcertscommand.cpp commands/refreshopenpgpcertscommand.h commands/refreshx509certscommand.cpp commands/refreshx509certscommand.h commands/reloadkeyscommand.cpp commands/reloadkeyscommand.h commands/revokecertificationcommand.cpp commands/revokecertificationcommand.h commands/revokekeycommand.cpp commands/revokekeycommand.h commands/revokeuseridcommand.cpp commands/revokeuseridcommand.h commands/selftestcommand.cpp commands/selftestcommand.h commands/setinitialpincommand.cpp commands/setinitialpincommand.h commands/setpivcardapplicationadministrationkeycommand.cpp commands/setpivcardapplicationadministrationkeycommand.h commands/setprimaryuseridcommand.cpp commands/setprimaryuseridcommand.h commands/signclipboardcommand.cpp commands/signclipboardcommand.h commands/signencryptfilescommand.cpp commands/signencryptfilescommand.h commands/signencryptfoldercommand.cpp commands/signencryptfoldercommand.h conf/configuredialog.cpp conf/configuredialog.h conf/groupsconfigdialog.cpp conf/groupsconfigdialog.h conf/groupsconfigpage.cpp conf/groupsconfigpage.h conf/groupsconfigwidget.cpp conf/groupsconfigwidget.h crypto/autodecryptverifyfilescontroller.cpp crypto/autodecryptverifyfilescontroller.h crypto/certificateresolver.cpp crypto/certificateresolver.h crypto/checksumsutils_p.cpp crypto/checksumsutils_p.h crypto/controller.cpp crypto/controller.h crypto/createchecksumscontroller.cpp crypto/createchecksumscontroller.h crypto/decryptverifyemailcontroller.cpp crypto/decryptverifyemailcontroller.h crypto/decryptverifyfilescontroller.cpp crypto/decryptverifyfilescontroller.h crypto/decryptverifytask.cpp crypto/decryptverifytask.h crypto/encryptemailcontroller.cpp crypto/encryptemailcontroller.h crypto/encryptemailtask.cpp crypto/encryptemailtask.h crypto/gui/certificatelineedit.cpp crypto/gui/certificatelineedit.h crypto/gui/certificateselectionline.cpp crypto/gui/certificateselectionline.h crypto/gui/decryptverifyfilesdialog.cpp crypto/gui/decryptverifyfilesdialog.h crypto/gui/decryptverifyfileswizard.cpp crypto/gui/decryptverifyfileswizard.h crypto/gui/decryptverifyoperationwidget.cpp crypto/gui/decryptverifyoperationwidget.h crypto/gui/encryptemailwizard.cpp crypto/gui/encryptemailwizard.h crypto/gui/newresultpage.cpp crypto/gui/newresultpage.h crypto/gui/objectspage.cpp crypto/gui/objectspage.h crypto/gui/resolverecipientspage.cpp crypto/gui/resolverecipientspage.h crypto/gui/resultitemwidget.cpp crypto/gui/resultitemwidget.h crypto/gui/resultlistwidget.cpp crypto/gui/resultlistwidget.h crypto/gui/resultpage.cpp crypto/gui/resultpage.h crypto/gui/signemailwizard.cpp crypto/gui/signemailwizard.h crypto/gui/signencryptemailconflictdialog.cpp crypto/gui/signencryptemailconflictdialog.h crypto/gui/signencryptfileswizard.cpp crypto/gui/signencryptfileswizard.h crypto/gui/signencryptwidget.cpp crypto/gui/signencryptwidget.h crypto/gui/signencryptwizard.cpp crypto/gui/signencryptwizard.h crypto/gui/signerresolvepage.cpp crypto/gui/signerresolvepage.h crypto/gui/signingcertificateselectiondialog.cpp crypto/gui/signingcertificateselectiondialog.h crypto/gui/signingcertificateselectionwidget.cpp crypto/gui/signingcertificateselectionwidget.h crypto/gui/unknownrecipientwidget.cpp crypto/gui/unknownrecipientwidget.h crypto/gui/verifychecksumsdialog.cpp crypto/gui/verifychecksumsdialog.h crypto/gui/wizard.cpp crypto/gui/wizard.h crypto/gui/wizardpage.cpp crypto/gui/wizardpage.h crypto/newsignencryptemailcontroller.cpp crypto/newsignencryptemailcontroller.h crypto/recipient.cpp crypto/recipient.h crypto/sender.cpp crypto/sender.h crypto/signemailcontroller.cpp crypto/signemailcontroller.h crypto/signemailtask.cpp crypto/signemailtask.h crypto/signencryptfilescontroller.cpp crypto/signencryptfilescontroller.h crypto/signencrypttask.cpp crypto/signencrypttask.h crypto/task.cpp crypto/task.h crypto/taskcollection.cpp crypto/taskcollection.h crypto/verifychecksumscontroller.cpp crypto/verifychecksumscontroller.h dialogs/adduseriddialog.cpp dialogs/adduseriddialog.h dialogs/certificatedetailsdialog.cpp dialogs/certificatedetailsdialog.h dialogs/certificatedetailsinputwidget.cpp dialogs/certificatedetailsinputwidget.h dialogs/certificatedetailswidget.cpp dialogs/certificatedetailswidget.h dialogs/certificateselectiondialog.cpp dialogs/certificateselectiondialog.h dialogs/certifycertificatedialog.cpp dialogs/certifycertificatedialog.h dialogs/certifywidget.cpp dialogs/certifywidget.h dialogs/createcsrforcardkeydialog.cpp dialogs/createcsrforcardkeydialog.h dialogs/deletecertificatesdialog.cpp dialogs/deletecertificatesdialog.h dialogs/editgroupdialog.cpp dialogs/editgroupdialog.h dialogs/expirydialog.cpp dialogs/expirydialog.h dialogs/exportdialog.cpp dialogs/exportdialog.h dialogs/gencardkeydialog.cpp dialogs/gencardkeydialog.h dialogs/groupdetailsdialog.cpp dialogs/groupdetailsdialog.h dialogs/lookupcertificatesdialog.cpp dialogs/lookupcertificatesdialog.h dialogs/nameandemailwidget.cpp dialogs/nameandemailwidget.h dialogs/newopenpgpcertificatedetailsdialog.cpp dialogs/newopenpgpcertificatedetailsdialog.h dialogs/ownertrustdialog.cpp dialogs/ownertrustdialog.h dialogs/pivcardapplicationadministrationkeyinputdialog.cpp dialogs/pivcardapplicationadministrationkeyinputdialog.h dialogs/revokekeydialog.cpp dialogs/revokekeydialog.h dialogs/selftestdialog.cpp dialogs/selftestdialog.h dialogs/setinitialpindialog.cpp dialogs/setinitialpindialog.h dialogs/subkeyswidget.cpp dialogs/subkeyswidget.h dialogs/trustchainwidget.cpp dialogs/trustchainwidget.h dialogs/updatenotification.cpp dialogs/updatenotification.h dialogs/weboftrustdialog.cpp dialogs/weboftrustdialog.h dialogs/weboftrustwidget.cpp dialogs/weboftrustwidget.h interfaces/anchorprovider.h interfaces/focusfirstchild.h newcertificatewizard/advancedsettingsdialog.cpp newcertificatewizard/advancedsettingsdialog_p.h newcertificatewizard/enterdetailspage.cpp newcertificatewizard/enterdetailspage_p.h newcertificatewizard/keyalgo.cpp newcertificatewizard/keyalgo_p.h newcertificatewizard/keycreationpage.cpp newcertificatewizard/keycreationpage_p.h newcertificatewizard/listwidget.cpp newcertificatewizard/listwidget.h newcertificatewizard/newcertificatewizard.cpp newcertificatewizard/newcertificatewizard.h newcertificatewizard/resultpage.cpp newcertificatewizard/resultpage_p.h newcertificatewizard/wizardpage.cpp newcertificatewizard/wizardpage_p.h selftest/compliancecheck.cpp selftest/compliancecheck.h selftest/enginecheck.cpp selftest/enginecheck.h selftest/gpgagentcheck.cpp selftest/gpgagentcheck.h selftest/gpgconfcheck.cpp selftest/gpgconfcheck.h selftest/libkleopatrarccheck.cpp selftest/libkleopatrarccheck.h selftest/selftest.cpp selftest/selftest.h smartcard/algorithminfo.h smartcard/card.cpp smartcard/card.h smartcard/deviceinfowatcher.cpp smartcard/deviceinfowatcher.h smartcard/keypairinfo.cpp smartcard/keypairinfo.h smartcard/netkeycard.cpp smartcard/netkeycard.h smartcard/openpgpcard.cpp smartcard/openpgpcard.h smartcard/p15card.cpp smartcard/p15card.h smartcard/pivcard.cpp smartcard/pivcard.h smartcard/readerstatus.cpp smartcard/readerstatus.h smartcard/utils.cpp smartcard/utils.h utils/accessibility.cpp utils/accessibility.h utils/action_data.cpp utils/action_data.h utils/applicationstate.cpp utils/applicationstate.h utils/archivedefinition.cpp utils/archivedefinition.h utils/auditlog.cpp utils/auditlog.h utils/clipboardmenu.cpp utils/clipboardmenu.h utils/debug-helpers.cpp utils/debug-helpers.h utils/dragqueen.cpp utils/dragqueen.h utils/email.cpp utils/email.h utils/emptypassphraseprovider.cpp utils/emptypassphraseprovider.h utils/filedialog.cpp utils/filedialog.h utils/gui-helper.cpp utils/gui-helper.h utils/headerview.cpp utils/headerview.h utils/input.cpp utils/input.h utils/iodevicelogger.cpp utils/iodevicelogger.h utils/kdpipeiodevice.cpp utils/kdpipeiodevice.h utils/keyparameters.cpp utils/keyparameters.h utils/keys.cpp utils/keys.h utils/kuniqueservice.cpp utils/kuniqueservice.h utils/log.cpp utils/log.h utils/multivalidator.cpp utils/multivalidator.h utils/output.cpp utils/output.h utils/path-helper.cpp utils/path-helper.h utils/scrollarea.cpp utils/scrollarea.h utils/systemtrayicon.cpp utils/systemtrayicon.h utils/tags.cpp utils/tags.h utils/types.cpp utils/types.h utils/userinfo.cpp utils/userinfo.h utils/validation.cpp utils/validation.h utils/writecertassuantransaction.cpp utils/writecertassuantransaction.h utils/wsastarter.cpp utils/wsastarter.h view/anchorcache.cpp view/anchorcache_p.h view/errorlabel.cpp view/errorlabel.h view/formtextinput.cpp view/formtextinput.h view/htmllabel.cpp view/htmllabel.h view/infofield.cpp view/infofield.h view/keycacheoverlay.cpp view/keycacheoverlay.h view/keylistcontroller.cpp view/keylistcontroller.h view/keytreeview.cpp view/keytreeview.h view/netkeywidget.cpp view/netkeywidget.h view/nullpinwidget.cpp view/nullpinwidget.h view/openpgpkeycardwidget.cpp view/openpgpkeycardwidget.h view/p15cardwidget.cpp view/p15cardwidget.h view/padwidget.cpp view/padwidget.h view/pgpcardwidget.cpp view/pgpcardwidget.h view/pivcardwidget.cpp view/pivcardwidget.h view/searchbar.cpp view/searchbar.h view/smartcardwidget.cpp view/smartcardwidget.h view/tabwidget.cpp view/tabwidget.h view/urllabel.cpp view/urllabel.h view/waitwidget.cpp view/waitwidget.h view/welcomewidget.cpp view/welcomewidget.h aboutdata.cpp aboutdata.h kleopatra.qrc kleopatraapplication.cpp kleopatraapplication.h main.cpp mainwindow.cpp mainwindow.h systrayicon.cpp systrayicon.h ) if(WIN32) configure_file (versioninfo.rc.in versioninfo.rc) set(_kleopatra_SRCS ${CMAKE_CURRENT_BINARY_DIR}/versioninfo.rc ${_kleopatra_SRCS}) endif() set (_kleopatra_SRCS conf/kleopageconfigdialog.cpp ${_kleopatra_SRCS}) ecm_qt_declare_logging_category(_kleopatra_SRCS HEADER kleopatra_debug.h IDENTIFIER KLEOPATRA_LOG CATEGORY_NAME org.kde.pim.kleopatra DESCRIPTION "kleopatra (kleopatra)" OLD_CATEGORY_NAMES log_kleopatra EXPORT KLEOPATRA ) if(KLEO_MODEL_TEST) add_definitions(-DKLEO_MODEL_TEST) set(_kleopatra_SRCS ${_kleopatra_SRCS} models/modeltest.cpp) endif() ki18n_wrap_ui(_kleopatra_SRCS dialogs/ownertrustdialog.ui dialogs/selectchecklevelwidget.ui dialogs/setinitialpindialog.ui dialogs/trustchainwidget.ui newcertificatewizard/listwidget.ui ) kconfig_add_kcfg_files(_kleopatra_SRCS kcfg/emailoperationspreferences.kcfgc kcfg/fileoperationspreferences.kcfgc kcfg/settings.kcfgc kcfg/smimevalidationpreferences.kcfgc kcfg/tagspreferences.kcfgc kcfg/tooltippreferences.kcfgc ) file(GLOB ICONS_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/icons/*-apps-kleopatra.png") ecm_add_app_icon(_kleopatra_SRCS ICONS ${ICONS_SRCS}) add_executable(kleopatra_bin ${_kleopatra_SRCS} ${_kleopatra_uiserver_SRCS}) # For the ConfigureDialog & KCMs target_link_libraries(kleopatra_bin kcm_kleopatra_static) #if (COMPILE_WITH_UNITY_CMAKE_SUPPORT) # set_target_properties(kleopatra_bin PROPERTIES UNITY_BUILD ON) #endif() set_target_properties(kleopatra_bin PROPERTIES OUTPUT_NAME kleopatra) if (WIN32) set(_kleopatra_platform_libs "secur32") endif () target_link_libraries(kleopatra_bin Gpgmepp ${_kleopatra_extra_libs} KF5::Libkleo KF5::Mime KF5::I18n KF5::XmlGui KF5::IconThemes KF5::WindowSystem KF5::CoreAddons KF5::ItemModels KF5::Crash ${_kleopatra_mail_libs} Qt::Network Qt::PrintSupport # Printing secret keys ${_kleopatra_uiserver_extra_libs} ${_kleopatra_dbusaddons_libs} kleopatraclientcore ${_kleopatra_platform_libs} ) if (QT_MAJOR_VERSION STREQUAL "6") target_link_libraries(kleopatra_bin QGpgmeQt6) else() target_link_libraries(kleopatra_bin QGpgme) endif() install(TARGETS kleopatra_bin ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) install( PROGRAMS data/org.kde.kleopatra.desktop data/kleopatra_import.desktop DESTINATION ${KDE_INSTALL_APPDIR} ) install(FILES data/org.kde.kleopatra.appdata.xml DESTINATION ${KDE_INSTALL_METAINFODIR}) install( PROGRAMS data/kleopatra_signencryptfiles.desktop data/kleopatra_signencryptfolders.desktop data/kleopatra_decryptverifyfiles.desktop data/kleopatra_decryptverifyfolders.desktop DESTINATION ${KDE_INSTALL_DATADIR}/kio/servicemenus ) diff --git a/src/commands/openpgpgeneratecardkeycommand.cpp b/src/commands/openpgpgeneratecardkeycommand.cpp new file mode 100644 index 000000000..6fabed17c --- /dev/null +++ b/src/commands/openpgpgeneratecardkeycommand.cpp @@ -0,0 +1,202 @@ +/* commands/openpgpgeneratecardkeycommand.cpp + + This file is part of Kleopatra, the KDE keymanager + SPDX-FileCopyrightText: 2022 g10 Code GmbH + SPDX-FileContributor: Ingo Klöcker + + SPDX-License-Identifier: GPL-2.0-or-later +*/ + +#include + +#include "openpgpgeneratecardkeycommand.h" + +#include "cardcommand_p.h" + +#include "smartcard/algorithminfo.h" +#include "smartcard/openpgpcard.h" +#include "smartcard/readerstatus.h" + +#include "dialogs/gencardkeydialog.h" + +#include + +#include + +#include + +#include "kleopatra_debug.h" + +using namespace Kleo; +using namespace Kleo::Commands; +using namespace Kleo::SmartCard; +using namespace GpgME; + +class OpenPGPGenerateCardKeyCommand::Private : public CardCommand::Private +{ + friend class ::Kleo::Commands::OpenPGPGenerateCardKeyCommand; + OpenPGPGenerateCardKeyCommand *q_func() const + { + return static_cast(q); + } +public: + explicit Private(OpenPGPGenerateCardKeyCommand *qq, const std::string &keyref, const std::string &serialNumber, QWidget *p); + + void init(); + +private: + void slotDialogAccepted(); + void slotDialogRejected(); + void slotResult(const Error &err); + +private: + void ensureDialogCreated(); + void generateKey(); + +private: + std::string keyRef; + bool overwriteExistingKey = false; + std::string algorithm; + QPointer dialog; +}; + +OpenPGPGenerateCardKeyCommand::Private *OpenPGPGenerateCardKeyCommand::d_func() +{ + return static_cast(d.get()); +} +const OpenPGPGenerateCardKeyCommand::Private *OpenPGPGenerateCardKeyCommand::d_func() const +{ + return static_cast(d.get()); +} + +#define d d_func() +#define q q_func() + +OpenPGPGenerateCardKeyCommand::Private::Private(OpenPGPGenerateCardKeyCommand *qq, const std::string &keyRef_, const std::string &serialNumber, QWidget *p) + : CardCommand::Private(qq, serialNumber, p) + , keyRef{keyRef_} +{ +} + +void OpenPGPGenerateCardKeyCommand::Private::init() +{ +} + +void OpenPGPGenerateCardKeyCommand::Private::slotDialogAccepted() +{ + algorithm = dialog->getKeyParams().algorithm; + generateKey(); +} + +void OpenPGPGenerateCardKeyCommand::Private::slotDialogRejected() +{ + finished(); +} + +void OpenPGPGenerateCardKeyCommand::Private::slotResult(const GpgME::Error& err) +{ + qCDebug(KLEOPATRA_LOG).nospace() << q << "::Private::" << __func__ << err; + + if (err) { + error(i18nc("@info", "Generating key failed: %1", QString::fromLatin1(err.asString()))); + } else if (!err.isCanceled()) { + success(i18nc("@info", "Key successfully generated.")); + ReaderStatus::mutableInstance()->updateStatus(); + } + finished(); +} + +void OpenPGPGenerateCardKeyCommand::Private::ensureDialogCreated() +{ + if (dialog) { + return; + } + + dialog = new GenCardKeyDialog(GenCardKeyDialog::KeyAlgorithm, parentWidgetOrView()); + dialog->setAttribute(Qt::WA_DeleteOnClose); + + connect(dialog, &QDialog::accepted, q, [this]() { slotDialogAccepted(); }); + connect(dialog, &QDialog::rejected, q, [this]() { slotDialogRejected(); }); +} + +void OpenPGPGenerateCardKeyCommand::Private::generateKey() +{ + qCDebug(KLEOPATRA_LOG).nospace() << q << "::Private::" << __func__; + + auto pgpCard = ReaderStatus::instance()->getCard(serialNumber()); + if (!pgpCard) { + error(i18n("Failed to find the OpenPGP card with the serial number: %1", QString::fromStdString(serialNumber()))); + finished(); + return; + } + + QByteArrayList command; + command << "SCD GENKEY"; + if (overwriteExistingKey) { + command << "--force"; + } + if (!algorithm.empty()) { + command << "--algo=" + QByteArray::fromStdString(algorithm); + } + command << "--" << QByteArray::fromStdString(keyRef); + ReaderStatus::mutableInstance()->startSimpleTransaction(pgpCard, command.join(' '), q, [this](const GpgME::Error &err) { + slotResult(err); + }); +} + +OpenPGPGenerateCardKeyCommand::OpenPGPGenerateCardKeyCommand(const std::string &keyref, const std::string &serialNumber, QWidget *p) + : CardCommand(new Private(this, keyref, serialNumber, p)) +{ + d->init(); +} + +OpenPGPGenerateCardKeyCommand::~OpenPGPGenerateCardKeyCommand() +{ + qCDebug(KLEOPATRA_LOG).nospace() << this << "::" << __func__; +} + +void OpenPGPGenerateCardKeyCommand::doStart() +{ + qCDebug(KLEOPATRA_LOG).nospace() << this << "::" << __func__; + + // check if key exists + auto pgpCard = ReaderStatus::instance()->getCard(d->serialNumber()); + if (!pgpCard) { + d->error(i18n("Failed to find the OpenPGP card with the serial number: %1", QString::fromStdString(d->serialNumber()))); + d->finished(); + return; + } + + auto existingKey = pgpCard->keyInfo(d->keyRef).grip; + if (!existingKey.empty()) { + const QString warningText = i18nc("@info", + "

This card already contains a key in this slot. Continuing will overwrite that key.

" + "

If there is no backup the existing key will be irrecoverably lost.

") + + i18n("The existing key has the ID:") + QStringLiteral("
%1
").arg(QString::fromStdString(existingKey)) + + (d->keyRef == OpenPGPCard::pgpEncKeyRef() ? + i18n("It will no longer be possible to decrypt past communication encrypted for the existing key.") : + QString()); + const auto choice = KMessageBox::warningContinueCancel(d->parentWidgetOrView(), warningText, + i18nc("@title:window", "Overwrite Existing Key"), + KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QString(), KMessageBox::Notify | KMessageBox::Dangerous); + if (choice != KMessageBox::Continue) { + d->finished(); + return; + } + d->overwriteExistingKey = true; + } + + d->ensureDialogCreated(); + Q_ASSERT(d->dialog); + d->dialog->setSupportedAlgorithms(pgpCard->supportedAlgorithms(d->keyRef), "rsa2048"); + d->dialog->show(); +} + +void OpenPGPGenerateCardKeyCommand::doCancel() +{ +} + +#undef d +#undef q + +#include "moc_openpgpgeneratecardkeycommand.cpp" diff --git a/src/commands/openpgpgeneratecardkeycommand.h b/src/commands/openpgpgeneratecardkeycommand.h new file mode 100644 index 000000000..314b7c63c --- /dev/null +++ b/src/commands/openpgpgeneratecardkeycommand.h @@ -0,0 +1,36 @@ +/* commands/openpgpgeneratecardkeycommand.h + + This file is part of Kleopatra, the KDE keymanager + SPDX-FileCopyrightText: 2022 g10 Code GmbH + SPDX-FileContributor: Ingo Klöcker + + SPDX-License-Identifier: GPL-2.0-or-later +*/ +#pragma once + +#include "cardcommand.h" + +namespace Kleo +{ +namespace Commands +{ + +class OpenPGPGenerateCardKeyCommand : public CardCommand +{ + Q_OBJECT +public: + explicit OpenPGPGenerateCardKeyCommand(const std::string &keyref, const std::string &serialNumber, QWidget *parent); + ~OpenPGPGenerateCardKeyCommand() override; + +private: + void doStart() override; + void doCancel() override; + +private: + class Private; + inline Private *d_func(); + inline const Private *d_func() const; +}; + +} // namespace Commands +} // namespace Kleo diff --git a/src/smartcard/openpgpcard.cpp b/src/smartcard/openpgpcard.cpp index aa057901b..7dbfdb4e0 100644 --- a/src/smartcard/openpgpcard.cpp +++ b/src/smartcard/openpgpcard.cpp @@ -1,163 +1,163 @@ /* smartcard/openpgpcard.cpp This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2017 Bundesamt für Sicherheit in der Informationstechnik SPDX-FileContributor: Intevation GmbH SPDX-FileCopyrightText: 2020, 2022 g10 Code GmbH SPDX-FileContributor: Ingo Klöcker SPDX-License-Identifier: GPL-2.0-or-later */ /* Code in this file is partly based on the GNU Privacy Assistant * (cm-openpgp.c) git rev. 0a78795146661234070681737b3e08228616441f * * Whis is: * SPDX-FileCopyrightText: 2008, 2009 g 10 Code GmbH * * And may be licensed under the GNU General Public License * as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. */ #include "openpgpcard.h" #include "algorithminfo.h" #include #include #include "kleopatra_debug.h" using namespace Kleo; using namespace Kleo::SmartCard; static QDebug operator<<(QDebug s, const std::string &string) { return s << QString::fromStdString(string); } // static const std::string OpenPGPCard::AppName = "openpgp"; OpenPGPCard::OpenPGPCard(const Card &card) : Card(card) { setAppName(AppName); setInitialKeyInfos(OpenPGPCard::supportedKeys()); } // static std::string OpenPGPCard::pgpSigKeyRef() { return std::string("OPENPGP.1"); } // static std::string OpenPGPCard::pgpEncKeyRef() { return std::string("OPENPGP.2"); } // static std::string OpenPGPCard::pgpAuthKeyRef() { return std::string("OPENPGP.3"); } // static std::string OpenPGPCard::pinKeyRef() { return std::string("OPENPGP.1"); } // static std::string OpenPGPCard::adminPinKeyRef() { return std::string("OPENPGP.3"); } // static std::string OpenPGPCard::resetCodeKeyRef() { return std::string("OPENPGP.2"); } // static const std::vector & OpenPGPCard::supportedKeys() { static const std::vector keyInfos = { {OpenPGPCard::pgpSigKeyRef(), "", "sc", "", ""}, {OpenPGPCard::pgpEncKeyRef(), "", "e", "", ""}, {OpenPGPCard::pgpAuthKeyRef(), "", "a", "", ""} }; return keyInfos; } // static QString OpenPGPCard::keyDisplayName(const std::string &keyRef) { static const QMap displayNames = { { OpenPGPCard::pgpSigKeyRef(), i18n("Signature") }, { OpenPGPCard::pgpEncKeyRef(), i18n("Encryption") }, { OpenPGPCard::pgpAuthKeyRef(), i18n("Authentication") } }; return displayNames.value(keyRef); } void OpenPGPCard::setSupportedAlgorithms(const std::vector &algorithms) { - const static std::vector allowedAlgorithms = { + static const std::vector allowedAlgorithms = { "brainpoolP256r1", "brainpoolP384r1", "brainpoolP512r1", "curve25519", "nistp256", "nistp384", "nistp521", "rsa2048", "rsa3072", "rsa4096", }; mAlgorithms.clear(); std::copy_if(algorithms.begin(), algorithms.end(), std::back_inserter(mAlgorithms), [](const auto &algo) { return Kleo::contains(allowedAlgorithms, algo); }); if (mAlgorithms.size() < algorithms.size()) { qWarning(KLEOPATRA_LOG).nospace() << "OpenPGPCard::" << __func__ << " Invalid algorithm in " << algorithms << " (allowed algorithms: " << allowedAlgorithms << ")"; } } std::string OpenPGPCard::pubkeyUrl() const { return cardInfo("PUBKEY-URL"); } std::vector OpenPGPCard::supportedAlgorithms(const std::string &keyRef) { - const static std::map displayNames = { + static const std::map displayNames = { { "brainpoolP256r1", i18nc("@info", "ECC (Brainpool P-256)") }, { "brainpoolP384r1", i18nc("@info", "ECC (Brainpool P-384)") }, { "brainpoolP512r1", i18nc("@info", "ECC (Brainpool P-512)") }, - { "curve25519", i18nc("@info", "ECC (Curve 25519)") }, + { "curve25519", i18nc("@info", "ECC (Curve25519)") }, { "nistp256", i18nc("@info", "ECC (NIST P-256)") }, { "nistp384", i18nc("@info", "ECC (NIST P-384)") }, { "nistp521", i18nc("@info", "ECC (NIST P-521)") }, { "rsa2048", i18nc("@info", "RSA 2048") }, { "rsa3072", i18nc("@info", "RSA 3072") }, { "rsa4096", i18nc("@info", "RSA 4096") }, }; const std::string curve25519Algo = keyRef == OpenPGPCard::pgpEncKeyRef() ? "cv25519" : "ed25519"; std::vector algos; std::transform(mAlgorithms.cbegin(), mAlgorithms.cend(), std::back_inserter(algos), [curve25519Algo](const auto &algo) { if (algo == "curve25519") { return AlgorithmInfo{curve25519Algo, displayNames.at(algo)}; } return AlgorithmInfo{algo, displayNames.at(algo)}; }); return algos; } diff --git a/src/view/openpgpkeycardwidget.cpp b/src/view/openpgpkeycardwidget.cpp index b17d8cd27..ceee2d592 100644 --- a/src/view/openpgpkeycardwidget.cpp +++ b/src/view/openpgpkeycardwidget.cpp @@ -1,253 +1,266 @@ /* view/openpgpkeycardwidget.cpp This file is part of Kleopatra, the KDE keymanager - SPDX-FileCopyrightText: 2021 g10 Code GmbH + SPDX-FileCopyrightText: 2021, 2022 g10 Code GmbH SPDX-FileContributor: Ingo Klöcker SPDX-License-Identifier: GPL-2.0-or-later */ #include "openpgpkeycardwidget.h" #include "commands/detailscommand.h" #include "smartcard/card.h" #include "smartcard/keypairinfo.h" #include "smartcard/openpgpcard.h" #include #include #include #include #include #include #include #include using namespace Kleo; using namespace SmartCard; namespace { struct KeyWidgets { std::string cardKeyRef; std::string keyGrip; std::string keyFingerprint; QLabel *keyTitleLabel = nullptr; QLabel *keyInfoLabel = nullptr; QPushButton *showCertificateDetailsButton = nullptr; + QPushButton *generateButton = nullptr; QPushButton *createCSRButton = nullptr; }; KeyWidgets createKeyWidgets(const KeyPairInfo &keyInfo, QWidget *parent) { KeyWidgets keyWidgets; keyWidgets.keyTitleLabel = new QLabel{OpenPGPCard::keyDisplayName(keyInfo.keyRef), parent}; keyWidgets.keyInfoLabel = new QLabel{parent}; keyWidgets.keyInfoLabel->setTextInteractionFlags(Qt::TextBrowserInteraction | Qt::TextSelectableByKeyboard); keyWidgets.showCertificateDetailsButton = new QPushButton{i18nc("@action:button", "Show Details"), parent}; keyWidgets.showCertificateDetailsButton->setToolTip(i18nc("@action:tooltip", "Show detailed information about this key")); keyWidgets.showCertificateDetailsButton->setEnabled(false); + keyWidgets.generateButton = new QPushButton{i18nc("@action:button", "Generate Key"), parent}; + keyWidgets.generateButton->setEnabled(false); if (keyInfo.canCertify() || keyInfo.canSign() || keyInfo.canAuthenticate()) { keyWidgets.createCSRButton = new QPushButton{i18nc("@action:button", "Create CSR"), parent}; keyWidgets.createCSRButton->setToolTip(i18nc("@info:tooltip", "Create a certificate signing request for this key")); keyWidgets.createCSRButton->setEnabled(false); } return keyWidgets; } } class OpenPGPKeyCardWidget::Private { public: explicit Private(OpenPGPKeyCardWidget *q); ~Private() = default; void setAllowedActions(Actions actions); void update(const Card *card = nullptr); private: void updateCachedValues(const std::string &openPGPKeyRef, const std::string &cardKeyRef, const Card *card); void updateKeyWidgets(const std::string &openPGPKeyRef); void showCertificateDetails(const std::string &openPGPKeyRef); private: OpenPGPKeyCardWidget *const q; Actions mAllowedActions = AllActions; std::map mKeyWidgets; }; OpenPGPKeyCardWidget::Private::Private(OpenPGPKeyCardWidget *q) : q{q} { auto grid = new QGridLayout{q}; grid->setContentsMargins(0, 0, 0, 0); for (const auto &keyInfo : OpenPGPCard::supportedKeys()) { const KeyWidgets keyWidgets = createKeyWidgets(keyInfo, q); const std::string keyRef = keyInfo.keyRef; connect(keyWidgets.showCertificateDetailsButton, &QPushButton::clicked, q, [this, keyRef] () { showCertificateDetails(keyRef); }); + connect(keyWidgets.generateButton, &QPushButton::clicked, + q, [q, keyRef] () { Q_EMIT q->generateKeyRequested(keyRef); }); if (keyWidgets.createCSRButton) { connect(keyWidgets.createCSRButton, &QPushButton::clicked, q, [q, keyRef] () { Q_EMIT q->createCSRRequested(keyRef); }); } const int row = grid->rowCount(); grid->addWidget(keyWidgets.keyTitleLabel, row, 0, Qt::AlignTop); grid->addWidget(keyWidgets.keyInfoLabel, row, 1, Qt::AlignTop); auto buttons = new QHBoxLayout; buttons->addWidget(keyWidgets.showCertificateDetailsButton); + buttons->addWidget(keyWidgets.generateButton); if (keyWidgets.createCSRButton) { buttons->addWidget(keyWidgets.createCSRButton); } buttons->addStretch(1); grid->addLayout(buttons, row, 2, Qt::AlignTop); mKeyWidgets.insert({keyInfo.keyRef, keyWidgets}); } grid->setColumnStretch(grid->columnCount(), 1); } void OpenPGPKeyCardWidget::Private::setAllowedActions(Actions actions) { mAllowedActions = actions; update(); } void OpenPGPKeyCardWidget::Private::update(const Card *card) { if (card) { updateCachedValues(OpenPGPCard::pgpSigKeyRef(), card->signingKeyRef(), card); updateCachedValues(OpenPGPCard::pgpEncKeyRef(), card->encryptionKeyRef(), card); updateCachedValues(OpenPGPCard::pgpAuthKeyRef(), card->authenticationKeyRef(), card); } updateKeyWidgets(OpenPGPCard::pgpSigKeyRef()); updateKeyWidgets(OpenPGPCard::pgpEncKeyRef()); updateKeyWidgets(OpenPGPCard::pgpAuthKeyRef()); } void OpenPGPKeyCardWidget::Private::updateCachedValues(const std::string &openPGPKeyRef, const std::string &cardKeyRef, const Card *card) { KeyWidgets &widgets = mKeyWidgets.at(openPGPKeyRef); widgets.cardKeyRef = cardKeyRef; widgets.keyGrip = card->keyInfo(cardKeyRef).grip; widgets.keyFingerprint = card->keyFingerprint(openPGPKeyRef); } void OpenPGPKeyCardWidget::Private::updateKeyWidgets(const std::string &openPGPKeyRef) { const KeyWidgets &widgets = mKeyWidgets.at(openPGPKeyRef); const auto cardSupportsKey = !widgets.cardKeyRef.empty(); widgets.keyTitleLabel->setVisible(cardSupportsKey); widgets.keyInfoLabel->setVisible(cardSupportsKey); widgets.showCertificateDetailsButton->setVisible(cardSupportsKey); + widgets.generateButton->setVisible(cardSupportsKey && (mAllowedActions & Action::GenerateKey)); if (widgets.createCSRButton) { widgets.createCSRButton->setVisible(cardSupportsKey && (mAllowedActions & Action::CreateCSR)); } if (!cardSupportsKey) { return; } widgets.showCertificateDetailsButton->setEnabled(false); if (widgets.keyFingerprint.empty()) { widgets.keyInfoLabel->setTextFormat(Qt::RichText); widgets.keyInfoLabel->setText(i18nc("@info", "No key")); + widgets.generateButton->setText(i18nc("@action:button", "Generate Key")); + widgets.generateButton->setToolTip(i18nc("@info:tooltip", "Generate a key for this card slot")); if (widgets.createCSRButton) { widgets.createCSRButton->setEnabled(false); } } else { QStringList lines; if (widgets.keyFingerprint.size() >= 16) { const std::string keyid = widgets.keyFingerprint.substr(widgets.keyFingerprint.size() - 16); const auto subkeys = KeyCache::instance()->findSubkeysByKeyID({keyid}); if (subkeys.empty() || subkeys[0].isNull()) { widgets.keyInfoLabel->setTextFormat(Qt::RichText); lines.push_back(i18nc("@info", "Public key not found locally")); widgets.keyInfoLabel->setToolTip({}); } else { // force interpretation of text as plain text to avoid problems with HTML in user IDs widgets.keyInfoLabel->setTextFormat(Qt::PlainText); QStringList toolTips; toolTips.reserve(subkeys.size()); for (const auto &sub: subkeys) { // Yep you can have one subkey associated with multiple primary keys. const GpgME::Key key = sub.parent(); toolTips << Formatting::toolTip(key, Formatting::Validity | Formatting::ExpiryDates | Formatting::UserIDs | Formatting::Fingerprint); const auto uids = key.userIDs(); for (const auto &uid: uids) { lines.push_back(Formatting::prettyUserID(uid)); } } widgets.keyInfoLabel->setToolTip(toolTips.join(QLatin1String("
"))); widgets.showCertificateDetailsButton->setEnabled(true); } } else { widgets.keyInfoLabel->setTextFormat(Qt::RichText); lines.push_back(i18nc("@info", "Invalid fingerprint")); } const QString fingerprint = widgets.keyInfoLabel->textFormat() == Qt::RichText ? Formatting::prettyID(widgets.keyFingerprint.c_str()).replace(QLatin1Char(' '), QLatin1String(" ")) : Formatting::prettyID(widgets.keyFingerprint.c_str()); lines.insert(0, fingerprint); const auto lineSeparator = widgets.keyInfoLabel->textFormat() == Qt::PlainText ? QLatin1String("\n") : QLatin1String("
"); widgets.keyInfoLabel->setText(lines.join(lineSeparator)); + widgets.generateButton->setText(i18nc("@action:button", "Regenerate Key")); + widgets.generateButton->setToolTip(i18nc("@info:tooltip", "Generate a new key for this card slot replacing the existing key")); if (widgets.createCSRButton) { widgets.createCSRButton->setEnabled(true); } } + + widgets.generateButton->setEnabled(!widgets.generateButton->isHidden()); } void OpenPGPKeyCardWidget::Private::showCertificateDetails(const std::string &openPGPKeyRef) { const KeyWidgets &widgets = mKeyWidgets.at(openPGPKeyRef); if (widgets.keyFingerprint.size() >= 16) { const std::string keyid = widgets.keyFingerprint.substr(widgets.keyFingerprint.size() - 16); const auto subkeys = KeyCache::instance()->findSubkeysByKeyID({keyid}); if (!subkeys.empty() && !subkeys[0].isNull()) { auto cmd = new Commands::DetailsCommand(subkeys[0].parent()); cmd->setParentWidget(q); cmd->start(); return; } } KMessageBox::error(q, i18nc("@info", "Sorry, I cannot find the key with fingerprint %1.", Formatting::prettyID(widgets.keyFingerprint.c_str()))); } OpenPGPKeyCardWidget::OpenPGPKeyCardWidget(QWidget *parent) : QWidget{parent} , d{std::make_unique(this)} { connect(KeyCache::instance().get(), &KeyCache::keysMayHaveChanged, this, [this]() { d->update(); }); } OpenPGPKeyCardWidget::~OpenPGPKeyCardWidget() = default; void OpenPGPKeyCardWidget::setAllowedActions(Actions actions) { d->setAllowedActions(actions); } void OpenPGPKeyCardWidget::update(const Card *card) { d->update(card); } diff --git a/src/view/openpgpkeycardwidget.h b/src/view/openpgpkeycardwidget.h index f81e6cc35..079c94c3e 100644 --- a/src/view/openpgpkeycardwidget.h +++ b/src/view/openpgpkeycardwidget.h @@ -1,52 +1,54 @@ /* view/openpgpkeycardwidget.h This file is part of Kleopatra, the KDE keymanager - SPDX-FileCopyrightText: 2021 g10 Code GmbH + SPDX-FileCopyrightText: 2021, 2022 g10 Code GmbH SPDX-FileContributor: Ingo Klöcker SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include #include namespace Kleo { namespace SmartCard { class Card; } class OpenPGPKeyCardWidget: public QWidget { Q_OBJECT public: enum Action { NoAction = 0x00, CreateCSR = 0x01, - AllActions = CreateCSR, + GenerateKey = 0x02, + AllActions = CreateCSR | GenerateKey, }; Q_DECLARE_FLAGS(Actions, Action) explicit OpenPGPKeyCardWidget(QWidget *parent = nullptr); ~OpenPGPKeyCardWidget() override; void setAllowedActions(Actions actions); public Q_SLOTS: void update(const SmartCard::Card *card); Q_SIGNALS: void createCSRRequested(const std::string &keyRef); + void generateKeyRequested(const std::string &keyRef); private: class Private; std::unique_ptr d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(OpenPGPKeyCardWidget::Actions) } diff --git a/src/view/pgpcardwidget.cpp b/src/view/pgpcardwidget.cpp index 383fefeb8..c4678fdc4 100644 --- a/src/view/pgpcardwidget.cpp +++ b/src/view/pgpcardwidget.cpp @@ -1,508 +1,521 @@ /* view/pgpcardwiget.cpp This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2017 Bundesamt für Sicherheit in der Informationstechnik SPDX-FileContributor: Intevation GmbH - SPDX-FileCopyrightText: 2020 g10 Code GmbH + SPDX-FileCopyrightText: 2020, 2022 g10 Code GmbH SPDX-FileContributor: Ingo Klöcker SPDX-License-Identifier: GPL-2.0-or-later */ #include "pgpcardwidget.h" #include "openpgpkeycardwidget.h" #include "kleopatra_debug.h" #include "commands/createcsrforcardkeycommand.h" #include "commands/createopenpgpkeyfromcardkeyscommand.h" +#include "commands/openpgpgeneratecardkeycommand.h" #include "smartcard/algorithminfo.h" #include "smartcard/openpgpcard.h" #include "smartcard/readerstatus.h" #include "dialogs/gencardkeydialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Kleo; using namespace Kleo::Commands; using namespace Kleo::SmartCard; namespace { class GenKeyThread: public QThread { Q_OBJECT public: explicit GenKeyThread(const GenCardKeyDialog::KeyParams ¶ms, const std::string &serial): mSerial(serial), mParams(params) { } GpgME::Error error() { return mErr; } std::string bkpFile() { return mBkpFile; } protected: void run() override { auto ei = new GpgME::GpgGenCardKeyInteractor(mSerial); ei->setAlgo(GpgME::GpgGenCardKeyInteractor::RSA); ei->setKeySize(QByteArray::fromStdString(mParams.algorithm).toInt()); ei->setNameUtf8(mParams.name.toStdString()); ei->setEmailUtf8(mParams.email.toStdString()); ei->setDoBackup(mParams.backup); const auto ctx = std::shared_ptr (GpgME::Context::createForProtocol(GpgME::OpenPGP)); QGpgME::QByteArrayDataProvider dp; GpgME::Data data(&dp); mErr = ctx->cardEdit(GpgME::Key(), std::unique_ptr (ei), data); mBkpFile = ei->backupFileName(); } private: GpgME::Error mErr; std::string mSerial; GenCardKeyDialog::KeyParams mParams; std::string mBkpFile; }; } // Namespace PGPCardWidget::PGPCardWidget(QWidget *parent): QWidget(parent), mSerialNumber(new QLabel(this)), mCardHolderLabel(new QLabel(this)), mVersionLabel(new QLabel(this)), mUrlLabel(new QLabel(this)), mCardIsEmpty(false) { // Set up the scroll area auto myLayout = new QVBoxLayout(this); myLayout->setContentsMargins(0, 0, 0, 0); auto area = new QScrollArea; area->setFrameShape(QFrame::NoFrame); area->setWidgetResizable(true); myLayout->addWidget(area); auto areaWidget = new QWidget; area->setWidget(areaWidget); auto areaVLay = new QVBoxLayout(areaWidget); auto cardInfoGrid = new QGridLayout; { int row = 0; // Version and Serialnumber cardInfoGrid->addWidget(mVersionLabel, row, 0, 1, 2); mVersionLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); row++; cardInfoGrid->addWidget(new QLabel(i18n("Serial number:")), row, 0); cardInfoGrid->addWidget(mSerialNumber, row, 1); mSerialNumber->setTextInteractionFlags(Qt::TextBrowserInteraction); row++; // Cardholder Row cardInfoGrid->addWidget(new QLabel(i18nc("The owner of a smartcard. GnuPG refers to this as cardholder.", "Cardholder:")), row, 0); cardInfoGrid->addWidget(mCardHolderLabel, row, 1); mCardHolderLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); { auto button = new QPushButton; button->setIcon(QIcon::fromTheme(QStringLiteral("cell_edit"))); button->setAccessibleName(i18nc("@action:button", "Edit")); button->setToolTip(i18n("Change")); cardInfoGrid->addWidget(button, row, 2); connect(button, &QPushButton::clicked, this, &PGPCardWidget::changeNameRequested); } row++; // URL Row cardInfoGrid->addWidget(new QLabel(i18nc("The URL under which a public key that " "corresponds to a smartcard can be downloaded", "Pubkey URL:")), row, 0); cardInfoGrid->addWidget(mUrlLabel, row, 1); mUrlLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); { auto button = new QPushButton; button->setIcon(QIcon::fromTheme(QStringLiteral("cell_edit"))); button->setAccessibleName(i18nc("@action:button", "Edit")); button->setToolTip(i18n("Change")); cardInfoGrid->addWidget(button, row, 2); connect(button, &QPushButton::clicked, this, &PGPCardWidget::changeUrlRequested); } cardInfoGrid->setColumnStretch(cardInfoGrid->columnCount(), 1); } areaVLay->addLayout(cardInfoGrid); areaVLay->addWidget(new KSeparator(Qt::Horizontal)); // The keys areaVLay->addWidget(new QLabel(QStringLiteral("%1").arg(i18n("Keys:")))); mKeysWidget = new OpenPGPKeyCardWidget{this}; areaVLay->addWidget(mKeysWidget); connect(mKeysWidget, &OpenPGPKeyCardWidget::createCSRRequested, this, &PGPCardWidget::createCSR); + connect(mKeysWidget, &OpenPGPKeyCardWidget::generateKeyRequested, this, &PGPCardWidget::generateKey); areaVLay->addWidget(new KSeparator(Qt::Horizontal)); areaVLay->addWidget(new QLabel(QStringLiteral("%1").arg(i18n("Actions:")))); auto actionLayout = new QHBoxLayout; { auto generateButton = new QPushButton(i18n("Generate New Keys")); generateButton->setToolTip(i18n("Create a new primary key and generate subkeys on the card.")); actionLayout->addWidget(generateButton); connect(generateButton, &QPushButton::clicked, this, &PGPCardWidget::genkeyRequested); } { auto pinButton = new QPushButton(i18n("Change PIN")); pinButton->setToolTip(i18n("Change the PIN required for using the keys on the smartcard.")); actionLayout->addWidget(pinButton); connect(pinButton, &QPushButton::clicked, this, [this] () { doChangePin(OpenPGPCard::pinKeyRef()); }); } { auto unblockButton = new QPushButton(i18n("Unblock Card")); unblockButton->setToolTip(i18n("Unblock the smartcard and set a new PIN.")); actionLayout->addWidget(unblockButton); connect(unblockButton, &QPushButton::clicked, this, [this] () { doChangePin(OpenPGPCard::resetCodeKeyRef()); }); } { auto pukButton = new QPushButton(i18n("Change Admin PIN")); pukButton->setToolTip(i18n("Change the PIN required for administrative operations.")); actionLayout->addWidget(pukButton); connect(pukButton, &QPushButton::clicked, this, [this] () { doChangePin(OpenPGPCard::adminPinKeyRef()); }); } { auto resetCodeButton = new QPushButton(i18n("Change Reset Code")); resetCodeButton->setToolTip(i18n("Change the PIN required to unblock the smartcard and set a new PIN.")); actionLayout->addWidget(resetCodeButton); connect(resetCodeButton, &QPushButton::clicked, this, [this] () { doChangePin(OpenPGPCard::resetCodeKeyRef(), ChangePinCommand::ResetMode); }); } if (CreateOpenPGPKeyFromCardKeysCommand::isSupported()) { mKeyForCardKeysButton = new QPushButton(this); mKeyForCardKeysButton->setText(i18n("Create OpenPGP Key")); mKeyForCardKeysButton->setToolTip(i18n("Create an OpenPGP key for the keys stored on the card.")); actionLayout->addWidget(mKeyForCardKeysButton); connect(mKeyForCardKeysButton, &QPushButton::clicked, this, &PGPCardWidget::createKeyFromCardKeys); } actionLayout->addStretch(-1); areaVLay->addLayout(actionLayout); areaVLay->addStretch(1); } void PGPCardWidget::setCard(const OpenPGPCard *card) { const QString version = card->displayAppVersion(); mIs21 = card->appVersion() >= 0x0201; const QString manufacturer = QString::fromStdString(card->manufacturer()); const bool manufacturerIsUnknown = manufacturer.isEmpty() || manufacturer == QLatin1String("unknown"); mVersionLabel->setText(manufacturerIsUnknown ? i18nc("Placeholder is a version number", "Unknown OpenPGP v%1 card", version) : i18nc("First placeholder is manufacturer, second placeholder is a version number", "%1 OpenPGP v%2 card", manufacturer, version)); mSerialNumber->setText(card->displaySerialNumber()); mRealSerial = card->serialNumber(); const auto holder = card->cardHolder(); const auto url = QString::fromStdString(card->pubkeyUrl()); mCardHolderLabel->setText(holder.isEmpty() ? i18n("not set") : holder); mUrl = url; mUrlLabel->setText(url.isEmpty() ? i18n("not set") : QStringLiteral("%1").arg(url.toHtmlEscaped())); mUrlLabel->setOpenExternalLinks(true); mKeysWidget->update(card); mCardIsEmpty = card->keyFingerprint(OpenPGPCard::pgpSigKeyRef()).empty() && card->keyFingerprint(OpenPGPCard::pgpEncKeyRef()).empty() && card->keyFingerprint(OpenPGPCard::pgpAuthKeyRef()).empty(); if (mKeyForCardKeysButton) { mKeyForCardKeysButton->setEnabled(card->hasSigningKey() && card->hasEncryptionKey()); } } void PGPCardWidget::doChangePin(const std::string &keyRef, ChangePinCommand::ChangePinMode mode) { auto cmd = new ChangePinCommand(mRealSerial, OpenPGPCard::AppName, this); this->setEnabled(false); connect(cmd, &ChangePinCommand::finished, this, [this]() { this->setEnabled(true); }); cmd->setKeyRef(keyRef); cmd->setMode(mode); cmd->start(); } void PGPCardWidget::doGenKey(GenCardKeyDialog *dlg) { const GpgME::Error err = ReaderStatus::switchCardAndApp(mRealSerial, OpenPGPCard::AppName); if (err) { return; } const auto params = dlg->getKeyParams(); auto progress = new QProgressDialog(this, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::Dialog); progress->setAutoClose(true); progress->setMinimumDuration(0); progress->setMaximum(0); progress->setMinimum(0); progress->setModal(true); progress->setCancelButton(nullptr); progress->setWindowTitle(i18nc("@title:window", "Generating Keys")); progress->setLabel(new QLabel(i18n("This may take several minutes..."))); auto workerThread = new GenKeyThread(params, mRealSerial); connect(workerThread, &QThread::finished, this, [this, workerThread, progress] { progress->accept(); progress->deleteLater(); genKeyDone(workerThread->error(), workerThread->bkpFile()); delete workerThread; }); workerThread->start(); progress->exec(); } void PGPCardWidget::genKeyDone(const GpgME::Error &err, const std::string &backup) { if (err) { KMessageBox::error(this, i18nc("@info", "Failed to generate new key: %1", QString::fromLatin1(err.asString()))); return; } if (err.isCanceled()) { return; } if (!backup.empty()) { const auto bkpFile = QString::fromStdString(backup); QFileInfo fi(bkpFile); const auto target = QFileDialog::getSaveFileName(this, i18n("Save backup of encryption key"), fi.fileName(), QStringLiteral("%1 (*.gpg)").arg(i18n("Backup Key"))); if (!target.isEmpty() && !QFile::copy(bkpFile, target)) { KMessageBox::error(this, i18nc("@info", "Failed to move backup. The backup key is still stored under: %1", bkpFile)); } else if (!target.isEmpty()) { QFile::remove(bkpFile); } } KMessageBox::information(this, i18nc("@info", "Successfully generated a new key for this card."), i18nc("@title", "Success")); ReaderStatus::mutableInstance()->updateStatus(); } void PGPCardWidget::genkeyRequested() { if (!mCardIsEmpty) { auto ret = KMessageBox::warningContinueCancel(this, i18n("The existing keys on this card will be deleted " "and replaced by new keys.") + QStringLiteral("

") + i18n("It will no longer be possible to decrypt past communication " "encrypted for the existing key."), i18n("Secret Key Deletion"), KStandardGuiItem::guiItem(KStandardGuiItem::Delete), KStandardGuiItem::cancel(), QString(), KMessageBox::Notify | KMessageBox::Dangerous); if (ret != KMessageBox::Continue) { return; } } auto dlg = new GenCardKeyDialog(GenCardKeyDialog::AllKeyAttributes, this); std::vector algos = { { "1024", QStringLiteral("RSA 1024") }, { "2048", QStringLiteral("RSA 2048") }, { "3072", QStringLiteral("RSA 3072") } }; // There is probably a better way to check for capabilities if (mIs21) { algos.push_back({"4096", QStringLiteral("RSA 4096")}); } dlg->setSupportedAlgorithms(algos, "2048"); connect(dlg, &QDialog::accepted, this, [this, dlg] () { doGenKey(dlg); dlg->deleteLater(); }); dlg->setModal(true); dlg->show(); } void PGPCardWidget::changeNameRequested() { QString text = mCardHolderLabel->text(); while (true) { bool ok = false; text = QInputDialog::getText(this, i18n("Change cardholder"), i18n("New name:"), QLineEdit::Normal, text, &ok, Qt::WindowFlags(), Qt::ImhLatinOnly); if (!ok) { return; } // Some additional restrictions imposed by gnupg if (text.contains(QLatin1Char('<'))) { KMessageBox::error(this, i18nc("@info", "The \"<\" character may not be used.")); continue; } if (text.contains(QLatin1String(" "))) { KMessageBox::error(this, i18nc("@info", "Double spaces are not allowed")); continue; } if (text.size() > 38) { KMessageBox::error(this, i18nc("@info", "The size of the name may not exceed 38 characters.")); } break; } auto parts = text.split(QLatin1Char(' ')); const auto lastName = parts.takeLast(); const QString formatted = lastName + QStringLiteral("<<") + parts.join(QLatin1Char('<')); const auto pgpCard = ReaderStatus::instance()->getCard(mRealSerial); if (!pgpCard) { KMessageBox::error(this, i18n("Failed to find the OpenPGP card with the serial number: %1", QString::fromStdString(mRealSerial))); return; } const QByteArray command = QByteArrayLiteral("SCD SETATTR DISP-NAME ") + formatted.toUtf8(); ReaderStatus::mutableInstance()->startSimpleTransaction(pgpCard, command, this, [this](const GpgME::Error &err) { changeNameResult(err); }); } void PGPCardWidget::changeNameResult(const GpgME::Error &err) { if (err) { KMessageBox::error(this, i18nc("@info", "Name change failed: %1", QString::fromLatin1(err.asString()))); return; } if (!err.isCanceled()) { KMessageBox::information(this, i18nc("@info", "Name successfully changed."), i18nc("@title", "Success")); ReaderStatus::mutableInstance()->updateStatus(); } } void PGPCardWidget::changeUrlRequested() { QString text = mUrl; while (true) { bool ok = false; text = QInputDialog::getText(this, i18n("Change the URL where the pubkey can be found"), i18n("New pubkey URL:"), QLineEdit::Normal, text, &ok, Qt::WindowFlags(), Qt::ImhLatinOnly); if (!ok) { return; } // Some additional restrictions imposed by gnupg if (text.size() > 254) { KMessageBox::error(this, i18nc("@info", "The size of the URL may not exceed 254 characters.")); } break; } const auto pgpCard = ReaderStatus::instance()->getCard(mRealSerial); if (!pgpCard) { KMessageBox::error(this, i18n("Failed to find the OpenPGP card with the serial number: %1", QString::fromStdString(mRealSerial))); return; } const QByteArray command = QByteArrayLiteral("SCD SETATTR PUBKEY-URL ") + text.toUtf8(); ReaderStatus::mutableInstance()->startSimpleTransaction(pgpCard, command, this, [this](const GpgME::Error &err) { changeUrlResult(err); }); } void PGPCardWidget::changeUrlResult(const GpgME::Error &err) { if (err) { KMessageBox::error(this, i18nc("@info", "URL change failed: %1", QString::fromLatin1(err.asString()))); return; } if (!err.isCanceled()) { KMessageBox::information(this, i18nc("@info", "URL successfully changed."), i18nc("@title", "Success")); ReaderStatus::mutableInstance()->updateStatus(); } } void PGPCardWidget::createKeyFromCardKeys() { auto cmd = new CreateOpenPGPKeyFromCardKeysCommand(mRealSerial, OpenPGPCard::AppName, this); this->setEnabled(false); connect(cmd, &CreateOpenPGPKeyFromCardKeysCommand::finished, this, [this]() { this->setEnabled(true); }); cmd->start(); } void PGPCardWidget::createCSR(const std::string &keyref) { auto cmd = new CreateCSRForCardKeyCommand(keyref, mRealSerial, OpenPGPCard::AppName, this); this->setEnabled(false); connect(cmd, &CreateCSRForCardKeyCommand::finished, this, [this]() { this->setEnabled(true); }); cmd->start(); } +void PGPCardWidget::generateKey(const std::string &keyref) +{ + auto cmd = new OpenPGPGenerateCardKeyCommand(keyref, mRealSerial, this); + this->setEnabled(false); + connect(cmd, &OpenPGPGenerateCardKeyCommand::finished, + this, [this]() { + this->setEnabled(true); + }); + cmd->start(); +} + #include "pgpcardwidget.moc" diff --git a/src/view/pgpcardwidget.h b/src/view/pgpcardwidget.h index e03a7cb02..7f5708fc1 100644 --- a/src/view/pgpcardwidget.h +++ b/src/view/pgpcardwidget.h @@ -1,70 +1,71 @@ /* view/pgpcardwiget.h This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2017 Bundesamt für Sicherheit in der Informationstechnik SPDX-FileContributor: Intevation GmbH - SPDX-FileCopyrightText: 2020 g10 Code GmbH + SPDX-FileCopyrightText: 2020, 2022 g10 Code GmbH SPDX-FileContributor: Ingo Klöcker SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include "commands/changepincommand.h" #include #include #include class QLabel; class QPushButton; namespace Kleo { class GenCardKeyDialog; class OpenPGPKeyCardWidget; namespace SmartCard { struct KeyPairInfo; class OpenPGPCard; } // namespace SmartCard class PGPCardWidget: public QWidget { Q_OBJECT public: explicit PGPCardWidget(QWidget *parent = nullptr); void setCard(const SmartCard::OpenPGPCard* card); void doGenKey(GenCardKeyDialog *dlg); void genKeyDone(const GpgME::Error &err, const std::string &backup); public Q_SLOTS: void genkeyRequested(); void changeNameRequested(); void changeNameResult(const GpgME::Error &err); void changeUrlRequested(); void changeUrlResult(const GpgME::Error &err); void createKeyFromCardKeys(); void createCSR(const std::string &keyref); + void generateKey(const std::string &keyref); private: void doChangePin(const std::string &keyRef, Commands::ChangePinCommand::ChangePinMode mode = Commands::ChangePinCommand::NormalMode); private: QLabel *mSerialNumber = nullptr, *mCardHolderLabel = nullptr, *mVersionLabel = nullptr, *mUrlLabel = nullptr; QPushButton *mKeyForCardKeysButton = nullptr; OpenPGPKeyCardWidget *mKeysWidget = nullptr; QString mUrl; bool mCardIsEmpty = false; bool mIs21 = false; std::string mRealSerial; }; } // namespace Kleo