Merge pull request #12004 from Chocobo1/authCount

Add configurable ban options for WebUI
This commit is contained in:
Mike Tzou 2020-02-15 09:43:16 +08:00 committed by GitHub
commit dbea2d95f9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 147 additions and 38 deletions

View file

@ -29,6 +29,8 @@
#include "preferences.h"
#include <chrono>
#ifdef Q_OS_MACOS
#include <CoreServices/CoreServices.h>
#endif
@ -621,6 +623,26 @@ void Preferences::setWebUIPassword(const QByteArray &password)
setValue("Preferences/WebUI/Password_PBKDF2", password);
}
int Preferences::getWebUIMaxAuthFailCount() const
{
return value("Preferences/WebUI/MaxAuthenticationFailCount", 5).toInt();
}
void Preferences::setWebUIMaxAuthFailCount(const int count)
{
setValue("Preferences/WebUI/MaxAuthenticationFailCount", count);
}
std::chrono::seconds Preferences::getWebUIBanDuration() const
{
return std::chrono::seconds {value("Preferences/WebUI/BanDuration", 3600).toInt()};
}
void Preferences::setWebUIBanDuration(const std::chrono::seconds duration)
{
setValue("Preferences/WebUI/BanDuration", static_cast<int>(duration.count()));
}
int Preferences::getWebUISessionTimeout() const
{
return value("Preferences/WebUI/SessionTimeout", 3600).toInt();

View file

@ -194,6 +194,10 @@ public:
void setWebUiUsername(const QString &username);
QByteArray getWebUIPassword() const;
void setWebUIPassword(const QByteArray &password);
int getWebUIMaxAuthFailCount() const;
void setWebUIMaxAuthFailCount(int count);
std::chrono::seconds getWebUIBanDuration() const;
void setWebUIBanDuration(std::chrono::seconds duration);
int getWebUISessionTimeout() const;
void setWebUISessionTimeout(int timeout);

View file

@ -421,6 +421,8 @@ OptionsDialog::OptionsDialog(QWidget *parent)
connect(m_ui->checkBypassLocalAuth, &QAbstractButton::toggled, this, &ThisType::enableApplyButton);
connect(m_ui->checkBypassAuthSubnetWhitelist, &QAbstractButton::toggled, this, &ThisType::enableApplyButton);
connect(m_ui->checkBypassAuthSubnetWhitelist, &QAbstractButton::toggled, m_ui->IPSubnetWhitelistButton, &QPushButton::setEnabled);
connect(m_ui->spinBanCounter, qSpinBoxValueChanged, this, &ThisType::enableApplyButton);
connect(m_ui->spinBanDuration, qSpinBoxValueChanged, this, &ThisType::enableApplyButton);
connect(m_ui->spinSessionTimeout, qSpinBoxValueChanged, this, &ThisType::enableApplyButton);
connect(m_ui->checkClickjacking, &QCheckBox::toggled, this, &ThisType::enableApplyButton);
connect(m_ui->checkCSRFProtection, &QCheckBox::toggled, this, &ThisType::enableApplyButton);
@ -770,6 +772,8 @@ void OptionsDialog::saveOptions()
pref->setWebUiHttpsEnabled(m_ui->checkWebUiHttps->isChecked());
pref->setWebUIHttpsCertificatePath(m_ui->textWebUIHttpsCert->selectedPath());
pref->setWebUIHttpsKeyPath(m_ui->textWebUIHttpsKey->selectedPath());
pref->setWebUIMaxAuthFailCount(m_ui->spinBanCounter->value());
pref->setWebUIBanDuration(std::chrono::seconds {m_ui->spinBanDuration->value()});
pref->setWebUISessionTimeout(m_ui->spinSessionTimeout->value());
// Authentication
pref->setWebUiUsername(webUiUsername());
@ -1153,6 +1157,8 @@ void OptionsDialog::loadOptions()
m_ui->checkBypassLocalAuth->setChecked(!pref->isWebUiLocalAuthEnabled());
m_ui->checkBypassAuthSubnetWhitelist->setChecked(pref->isWebUiAuthSubnetWhitelistEnabled());
m_ui->IPSubnetWhitelistButton->setEnabled(m_ui->checkBypassAuthSubnetWhitelist->isChecked());
m_ui->spinBanCounter->setValue(pref->getWebUIMaxAuthFailCount());
m_ui->spinBanDuration->setValue(pref->getWebUIBanDuration().count());
m_ui->spinSessionTimeout->setValue(pref->getWebUISessionTimeout());
// Security

View file

@ -2986,6 +2986,63 @@ Specify an IPv4 or IPv6 address. You can specify &quot;0.0.0.0&quot; for any IPv
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout_10">
<item row="0" column="0">
<widget class="QLabel" name="lblBanCounter">
<property name="text">
<string>Ban client after consecutive failures:</string>
</property>
</widget>
</item>
<item row="0" column="2">
<spacer name="horizontalSpacer_15">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="spinBanCounter">
<property name="specialValueText">
<string>Never</string>
</property>
<property name="maximum">
<number>2147483647</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="lblBanDuration">
<property name="text">
<string>ban for:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QSpinBox" name="spinBanDuration">
<property name="suffix">
<string> sec</string>
</property>
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>2147483647</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_13">
<item>

View file

@ -232,6 +232,8 @@ void AppController::preferencesAction()
for (const Utils::Net::Subnet &subnet : asConst(pref->getWebUiAuthSubnetWhitelist()))
authSubnetWhitelistStringList << Utils::Net::subnetToString(subnet);
data["bypass_auth_subnet_whitelist"] = authSubnetWhitelistStringList.join("\n");
data["web_ui_max_auth_fail_count"] = pref->getWebUIMaxAuthFailCount();
data["web_ui_ban_duration"] = static_cast<int>(pref->getWebUIBanDuration().count());
data["web_ui_session_timeout"] = pref->getWebUISessionTimeout();
// Use alternative Web UI
data["alternative_webui_enabled"] = pref->isAltWebUiEnabled();
@ -601,6 +603,10 @@ void AppController::setPreferencesAction()
// recognize new lines and commas as delimiters
pref->setWebUiAuthSubnetWhitelist(it.value().toString().split(QRegularExpression("\n|,"), QString::SkipEmptyParts));
}
if (hasKey("web_ui_max_auth_fail_count"))
pref->setWebUIMaxAuthFailCount(it.value().toInt());
if (hasKey("web_ui_ban_duration"))
pref->setWebUIBanDuration(std::chrono::seconds {it.value().toInt()});
if (hasKey("web_ui_session_timeout"))
pref->setWebUISessionTimeout(it.value().toInt());
// Use alternative Web UI

View file

@ -28,7 +28,6 @@
#include "authcontroller.h"
#include <QDateTime>
#include <QString>
#include "base/logger.h"
@ -37,9 +36,6 @@
#include "apierror.h"
#include "isessionmanager.h"
constexpr int BAN_TIME = 3600000; // 1 hour
constexpr int MAX_AUTH_FAILED_ATTEMPTS = 5;
void AuthController::loginAction()
{
if (sessionManager()->session()) {
@ -74,7 +70,8 @@ void AuthController::loginAction()
LogMsg(tr("WebAPI login success. IP: %1").arg(clientAddr));
}
else {
increaseFailedAttempts();
if (Preferences::instance()->getWebUIMaxAuthFailCount() > 0)
increaseFailedAttempts();
setResult(QLatin1String("Fails."));
LogMsg(tr("WebAPI login failure. Reason: invalid credentials, attempt count: %1, IP: %2, username: %3")
.arg(QString::number(failedAttemptsCount()), clientAddr, usernameFromWeb)
@ -82,19 +79,20 @@ void AuthController::loginAction()
}
}
void AuthController::logoutAction()
void AuthController::logoutAction() const
{
sessionManager()->sessionEnd();
}
bool AuthController::isBanned() const
{
const qint64 now = QDateTime::currentMSecsSinceEpoch() / 1000;
const FailedLogin failedLogin = m_clientFailedLogins.value(sessionManager()->clientId());
const auto failedLoginIter = m_clientFailedLogins.find(sessionManager()->clientId());
if (failedLoginIter == m_clientFailedLogins.end())
return false;
bool isBanned = (failedLogin.bannedAt > 0);
if (isBanned && ((now - failedLogin.bannedAt) > BAN_TIME)) {
m_clientFailedLogins.remove(sessionManager()->clientId());
bool isBanned = (failedLoginIter->banTimer.remainingTime() >= 0);
if (isBanned && failedLoginIter->banTimer.hasExpired()) {
m_clientFailedLogins.erase(failedLoginIter);
isBanned = false;
}
@ -108,12 +106,14 @@ int AuthController::failedAttemptsCount() const
void AuthController::increaseFailedAttempts()
{
Q_ASSERT(Preferences::instance()->getWebUIMaxAuthFailCount() > 0);
FailedLogin &failedLogin = m_clientFailedLogins[sessionManager()->clientId()];
++failedLogin.failedAttemptsCount;
if (failedLogin.failedAttemptsCount == MAX_AUTH_FAILED_ATTEMPTS) {
if (failedLogin.failedAttemptsCount >= Preferences::instance()->getWebUIMaxAuthFailCount()) {
// Max number of failed attempts reached
// Start ban period
failedLogin.bannedAt = QDateTime::currentMSecsSinceEpoch() / 1000;
failedLogin.banTimer.setRemainingTime(Preferences::instance()->getWebUIBanDuration());
}
}

View file

@ -28,6 +28,7 @@
#pragma once
#include <QDeadlineTimer>
#include <QHash>
#include "apicontroller.h"
@ -44,7 +45,7 @@ public:
private slots:
void loginAction();
void logoutAction();
void logoutAction() const;
private:
bool isBanned() const;
@ -54,7 +55,7 @@ private:
struct FailedLogin
{
int failedAttemptsCount = 0;
qint64 bannedAt = 0;
QDeadlineTimer banTimer {-1};
};
mutable QHash<QString, FailedLogin> m_clientFailedLogins;
};

View file

@ -562,28 +562,27 @@
<td>
<input type="text" id="max_ratio_value" style="width: 4em;" />
</td>
<tr>
<td>
<input type="checkbox" id="max_seeding_time_checkbox" onclick="qBittorrent.Preferences.updateMaxRatioTimeEnabled();" />
<label for="max_seeding_time_checkbox">QBT_TR(When seeding time reaches)QBT_TR[CONTEXT=OptionsDialog]</label>
</td>
<td>
<input type="text" id="max_seeding_time_value" style="width: 4em;" /> QBT_TR(minutes)QBT_TR[CONTEXT=OptionsDialog]
</td>
</tr>
<tr>
<td style="text-align: right;">
QBT_TR(then)QBT_TR[CONTEXT=OptionsDialog]
</td>
<td>
<select id="max_ratio_act">
<option value="0">QBT_TR(Pause torrent)QBT_TR[CONTEXT=OptionsDialog]</option>
<option value="1">QBT_TR(Remove torrent)QBT_TR[CONTEXT=OptionsDialog]</option>
<option value="3">QBT_TR(Remove torrent and its files)QBT_TR[CONTEXT=OptionsDialog]</option>
<option value="2">QBT_TR(Enable super seeding for torrent)QBT_TR[CONTEXT=OptionsDialog]</option>
</select>
</td>
</tr>
</tr>
<tr>
<td>
<label for="max_seeding_time_checkbox">QBT_TR(When seeding time reaches)QBT_TR[CONTEXT=OptionsDialog]</label>
<input type="checkbox" id="max_seeding_time_checkbox" onclick="qBittorrent.Preferences.updateMaxRatioTimeEnabled();" />
</td>
<td>
<input type="text" id="max_seeding_time_value" style="width: 4em;" />QBT_TR(minutes)QBT_TR[CONTEXT=OptionsDialog]
</td>
</tr>
<tr>
<td style="text-align: right;"><label for="max_ratio_act">QBT_TR(then)QBT_TR[CONTEXT=OptionsDialog]</label></td>
<td>
<select id="max_ratio_act">
<option value="0">QBT_TR(Pause torrent)QBT_TR[CONTEXT=OptionsDialog]</option>
<option value="1">QBT_TR(Remove torrent)QBT_TR[CONTEXT=OptionsDialog]</option>
<option value="3">QBT_TR(Remove torrent and its files)QBT_TR[CONTEXT=OptionsDialog]</option>
<option value="2">QBT_TR(Enable super seeding for torrent)QBT_TR[CONTEXT=OptionsDialog]</option>
</select>
</td>
</tr>
</table>
</fieldset>
@ -729,10 +728,20 @@
<div class="formRow" style="padding-left: 30px; padding-top: 5px;">
<textarea id="bypass_auth_subnet_whitelist_textarea" rows="5" cols="48" placeholder="Example: 172.17.32.0/24, fdff:ffff:c8::/40"></textarea>
</div>
<table>
<tr>
<td><label for="webUIMaxAuthFailCountInput">QBT_TR(Ban client after consecutive failures:)QBT_TR[CONTEXT=OptionsDialog]</label></td>
<td><input type="number" id="webUIMaxAuthFailCountInput" style="width: 4em;" min="0" /></td>
</tr>
<tr>
<td style="text-align: right;"><label for="webUIBanDurationInput">QBT_TR(ban for:)QBT_TR[CONTEXT=OptionsDialog]</label></td>
<td><input type="number" id="webUIBanDurationInput" style="width: 4em;" min="1" />QBT_TR(seconds)QBT_TR[CONTEXT=OptionsDialog]</td>
</tr>
</table>
<table>
<tr>
<td><label for="webUISessionTimeoutInput">QBT_TR(Session timeout:)QBT_TR[CONTEXT=OptionsDialog]</label></td>
<td><input type="number" id="webUISessionTimeoutInput" style="width: 4em;" min="0" />&nbsp;&nbsp;QBT_TR(sec)QBT_TR[CONTEXT=OptionsDialog]</td>
<td><input type="number" id="webUISessionTimeoutInput" style="width: 4em;" min="0" />&nbsp;&nbsp;QBT_TR(seconds)QBT_TR[CONTEXT=OptionsDialog]</td>
</tr>
</table>
</fieldset>
@ -1719,6 +1728,8 @@
$('bypass_auth_subnet_whitelist_checkbox').setProperty('checked', pref.bypass_auth_subnet_whitelist_enabled);
$('bypass_auth_subnet_whitelist_textarea').setProperty('value', pref.bypass_auth_subnet_whitelist);
updateBypasssAuthSettings();
$('webUIMaxAuthFailCountInput').setProperty('value', pref.web_ui_max_auth_fail_count.toInt());
$('webUIBanDurationInput').setProperty('value', pref.web_ui_ban_duration.toInt());
$('webUISessionTimeoutInput').setProperty('value', pref.web_ui_session_timeout.toInt());
// Use alternative Web UI
@ -2082,6 +2093,8 @@
settings.set('bypass_local_auth', $('bypass_local_auth_checkbox').getProperty('checked'));
settings.set('bypass_auth_subnet_whitelist_enabled', $('bypass_auth_subnet_whitelist_checkbox').getProperty('checked'));
settings.set('bypass_auth_subnet_whitelist', $('bypass_auth_subnet_whitelist_textarea').getProperty('value'));
settings.set('web_ui_max_auth_fail_count', $('webUIMaxAuthFailCountInput').getProperty('value'));
settings.set('web_ui_ban_duration', $('webUIBanDurationInput').getProperty('value'));
settings.set('web_ui_session_timeout', $('webUISessionTimeoutInput').getProperty('value'));
// Use alternative Web UI