Welcome to mirror list, hosted at ThFree Co, Russian Federation.

shibbolethcredentials.cpp « creds « gui « src - github.com/nextcloud/desktop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b19133785536d4efec959fda01e895def8c761ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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
/*
 * Copyright (C) by Krzesimir Nowak <krzesimir@endocode.com>
 * Copyright (C) by Klaas Freitag <freitag@owncloud.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 <QSettings>
#include <QNetworkReply>
#include <QMessageBox>
#include <QAuthenticator>

#include "creds/shibbolethcredentials.h"
#include "creds/shibboleth/shibbolethwebview.h"
#include "creds/shibbolethcredentials.h"
#include "shibboleth/shibbolethuserjob.h"
#include "creds/credentialscommon.h"
#include "creds/httpcredentialsgui.h"

#include "accessmanager.h"
#include "account.h"
#include "configfile.h"
#include "theme.h"
#include "cookiejar.h"
#include "owncloudgui.h"
#include "syncengine.h"

#include <keychain.h>

using namespace QKeychain;

namespace OCC {

Q_LOGGING_CATEGORY(lcShibboleth, "nextcloud.gui.credentials.shibboleth", QtInfoMsg)

namespace {

    // Not "user" because it has a special meaning for http
    const char userC[] = "shib_user";
    const char shibCookieNameC[] = "_shibsession_";

} // ns

ShibbolethCredentials::ShibbolethCredentials()
    : AbstractCredentials()
{
}

ShibbolethCredentials::ShibbolethCredentials(const QNetworkCookie &cookie)
    : _ready(true)
    , _stillValid(true)
    , _browser(nullptr)
    , _shibCookie(cookie)
    , _keychainMigration(false)
{
}

void ShibbolethCredentials::setAccount(Account *account)
{
    AbstractCredentials::setAccount(account);

    // This is for existing saved accounts.
    if (_user.isEmpty()) {
        _user = _account->credentialSetting(QLatin1String(userC)).toString();
    }

    // When constructed with a cookie (by the wizard), we usually don't know the
    // user name yet. Request it now from the server.
    if (_ready && _user.isEmpty()) {
        QTimer::singleShot(1234, this, &ShibbolethCredentials::slotFetchUser);
    }
}

QString ShibbolethCredentials::authType() const
{
    return QString::fromLatin1("shibboleth");
}

QString ShibbolethCredentials::user() const
{
    return _user;
}

QNetworkAccessManager *ShibbolethCredentials::createQNAM() const
{
    QNetworkAccessManager *qnam(new AccessManager);
    connect(qnam, &QNetworkAccessManager::finished,
        this, &ShibbolethCredentials::slotReplyFinished);
    return qnam;
}

void ShibbolethCredentials::slotReplyFinished(QNetworkReply *r)
{
    if (!_browser.isNull()) {
        return;
    }

    QVariant target = r->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if (target.isValid()) {
        _stillValid = false;
        // The Login window will be opened in NetworkJob's finished signal
        qCWarning(lcShibboleth) << "detected redirect, will open Login Window";
    } else {
        //_stillValid = true; // gets set when reading from keychain or getting it from browser
    }
}

bool ShibbolethCredentials::ready() const
{
    return _ready;
}

void ShibbolethCredentials::fetchFromKeychain()
{
    _wasFetched = true;

    if (_user.isEmpty()) {
        _user = _account->credentialSetting(QLatin1String(userC)).toString();
    }
    if (_ready) {
        Q_EMIT fetched();
    } else {
        _url = _account->url();
        _keychainMigration = false;
        fetchFromKeychainHelper();
    }
}

void ShibbolethCredentials::fetchFromKeychainHelper()
{
    auto *job = new ReadPasswordJob(Theme::instance()->appName());
    job->setSettings(ConfigFile::settingsWithGroup(Theme::instance()->appName(), job).release());
    job->setInsecureFallback(false);
    job->setKey(keychainKey(_url.toString(), user(),
        _keychainMigration ? QString() : _account->id()));
    connect(job, &Job::finished, this, &ShibbolethCredentials::slotReadJobDone);
    job->start();
}

void ShibbolethCredentials::askFromUser()
{
    // First, we do a DetermineAuthTypeJob to make sure that the server is still using shibboleth and did not upgrade to oauth
    auto *job = new DetermineAuthTypeJob(_account->sharedFromThis(), this);
    connect(job, &DetermineAuthTypeJob::authType, [this, job](DetermineAuthTypeJob::AuthType type) {
        if (type == DetermineAuthTypeJob::Shibboleth) {
            // Normal case, still shibboleth
            showLoginWindow();
        } else if (type == DetermineAuthTypeJob::OAuth) {
            // Hack: upgrade to oauth
            auto newCred = new HttpCredentialsGui;
            job->setParent(nullptr);
            job->deleteLater();
            auto account = this->_account;
            auto user = this->_user;
            account->setCredentials(newCred); // delete this
            account->setCredentialSetting(QLatin1String("user"), user);
            newCred->fetchUser();
            newCred->askFromUser();
        } else {
            // Basic auth or unkown. Since it may be unkown it might be a temporary failure, don't replace the credentials here
            // Still show the login window in that case not to break the flow.
            showLoginWindow();
        }

    });
    job->start();
}

bool ShibbolethCredentials::stillValid(QNetworkReply *reply)
{
    Q_UNUSED(reply)
    return _stillValid;
}

void ShibbolethCredentials::persist()
{
    storeShibCookie(_shibCookie);
    if (!_user.isEmpty()) {
        _account->setCredentialSetting(QLatin1String(userC), _user);
    }
}

void ShibbolethCredentials::invalidateToken()
{
    _ready = false;

    auto *jar = static_cast<CookieJar *>(_account->networkAccessManager()->cookieJar());

    // Remove the _shibCookie
    auto cookies = jar->allCookies();
    for (auto it = cookies.begin(); it != cookies.end();) {
        if (it->name() == _shibCookie.name()) {
            it = cookies.erase(it);
        } else {
            ++it;
        }
    }
    jar->setAllCookies(cookies);

    // Clear all other temporary cookies
    jar->clearSessionCookies();
    removeShibCookie();
    _shibCookie = QNetworkCookie();
}

void ShibbolethCredentials::forgetSensitiveData()
{
    invalidateToken();
}

void ShibbolethCredentials::onShibbolethCookieReceived(const QNetworkCookie &shibCookie)
{
    storeShibCookie(shibCookie);
    _shibCookie = shibCookie;
    addToCookieJar(shibCookie);

    slotFetchUser();
}

void ShibbolethCredentials::slotFetchUser()
{
    // We must first do a request to webdav so the session is enabled.
    // (because for some reason we can't access the API without that..  a bug in the server maybe?)
    auto *job = new EntityExistsJob(_account->sharedFromThis(), _account->davPath(), this);
    connect(job, &EntityExistsJob::exists, this, &ShibbolethCredentials::slotFetchUserHelper);
    job->setIgnoreCredentialFailure(true);
    job->start();
}

void ShibbolethCredentials::slotFetchUserHelper()
{
    auto *job = new ShibbolethUserJob(_account->sharedFromThis(), this);
    connect(job, &ShibbolethUserJob::userFetched, this, &ShibbolethCredentials::slotUserFetched);
    job->start();
}

void ShibbolethCredentials::slotUserFetched(const QString &user)
{
    if (_user.isEmpty()) {
        if (user.isEmpty()) {
            qCWarning(lcShibboleth) << "Failed to fetch the shibboleth user";
        }
        _user = user;
    } else if (user != _user) {
        qCWarning(lcShibboleth) << "Wrong user: " << user << "!=" << _user;
        QMessageBox::warning(_browser, tr("Login Error"), tr("You must sign in as user %1").arg(_user));
        invalidateToken();
        showLoginWindow();
        return;
    }

    _stillValid = true;
    _ready = true;
    Q_EMIT asked();
}


void ShibbolethCredentials::slotBrowserRejected()
{
    _ready = false;
    Q_EMIT asked();
}

void ShibbolethCredentials::slotReadJobDone(QKeychain::Job *job)
{
    // If we can't find the credentials at the keys that include the account id,
    // try to read them from the legacy locations that don't have a account id.
    if (!_keychainMigration && job->error() == QKeychain::EntryNotFound) {
        qCWarning(lcShibboleth)
            << "Could not find keychain entry, attempting to read from legacy location";
        _keychainMigration = true;
        fetchFromKeychainHelper();
        return;
    }

    if (job->error() == QKeychain::NoError) {
        auto *readJob = static_cast<ReadPasswordJob *>(job);
        delete readJob->settings();
        QList<QNetworkCookie> cookies = QNetworkCookie::parseCookies(readJob->textData().toUtf8());
        if (cookies.count() > 0) {
            _shibCookie = cookies.first();
            addToCookieJar(_shibCookie);
        }
        // access
        job->setSettings(ConfigFile::settingsWithGroup(Theme::instance()->appName(), job).release());

        _ready = true;
        _stillValid = true;
        Q_EMIT fetched();
    } else {
        _ready = false;
        Q_EMIT fetched();
    }


    // If keychain data was read from legacy location, wipe these entries and store new ones
    if (_keychainMigration && _ready) {
        persist();

        auto *job = new DeletePasswordJob(Theme::instance()->appName());
        job->setSettings(ConfigFile::settingsWithGroup(Theme::instance()->appName(), job).release());
        job->setKey(keychainKey(_account->url().toString(), user(), QString()));
        job->start();

        qCWarning(lcShibboleth) << "Migrated old keychain entries";
    }
}

void ShibbolethCredentials::showLoginWindow()
{
    if (!_browser.isNull()) {
        ownCloudGui::raiseDialog(_browser);
        return;
    }

    auto *jar = static_cast<CookieJar *>(_account->networkAccessManager()->cookieJar());
    // When opening a new window clear all the session cookie that might keep the user from logging in
    // (or the session may already be open in the server, and there will not be redirect asking for the
    // real long term cookie we want to store)
    jar->clearSessionCookies();

    _browser = new ShibbolethWebView(_account->sharedFromThis());
    connect(_browser.data(), &ShibbolethWebView::shibbolethCookieReceived,
        this, &ShibbolethCredentials::onShibbolethCookieReceived, Qt::QueuedConnection);
    connect(_browser.data(), &ShibbolethWebView::rejected, this, &ShibbolethCredentials::slotBrowserRejected);

    ownCloudGui::raiseDialog(_browser);
}

QList<QNetworkCookie> ShibbolethCredentials::accountCookies(Account *account)
{
    return account->networkAccessManager()->cookieJar()->cookiesForUrl(account->davUrl());
}

QNetworkCookie ShibbolethCredentials::findShibCookie(Account *account, QList<QNetworkCookie> cookies)
{
    if (cookies.isEmpty()) {
        cookies = accountCookies(account);
    }

    Q_FOREACH (QNetworkCookie cookie, cookies) {
        if (cookie.name().startsWith(shibCookieNameC)) {
            return cookie;
        }
    }
    return QNetworkCookie();
}

QByteArray ShibbolethCredentials::shibCookieName()
{
    return QByteArray(shibCookieNameC);
}

void ShibbolethCredentials::storeShibCookie(const QNetworkCookie &cookie)
{
    auto *job = new WritePasswordJob(Theme::instance()->appName());
    job->setSettings(ConfigFile::settingsWithGroup(Theme::instance()->appName(), job).release());
    // we don't really care if it works...
    //connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotWriteJobDone(QKeychain::Job*)));
    job->setKey(keychainKey(_account->url().toString(), user(), _account->id()));
    job->setTextData(QString::fromUtf8(cookie.toRawForm()));
    job->start();
}

void ShibbolethCredentials::removeShibCookie()
{
    auto *job = new DeletePasswordJob(Theme::instance()->appName());
    job->setSettings(ConfigFile::settingsWithGroup(Theme::instance()->appName(), job).release());
    job->setKey(keychainKey(_account->url().toString(), user(), _account->id()));
    job->start();
}

void ShibbolethCredentials::addToCookieJar(const QNetworkCookie &cookie)
{
    QList<QNetworkCookie> cookies;
    cookies << cookie;
    QNetworkCookieJar *jar = _account->networkAccessManager()->cookieJar();
    jar->blockSignals(true); // otherwise we'd call ourselves
    jar->setCookiesFromUrl(cookies, _account->url());
    jar->blockSignals(false);
}

} // namespace OCC