diff --git a/kded/engine/backends/cryfs/cryfsbackend.cpp b/kded/engine/backends/cryfs/cryfsbackend.cpp index f6ef54f..7884efb 100644 --- a/kded/engine/backends/cryfs/cryfsbackend.cpp +++ b/kded/engine/backends/cryfs/cryfsbackend.cpp @@ -1,146 +1,246 @@ /* * Copyright 2017 by Ivan Cukic * * This program 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program 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, see . */ #include "cryfsbackend.h" #include #include #include +#include #include #include #include #include #include #include #include #include using namespace AsynQt; namespace PlasmaVault { + +// see: https://github.com/cryfs/cryfs/blob/develop/src/cryfs/ErrorCodes.h +enum class ExitCode : int{ + Success = 0, + + // An error happened that doesn't have an error code associated with it + UnspecifiedError = 1, + + // The command line arguments are invalid. + InvalidArguments = 10, + + // Couldn't load config file. Probably the password is wrong + WrongPassword = 11, + + // Password cannot be empty + EmptyPassword = 12, + + // The file system format is too new for this CryFS version. Please update your CryFS version. + TooNewFilesystemFormat = 13, + + // The file system format is too old for this CryFS version. Run with --allow-filesystem-upgrade to upgrade it. + TooOldFilesystemFormat = 14, + + // The file system uses a different cipher than the one specified on the command line using the --cipher argument. + WrongCipher = 15, + + // Base directory doesn't exist or is inaccessible (i.e. not read or writable or not a directory) + InaccessibleBaseDir = 16, + + // Mount directory doesn't exist or is inaccessible (i.e. not read or writable or not a directory) + InaccessibleMountDir = 17, + + // Base directory can't be a subdirectory of the mount directory + BaseDirInsideMountDir = 18, + + // Something's wrong with the file system. + InvalidFilesystem = 19, +}; + + + CryFsBackend::CryFsBackend() { } CryFsBackend::~CryFsBackend() { } Backend::Ptr CryFsBackend::instance() { return singleton::instance(); } FutureResult<> CryFsBackend::mount(const Device &device, const MountPoint &mountPoint, const Vault::Payload &payload) { QDir dir; - const auto password = payload[KEY_PASSWORD].toString(); - const auto cypher = payload["cryfs-cipher"].toString(); + const auto password = payload[KEY_PASSWORD].toString(); + const auto cypher = payload["cryfs-cipher"].toString(); + const auto shouldUpgrade = payload["cryfs-fs-upgrade"].toBool(); if (!dir.mkpath(device) || !dir.mkpath(mountPoint)) { return errorResult(Error::BackendError, i18n("Failed to create directories, check your permissions")); } auto process = - cypher.isEmpty() ? - // Cypher is not specified, use the default, whatever it is + // Cypher is specified, use it to create the device + (!cypher.isEmpty()) ? cryfs({ + "--cipher", + cypher, device, // source directory to initialize cryfs in mountPoint // where to mount the file system }) - : // Cypher is specified, use it to create the device + // Cypher is not specified, use the default, whatever it is + :shouldUpgrade ? cryfs({ - "--cipher", - cypher, - device, // source directory to initialize cryfs in + device, // source directory to initialize cryfs in + mountPoint, // where to mount the file system + "--allow-filesystem-upgrade" + }) + + : cryfs({ + device, // source directory to initialize cryfs in mountPoint // where to mount the file system }) + ; - auto result - = makeFuture(process, hasProcessFinishedSuccessfully); + auto result = makeFuture(process, [this, device, mountPoint, payload] (QProcess *process) { + const auto out = process->readAllStandardOutput(); + const auto err = process->readAllStandardError(); + + const auto exitCode = (ExitCode) process->exitCode(); + + auto upgradeFileSystem = [this, device, mountPoint, payload] { + const auto upgrade = + QMessageBox::Yes == QMessageBox::question( + nullptr, + i18n("Upgrade the vault?"), + i18n("This vault was created with an older version of cryfs and needs to be upgraded.\n\nMind that this process is irreversable and the vault will no longer work with older versions of cryfs.\n\nDo you want to perform the upgrade now?")); + + if (!upgrade) { + return Result<>::error(Error::BackendError, + i18n("The vault needs to be upgraded before it can be opened with this version of cryfs")); + } + + auto new_payload = payload; + new_payload["cryfs-fs-upgrade"] = true; + + return AsynQt::await(mount(device, mountPoint, new_payload)); + }; + + return + // If all went well, just return success + (process->exitStatus() == QProcess::NormalExit && exitCode == ExitCode::Success) ? + Result<>::success() : + + // If we tried to mount into a non-empty location, report + err.contains("'nonempty'") ? + Result<>::error(Error::CommandError, + i18n("The mount point directory is not empty, refusing to open the vault")) : + + exitCode == ExitCode::WrongPassword ? + Result<>::error(Error::BackendError, + i18n("You entered the wrong password")) : + + exitCode == ExitCode::TooNewFilesystemFormat ? + Result<>::error(Error::BackendError, + i18n("The installed version of cryfs is too old to open this vault.")) : + + exitCode == ExitCode::TooOldFilesystemFormat ? + upgradeFileSystem() : + + // otherwise just report that we failed + Result<>::error(Error::CommandError, + i18n("Unable to perform the operation (error code %1).", QString::number((int)exitCode))); + + + }); // Writing the password process->write(password.toUtf8()); process->write("\n"); return result; } FutureResult<> CryFsBackend::validateBackend() { using namespace AsynQt::operators; // We need to check whether all the commands are installed // and whether the user has permissions to run them return - collect(checkVersion(cryfs({ "--version" }), std::make_tuple(0, 9, 6)), + collect(checkVersion(cryfs({ "--version" }), std::make_tuple(0, 9, 9)), checkVersion(fusermount({ "--version" }), std::make_tuple(2, 9, 7))) | transform([this] (const QPair &cryfs, const QPair &fusermount) { bool success = cryfs.first && fusermount.first; QString message = formatMessageLine("cryfs", cryfs) + formatMessageLine("fusermount", fusermount); return success ? Result<>::success() : Result<>::error(Error::BackendError, message); }); } bool CryFsBackend::isInitialized(const Device &device) const { QFile cryFsConfig(device + "/cryfs.config"); return cryFsConfig.exists(); } QProcess *CryFsBackend::cryfs(const QStringList &arguments) const { return process("cryfs", arguments, { { "CRYFS_FRONTEND", "noninteractive" } }); } } // namespace PlasmaVault diff --git a/kded/ui/vaultcreationwizard.cpp b/kded/ui/vaultcreationwizard.cpp index 8c4742c..d12fa61 100644 --- a/kded/ui/vaultcreationwizard.cpp +++ b/kded/ui/vaultcreationwizard.cpp @@ -1,313 +1,313 @@ /* * Copyright 2017 by Ivan Cukic * * This program 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program 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, see . */ #include "vaultcreationwizard.h" #include "ui_vaultcreationwizard.h" #include #include #include #include #include "dialogdsl.h" #include "vault.h" using namespace DialogDsl; using namespace DialogDsl::operators; #include "backendchooserwidget.h" #include "activitieslinkingwidget.h" #include "cryfscypherchooserwidget.h" #include "directorypairchooserwidget.h" #include "noticewidget.h" #include "passwordchooserwidget.h" #include "offlineonlywidget.h" class VaultCreationWizard::Private { public: VaultCreationWizard *const q; Ui::VaultCreationWizard ui; QPushButton *buttonPrevious; QPushButton *buttonNext; QPushButton *buttonCreate; QStackedLayout *layout; inline void buttonNextSetEnabled(bool enabled) { buttonNext->setEnabled(enabled); buttonCreate->setEnabled(enabled); } QVector currentStepModules; steps currentSteps; BackendChooserWidget *firstStepModule = nullptr; DialogDsl::DialogModule *currentModule = nullptr; Logic logic { { "encfs" / i18n("EncFS"), { step { notice("encfs-message", i18n("Security notice:\n\ According to a security audit by Taylor Hornby (Defuse Security),\n\ the current implementation of Encfs is vulnerable or potentially vulnerable\n\ to multiple types of attacks.\n\ For example, an attacker with read/write access\n\ to encrypted data might lower the decryption complexity\n\ for subsequently encrypted data without this being noticed by a legitimate user,\n\ or might use timing analysis to deduce information.\n\

\n\ This means that you should not synchronize\n\ the encrypted data to a cloud storage service,\n\ or use it in other circumstances where the attacker\n\ can frequently access the encrypted data.\n\

\n\ See defuse.ca/audits/encfs.htm for more information.")) }, step { passwordChooser() }, step { directoryPairChooser(DirectoryPairChooserWidget::SkipDevicePicker) }, step { activitiesChooser(), offlineOnlyChooser() } } }, { "cryfs" / i18n("CryFS"), { step { notice("cryfs-message", i18n("Security notice:\n\ CryFS encrypts your files, so you can safely store them anywhere.\n\ It works well together with cloud services like Dropbox, iCloud, OneDrive and others.\n\

\n\ Unlike some other file-system overlay solutions,\n\ it does not expose the directory structure,\n\ the number of files nor the file sizes\n\ through the encrypted data format.\n\

\n\ One important thing to note is that,\n\ while CryFS is considered safe,\n\ there is no independent security audit\n\ which confirms this.")) }, step { passwordChooser() }, step { directoryPairChooser() }, step { cryfsCypherChooser(), activitiesChooser(), offlineOnlyChooser() } } } }; // to suggest the highest priority to the user as a starting value QMap priorities = { - { "encfs", 2 }, - { "cryfs", 1 } + { "encfs", 1 }, + { "cryfs", 2 } }; template QPushButton *addDialogButton(const QString &icon, const QString &title, ClickHandler clickHandler) { auto button = new QPushButton(QIcon::fromTheme(icon), title); ui.buttons->addButton(button, QDialogButtonBox::ActionRole); QObject::connect(button, &QPushButton::clicked, q, clickHandler); return button; } Private(VaultCreationWizard *parent) : q(parent) { ui.setupUi(parent); ui.message->hide(); layout = new QStackedLayout(); layout->setContentsMargins(0, 0, 0, 0); ui.container->setLayout(layout); // The dialog buttons do not have previous/next by default // so we need to create them buttonPrevious = addDialogButton("go-previous", i18n("Previous"), [this] { previousStep(); }); buttonNext = addDialogButton("go-next", i18n("Next"), [this] { nextStep(); }); buttonCreate = addDialogButton("dialog-ok-apply", i18n("Create"), [this] { createVault(); }); // The 'Create' button should be hidden by default buttonCreate->hide(); buttonPrevious->setEnabled(false); buttonNextSetEnabled(false); // Loading the fist page of the wizard firstStepModule = new BackendChooserWidget(); setCurrentModule(firstStepModule); layout->addWidget(firstStepModule); // Loading the backends to the combo box for (const auto& key: logic.keys()) { firstStepModule->addItem(key, key.translation(), priorities.value(key)); } firstStepModule->checkBackendAvailable(); } void setCurrentModule(DialogDsl::DialogModule *module) { // If there is a current module already, disconnect it if (currentModule) { currentModule->aboutToBeHidden(); currentModule->disconnect(); } // The current module needs to be changed currentModule = module; currentModule->aboutToBeShown(); QObject::connect( currentModule, &DialogModule::isValidChanged, q, [&] (bool valid) { buttonNextSetEnabled(valid); }); // Lets update the button states // 1. next/create button is enabled only if the current // module is in the valid state buttonNextSetEnabled(currentModule->isValid()); // 2. previous button is enabled only if we are not on // the first page buttonPrevious->setEnabled(currentStepModules.size() > 0); // 3. If we have loaded the last page, we want to show the // 'Create' button instead of 'Next' if (!currentSteps.isEmpty() && currentStepModules.size() == currentSteps.size()) { buttonNext->hide(); buttonCreate->show(); } else { buttonNext->show(); buttonCreate->hide(); } // Calling to initialize the module -- we are passing all the // previously collected data to it auto collectedPayload = firstStepModule->fields(); for (const auto* module: currentStepModules) { collectedPayload.unite(module->fields()); } currentModule->init(collectedPayload); } void previousStep() { if (currentStepModules.isEmpty()) return; // We want to kill the current module, and move to the previous one currentStepModules.takeLast(); currentModule->deleteLater();; if (currentStepModules.size()) { setCurrentModule(currentStepModules.last()); } else { setCurrentModule(firstStepModule); } if (!currentModule->shouldBeShown()) { previousStep(); } } void nextStep() { // If the step modules are empty, this means that we // have just started - the user chose the backend // and we need to load the vault creation steps if (currentStepModules.isEmpty()) { const auto &fields = firstStepModule->fields(); currentSteps = logic[fields[KEY_BACKEND].toByteArray()]; } // Loading the modulws that we need to show now auto subModules = currentSteps[currentStepModules.size()]; // If there is only one module on the current page, // lets not complicate things by creating the compound module DialogModule *stepWidget = (subModules.size() == 1) ? subModules.first()() : new CompoundDialogModule(subModules); // Adding the widget to the list and the layout currentStepModules << stepWidget; layout->addWidget(stepWidget); layout->setCurrentWidget(stepWidget); // Set the newly added module to be the current setCurrentModule(stepWidget); if (!currentModule->shouldBeShown()) { nextStep(); } } void createVault() { auto collectedPayload = firstStepModule->fields(); for (const auto* module: currentStepModules) { collectedPayload.unite(module->fields()); } const auto name = collectedPayload[KEY_NAME].toString(); const PlasmaVault::Device device(collectedPayload[KEY_DEVICE].toString()); const PlasmaVault::MountPoint mountPoint(collectedPayload[KEY_MOUNT_POINT].toString()); auto vault = new PlasmaVault::Vault(device, q); auto future = vault->create(name, mountPoint, collectedPayload); auto result = AsynQt::await(future); if (result) { emit q->createdVault(vault); q->QDialog::accept(); } else { ui.message->setText(result.error().message()); ui.message->setMessageType(KMessageWidget::Error); ui.message->show(); delete vault; } } }; VaultCreationWizard::VaultCreationWizard(QWidget *parent) : QDialog(parent) , d(new Private(this)) { setWindowTitle(i18nc("@title:window", "Create a New Vault")); } VaultCreationWizard::~VaultCreationWizard() { }