summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Web/RememberMe.php
blob: 10023960c5369b3d02cf97183a6d17aa8c2d6b5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
<?php
/* Icinga Web 2 | (c) 2021 Icinga GmbH | GPLv2+ */

namespace Icinga\Web;

use Icinga\Application\Config;
use Icinga\Authentication\Auth;
use Icinga\Crypt\AesCrypt;
use Icinga\Common\Database;
use Icinga\User;
use ipl\Sql\Expression;
use ipl\Sql\Select;
use RuntimeException;

/**
 * Remember me component
 *
 * Retains credentials for 30 days by default in order to stay signed in even after the session is closed.
 */
class RememberMe
{
    use Database;

    /** @var string Cookie name */
    const COOKIE = 'icingaweb2-remember-me';

    /** @var string Database table name */
    const TABLE = 'icingaweb_rememberme';

    /** @var string Encrypted password of the user */
    protected $encryptedPassword;

    /** @var string */
    protected $username;

    /** @var AesCrypt Instance for encrypting/decrypting the credentials */
    protected $aesCrypt;

    /** @var int Timestamp when the remember me cookie expires */
    protected $expiresAt;

    /**
     * Get whether staying logged in is possible
     *
     * @return bool
     */
    public static function isSupported()
    {
        $self = new self();

        if (! $self->hasDb()) {
            return false;
        }

        try {
            (new AesCrypt())->getMethod();
        } catch (RuntimeException $_) {
            return false;
        }

        return true;
    }

    /**
     * Get whether the remember cookie is set
     *
     * @return bool
     */
    public static function hasCookie()
    {
        return isset($_COOKIE[static::COOKIE]);
    }

    /**
     * Remove the database entry if exists and unset the remember me cookie from PHP's `$_COOKIE` superglobal
     *
     * @return Cookie The invalidation cookie which has to be sent to client in oder to remove the remember me cookie
     */
    public static function forget()
    {
        if (self::hasCookie()) {
            $data = explode('|', $_COOKIE[static::COOKIE]);
            $iv = base64_decode(array_pop($data));
            (new self())->remove(bin2hex($iv));
        }

        unset($_COOKIE[static::COOKIE]);

        return (new Cookie(static::COOKIE))
            ->setHttpOnly(true)
            ->forgetMe();
    }

    /**
     * Create the remember me component from the remember me cookie
     *
     * @return static
     */
    public static function fromCookie()
    {
        $data = explode('|', $_COOKIE[static::COOKIE]);
        $iv = base64_decode(array_pop($data));

        $select = (new Select())
            ->from(static::TABLE)
            ->columns('*')
            ->where(['random_iv = ?' => bin2hex($iv)]);

        $rememberMe = new static();
        $rs = $rememberMe->getDb()->select($select)->fetch();

        if (! $rs) {
            throw new RuntimeException(sprintf(
                "No database entry found for IV '%s'",
                bin2hex($iv)
            ));
        }

        $rememberMe->aesCrypt = (new AesCrypt())
            ->setKey(hex2bin($rs->passphrase))
            ->setIV($iv);

        if (count($data) > 1) {
            $rememberMe->aesCrypt->setTag(
                base64_decode(array_pop($data))
            );
        } elseif ($rememberMe->aesCrypt->isAuthenticatedEncryptionRequired()) {
            throw new RuntimeException(
                "The given decryption method needs a tag, but is not specified. "
                . "You have probably updated the PHP version."
            );
        }

        $rememberMe->username = $rs->username;
        $rememberMe->encryptedPassword = $data[0];

        return $rememberMe;
    }

    /**
     * Create the remember me component from the given username and password
     *
     * @param string $username
     * @param string $password
     *
     * @return static
     */
    public static function fromCredentials($username, $password)
    {
        $aesCrypt = new AesCrypt();
        $rememberMe = new static();
        $rememberMe->encryptedPassword = $aesCrypt->encrypt($password);
        $rememberMe->username = $username;
        $rememberMe->aesCrypt = $aesCrypt;

        return $rememberMe;
    }

    /**
     * Remove expired remember me information from the database
     */
    public static function removeExpired()
    {
        $rememberMe = new static();
        if (! $rememberMe->hasDb()) {
            return;
        }

        $rememberMe->getDb()->delete(static::TABLE, [
            'expires_at < NOW()'
        ]);
    }

    /**
     * Get the remember me cookie
     *
     * @return Cookie
     */
    public function getCookie()
    {
        $values = [
            $this->encryptedPassword,
            base64_encode($this->aesCrypt->getIV()),
        ];

        if ($this->aesCrypt->isAuthenticatedEncryptionRequired()) {
            array_splice($values, 1, 0, base64_encode($this->aesCrypt->getTag()));
        }

        return (new Cookie(static::COOKIE))
            ->setExpire($this->getExpiresAt())
            ->setHttpOnly(true)
            ->setValue(implode('|', $values));
    }

    /**
     * Get the timestamp when the cookie expires
     *
     * Defaults to now plus 30 days, if not set via {@link setExpiresAt()}.
     *
     * @return int
     */
    public function getExpiresAt()
    {
        if ($this->expiresAt === null) {
            $this->expiresAt = time() + 60 * 60 * 24 * 30;
        }

        return $this->expiresAt;
    }

    /**
     * Set the timestamp when the cookie expires
     *
     * @param int $expiresAt
     *
     * @return $this
     */
    public function setExpiresAt($expiresAt)
    {
        $this->expiresAt = $expiresAt;

        return $this;
    }

    /**
     * Authenticate via the remember me cookie
     *
     * @return bool
     *
     * @throws \Icinga\Exception\AuthenticationException
     */
    public function authenticate()
    {
        $auth = Auth::getInstance();
        $authChain = $auth->getAuthChain();
        $authChain->setSkipExternalBackends(true);
        $user = new User($this->username);
        if (! $user->hasDomain()) {
            $user->setDomain(Config::app()->get('authentication', 'default_domain'));
        }

        $authenticated = $authChain->authenticate(
            $user,
            $this->aesCrypt->decrypt($this->encryptedPassword)
        );

        if ($authenticated) {
            $auth->setAuthenticated($user);
        }

        return $authenticated;
    }

    /**
     * Persist the remember me information into the database
     *
     * To remove any previous stored information, set the iv
     *
     * @param string|null $iv To remove a specific iv record from the database
     *
     * @return $this
     */
    public function persist($iv = null)
    {
        if ($iv) {
            $this->remove(bin2hex($iv));
        }

        $this->getDb()->insert(static::TABLE, [
            'username'          => $this->username,
            'passphrase'        => bin2hex($this->aesCrypt->getKey()),
            'random_iv'         => bin2hex($this->aesCrypt->getIV()),
            'http_user_agent'   => (new UserAgent)->getAgent(),
            'expires_at'        => date('Y-m-d H:i:s', $this->getExpiresAt()),
            'ctime'             => new Expression('NOW()'),
            'mtime'             => new Expression('NOW()')
        ]);

        return $this;
    }

    /**
     * Remove remember me information from the database on the basis of iv
     *
     * @param string $iv
     *
     * @return $this
     */
    public function remove($iv)
    {
        $this->getDb()->delete(static::TABLE, [
            'random_iv = ?' => $iv
        ]);

        return $this;
    }

    /**
     * Create renewed remember me cookie
     *
     * @return static New remember me cookie which has to be sent to the client
     */
    public function renew()
    {
        return static::fromCredentials(
            $this->username,
            $this->aesCrypt->decrypt($this->encryptedPassword)
        );
    }

    /**
     * Get all users using remember me cookie
     *
     * @return array Array of users
     */
    public static function getAllUser()
    {
        $rememberMe = new static();
        if (! $rememberMe->hasDb()) {
            return [];
        }

        $select = (new Select())
            ->from(static::TABLE)
            ->columns('username')
            ->groupBy('username');

        return $rememberMe->getDb()->select($select)->fetchAll();
    }

    /**
     * Get all remember me entries from the database of the given user.
     *
     * @param $username
     *
     * @return array Array of database entries
     */
    public static function getAllByUsername($username)
    {
        $rememberMe = new static();
        if (! $rememberMe->hasDb()) {
            return [];
        }

        $select = (new Select())
            ->from(static::TABLE)
            ->columns(['http_user_agent', 'random_iv'])
            ->where(['username = ?' => $username]);

        return $rememberMe->getDb()->select($select)->fetchAll();
    }

    /**
     * Get the AesCrypt instance
     *
     * @return AesCrypt
     */
    public function getAesCrypt()
    {
        return $this->aesCrypt;
    }
}