aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/security
diff options
context:
space:
mode:
Diffstat (limited to 'application/security')
-rw-r--r--application/security/BanManager.php213
-rw-r--r--application/security/LoginManager.php103
2 files changed, 230 insertions, 86 deletions
diff --git a/application/security/BanManager.php b/application/security/BanManager.php
new file mode 100644
index 00000000..68190c54
--- /dev/null
+++ b/application/security/BanManager.php
@@ -0,0 +1,213 @@
1<?php
2
3
4namespace Shaarli\Security;
5
6use Shaarli\FileUtils;
7
8/**
9 * Class BanManager
10 *
11 * Failed login attempts will store the associated IP address.
12 * After N failed attempts, the IP will be prevented from log in for duration D.
13 * Both N and D can be set in the configuration file.
14 *
15 * @package Shaarli\Security
16 */
17class BanManager
18{
19 /** @var array List of allowed proxies IP */
20 protected $trustedProxies;
21
22 /** @var int Number of allowed failed attempt before the ban */
23 protected $nbAttempts;
24
25 /** @var int Ban duration in seconds */
26 protected $banDuration;
27
28 /** @var string Path to the file containing IP bans and failures */
29 protected $banFile;
30
31 /** @var string Path to the log file, used to log bans */
32 protected $logFile;
33
34 /** @var array List of IP with their associated number of failed attempts */
35 protected $failures = [];
36
37 /** @var array List of banned IP with their associated unban timestamp */
38 protected $bans = [];
39
40 /**
41 * BanManager constructor.
42 *
43 * @param array $trustedProxies List of allowed proxies IP
44 * @param int $nbAttempts Number of allowed failed attempt before the ban
45 * @param int $banDuration Ban duration in seconds
46 * @param string $banFile Path to the file containing IP bans and failures
47 * @param string $logFile Path to the log file, used to log bans
48 */
49 public function __construct($trustedProxies, $nbAttempts, $banDuration, $banFile, $logFile) {
50 $this->trustedProxies = $trustedProxies;
51 $this->nbAttempts = $nbAttempts;
52 $this->banDuration = $banDuration;
53 $this->banFile = $banFile;
54 $this->logFile = $logFile;
55 $this->readBanFile();
56 }
57
58 /**
59 * Handle a failed login and ban the IP after too many failed attempts
60 *
61 * @param array $server The $_SERVER array
62 */
63 public function handleFailedAttempt($server)
64 {
65 $ip = $this->getIp($server);
66 // the IP is behind a trusted forward proxy, but is not forwarded
67 // in the HTTP headers, so we do nothing
68 if (empty($ip)) {
69 return;
70 }
71
72 // increment the fail count for this IP
73 if (isset($this->failures[$ip])) {
74 $this->failures[$ip]++;
75 } else {
76 $this->failures[$ip] = 1;
77 }
78
79 if ($this->failures[$ip] >= $this->nbAttempts) {
80 $this->bans[$ip] = time() + $this->banDuration;
81 logm(
82 $this->logFile,
83 $server['REMOTE_ADDR'],
84 'IP address banned from login: '. $ip
85 );
86 }
87 $this->writeBanFile();
88 }
89
90 /**
91 * Remove failed attempts for the provided client.
92 *
93 * @param array $server $_SERVER
94 */
95 public function clearFailures($server)
96 {
97 $ip = $this->getIp($server);
98 // the IP is behind a trusted forward proxy, but is not forwarded
99 // in the HTTP headers, so we do nothing
100 if (empty($ip)) {
101 return;
102 }
103
104 if (isset($this->failures[$ip])) {
105 unset($this->failures[$ip]);
106 }
107 $this->writeBanFile();
108 }
109
110 /**
111 * Check whether the client IP is banned or not.
112 *
113 * @param array $server $_SERVER
114 *
115 * @return bool True if the IP is banned, false otherwise
116 */
117 public function isBanned($server)
118 {
119 $ip = $this->getIp($server);
120 // the IP is behind a trusted forward proxy, but is not forwarded
121 // in the HTTP headers, so we allow the authentication attempt.
122 if (empty($ip)) {
123 return false;
124 }
125
126 // the user is not banned
127 if (! isset($this->bans[$ip])) {
128 return false;
129 }
130
131 // the user is still banned
132 if ($this->bans[$ip] > time()) {
133 return true;
134 }
135
136 // the ban has expired, the user can attempt to log in again
137 if (isset($this->failures[$ip])) {
138 unset($this->failures[$ip]);
139 }
140 unset($this->bans[$ip]);
141 logm($this->logFile, $server['REMOTE_ADDR'], 'Ban lifted for: '. $ip);
142
143 $this->writeBanFile();
144 return false;
145 }
146
147 /**
148 * Retrieve the IP from $_SERVER.
149 * If the actual IP is behind an allowed reverse proxy,
150 * we try to extract the forwarded IP from HTTP headers.
151 *
152 * @param array $server $_SERVER
153 *
154 * @return string|bool The IP or false if none could be extracted
155 */
156 protected function getIp($server)
157 {
158 $ip = $server['REMOTE_ADDR'];
159 if (! in_array($ip, $this->trustedProxies)) {
160 return $ip;
161 }
162 return getIpAddressFromProxy($server, $this->trustedProxies);
163 }
164
165 /**
166 * Read a file containing banned IPs
167 */
168 protected function readBanFile()
169 {
170 $data = FileUtils::readFlatDB($this->banFile);
171 if (isset($data['failures']) && is_array($data['failures'])) {
172 $this->failures = $data['failures'];
173 }
174
175 if (isset($data['bans']) && is_array($data['bans'])) {
176 $this->bans = $data['bans'];
177 }
178 }
179
180 /**
181 * Write the banned IPs to a file
182 */
183 protected function writeBanFile()
184 {
185 return FileUtils::writeFlatDB(
186 $this->banFile,
187 [
188 'failures' => $this->failures,
189 'bans' => $this->bans,
190 ]
191 );
192 }
193
194 /**
195 * Get the Failures (for UT purpose).
196 *
197 * @return array
198 */
199 public function getFailures()
200 {
201 return $this->failures;
202 }
203
204 /**
205 * Get the Bans (for UT purpose).
206 *
207 * @return array
208 */
209 public function getBans()
210 {
211 return $this->bans;
212 }
213}
diff --git a/application/security/LoginManager.php b/application/security/LoginManager.php
index 0f315483..0b0ce0b1 100644
--- a/application/security/LoginManager.php
+++ b/application/security/LoginManager.php
@@ -20,8 +20,8 @@ class LoginManager
20 /** @var SessionManager Session Manager instance **/ 20 /** @var SessionManager Session Manager instance **/
21 protected $sessionManager = null; 21 protected $sessionManager = null;
22 22
23 /** @var string Path to the file containing IP bans */ 23 /** @var BanManager Ban Manager instance **/
24 protected $banFile = ''; 24 protected $banManager;
25 25
26 /** @var bool Whether the user is logged in **/ 26 /** @var bool Whether the user is logged in **/
27 protected $isLoggedIn = false; 27 protected $isLoggedIn = false;
@@ -35,17 +35,21 @@ class LoginManager
35 /** 35 /**
36 * Constructor 36 * Constructor
37 * 37 *
38 * @param array $globals The $GLOBALS array (reference)
39 * @param ConfigManager $configManager Configuration Manager instance 38 * @param ConfigManager $configManager Configuration Manager instance
40 * @param SessionManager $sessionManager SessionManager instance 39 * @param SessionManager $sessionManager SessionManager instance
41 */ 40 */
42 public function __construct(& $globals, $configManager, $sessionManager) 41 public function __construct($configManager, $sessionManager)
43 { 42 {
44 $this->globals = &$globals;
45 $this->configManager = $configManager; 43 $this->configManager = $configManager;
46 $this->sessionManager = $sessionManager; 44 $this->sessionManager = $sessionManager;
47 $this->banFile = $this->configManager->get('resource.ban_file', 'data/ipbans.php'); 45 $this->banManager = new BanManager(
48 $this->readBanFile(); 46 $this->configManager->get('security.trusted_proxies', []),
47 $this->configManager->get('security.ban_after'),
48 $this->configManager->get('security.ban_duration'),
49 $this->configManager->get('resource.ban_file', 'data/ipbans.php'),
50 $this->configManager->get('resource.log')
51 );
52
49 if ($this->configManager->get('security.open_shaarli') === true) { 53 if ($this->configManager->get('security.open_shaarli') === true) {
50 $this->openShaarli = true; 54 $this->openShaarli = true;
51 } 55 }
@@ -58,6 +62,9 @@ class LoginManager
58 */ 62 */
59 public function generateStaySignedInToken($clientIpAddress) 63 public function generateStaySignedInToken($clientIpAddress)
60 { 64 {
65 if ($this->configManager->get('security.session_protection_disabled') === true) {
66 $clientIpAddress = '';
67 }
61 $this->staySignedInToken = sha1( 68 $this->staySignedInToken = sha1(
62 $this->configManager->get('credentials.hash') 69 $this->configManager->get('credentials.hash')
63 . $clientIpAddress 70 . $clientIpAddress
@@ -155,65 +162,13 @@ class LoginManager
155 } 162 }
156 163
157 /** 164 /**
158 * Read a file containing banned IPs
159 */
160 protected function readBanFile()
161 {
162 if (! file_exists($this->banFile)) {
163 return;
164 }
165 include $this->banFile;
166 }
167
168 /**
169 * Write the banned IPs to a file
170 */
171 protected function writeBanFile()
172 {
173 if (! array_key_exists('IPBANS', $this->globals)) {
174 return;
175 }
176 file_put_contents(
177 $this->banFile,
178 "<?php\n\$GLOBALS['IPBANS']=" . var_export($this->globals['IPBANS'], true) . ";\n?>"
179 );
180 }
181
182 /**
183 * Handle a failed login and ban the IP after too many failed attempts 165 * Handle a failed login and ban the IP after too many failed attempts
184 * 166 *
185 * @param array $server The $_SERVER array 167 * @param array $server The $_SERVER array
186 */ 168 */
187 public function handleFailedLogin($server) 169 public function handleFailedLogin($server)
188 { 170 {
189 $ip = $server['REMOTE_ADDR']; 171 $this->banManager->handleFailedAttempt($server);
190 $trusted = $this->configManager->get('security.trusted_proxies', []);
191
192 if (in_array($ip, $trusted)) {
193 $ip = getIpAddressFromProxy($server, $trusted);
194 if (! $ip) {
195 // the IP is behind a trusted forward proxy, but is not forwarded
196 // in the HTTP headers, so we do nothing
197 return;
198 }
199 }
200
201 // increment the fail count for this IP
202 if (isset($this->globals['IPBANS']['FAILURES'][$ip])) {
203 $this->globals['IPBANS']['FAILURES'][$ip]++;
204 } else {
205 $this->globals['IPBANS']['FAILURES'][$ip] = 1;
206 }
207
208 if ($this->globals['IPBANS']['FAILURES'][$ip] >= $this->configManager->get('security.ban_after')) {
209 $this->globals['IPBANS']['BANS'][$ip] = time() + $this->configManager->get('security.ban_duration', 1800);
210 logm(
211 $this->configManager->get('resource.log'),
212 $server['REMOTE_ADDR'],
213 'IP address banned from login'
214 );
215 }
216 $this->writeBanFile();
217 } 172 }
218 173
219 /** 174 /**
@@ -223,13 +178,7 @@ class LoginManager
223 */ 178 */
224 public function handleSuccessfulLogin($server) 179 public function handleSuccessfulLogin($server)
225 { 180 {
226 $ip = $server['REMOTE_ADDR']; 181 $this->banManager->clearFailures($server);
227 // FIXME unban when behind a trusted proxy?
228
229 unset($this->globals['IPBANS']['FAILURES'][$ip]);
230 unset($this->globals['IPBANS']['BANS'][$ip]);
231
232 $this->writeBanFile();
233 } 182 }
234 183
235 /** 184 /**
@@ -241,24 +190,6 @@ class LoginManager
241 */ 190 */
242 public function canLogin($server) 191 public function canLogin($server)
243 { 192 {
244 $ip = $server['REMOTE_ADDR']; 193 return ! $this->banManager->isBanned($server);
245
246 if (! isset($this->globals['IPBANS']['BANS'][$ip])) {
247 // the user is not banned
248 return true;
249 }
250
251 if ($this->globals['IPBANS']['BANS'][$ip] > time()) {
252 // the user is still banned
253 return false;
254 }
255
256 // the ban has expired, the user can attempt to log in again
257 logm($this->configManager->get('resource.log'), $server['REMOTE_ADDR'], 'Ban lifted.');
258 unset($this->globals['IPBANS']['FAILURES'][$ip]);
259 unset($this->globals['IPBANS']['BANS'][$ip]);
260
261 $this->writeBanFile();
262 return true;
263 } 194 }
264} 195}