]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/security/LoginManager.php
Add ldap connection
[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 protected $lastErrorReason = '';
36 protected $lastErrorIsBanishable = false;
37
38 /**
39 * Constructor
40 *
41 * @param array $globals The $GLOBALS array (reference)
42 * @param ConfigManager $configManager Configuration Manager instance
43 * @param SessionManager $sessionManager SessionManager instance
44 */
45 public function __construct(& $globals, $configManager, $sessionManager)
46 {
47 $this->globals = &$globals;
48 $this->configManager = $configManager;
49 $this->sessionManager = $sessionManager;
50 $this->banFile = $this->configManager->get('resource.ban_file', 'data/ipbans.php');
51 $this->readBanFile();
52 if ($this->configManager->get('security.open_shaarli') === true) {
53 $this->openShaarli = true;
54 }
55 }
56
57 /**
58 * Generate a token depending on deployment salt, user password and client IP
59 *
60 * @param string $clientIpAddress The remote client IP address
61 */
62 public function generateStaySignedInToken($clientIpAddress)
63 {
64 $this->staySignedInToken = sha1(
65 $this->configManager->get('credentials.hash')
66 . $clientIpAddress
67 . $this->configManager->get('credentials.salt')
68 );
69 }
70
71 /**
72 * Return the user's client stay-signed-in token
73 *
74 * @return string User's client stay-signed-in token
75 */
76 public function getStaySignedInToken()
77 {
78 return $this->staySignedInToken;
79 }
80
81 /**
82 * Check user session state and validity (expiration)
83 *
84 * @param array $cookie The $_COOKIE array
85 * @param string $clientIpId Client IP address identifier
86 */
87 public function checkLoginState($cookie, $clientIpId)
88 {
89 if (! $this->configManager->exists('credentials.login') || (isset($_SESSION['username']) && $_SESSION['username'] && $this->configManager->get('credentials.login') !== $_SESSION['username'])) {
90 // Shaarli is not configured yet
91 $this->isLoggedIn = false;
92 return;
93 }
94
95 if (isset($cookie[self::$STAY_SIGNED_IN_COOKIE])
96 && $cookie[self::$STAY_SIGNED_IN_COOKIE] === $this->staySignedInToken
97 ) {
98 // The user client has a valid stay-signed-in cookie
99 // Session information is updated with the current client information
100 $this->sessionManager->storeLoginInfo($clientIpId);
101
102 } elseif ($this->sessionManager->hasSessionExpired()
103 || $this->sessionManager->hasClientIpChanged($clientIpId)
104 ) {
105 $this->sessionManager->logout();
106 $this->isLoggedIn = false;
107 return;
108 }
109
110 $this->isLoggedIn = true;
111 $this->sessionManager->extendSession();
112 }
113
114 /**
115 * Return whether the user is currently logged in
116 *
117 * @return true when the user is logged in, false otherwise
118 */
119 public function isLoggedIn()
120 {
121 if ($this->openShaarli) {
122 return true;
123 }
124 return $this->isLoggedIn;
125 }
126
127 /**
128 * Check user credentials are valid
129 *
130 * @param string $remoteIp Remote client IP address
131 * @param string $clientIpId Client IP address identifier
132 * @param string $login Username
133 * @param string $password Password
134 *
135 * @return bool true if the provided credentials are valid, false otherwise
136 */
137 public function checkCredentials($remoteIp, $clientIpId, $login, $password)
138 {
139 $this->lastErrorIsBanishable = false;
140
141 if ($this->configManager->getUserSpace() !== null && $this->configManager->getUserSpace() !== $login) {
142 logm($this->configManager->get('resource.log'),
143 $remoteIp,
144 'Trying to login to wrong user space');
145 $this->lastErrorReason = 'You’re trying to access the wrong account.';
146 return false;
147 }
148
149 logm($this->configManager->get('resource.log'),
150 $remoteIp,
151 'Trying LDAP connection');
152 $result = $this->configManager->findLDAPUser($login, $password);
153 if ($result === false) {
154 logm(
155 $this->configManager->get('resource.log'),
156 $remoteIp,
157 'Impossible to connect to LDAP'
158 );
159 $this->lastErrorReason = 'Server error.';
160 return false;
161 } else if (is_null($result)) {
162 logm(
163 $this->configManager->get('resource.log'),
164 $remoteIp,
165 'Login failed for user ' . $login
166 );
167 $this->lastErrorIsBanishable = true;
168 $this->lastErrorReason = 'Wrong login/password.';
169 return false;
170 }
171
172 $this->sessionManager->storeLoginInfo($clientIpId, $login);
173 logm(
174 $this->configManager->get('resource.log'),
175 $remoteIp,
176 'Login successful'
177 );
178 return true;
179 }
180
181 /**
182 * Read a file containing banned IPs
183 */
184 protected function readBanFile()
185 {
186 if (! file_exists($this->banFile)) {
187 return;
188 }
189 include $this->banFile;
190 }
191
192 /**
193 * Write the banned IPs to a file
194 */
195 protected function writeBanFile()
196 {
197 if (! array_key_exists('IPBANS', $this->globals)) {
198 return;
199 }
200 file_put_contents(
201 $this->banFile,
202 "<?php\n\$GLOBALS['IPBANS']=" . var_export($this->globals['IPBANS'], true) . ";\n?>"
203 );
204 }
205
206 /**
207 * Handle a failed login and ban the IP after too many failed attempts
208 *
209 * @param array $server The $_SERVER array
210 */
211 public function handleFailedLogin($server)
212 {
213 if (!$this->lastErrorIsBanishable) {
214 return $this->lastErrorReason ?: 'Error during login.';
215 };
216
217 $ip = $server['REMOTE_ADDR'];
218 $trusted = $this->configManager->get('security.trusted_proxies', []);
219
220 if (in_array($ip, $trusted)) {
221 $ip = getIpAddressFromProxy($server, $trusted);
222 if (! $ip) {
223 // the IP is behind a trusted forward proxy, but is not forwarded
224 // in the HTTP headers, so we do nothing
225 return;
226 }
227 }
228
229 // increment the fail count for this IP
230 if (isset($this->globals['IPBANS']['FAILURES'][$ip])) {
231 $this->globals['IPBANS']['FAILURES'][$ip]++;
232 } else {
233 $this->globals['IPBANS']['FAILURES'][$ip] = 1;
234 }
235
236 if ($this->globals['IPBANS']['FAILURES'][$ip] >= $this->configManager->get('security.ban_after')) {
237 $this->globals['IPBANS']['BANS'][$ip] = time() + $this->configManager->get('security.ban_duration', 1800);
238 logm(
239 $this->configManager->get('resource.log'),
240 $server['REMOTE_ADDR'],
241 'IP address banned from login'
242 );
243 }
244 $this->writeBanFile();
245 return $this->lastErrorReason ?: 'Error during login.';
246 }
247
248 /**
249 * Handle a successful login
250 *
251 * @param array $server The $_SERVER array
252 */
253 public function handleSuccessfulLogin($server)
254 {
255 $ip = $server['REMOTE_ADDR'];
256 // FIXME unban when behind a trusted proxy?
257
258 unset($this->globals['IPBANS']['FAILURES'][$ip]);
259 unset($this->globals['IPBANS']['BANS'][$ip]);
260
261 $this->writeBanFile();
262 }
263
264 /**
265 * Check if the user can login from this IP
266 *
267 * @param array $server The $_SERVER array
268 *
269 * @return bool true if the user is allowed to login
270 */
271 public function canLogin($server)
272 {
273 $ip = $server['REMOTE_ADDR'];
274
275 if (! isset($this->globals['IPBANS']['BANS'][$ip])) {
276 // the user is not banned
277 return true;
278 }
279
280 if ($this->globals['IPBANS']['BANS'][$ip] > time()) {
281 // the user is still banned
282 return false;
283 }
284
285 // the ban has expired, the user can attempt to log in again
286 logm($this->configManager->get('resource.log'), $server['REMOTE_ADDR'], 'Ban lifted.');
287 unset($this->globals['IPBANS']['FAILURES'][$ip]);
288 unset($this->globals['IPBANS']['BANS'][$ip]);
289
290 $this->writeBanFile();
291 return true;
292 }
293 }