Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add configurable ban options for WebUI #12004

Merged
merged 4 commits into from
Feb 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/base/preferences.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@

#include "preferences.h"

#include <chrono>

#ifdef Q_OS_MACOS
#include <CoreServices/CoreServices.h>
#endif
Expand Down Expand Up @@ -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();
Expand Down
4 changes: 4 additions & 0 deletions src/base/preferences.h
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,10 @@ class Preferences : public QObject
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);

Expand Down
6 changes: 6 additions & 0 deletions src/gui/optionsdialog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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
Expand Down
57 changes: 57 additions & 0 deletions src/gui/optionsdialog.ui
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand Down
6 changes: 6 additions & 0 deletions src/webui/api/appcontroller.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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
Expand Down
26 changes: 13 additions & 13 deletions src/webui/api/authcontroller.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@

#include "authcontroller.h"

#include <QDateTime>
#include <QString>

#include "base/logger.h"
Expand All @@ -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()) {
Expand Down Expand Up @@ -74,27 +70,29 @@ void AuthController::loginAction()
LogMsg(tr("WebAPI login success. IP: %1").arg(clientAddr));
}
else {
increaseFailedAttempts();
if (Preferences::instance()->getWebUIMaxAuthFailCount() > 0)
Chocobo1 marked this conversation as resolved.
Show resolved Hide resolved
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)
, Log::WARNING);
}
}

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;
}

Expand All @@ -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()) {
Chocobo1 marked this conversation as resolved.
Show resolved Hide resolved
// Max number of failed attempts reached
// Start ban period
failedLogin.bannedAt = QDateTime::currentMSecsSinceEpoch() / 1000;
failedLogin.banTimer.setRemainingTime(Preferences::instance()->getWebUIBanDuration());
}
}
5 changes: 3 additions & 2 deletions src/webui/api/authcontroller.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

#pragma once

#include <QDeadlineTimer>
#include <QHash>

#include "apicontroller.h"
Expand All @@ -44,7 +45,7 @@ class AuthController : public APIController

private slots:
void loginAction();
void logoutAction();
void logoutAction() const;

private:
bool isBanned() const;
Expand All @@ -54,7 +55,7 @@ private slots:
struct FailedLogin
{
int failedAttemptsCount = 0;
qint64 bannedAt = 0;
QDeadlineTimer banTimer {-1};
};
mutable QHash<QString, FailedLogin> m_clientFailedLogins;
};
59 changes: 36 additions & 23 deletions src/webui/www/private/views/preferences.html
Original file line number Diff line number Diff line change
Expand Up @@ -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>

Expand Down Expand Up @@ -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>
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down