diff --git a/src/commands/changeroottrustcommand.cpp b/src/commands/changeroottrustcommand.cpp index 865627cfd..afd268f0f 100644 --- a/src/commands/changeroottrustcommand.cpp +++ b/src/commands/changeroottrustcommand.cpp @@ -1,383 +1,383 @@ /* -*- mode: c++; c-basic-offset:4 -*- commands/changeroottrustcommand.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2010 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of 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. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include #include "changeroottrustcommand.h" #include "command_p.h" #include #include #include "kleopatra_debug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Kleo; using namespace Kleo::Commands; using namespace GpgME; class ChangeRootTrustCommand::Private : public QThread, public Command::Private { Q_OBJECT private: friend class ::Kleo::Commands::ChangeRootTrustCommand; ChangeRootTrustCommand *q_func() const { return static_cast(q); } public: explicit Private(ChangeRootTrustCommand *qq, KeyListController *c) : QThread(), Command::Private(qq, c), mutex(), trust(Key::Ultimate), trustListFile(QDir(gnupgHomeDirectory()).absoluteFilePath(QStringLiteral("trustlist.txt"))), canceled(false) { } private: void init() { q->setWarnWhenRunningAtShutdown(false); connect(this, SIGNAL(finished()), q_func(), SLOT(slotOperationFinished())); } void run() override; private: void slotOperationFinished() { KeyCache::mutableInstance()->enableFileSystemWatcher(true); if (error.isEmpty()) { KeyCache::mutableInstance()->reload(GpgME::CMS); } else Command::Private::error(i18n("Failed to update the trust database:\n" "%1", error), i18n("Root Trust Update Failed")); Command::Private::finished(); } private: mutable QMutex mutex; Key::OwnerTrust trust; QString trustListFile; QString gpgConfPath; QString error; volatile bool canceled; }; ChangeRootTrustCommand::Private *ChangeRootTrustCommand::d_func() { return static_cast(d.get()); } const ChangeRootTrustCommand::Private *ChangeRootTrustCommand::d_func() const { return static_cast(d.get()); } #define q q_func() #define d d_func() ChangeRootTrustCommand::ChangeRootTrustCommand(KeyListController *p) : Command(new Private(this, p)) { d->init(); } ChangeRootTrustCommand::ChangeRootTrustCommand(QAbstractItemView *v, KeyListController *p) : Command(v, new Private(this, p)) { d->init(); } ChangeRootTrustCommand::ChangeRootTrustCommand(const GpgME::Key &key, KeyListController *p) : Command(new Private(this, p)) { Q_ASSERT(!key.isNull()); d->init(); setKey(key); } ChangeRootTrustCommand::ChangeRootTrustCommand(const GpgME::Key &key, QAbstractItemView *v, KeyListController *p) : Command(v, new Private(this, p)) { Q_ASSERT(!key.isNull()); d->init(); setKey(key); } ChangeRootTrustCommand::~ChangeRootTrustCommand() {} void ChangeRootTrustCommand::setTrust(Key::OwnerTrust trust) { Q_ASSERT(!d->isRunning()); const QMutexLocker locker(&d->mutex); d->trust = trust; } Key::OwnerTrust ChangeRootTrustCommand::trust() const { const QMutexLocker locker(&d->mutex); return d->trust; } void ChangeRootTrustCommand::setTrustListFile(const QString &trustListFile) { Q_ASSERT(!d->isRunning()); const QMutexLocker locker(&d->mutex); d->trustListFile = trustListFile; } QString ChangeRootTrustCommand::trustListFile() const { const QMutexLocker locker(&d->mutex); return d->trustListFile; } void ChangeRootTrustCommand::doStart() { const std::vector keys = d->keys(); Key key; if (keys.size() == 1) { key = keys.front(); } else { qCWarning(KLEOPATRA_LOG) << "can only work with one certificate at a time"; } if (key.isNull()) { d->Command::Private::finished(); return; } d->gpgConfPath = gpgConfPath(); KeyCache::mutableInstance()->enableFileSystemWatcher(false); d->start(); } void ChangeRootTrustCommand::doCancel() { const QMutexLocker locker(&d->mutex); d->canceled = true; } static QString change_trust_file(const QString &trustListFile, const QString &key, Key::OwnerTrust trust); static QString run_gpgconf_reload_gpg_agent(const QString &gpgConfPath); void ChangeRootTrustCommand::Private::run() { QMutexLocker locker(&mutex); const QString key = QString::fromLatin1(keys().front().primaryFingerprint()); const Key::OwnerTrust trust = this->trust; const QString trustListFile = this->trustListFile; const QString gpgConfPath = this->gpgConfPath; locker.unlock(); QString err = change_trust_file(trustListFile, key, trust); if (err.isEmpty()) { err = run_gpgconf_reload_gpg_agent(gpgConfPath); } locker.relock(); this->error = err; } static QString add_colons(const QString &fpr) { QString result; result.reserve(fpr.size() / 2 * 3 + 1); bool needColon = false; for (QChar ch : fpr) { result += ch; if (needColon) { result += QLatin1Char(':'); } needColon = !needColon; } if (result.endsWith(QLatin1Char(':'))) { result.chop(1); } return result; } namespace { // fix stupid default-finalize behaviour... class KFixedSaveFile : public QSaveFile { public: explicit KFixedSaveFile(const QString &fileName) : QSaveFile(fileName) {} ~KFixedSaveFile() { cancelWriting(); } }; } // static QString change_trust_file(const QString &trustListFile, const QString &key, Key::OwnerTrust trust) { QList trustListFileContents; { QFile in(trustListFile); if (in.exists()) { // non-existence is not fatal... if (in.open(QIODevice::ReadOnly)) { trustListFileContents = in.readAll().split('\n'); } else { // ...but failure to open an existing file _is_ return i18n("Cannot open existing file \"%1\" for reading: %2", trustListFile, in.errorString()); } } // close, so KSaveFile doesn't clobber the original } KFixedSaveFile out(trustListFile); if (!out.open(QIODevice::WriteOnly)) return i18n("Cannot open file \"%1\" for reading and writing: %2", out.fileName() /*sic!*/, out.errorString()); if (!out.setPermissions(QFile::ReadOwner | QFile::WriteOwner)) return i18n("Cannot set restrictive permissions on file %1: %2", out.fileName() /*sic!*/, out.errorString()); const QString keyColon = add_colons(key); qCDebug(KLEOPATRA_LOG) << qPrintable(key) << " -> " << qPrintable(keyColon); // ( 1) ( 2 ) ( 3 )( 4) QRegExp rx(QLatin1String("\\s*(!?)\\s*([a-fA-F0-9]{40}|(?:[a-fA-F0-9]{2}:){19}[a-fA-F0-9]{2})\\s*([SsPp*])(.*)")); bool found = false; for (const QByteArray &rawLine : qAsConst(trustListFileContents)) { const QString line = QString::fromLatin1(rawLine.data(), rawLine.size()); if (!rx.exactMatch(line)) { qCDebug(KLEOPATRA_LOG) << "line \"" << rawLine.data() << "\" does not match"; out.write(rawLine + '\n'); continue; } const QString cap2 = rx.cap(2); if (cap2 != key && cap2 != keyColon) { qCDebug(KLEOPATRA_LOG) << qPrintable(key) << " != " << qPrintable(cap2) << " != " << qPrintable(keyColon); out.write(rawLine + '\n'); continue; } found = true; - const bool disabled = rx.cap(1) == QLatin1String("!"); + const bool disabled = rx.cap(1) == QLatin1Char('!'); const QByteArray flags = rx.cap(3).toLatin1(); const QByteArray rests = rx.cap(4).toLatin1(); if (trust == Key::Ultimate) if (!disabled) { // unchanged out.write(rawLine + '\n'); } else { out.write(keyColon.toLatin1() + ' ' + flags + rests + '\n'); } else if (trust == Key::Never) { if (disabled) { // unchanged out.write(rawLine + '\n'); } else { out.write('!' + keyColon.toLatin1() + ' ' + flags + rests + '\n'); } } // else: trust == Key::Unknown // -> don't write - ie.erase } if (!found) { // add if (trust == Key::Ultimate) { out.write(keyColon.toLatin1() + ' ' + 'S' + '\n'); } else if (trust == Key::Never) { out.write('!' + keyColon.toLatin1() + ' ' + 'S' + '\n'); } } if (!out.commit()) return i18n("Failed to move file %1 to its final destination, %2: %3", out.fileName(), trustListFile, out.errorString()); return QString(); } // static QString run_gpgconf_reload_gpg_agent(const QString &gpgConfPath) { if (gpgConfPath.isEmpty()) { return i18n("Could not find gpgconf executable"); } QProcess p; p.start(gpgConfPath, QStringList() << QStringLiteral("--reload") << QStringLiteral("gpg-agent")); qCDebug(KLEOPATRA_LOG) << "starting " << qPrintable(gpgConfPath) << " --reload gpg-agent"; p.waitForFinished(-1); qCDebug(KLEOPATRA_LOG) << "done"; if (p.error() == QProcess::UnknownError) { return QString(); } else { return i18n("\"gpgconf --reload gpg-agent\" failed: %1", p.errorString()); } } #undef q_func #undef d_func #include "moc_changeroottrustcommand.cpp" #include "changeroottrustcommand.moc" diff --git a/src/smartcard/openpgpcard.cpp b/src/smartcard/openpgpcard.cpp index eeb52ec13..e01f7be29 100644 --- a/src/smartcard/openpgpcard.cpp +++ b/src/smartcard/openpgpcard.cpp @@ -1,236 +1,236 @@ /* smartcard/openpgpcard.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2017 by Bundesamt für Sicherheit in der Informationstechnik Software engineering by Intevation GmbH Kleopatra is free software; you can redistribute it and/or modify it under the terms of 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. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ /* Code in this file is partly based on the GNU Privacy Assistant * (cm-openpgp.c) git rev. 0a78795146661234070681737b3e08228616441f * * Whis is: * Copyright (C) 2008, 2009 g10 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 "kleopatra_debug.h" using namespace Kleo; using namespace Kleo::SmartCard; #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) namespace { static const char * get_manufacturer (unsigned int no) { switch (no) { case 0x0001: return "PPC Card Systems"; case 0x0002: return "Prism"; case 0x0003: return "OpenFortress"; case 0x0004: return "Wewid"; case 0x0005: return "ZeitControl"; case 0x0006: return "Yubico"; case 0x0007: return "OpenKMS"; case 0x0008: return "LogoEmail"; case 0x002A: return "Magrathea"; case 0x1337: return "Warsaw Hackerspace"; case 0xF517: return "FSIJ"; /* 0x0000 and 0xFFFF are defined as test cards per spec, 0xFF00 to 0xFFFE are assigned for use with randomly created serial numbers. */ case 0x0000: case 0xffff: return "test card"; default: return (no & 0xff00) == 0xff00? "unmanaged S/N range":"unknown"; } } } // namespace OpenPGPCard::OpenPGPCard() { setAppType(Card::OpenPGPApplication); } OpenPGPCard::OpenPGPCard(const std::string &serialno): OpenPGPCard() { setSerialNumber(serialno); } std::string OpenPGPCard::sigFpr() const { return mMetaInfo.value("SIGKEY-FPR"); } std::string OpenPGPCard::encFpr() const { return mMetaInfo.value("ENCKEY-FPR"); } std::string OpenPGPCard::authFpr() const { return mMetaInfo.value("AUTHKEY-FPR"); } void OpenPGPCard::setKeyPairInfo(const std::vector< std::pair > &infos) { qCDebug(KLEOPATRA_LOG) << "Card" << serialNumber().c_str() << "info:"; for (const auto &pair: infos) { qCDebug(KLEOPATRA_LOG) << pair.first.c_str() << ":" << pair.second.c_str(); if (pair.first == "KEY-FPR" || pair.first == "KEY-TIME") { // Key fpr and key time need to be distinguished, the number // of the key decides the usage. const auto values = QString::fromStdString(pair.second).split(QLatin1Char(' ')); if (values.size() < 2) { qCWarning(KLEOPATRA_LOG) << "Invalid entry."; setStatus(Card::CardError); continue; } const auto usage = values[0]; const auto fpr = values[1].toStdString(); - if (usage == QLatin1String("1")) { + if (usage == QLatin1Char('1')) { mMetaInfo.insert(std::string("SIG") + pair.first, fpr); - } else if (usage == QLatin1String("2")) { + } else if (usage == QLatin1Char('2')) { mMetaInfo.insert(std::string("ENC") + pair.first, fpr); - } else if (usage == QLatin1String("3")) { + } else if (usage == QLatin1Char('3')) { mMetaInfo.insert(std::string("AUTH") + pair.first, fpr); } else { // Maybe more keyslots in the future? qCDebug(KLEOPATRA_LOG) << "Unhandled keyslot"; } } else if (pair.first == "KEYPAIRINFO") { // Fun, same as above but the other way around. const auto values = QString::fromStdString(pair.second).split(QLatin1Char(' ')); if (values.size() < 2) { qCWarning(KLEOPATRA_LOG) << "Invalid entry."; setStatus(Card::CardError); continue; } const auto usage = values[1]; const auto grip = values[0].toStdString(); if (usage == QLatin1String("OPENPGP.1")) { mMetaInfo.insert(std::string("SIG") + pair.first, grip); } else if (usage == QLatin1String("OPENPGP.2")) { mMetaInfo.insert(std::string("ENC") + pair.first, grip); } else if (usage == QLatin1String("OPENPGP.3")) { mMetaInfo.insert(std::string("AUTH") + pair.first, grip); } else { // Maybe more keyslots in the future? qCDebug(KLEOPATRA_LOG) << "Unhandled keyslot"; } } else { mMetaInfo.insert(pair.first, pair.second); } } } void OpenPGPCard::setSerialNumber(const std::string &serialno) { char version_buffer[6]; const char *version = ""; const char *string = serialno.c_str(); Card::setSerialNumber(serialno); if (strncmp(string, "D27600012401", 12) || strlen(string) != 32 ) { /* Not a proper OpenPGP card serialnumber. Display the full serialnumber. */ mManufacturer = "unknown"; } else { /* Reformat the version number to be better human readable. */ char *p = version_buffer; if (string[12] != '0') { *p++ = string[12]; } *p++ = string[13]; *p++ = '.'; if (string[14] != '0') { *p++ = string[14]; } *p++ = string[15]; *p++ = '\0'; version = version_buffer; /* Get the manufacturer. */ mManufacturer = get_manufacturer(xtoi_2(string + 16)*256 + xtoi_2(string + 18)); } mIsV2 = !((*version == '1' || *version == '0') && version[1] == '.'); mCardVersion = version; } bool OpenPGPCard::operator == (const Card& rhs) const { const OpenPGPCard *other = dynamic_cast(&rhs); if (!other) { return false; } return Card::operator ==(rhs) && sigFpr() == other->sigFpr() && encFpr() == other->encFpr() && authFpr() == other->authFpr() && manufacturer() == other->manufacturer() && cardVersion() == other->cardVersion() && cardHolder() == other->cardHolder() && pubkeyUrl() == other->pubkeyUrl(); } std::string OpenPGPCard::manufacturer() const { return mManufacturer; } std::string OpenPGPCard::cardVersion() const { return mCardVersion; } std::string OpenPGPCard::cardHolder() const { auto list = QString::fromStdString(mMetaInfo.value("DISP-NAME")).split(QStringLiteral("<<")); std::reverse(list.begin(), list.end()); return list.join(QLatin1Char(' ')).toStdString(); } std::string OpenPGPCard::pubkeyUrl() const { return mMetaInfo.value("PUBKEY-URL"); }