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
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\Login\Security;
use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\Date;
use Piwik\Db;
use Piwik\Plugins\Login\Emails\SuspiciousLoginAttemptsInLastHourEmail;
use Piwik\Plugins\Login\Model;
use Piwik\Plugins\Login\SystemSettings;
use Piwik\Updater;
use Piwik\Log\LoggerInterface;
class BruteForceDetection
{
public const OVERALL_LOGIN_LOCKOUT_THRESHOLD_MIN = 10;
public const TABLE_NAME = 'brute_force_log';
private $minutesTimeRange;
private $maxLogAttempts;
private $table = self::TABLE_NAME;
private $tablePrefixed = '';
/**
* @var SystemSettings
*/
private $settings;
/**
* @var Updater
*/
private $updater;
/**
* @var Model
*/
private $model;
public function __construct(SystemSettings $systemSettings, Model $model)
{
$this->tablePrefixed = Common::prefixTable($this->table);
$this->settings = $systemSettings;
$this->minutesTimeRange = $systemSettings->loginAttemptsTimeRange->getValue();
$this->maxLogAttempts = $systemSettings->maxFailedLoginsPerMinutes->getValue();
$this->updater = new Updater();
$this->model = $model;
}
public function isEnabled(): bool
{
$dbSchemaVersion = $this->updater->getCurrentComponentVersion('core');
if ($dbSchemaVersion && version_compare($dbSchemaVersion, '3.8.0') == -1) {
return false; // do not enable brute force detection before the tables exist
}
return $this->settings->enableBruteForceDetection->getValue();
}
public function addFailedAttempt($ipAddress, $login = null)
{
$now = $this->getNow()->getDatetime();
$db = Db::get();
try {
$db->query('INSERT INTO ' . $this->tablePrefixed . ' (ip_address, attempted_at, login) VALUES(?,?,?)', array($ipAddress, $now, $login));
} catch (\Exception $ex) {
$this->ignoreExceptionIfThrownDuringOneClickUpdate($ex);
}
}
public function isAllowedToLogin($ipAddress)
{
if ($this->settings->isBlacklistedIp($ipAddress)) {
return false;
}
if ($this->settings->isWhitelistedIp($ipAddress)) {
return true;
}
$db = Db::get();
$startTime = $this->getStartTimeRange();
$sql = 'SELECT count(*) as numLogins FROM `' . $this->tablePrefixed . '` WHERE ip_address = ? AND attempted_at > ?';
$numLogins = $db->fetchOne($sql, array($ipAddress, $startTime));
return empty($numLogins) || $numLogins <= $this->maxLogAttempts;
}
public function getCurrentlyBlockedIps()
{
$sql = 'SELECT ip_address
FROM `' . $this->tablePrefixed . '`
WHERE attempted_at > ?
GROUP BY ip_address
HAVING count(*) > ' . (int) $this->maxLogAttempts;
$rows = Db::get()->fetchAll($sql, array($this->getStartTimeRange()));
$ips = array();
foreach ($rows as $row) {
if ($this->settings->isWhitelistedIp($row['ip_address'])) {
continue;
}
$ips[] = $row['ip_address'];
}
return $ips;
}
public function unblockIp($ip)
{
// we only delete where attempted_at was recent and keep other IPs for history purposes
Db::get()->query('DELETE FROM `' . $this->tablePrefixed . '` WHERE ip_address = ? and attempted_at > ?', [$ip, $this->getStartTimeRange()]);
}
public function cleanupOldEntries()
{
// we delete all entries older than 7 days (or more if more attempts are logged)
$minutesAutoDelete = 10080;
$minutes = max($minutesAutoDelete, $this->minutesTimeRange);
$deleteOlderDate = $this->getDateTimeSubMinutes($minutes);
Db::get()->query('DELETE FROM `' . $this->tablePrefixed . '` WHERE attempted_at < ?', [$deleteOlderDate]);
}
/**
* @internal tests only
*/
public function deleteAll()
{
return Db::query('DELETE FROM `' . $this->tablePrefixed . '`');
}
/**
* @internal tests only
*/
public function getAll()
{
return Db::get()->fetchAll('SELECT * FROM `' . $this->tablePrefixed . '`');
}
protected function getNow()
{
return Date::now();
}
private function getStartTimeRange()
{
return $this->getDateTimeSubMinutes($this->minutesTimeRange);
}
private function getDateTimeSubMinutes($minutes)
{
return $this->getNow()->subPeriod($minutes, 'minute')->getDatetime();
}
public function isUserLoginBlocked($login)
{
$count = 0;
try {
$count = $this->model->getTotalLoginAttemptsInLastHourForLogin($login);
} catch (\Exception $ex) {
$this->ignoreExceptionIfThrownDuringOneClickUpdate($ex);
}
if (!$this->hasTooManyTriesOverallInlastHour($count)) {
return false;
}
if (!$this->model->hasNotifiedUserAboutSuspiciousLogins($login)) {
$this->sendSuspiciousLoginsEmailToUser($login, $count);
}
return true;
}
private function hasTooManyTriesOverallInLastHour($count)
{
return $count > $this->getOverallLoginLockoutThreshold();
}
private function sendSuspiciousLoginsEmailToUser($login, $countOverall)
{
$distinctIps = $this->model->getDistinctIpsAttemptingLoginsInLastHour($login);
try {
// create from DI container so plugins can modify email contents if they want
$email = StaticContainer::getContainer()->make(SuspiciousLoginAttemptsInLastHourEmail::class, [
'login' => $login,
'countOverall' => $countOverall,
'countDistinctIps' => $distinctIps,
]);
$email->send();
$this->model->markSuspiciousLoginsNotifiedEmailSent($login);
} catch (\Exception $ex) {
// log if error is not that we can't find a user
if (strpos($ex->getMessage(), 'unable to find user to send') === false) {
StaticContainer::get(LoggerInterface::class)->info(
'Error when sending ' . SuspiciousLoginAttemptsInLastHourEmail::class . ' email. User exists but encountered {exception}',
['exception' => $ex]
);
}
}
}
protected function getOverallLoginLockoutThreshold()
{
$settings = new SystemSettings();
$threshold = $settings->maxFailedLoginsPerMinutes->getValue() * 3;
return max(self::OVERALL_LOGIN_LOCKOUT_THRESHOLD_MIN, $threshold);
}
private function ignoreExceptionIfThrownDuringOneClickUpdate(\Exception $ex)
{
// ignore column not found errors during one click update since the db will not be up to date while new code is being used
$module = Common::getRequestVar('module', false);
if (
strpos($ex->getMessage(), 'Unknown column') === false
|| $module != 'CoreUpdater'
) {
throw $ex;
}
}
}
|