2 namespace Shaarli\Security
;
4 use Shaarli\Config\ConfigManager
;
7 * User login management
11 /** @var string Name of the cookie set after logging in **/
12 public static $STAY_SIGNED_IN_COOKIE = 'shaarli_staySignedIn';
14 /** @var array A reference to the $_GLOBALS array */
15 protected $globals = [];
17 /** @var ConfigManager Configuration Manager instance **/
18 protected $configManager = null;
20 /** @var SessionManager Session Manager instance **/
21 protected $sessionManager = null;
23 /** @var string Path to the file containing IP bans */
24 protected $banFile = '';
26 /** @var bool Whether the user is logged in **/
27 protected $isLoggedIn = false;
29 /** @var bool Whether the Shaarli instance is open to public edition **/
30 protected $openShaarli = false;
32 /** @var string User sign-in token depending on remote IP and credentials */
33 protected $staySignedInToken = '';
35 protected $lastErrorReason = '';
36 protected $lastErrorIsBanishable = false;
41 * @param array $globals The $GLOBALS array (reference)
42 * @param ConfigManager $configManager Configuration Manager instance
43 * @param SessionManager $sessionManager SessionManager instance
45 public function __construct(& $globals, $configManager, $sessionManager)
47 $this->globals
= &$globals;
48 $this->configManager
= $configManager;
49 $this->sessionManager
= $sessionManager;
50 $this->banFile
= $this->configManager
->get('resource.ban_file', 'data/ipbans.php');
52 if ($this->configManager
->get('security.open_shaarli') === true) {
53 $this->openShaarli
= true;
58 * Generate a token depending on deployment salt, user password and client IP
60 * @param string $clientIpAddress The remote client IP address
62 public function generateStaySignedInToken($clientIpAddress)
64 $this->staySignedInToken
= sha1(
65 $this->configManager
->get('credentials.hash')
67 . $this->configManager
->get('credentials.salt')
72 * Return the user's client stay-signed-in token
74 * @return string User's client stay-signed-in token
76 public function getStaySignedInToken()
78 return $this->staySignedInToken
;
82 * Check user session state and validity (expiration)
84 * @param array $cookie The $_COOKIE array
85 * @param string $clientIpId Client IP address identifier
87 public function checkLoginState($cookie, $clientIpId)
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;
95 if (isset($cookie[self
::$STAY_SIGNED_IN_COOKIE])
96 && $cookie[self
::$STAY_SIGNED_IN_COOKIE] === $this->staySignedInToken
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);
102 } elseif ($this->sessionManager
->hasSessionExpired()
103 || $this->sessionManager
->hasClientIpChanged($clientIpId)
105 $this->sessionManager
->logout();
106 $this->isLoggedIn
= false;
110 $this->isLoggedIn
= true;
111 $this->sessionManager
->extendSession();
115 * Return whether the user is currently logged in
117 * @return true when the user is logged in, false otherwise
119 public function isLoggedIn()
121 if ($this->openShaarli
) {
124 return $this->isLoggedIn
;
128 * Check user credentials are valid
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
135 * @return bool true if the provided credentials are valid, false otherwise
137 public function checkCredentials($remoteIp, $clientIpId, $login, $password)
139 $this->lastErrorIsBanishable
= false;
141 if ($this->configManager
->getUserSpace() !== null && $this->configManager
->getUserSpace() !== $login) {
142 logm($this->configManager
->get('resource.log'),
144 'Trying to login to wrong user space');
145 $this->lastErrorReason
= 'You’re trying to access the wrong account.';
149 logm($this->configManager
->get('resource.log'),
151 'Trying LDAP connection');
152 $result = $this->configManager
->findLDAPUser($login, $password);
153 if ($result === false) {
155 $this->configManager
->get('resource.log'),
157 'Impossible to connect to LDAP'
159 $this->lastErrorReason
= 'Server error.';
161 } else if (is_null($result)) {
163 $this->configManager
->get('resource.log'),
165 'Login failed for user ' . $login
167 $this->lastErrorIsBanishable
= true;
168 $this->lastErrorReason
= 'Wrong login/password.';
172 $this->sessionManager
->storeLoginInfo($clientIpId, $login);
174 $this->configManager
->get('resource.log'),
182 * Read a file containing banned IPs
184 protected function readBanFile()
186 if (! file_exists($this->banFile
)) {
189 include $this->banFile
;
193 * Write the banned IPs to a file
195 protected function writeBanFile()
197 if (! array_key_exists('IPBANS', $this->globals
)) {
202 "<?php\n\$GLOBALS['IPBANS']=" . var_export($this->globals
['IPBANS'], true) . ";\n?>"
207 * Handle a failed login and ban the IP after too many failed attempts
209 * @param array $server The $_SERVER array
211 public function handleFailedLogin($server)
213 if (!$this->lastErrorIsBanishable
) {
214 return $this->lastErrorReason
?: 'Error during login.';
217 $ip = $server['REMOTE_ADDR'];
218 $trusted = $this->configManager
->get('security.trusted_proxies', []);
220 if (in_array($ip, $trusted)) {
221 $ip = getIpAddressFromProxy($server, $trusted);
223 // the IP is behind a trusted forward proxy, but is not forwarded
224 // in the HTTP headers, so we do nothing
229 // increment the fail count for this IP
230 if (isset($this->globals
['IPBANS']['FAILURES'][$ip])) {
231 $this->globals
['IPBANS']['FAILURES'][$ip]++
;
233 $this->globals
['IPBANS']['FAILURES'][$ip] = 1;
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);
239 $this->configManager
->get('resource.log'),
240 $server['REMOTE_ADDR'],
241 'IP address banned from login'
244 $this->writeBanFile();
245 return $this->lastErrorReason
?: 'Error during login.';
249 * Handle a successful login
251 * @param array $server The $_SERVER array
253 public function handleSuccessfulLogin($server)
255 $ip = $server['REMOTE_ADDR'];
256 // FIXME unban when behind a trusted proxy?
258 unset($this->globals
['IPBANS']['FAILURES'][$ip]);
259 unset($this->globals
['IPBANS']['BANS'][$ip]);
261 $this->writeBanFile();
265 * Check if the user can login from this IP
267 * @param array $server The $_SERVER array
269 * @return bool true if the user is allowed to login
271 public function canLogin($server)
273 $ip = $server['REMOTE_ADDR'];
275 if (! isset($this->globals
['IPBANS']['BANS'][$ip])) {
276 // the user is not banned
280 if ($this->globals
['IPBANS']['BANS'][$ip] > time()) {
281 // the user is still banned
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]);
290 $this->writeBanFile();