Passed
Push — master ( 60be72...4c6eb9 )
by Morris
12:37
created

Throttler::getAttempts()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 15
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 23
rs 9.7666
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * @copyright Copyright (c) 2016 Lukas Reschke <[email protected]>
6
 *
7
 * @author Bjoern Schiessle <[email protected]>
8
 * @author Christoph Wurst <[email protected]>
9
 * @author Lukas Reschke <[email protected]>
10
 * @author Mark Berezovsky <[email protected]>
11
 * @author Morris Jobke <[email protected]>
12
 * @author Robin Appelman <[email protected]>
13
 * @author Roeland Jago Douma <[email protected]>
14
 *
15
 * @license GNU AGPL version 3 or any later version
16
 *
17
 * This program is free software: you can redistribute it and/or modify
18
 * it under the terms of the GNU Affero General Public License as
19
 * published by the Free Software Foundation, either version 3 of the
20
 * License, or (at your option) any later version.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
 * GNU Affero General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU Affero General Public License
28
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29
 *
30
 */
31
32
namespace OC\Security\Bruteforce;
33
34
use OC\Security\Normalizer\IpAddress;
35
use OCP\AppFramework\Utility\ITimeFactory;
36
use OCP\IConfig;
37
use OCP\IDBConnection;
38
use OCP\ILogger;
39
use OCP\Security\Bruteforce\MaxDelayReached;
40
41
/**
42
 * Class Throttler implements the bruteforce protection for security actions in
43
 * Nextcloud.
44
 *
45
 * It is working by logging invalid login attempts to the database and slowing
46
 * down all login attempts from the same subnet. The max delay is 30 seconds and
47
 * the starting delay are 200 milliseconds. (after the first failed login)
48
 *
49
 * This is based on Paragonie's AirBrake for Airship CMS. You can find the original
50
 * code at https://github.com/paragonie/airship/blob/7e5bad7e3c0fbbf324c11f963fd1f80e59762606/src/Engine/Security/AirBrake.php
51
 *
52
 * @package OC\Security\Bruteforce
53
 */
54
class Throttler {
55
	public const LOGIN_ACTION = 'login';
56
	public const MAX_DELAY = 25;
57
	public const MAX_DELAY_MS = 25000; // in milliseconds
58
	public const MAX_ATTEMPTS = 10;
59
60
	/** @var IDBConnection */
61
	private $db;
62
	/** @var ITimeFactory */
63
	private $timeFactory;
64
	/** @var ILogger */
65
	private $logger;
66
	/** @var IConfig */
67
	private $config;
68
69
	/**
70
	 * @param IDBConnection $db
71
	 * @param ITimeFactory $timeFactory
72
	 * @param ILogger $logger
73
	 * @param IConfig $config
74
	 */
75
	public function __construct(IDBConnection $db,
76
								ITimeFactory $timeFactory,
77
								ILogger $logger,
78
								IConfig $config) {
79
		$this->db = $db;
80
		$this->timeFactory = $timeFactory;
81
		$this->logger = $logger;
82
		$this->config = $config;
83
	}
84
85
	/**
86
	 * Convert a number of seconds into the appropriate DateInterval
87
	 *
88
	 * @param int $expire
89
	 * @return \DateInterval
90
	 */
91
	private function getCutoff(int $expire): \DateInterval {
92
		$d1 = new \DateTime();
93
		$d2 = clone $d1;
94
		$d2->sub(new \DateInterval('PT' . $expire . 'S'));
95
		return $d2->diff($d1);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $d2->diff($d1) could return the type false which is incompatible with the type-hinted return DateInterval. Consider adding an additional type-check to rule them out.
Loading history...
96
	}
97
98
	/**
99
	 *  Calculate the cut off timestamp
100
	 *
101
	 * @param float $maxAgeHours
102
	 * @return int
103
	 */
104
	private function getCutoffTimestamp(float $maxAgeHours = 12.0): int {
105
		return (new \DateTime())
106
			->sub($this->getCutoff((int) ($maxAgeHours * 3600)))
107
			->getTimestamp();
108
	}
109
110
	/**
111
	 * Register a failed attempt to bruteforce a security control
112
	 *
113
	 * @param string $action
114
	 * @param string $ip
115
	 * @param array $metadata Optional metadata logged to the database
116
	 * @suppress SqlInjectionChecker
117
	 */
118
	public function registerAttempt(string $action,
119
									string $ip,
120
									array $metadata = []): void {
121
		// No need to log if the bruteforce protection is disabled
122
		if ($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
123
			return;
124
		}
125
126
		$ipAddress = new IpAddress($ip);
127
		$values = [
128
			'action' => $action,
129
			'occurred' => $this->timeFactory->getTime(),
130
			'ip' => (string)$ipAddress,
131
			'subnet' => $ipAddress->getSubnet(),
132
			'metadata' => json_encode($metadata),
133
		];
134
135
		$this->logger->notice(
136
			sprintf(
137
				'Bruteforce attempt from "%s" detected for action "%s".',
138
				$ip,
139
				$action
140
			),
141
			[
142
				'app' => 'core',
143
			]
144
		);
145
146
		$qb = $this->db->getQueryBuilder();
147
		$qb->insert('bruteforce_attempts');
148
		foreach ($values as $column => $value) {
149
			$qb->setValue($column, $qb->createNamedParameter($value));
150
		}
151
		$qb->execute();
152
	}
153
154
	/**
155
	 * Check if the IP is whitelisted
156
	 *
157
	 * @param string $ip
158
	 * @return bool
159
	 */
160
	private function isIPWhitelisted(string $ip): bool {
161
		if ($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
162
			return true;
163
		}
164
165
		$keys = $this->config->getAppKeys('bruteForce');
166
		$keys = array_filter($keys, function ($key) {
167
			return 0 === strpos($key, 'whitelist_');
168
		});
169
170
		if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
171
			$type = 4;
172
		} elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
173
			$type = 6;
174
		} else {
175
			return false;
176
		}
177
178
		$ip = inet_pton($ip);
179
180
		foreach ($keys as $key) {
181
			$cidr = $this->config->getAppValue('bruteForce', $key, null);
182
183
			$cx = explode('/', $cidr);
184
			$addr = $cx[0];
185
			$mask = (int)$cx[1];
186
187
			// Do not compare ipv4 to ipv6
188
			if (($type === 4 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ||
189
				($type === 6 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))) {
190
				continue;
191
			}
192
193
			$addr = inet_pton($addr);
194
195
			$valid = true;
196
			for ($i = 0; $i < $mask; $i++) {
197
				$part = ord($addr[(int)($i/8)]);
198
				$orig = ord($ip[(int)($i/8)]);
199
200
				$bitmask = 1 << (7 - ($i % 8));
201
202
				$part = $part & $bitmask;
203
				$orig = $orig & $bitmask;
204
205
				if ($part !== $orig) {
206
					$valid = false;
207
					break;
208
				}
209
			}
210
211
			if ($valid === true) {
212
				return true;
213
			}
214
		}
215
216
		return false;
217
	}
218
219
	/**
220
	 * Get the throttling delay (in milliseconds)
221
	 *
222
	 * @param string $ip
223
	 * @param string $action optionally filter by action
224
	 * @param float $maxAgeHours
225
	 * @return int
226
	 */
227
	public function getAttempts(string $ip, string $action = '', float $maxAgeHours = 12): int {
228
		$ipAddress = new IpAddress($ip);
229
		if ($this->isIPWhitelisted((string)$ipAddress)) {
230
			return 0;
231
		}
232
233
		$cutoffTime = $this->getCutoffTimestamp($maxAgeHours);
234
235
		$qb = $this->db->getQueryBuilder();
236
		$qb->select($qb->func()->count('*', 'attempts'))
237
			->from('bruteforce_attempts')
238
			->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime)))
239
			->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet())));
240
241
		if ($action !== '') {
242
			$qb->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action)));
243
		}
244
245
		$result = $qb->execute();
246
		$row = $result->fetch();
247
		$result->closeCursor();
248
249
		return (int) $row['attempts'];
250
	}
251
252
	/**
253
	 * Get the throttling delay (in milliseconds)
254
	 *
255
	 * @param string $ip
256
	 * @param string $action optionally filter by action
257
	 * @return int
258
	 */
259
	public function getDelay(string $ip, string $action = ''): int {
260
		$attempts = $this->getAttempts($ip, $action);
261
		if ($attempts === 0) {
262
			return 0;
263
		}
264
265
		$firstDelay = 0.1;
266
		if ($attempts > self::MAX_ATTEMPTS) {
267
			// Don't ever overflow. Just assume the maxDelay time:s
268
			return self::MAX_DELAY_MS;
269
		}
270
271
		$delay = $firstDelay * 2**$attempts;
272
		if ($delay > self::MAX_DELAY) {
273
			return self::MAX_DELAY_MS;
274
		}
275
		return (int) \ceil($delay * 1000);
276
	}
277
278
	/**
279
	 * Reset the throttling delay for an IP address, action and metadata
280
	 *
281
	 * @param string $ip
282
	 * @param string $action
283
	 * @param array $metadata
284
	 */
285
	public function resetDelay(string $ip, string $action, array $metadata): void {
286
		$ipAddress = new IpAddress($ip);
287
		if ($this->isIPWhitelisted((string)$ipAddress)) {
288
			return;
289
		}
290
291
		$cutoffTime = $this->getCutoffTimestamp();
292
293
		$qb = $this->db->getQueryBuilder();
294
		$qb->delete('bruteforce_attempts')
295
			->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime)))
296
			->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet())))
297
			->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action)))
298
			->andWhere($qb->expr()->eq('metadata', $qb->createNamedParameter(json_encode($metadata))));
299
300
		$qb->execute();
301
	}
302
303
	/**
304
	 * Reset the throttling delay for an IP address
305
	 *
306
	 * @param string $ip
307
	 */
308
	public function resetDelayForIP($ip) {
309
		$cutoffTime = $this->getCutoffTimestamp();
310
311
		$qb = $this->db->getQueryBuilder();
312
		$qb->delete('bruteforce_attempts')
313
			->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime)))
314
			->andWhere($qb->expr()->eq('ip', $qb->createNamedParameter($ip)));
315
316
		$qb->execute();
317
	}
318
319
	/**
320
	 * Will sleep for the defined amount of time
321
	 *
322
	 * @param string $ip
323
	 * @param string $action optionally filter by action
324
	 * @return int the time spent sleeping
325
	 */
326
	public function sleepDelay(string $ip, string $action = ''): int {
327
		$delay = $this->getDelay($ip, $action);
328
		usleep($delay * 1000);
329
		return $delay;
330
	}
331
332
	/**
333
	 * Will sleep for the defined amount of time unless maximum was reached in the last 30 minutes
334
	 * In this case a "429 Too Many Request" exception is thrown
335
	 *
336
	 * @param string $ip
337
	 * @param string $action optionally filter by action
338
	 * @return int the time spent sleeping
339
	 * @throws MaxDelayReached when reached the maximum
340
	 */
341
	public function sleepDelayOrThrowOnMax(string $ip, string $action = ''): int {
342
		$delay = $this->getDelay($ip, $action);
343
		if (($delay === self::MAX_DELAY_MS) && $this->getAttempts($ip, $action, 0.5) > self::MAX_ATTEMPTS) {
344
			// If the ip made too many attempts within the last 30 mins we don't execute anymore
345
			throw new MaxDelayReached('Reached maximum delay');
346
		}
347
		usleep($delay * 1000);
348
		return $delay;
349
	}
350
}
351