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

Throttler.php « Bruteforce « Security « private « lib - github.com/nextcloud/server.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0de7677285b975eac5e936f689799752e425e2da (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
<?php
/**
 * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OC\Security\Bruteforce;

use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\ILogger;

/**
 * Class Throttler implements the bruteforce protection for security actions in
 * Nextcloud.
 *
 * It is working by logging invalid login attempts to the database and slowing
 * down all login attempts from the same subnet. The max delay is 30 seconds and
 * the starting delay are 200 milliseconds. (after the first failed login)
 *
 * This is based on Paragonie's AirBrake for Airship CMS. You can find the original
 * code at https://github.com/paragonie/airship/blob/7e5bad7e3c0fbbf324c11f963fd1f80e59762606/src/Engine/Security/AirBrake.php
 *
 * @package OC\Security\Bruteforce
 */
class Throttler {
	const LOGIN_ACTION = 'login';

	/** @var IDBConnection */
	private $db;
	/** @var ITimeFactory */
	private $timeFactory;
	/** @var ILogger */
	private $logger;
	/** @var IConfig */
	private $config;

	/**
	 * @param IDBConnection $db
	 * @param ITimeFactory $timeFactory
	 * @param ILogger $logger
	 * @param IConfig $config
	 */
	public function __construct(IDBConnection $db,
								ITimeFactory $timeFactory,
								ILogger $logger,
								IConfig $config) {
		$this->db = $db;
		$this->timeFactory = $timeFactory;
		$this->logger = $logger;
		$this->config = $config;
	}

	/**
	 * Convert a number of seconds into the appropriate DateInterval
	 *
	 * @param int $expire
	 * @return \DateInterval
	 */
	private function getCutoff($expire) {
		$d1 = new \DateTime();
		$d2 = clone $d1;
		$d2->sub(new \DateInterval('PT' . $expire . 'S'));
		return $d2->diff($d1);
	}

	/**
	 * Return the given subnet for an IPv4 address and mask bits
	 *
	 * @param string $ip
	 * @param int $maskBits
	 * @return string
	 */
	private function getIPv4Subnet($ip,
								  $maskBits = 32) {
		$binary = \inet_pton($ip);
		for ($i = 32; $i > $maskBits; $i -= 8) {
			$j = \intdiv($i, 8) - 1;
			$k = (int) \min(8, $i - $maskBits);
			$mask = (0xff - ((pow(2, $k)) - 1));
			$int = \unpack('C', $binary[$j]);
			$binary[$j] = \pack('C', $int[1] & $mask);
		}
		return \inet_ntop($binary).'/'.$maskBits;
	}

	/**
	 * Return the given subnet for an IPv6 address and mask bits
	 *
	 * @param string $ip
	 * @param int $maskBits
	 * @return string
	 */
	private function getIPv6Subnet($ip, $maskBits = 48) {
		$binary = \inet_pton($ip);
		for ($i = 128; $i > $maskBits; $i -= 8) {
			$j = \intdiv($i, 8) - 1;
			$k = (int) \min(8, $i - $maskBits);
			$mask = (0xff - ((pow(2, $k)) - 1));
			$int = \unpack('C', $binary[$j]);
			$binary[$j] = \pack('C', $int[1] & $mask);
		}
		return \inet_ntop($binary).'/'.$maskBits;
	}

	/**
	 * Return the given subnet for an IP and the configured mask bits
	 *
	 * Determine if the IP is an IPv4 or IPv6 address, then pass to the correct
	 * method for handling that specific type.
	 *
	 * @param string $ip
	 * @return string
	 */
	private function getSubnet($ip) {
		if (\preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $ip)) {
			return $this->getIPv4Subnet(
				$ip,
				32
			);
		}
		return $this->getIPv6Subnet(
			$ip,
			128
		);
	}

	/**
	 * Register a failed attempt to bruteforce a security control
	 *
	 * @param string $action
	 * @param string $ip
	 * @param array $metadata Optional metadata logged to the database
	 */
	public function registerAttempt($action,
									$ip,
									array $metadata = []) {
		// No need to log if the bruteforce protection is disabled
		if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
			return;
		}

		$values = [
			'action' => $action,
			'occurred' => $this->timeFactory->getTime(),
			'ip' => $ip,
			'subnet' => $this->getSubnet($ip),
			'metadata' => json_encode($metadata),
		];

		$this->logger->notice(
			sprintf(
				'Bruteforce attempt from "%s" detected for action "%s".',
				$ip,
				$action
			),
			[
				'app' => 'core',
			]
		);

		$qb = $this->db->getQueryBuilder();
		$qb->insert('bruteforce_attempts');
		foreach($values as $column => $value) {
			$qb->setValue($column, $qb->createNamedParameter($value));
		}
		$qb->execute();
	}

	/**
	 * Get the throttling delay (in milliseconds)
	 *
	 * @param string $ip
	 * @return int
	 */
	public function getDelay($ip) {
		$cutoffTime = (new \DateTime())
			->sub($this->getCutoff(43200))
			->getTimestamp();

		$qb = $this->db->getQueryBuilder();
		$qb->select('*')
			->from('bruteforce_attempts')
			->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime)))
			->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($this->getSubnet($ip))));
		$attempts = count($qb->execute()->fetchAll());

		if ($attempts === 0) {
			return 0;
		}

		$maxDelay = 30;
		$firstDelay = 0.1;
		if ($attempts > (8 * PHP_INT_SIZE - 1))  {
			// Don't ever overflow. Just assume the maxDelay time:s
			$firstDelay = $maxDelay;
		} else {
			$firstDelay *= pow(2, $attempts);
			if ($firstDelay > $maxDelay) {
				$firstDelay = $maxDelay;
			}
		}
		return (int) \ceil($firstDelay * 1000);
	}

	/**
	 * Will sleep for the defined amount of time
	 *
	 * @param string $ip
	 */
	public function sleepDelay($ip) {
		usleep($this->getDelay($ip) * 1000);
	}
}