keychainchunk.cpp 13.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Copyright (C) by Michael Schuster <michael@nextcloud.com>
 *
 * 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) any later version.
 *
 * 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.
 */

#include "account.h"
#include "keychainchunk.h"
#include "theme.h"
#include "networkjobs.h"
#include "configfile.h"
#include "creds/abstractcredentials.h"

22 23
#include <QApplication>

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
using namespace QKeychain;

namespace OCC {

Q_LOGGING_CATEGORY(lcKeychainChunk, "nextcloud.sync.credentials.keychainchunk", QtInfoMsg)

namespace KeychainChunk {

#if defined(KEYCHAINCHUNK_ENABLE_INSECURE_FALLBACK)
static void addSettingsToJob(Account *account, QKeychain::Job *job)
{
    Q_UNUSED(account)
    auto settings = ConfigFile::settingsWithGroup(Theme::instance()->appName());
    settings->setParent(job); // make the job parent to make setting deleted properly
    job->setSettings(settings.release());
}
#endif

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#ifdef Q_OS_WIN
void jobKeyPrependAppName(QString &key)
{
    // NOTE: The following is normally done in AbstractCredentials::keychainKey
    //       when an _account is specified by our other ctr overload (see 'kck' in this file).

    // On Windows the credential keys aren't namespaced properly
    // by qtkeychain. To work around that we manually add namespacing
    // to the generated keys. See #6125.
    // It's safe to do that since the key format is changing for 2.4
    // anyway to include the account ids. That means old keys can be
    // migrated to new namespaced keys on windows for 2.4.
    key.prepend(QCoreApplication::applicationName() + "_");
}
#endif

58 59 60 61 62 63 64 65 66
/*
* Job
*/
Job::Job(QObject *parent)
    : QObject(parent)
{
    _serviceName = Theme::instance()->appName();
}

67 68 69 70 71 72
Job::~Job()
{
    _chunkCount = 0;
    _chunkBuffer.clear();
}

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
/*
* WriteJob
*/
WriteJob::WriteJob(Account *account, const QString &key, const QByteArray &data, QObject *parent)
    : Job(parent)
{
    _account = account;
    _key = key;

    // Windows workaround: Split the private key into chunks of 2048 bytes,
    // to allow 4k (4096 bit) keys to be saved (obey Windows's limits)
    _chunkBuffer = data;
    _chunkCount = 0;
}

88 89 90 91
WriteJob::WriteJob(const QString &key, const QByteArray &data, QObject *parent)
    : WriteJob(nullptr, key, data, parent)
{
#ifdef Q_OS_WIN
92
    jobKeyPrependAppName(_key);
93 94 95
#endif
}

96 97
void WriteJob::start()
{
98 99
    _error = QKeychain::NoError;

100 101 102
    slotWriteJobDone(nullptr);
}

103
bool WriteJob::exec()
104 105 106
{
    start();

107 108 109
    QEventLoop waitLoop;
    connect(this, &WriteJob::finished, &waitLoop, &QEventLoop::quit);
    waitLoop.exec();
110 111 112 113 114 115 116 117 118

    if (error() != NoError) {
        qCWarning(lcKeychainChunk) << "WritePasswordJob failed with" << errorString();
        return false;
    }

    return true;
}

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
void WriteJob::slotWriteJobDone(QKeychain::Job *incomingJob)
{
    QKeychain::WritePasswordJob *writeJob = static_cast<QKeychain::WritePasswordJob *>(incomingJob);

    // errors?
    if (writeJob) {
        _error = writeJob->error();
        _errorString = writeJob->errorString();

        if (writeJob->error() != NoError) {
            qCWarning(lcKeychainChunk) << "Error while writing" << writeJob->key() << "chunk" << writeJob->errorString();
            _chunkBuffer.clear();
        }
    }

    // write a chunk if there is any in the buffer
    if (!_chunkBuffer.isEmpty()) {
#if defined(Q_OS_WIN)
        // Windows workaround: Split the data into chunks of 2048 bytes,
        // to allow 4k (4096 bit) keys to be saved (obey Windows's limits)
        auto chunk = _chunkBuffer.left(KeychainChunk::ChunkSize);

        _chunkBuffer = _chunkBuffer.right(_chunkBuffer.size() - chunk.size());
#else
        // write full data in one chunk on non-Windows, as usual
        auto chunk = _chunkBuffer;

        _chunkBuffer.clear();
#endif
        auto index = (_chunkCount++);

        // keep the limit
        if (_chunkCount > KeychainChunk::MaxChunks) {
            qCWarning(lcKeychainChunk) << "Maximum chunk count exceeded while writing" << writeJob->key() << "chunk" << QString::number(index) << "cutting off after" << QString::number(KeychainChunk::MaxChunks) << "chunks";

            writeJob->deleteLater();

            _chunkBuffer.clear();

            emit finished(this);
159 160 161

            if (_autoDelete)
                deleteLater();
162 163 164
            return;
        }

165 166 167 168 169 170
        const QString keyWithIndex = _key + (index > 0 ? (QString(".") + QString::number(index)) : QString());
        const QString kck = _account ? AbstractCredentials::keychainKey(
                _account->url().toString(),
                keyWithIndex,
                _account->id()
            ) : keyWithIndex;
171

172
        auto *job = new QKeychain::WritePasswordJob(_serviceName, this);
173 174 175 176 177 178 179 180 181 182 183 184 185
#if defined(KEYCHAINCHUNK_ENABLE_INSECURE_FALLBACK)
        addSettingsToJob(_account, job);
#endif
        job->setInsecureFallback(_insecureFallback);
        connect(job, &QKeychain::Job::finished, this, &KeychainChunk::WriteJob::slotWriteJobDone);
        // only add the key's (sub)"index" after the first element, to stay compatible with older versions and non-Windows
        job->setKey(kck);
        job->setBinaryData(chunk);
        job->start();

        chunk.clear();
    } else {
        emit finished(this);
186 187 188

        if (_autoDelete)
            deleteLater();
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    }

    writeJob->deleteLater();
}

/*
* ReadJob
*/
ReadJob::ReadJob(Account *account, const QString &key, const bool &keychainMigration, QObject *parent)
    : Job(parent)
{
    _account = account;
    _key = key;

    _keychainMigration = keychainMigration;

    _chunkCount = 0;
    _chunkBuffer.clear();
}

209 210 211 212
ReadJob::ReadJob(const QString &key, QObject *parent)
    : ReadJob(nullptr, key, false, parent)
{
#ifdef Q_OS_WIN
213
    jobKeyPrependAppName(_key);
214 215 216
#endif
}

217 218 219 220
void ReadJob::start()
{
    _chunkCount = 0;
    _chunkBuffer.clear();
221
    _error = QKeychain::NoError;
222

223 224 225 226 227
    const QString kck = _account ? AbstractCredentials::keychainKey(
            _account->url().toString(),
            _key,
            _keychainMigration ? QString() : _account->id()
        ) : _key;
228

229
    auto *job = new QKeychain::ReadPasswordJob(_serviceName, this);
230 231 232 233 234 235 236 237 238
#if defined(KEYCHAINCHUNK_ENABLE_INSECURE_FALLBACK)
    addSettingsToJob(_account, job);
#endif
    job->setInsecureFallback(_insecureFallback);
    job->setKey(kck);
    connect(job, &QKeychain::Job::finished, this, &KeychainChunk::ReadJob::slotReadJobDone);
    job->start();
}

239
bool ReadJob::exec()
240 241 242
{
    start();

243 244 245
    QEventLoop waitLoop;
    connect(this, &ReadJob::finished, &waitLoop, &QEventLoop::quit);
    waitLoop.exec();
246 247 248 249 250 251 252 253 254 255 256 257 258

    if (error() == NoError) {
        return true;
    }

    _chunkCount = 0;
    _chunkBuffer.clear();
    if (error() != EntryNotFound) {
        qCWarning(lcKeychainChunk) << "ReadPasswordJob failed with" << errorString();
    }
    return false;
}

259 260 261 262 263 264 265 266 267 268 269 270 271
void ReadJob::slotReadJobDone(QKeychain::Job *incomingJob)
{
    // Errors or next chunk?
    QKeychain::ReadPasswordJob *readJob = static_cast<QKeychain::ReadPasswordJob *>(incomingJob);

    if (readJob) {
        if (readJob->error() == NoError && readJob->binaryData().length() > 0) {
            _chunkBuffer.append(readJob->binaryData());
            _chunkCount++;

#if defined(Q_OS_WIN)
            // try to fetch next chunk
            if (_chunkCount < KeychainChunk::MaxChunks) {
272 273 274 275 276 277
                const QString keyWithIndex = _key + QString(".") + QString::number(_chunkCount);
                const QString kck = _account ? AbstractCredentials::keychainKey(
                        _account->url().toString(),
                        keyWithIndex,
                        _keychainMigration ? QString() : _account->id()
                    ) : keyWithIndex;
278

279
                QKeychain::ReadPasswordJob *job = new QKeychain::ReadPasswordJob(_serviceName, this);
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
#if defined(KEYCHAINCHUNK_ENABLE_INSECURE_FALLBACK)
                addSettingsToJob(_account, job);
#endif
                job->setInsecureFallback(_insecureFallback);
                job->setKey(kck);
                connect(job, &QKeychain::Job::finished, this, &KeychainChunk::ReadJob::slotReadJobDone);
                job->start();

                readJob->deleteLater();
                return;
            } else {
                qCWarning(lcKeychainChunk) << "Maximum chunk count for" << readJob->key() << "reached, ignoring after" << KeychainChunk::MaxChunks;
            }
#endif
        } else {
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
            if (!readJob->insecureFallback()) { // If insecureFallback is set, the next test would be pointless
                if (_retryOnKeyChainError && (readJob->error() == QKeychain::NoBackendAvailable
                        || readJob->error() == QKeychain::OtherError)) {
                    // Could be that the backend was not yet available. Wait some extra seconds.
                    // (Issues #4274 and #6522)
                    // (For kwallet, the error is OtherError instead of NoBackendAvailable, maybe a bug in QtKeychain)
                    qCInfo(lcKeychainChunk) << "Backend unavailable (yet?) Retrying in a few seconds." << readJob->errorString();
                    QTimer::singleShot(10000, this, &ReadJob::start);
                    _retryOnKeyChainError = false;
                    readJob->deleteLater();
                    return;
                }
                _retryOnKeyChainError = false;
            }
#endif

            if (readJob->error() != QKeychain::EntryNotFound ||
                ((readJob->error() == QKeychain::EntryNotFound) && _chunkCount == 0)) {
314 315
                _error = readJob->error();
                _errorString = readJob->errorString();
316
                qCWarning(lcKeychainChunk) << "Unable to read" << readJob->key() << "chunk" << QString::number(_chunkCount) << readJob->errorString();
317
            }
318 319 320 321 322 323
        }

        readJob->deleteLater();
    }

    emit finished(this);
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

    if (_autoDelete)
        deleteLater();
}

/*
* DeleteJob
*/
DeleteJob::DeleteJob(Account *account, const QString &key, const bool &keychainMigration, QObject *parent)
    : Job(parent)
{
    _account = account;
    _key = key;

    _keychainMigration = keychainMigration;
}

DeleteJob::DeleteJob(const QString &key, QObject *parent)
    : DeleteJob(nullptr, key, false, parent)
{
#ifdef Q_OS_WIN
    jobKeyPrependAppName(_key);
#endif
}

void DeleteJob::start()
{
    _chunkCount = 0;
    _error = QKeychain::NoError;

    const QString kck = _account ? AbstractCredentials::keychainKey(
            _account->url().toString(),
            _key,
            _keychainMigration ? QString() : _account->id()
        ) : _key;

    auto *job = new QKeychain::DeletePasswordJob(_serviceName, this);
#if defined(KEYCHAINCHUNK_ENABLE_INSECURE_FALLBACK)
    addSettingsToJob(_account, job);
#endif
    job->setInsecureFallback(_insecureFallback);
    job->setKey(kck);
    connect(job, &QKeychain::Job::finished, this, &KeychainChunk::DeleteJob::slotDeleteJobDone);
    job->start();
}

bool DeleteJob::exec()
{
    start();

    QEventLoop waitLoop;
    connect(this, &DeleteJob::finished, &waitLoop, &QEventLoop::quit);
    waitLoop.exec();

    if (error() == NoError) {
        return true;
    }

    _chunkCount = 0;
    if (error() != EntryNotFound) {
        qCWarning(lcKeychainChunk) << "DeletePasswordJob failed with" << errorString();
    }
    return false;
}

void DeleteJob::slotDeleteJobDone(QKeychain::Job *incomingJob)
{
    // Errors or next chunk?
    auto *deleteJob = static_cast<QKeychain::DeletePasswordJob *>(incomingJob);

    if (deleteJob) {
        if (deleteJob->error() == NoError) {
            _chunkCount++;

#if defined(Q_OS_WIN)
            // try to delete next chunk
            if (_chunkCount < KeychainChunk::MaxChunks) {
                const QString keyWithIndex = _key + QString(".") + QString::number(_chunkCount);
                const QString kck = _account ? AbstractCredentials::keychainKey(
                        _account->url().toString(),
                        keyWithIndex,
                        _keychainMigration ? QString() : _account->id()
                    ) : keyWithIndex;

                QKeychain::DeletePasswordJob *job = new QKeychain::DeletePasswordJob(_serviceName, this);
#if defined(KEYCHAINCHUNK_ENABLE_INSECURE_FALLBACK)
                addSettingsToJob(_account, job);
#endif
                job->setInsecureFallback(_insecureFallback);
                job->setKey(kck);
                connect(job, &QKeychain::Job::finished, this, &KeychainChunk::DeleteJob::slotDeleteJobDone);
                job->start();

                deleteJob->deleteLater();
                return;
            } else {
                qCWarning(lcKeychainChunk) << "Maximum chunk count for" << deleteJob->key() << "reached, ignoring after" << KeychainChunk::MaxChunks;
            }
#endif
        } else {
            if (deleteJob->error() != QKeychain::EntryNotFound ||
                ((deleteJob->error() == QKeychain::EntryNotFound) && _chunkCount == 0)) {
                _error = deleteJob->error();
                _errorString = deleteJob->errorString();
                qCWarning(lcKeychainChunk) << "Unable to delete" << deleteJob->key() << "chunk" << QString::number(_chunkCount) << deleteJob->errorString();
            }
        }

        deleteJob->deleteLater();
    }

    emit finished(this);

    if (_autoDelete)
        deleteLater();
439 440 441 442 443
}

} // namespace KeychainChunk

} // namespace OCC