]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/security/LoginManager.php
41fa9a20ee9c4d025e6ae72f59897e9c7c3c2f17
[github/shaarli/Shaarli.git] / application / security / LoginManager.php
1 <?php
2 namespace Shaarli\Security;
3
4 use Shaarli\Config\ConfigManager;
5
6 /**
7 * User login management
8 */
9 class LoginManager
10 {
11 /** @var string Name of the cookie set after logging in **/
12 public static $STAY_SIGNED_IN_COOKIE = 'shaarli_staySignedIn';
13
14 /** @var array A reference to the $_GLOBALS array */
15 protected $globals = [];
16
17 /** @var ConfigManager Configuration Manager instance **/
18 protected $configManager = null;
19
20 /** @var SessionManager Session Manager instance **/
21 protected $sessionManager = null;
22
23 /** @var string Path to the file containing IP bans */
24 protected $banFile = '';
25
26 /** @var bool Whether the user is logged in **/
27 protected $isLoggedIn = false;
28
29 /** @var bool Whether the Shaarli instance is open to public edition **/
30 protected $openShaarli = false;
31
32 /** @var string User sign-in token depending on remote IP and credentials */
33 protected $staySignedInToken = '';
34
35 /**
36 * Constructor
37 *
38 * @param array $globals The $GLOBALS array (reference)
39 * @param ConfigManager $configManager Configuration Manager instance
40 * @param SessionManager $sessionManager SessionManager instance
41 */
42 public function __construct(& $globals, $configManager, $sessionManager)
43 {
44 $this->globals = &$globals;
45 $this->configManager = $configManager;
46 $this->sessionManager = $sessionManager;
47 $this->banFile = $this->configManager->get('resource.ban_file', 'data/ipbans.php');
48 $this->readBanFile();
49 if ($this->configManager->get('security.open_shaarli')) {
50 $this->openShaarli = true;
51 }
52 }
53
54 /**
55 * Generate a token depending on deployment salt, user password and client IP
56 *
57 * @param string $clientIpAddress The remote client IP address
58 */
59 public function generateStaySignedInToken($clientIpAddress)
60 {
61 $this->staySignedInToken = sha1(
62 $this->configManager->get('credentials.hash')
63 . $clientIpAddress
64 . $this->configManager->get('credentials.salt')
65 );
66 }
67
68 /**
69 * Return the user's client stay-signed-in token
70 *
71 * @return string User's client stay-signed-in token
72 */
73 public function getStaySignedInToken()
74 {
75 return $this->staySignedInToken;
76 }
77
78 /**
79 * Check user session state and validity (expiration)
80 *
81 * @param array $cookie The $_COOKIE array
82 * @param string $clientIpId Client IP address identifier
83 *
84 * @return bool true if the user session is valid, false otherwise
85 */
86 public function checkLoginState($cookie, $clientIpId)
87 {
88 if (! $this->configManager->exists('credentials.login')) {
89 // Shaarli is not configured yet
90 $this->isLoggedIn = false;
91 return;
92 }
93
94 if (isset($cookie[self::$STAY_SIGNED_IN_COOKIE])
95 && $cookie[self::$STAY_SIGNED_IN_COOKIE] === $this->staySignedInToken
96 ) {
97 $this->sessionManager->storeLoginInfo($clientIpId);
98 $this->isLoggedIn = true;
99 }
100
101 if ($this->sessionManager->hasSessionExpired()
102 || $this->sessionManager->hasClientIpChanged($clientIpId)
103 ) {
104 $this->sessionManager->logout();
105 $this->isLoggedIn = false;
106 return;
107 }
108
109 $this->sessionManager->extendSession();
110 }
111
112 /**
113 * Return whether the user is currently logged in
114 *
115 * @return true when the user is logged in, false otherwise
116 */
117 public function isLoggedIn()
118 {
119 if ($this->openShaarli) {
120 return true;
121 }
122 return $this->isLoggedIn;
123 }
124
125 /**
126 * Check user credentials are valid
127 *
128 * @param string $remoteIp Remote client IP address
129 * @param string $clientIpId Client IP address identifier
130 * @param string $login Username
131 * @param string $password Password
132 *
133 * @return bool true if the provided credentials are valid, false otherwise
134 */
135 public function checkCredentials($remoteIp, $clientIpId, $login, $password)
136 {
137 $hash = sha1($password . $login . $this->configManager->get('credentials.salt'));
138
139 if ($login != $this->configManager->get('credentials.login')
140 || $hash != $this->configManager->get('credentials.hash')
141 ) {
142 logm(
143 $this->configManager->get('resource.log'),
144 $remoteIp,
145 'Login failed for user ' . $login
146 );
147 return false;
148 }
149
150 $this->sessionManager->storeLoginInfo($clientIpId);
151 logm(
152 $this->configManager->get('resource.log'),
153 $remoteIp,
154 'Login successful'
155 );
156 return true;
157 }
158
159 /**
160 * Read a file containing banned IPs
161 */
162 protected function readBanFile()
163 {
164 if (! file_exists($this->banFile)) {
165 return;
166 }
167 include $this->banFile;
168 }
169
170 /**
171 * Write the banned IPs to a file
172 */
173 protected function writeBanFile()
174 {
175 if (! array_key_exists('IPBANS', $this->globals)) {
176 return;
177 }
178 file_put_contents(
179 $this->banFile,
180 "<?php\n\$GLOBALS['IPBANS']=" . var_export($this->globals['IPBANS'], true) . ";\n?>"
181 );
182 }
183
184 /**
185 * Handle a failed login and ban the IP after too many failed attempts
186 *
187 * @param array $server The $_SERVER array
188 */
189 public function handleFailedLogin($server)
190 {
191 $ip = $server['REMOTE_ADDR'];
192 $trusted = $this->configManager->get('security.trusted_proxies', []);
193
194 if (in_array($ip, $trusted)) {
195 $ip = getIpAddressFromProxy($server, $trusted);
196 if (! $ip) {
197 // the IP is behind a trusted forward proxy, but is not forwarded
198 // in the HTTP headers, so we do nothing
199 return;
200 }
201 }
202
203 // increment the fail count for this IP
204 if (isset($this->globals['IPBANS']['FAILURES'][$ip])) {
205 $this->globals['IPBANS']['FAILURES'][$ip]++;
206 } else {
207 $this->globals['IPBANS']['FAILURES'][$ip] = 1;
208 }
209
210 if ($this->globals['IPBANS']['FAILURES'][$ip] >= $this->configManager->get('security.ban_after')) {
211 $this->globals['IPBANS']['BANS'][$ip] = time() + $this->configManager->get('security.ban_duration', 1800);
212 logm(
213 $this->configManager->get('resource.log'),
214 $server['REMOTE_ADDR'],
215 'IP address banned from login'
216 );
217 }
218 $this->writeBanFile();
219 }
220
221 /**
222 * Handle a successful login
223 *
224 * @param array $server The $_SERVER array
225 */
226 public function handleSuccessfulLogin($server)
227 {
228 $ip = $server['REMOTE_ADDR'];
229 // FIXME unban when behind a trusted proxy?
230
231 unset($this->globals['IPBANS']['FAILURES'][$ip]);
232 unset($this->globals['IPBANS']['BANS'][$ip]);
233
234 $this->writeBanFile();
235 }
236
237 /**
238 * Check if the user can login from this IP
239 *
240 * @param array $server The $_SERVER array
241 *
242 * @return bool true if the user is allowed to login
243 */
244 public function canLogin($server)
245 {
246 $ip = $server['REMOTE_ADDR'];
247
248 if (! isset($this->globals['IPBANS']['BANS'][$ip])) {
249 // the user is not banned
250 return true;
251 }
252
253 if ($this->globals['IPBANS']['BANS'][$ip] > time()) {
254 // the user is still banned
255 return false;
256 }
257
258 // the ban has expired, the user can attempt to log in again
259 logm($this->configManager->get('resource.log'), $server['REMOTE_ADDR'], 'Ban lifted.');
260 unset($this->globals['IPBANS']['FAILURES'][$ip]);
261 unset($this->globals['IPBANS']['BANS'][$ip]);
262
263 $this->writeBanFile();
264 return true;
265 }
266 }