File: LogoutStore.php

package info (click to toggle)
simplesamlphp 1.19.7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 42,920 kB
  • sloc: php: 202,044; javascript: 14,867; xml: 2,700; sh: 225; perl: 82; makefile: 70; python: 5
file content (478 lines) | stat: -rw-r--r-- 18,714 bytes parent folder | download | duplicates (3)
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<?php

declare(strict_types=1);

namespace SimpleSAML\Module\saml\SP;

use PDO;
use SAML2\XML\saml\NameID;
use SimpleSAML\Logger;
use SimpleSAML\Session;
use SimpleSAML\Store;
use SimpleSAML\Utils;

/**
 * A directory over logout information.
 *
 * @package SimpleSAMLphp
 */

class LogoutStore
{
    /**
     * Create logout table in SQL, if it is missing.
     *
     * @param \SimpleSAML\Store\SQL $store  The datastore.
     * @return void
     */
    private static function createLogoutTable(Store\SQL $store): void
    {
        $tableVer = $store->getTableVersion('saml_LogoutStore');
        if ($tableVer === 4) {
            return;
        } elseif ($tableVer === 3) {
            /**
             * Table version 4 fixes the column type for the _expire column.
             * We now use DATETIME instead of TIMESTAMP to support MSSQL.
             */
            switch ($store->driver) {
                case 'pgsql':
                    // This does not affect the NOT NULL constraint
                    $update = [
                        'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore ALTER COLUMN _expire TYPE TIMESTAMP'
                    ];
                    break;
                case 'sqlsrv':
                    $update = [
                        'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore ALTER COLUMN _expire DATETIME NOT NULL'
                    ];
                    break;
                case 'sqlite':
                    /**
                     * Because SQLite does not support field alterations, the approach is to:
                     *     Create a new table without the proper column size
                     *     Copy the current data to the new table
                     *     Drop the old table
                     *     Rename the new table correctly
                     *     Read the index
                     */
                    $update = [
                        'CREATE TABLE ' . $store->prefix . '_saml_LogoutStore_new (' .
                        '_authSource VARCHAR(255) NOT NULL, _nameId VARCHAR(40) NOT NULL' .
                        ', _sessionIndex VARCHAR(50) NOT NULL, _expire DATETIME NOT NULL,' .
                        '_sessionId VARCHAR(50) NOT NULL, UNIQUE (_authSource, _nameID, _sessionIndex))',
                        'INSERT INTO ' . $store->prefix . '_saml_LogoutStore_new SELECT * FROM ' .
                        $store->prefix . '_saml_LogoutStore',
                        'DROP TABLE ' . $store->prefix . '_saml_LogoutStore',
                        'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore_new RENAME TO ' .
                        $store->prefix . '_saml_LogoutStore',
                        'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_expire ON ' .
                        $store->prefix . '_saml_LogoutStore (_expire)',
                        'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON ' .
                        $store->prefix . '_saml_LogoutStore (_authSource, _nameId)'
                    ];
                    break;
                default:
                    $update = [
                        'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore MODIFY _expire DATETIME NOT NULL'
                    ];
                    break;
            }

            try {
                foreach ($update as $query) {
                    $store->pdo->exec($query);
                }
            } catch (\Exception $e) {
                Logger::warning('Database error: ' . var_export($store->pdo->errorInfo(), true));
                return;
            }
            $store->setTableVersion('saml_LogoutStore', 4);
            return;
        } elseif ($tableVer === 2) {
            /**
             * TableVersion 3 fixes the indexes that were set to 255 in version 2;
             *   they cannot be larger than 191 on MySQL
             */

            if ($store->driver === 'mysql') {
                // Drop old indexes
                $query = 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore DROP INDEX ' .
                $store->prefix . '_saml_LogoutStore_nameId';
                $store->pdo->exec($query);
                $query = 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore DROP INDEX _authSource';
                $store->pdo->exec($query);

                // Create new indexes
                $query = 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON ';
                $query .= $store->prefix . '_saml_LogoutStore (_authSource(191), _nameId)';
                $store->pdo->exec($query);

                $query = 'ALTER TABLE ' . $store->prefix .
                '_saml_LogoutStore ADD UNIQUE KEY (_authSource(191), _nameID, _sessionIndex)';
                $store->pdo->exec($query);
            }

            $store->setTableVersion('saml_LogoutStore', 3);
            return;
        } elseif ($tableVer === 1) {
            // TableVersion 2 increased the column size to 255 (191 for mysql) which is the maximum length of a FQDN
            switch ($store->driver) {
                case 'pgsql':
                    // This does not affect the NOT NULL constraint
                    $update = [
                        'ALTER TABLE ' . $store->prefix .
                        '_saml_LogoutStore ALTER COLUMN _authSource TYPE VARCHAR(255)'];
                    break;
               case 'sqlsrv':
                    $update = [
                        'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore ALTER COLUMN _authSource VARCHAR(255) NOT NULL'
                    ];
                    break;
                case 'sqlite':
                    /**
                     * Because SQLite does not support field alterations, the approach is to:
                     *     Create a new table without the proper column size
                     *     Copy the current data to the new table
                     *     Drop the old table
                     *     Rename the new table correctly
                     *     Read the index
                     */
                    $update = [
                        'CREATE TABLE ' . $store->prefix .
                        '_saml_LogoutStore_new (_authSource VARCHAR(255) NOT NULL,' .
                        '_nameId VARCHAR(40) NOT NULL, _sessionIndex VARCHAR(50) NOT NULL, ' .
                        '_expire TIMESTAMP NOT NULL, _sessionId VARCHAR(50) NOT NULL, UNIQUE ' .
                        '(_authSource, _nameID, _sessionIndex))',
                        'INSERT INTO ' . $store->prefix . '_saml_LogoutStore_new SELECT * FROM ' .
                        $store->prefix . '_saml_LogoutStore',
                        'DROP TABLE ' . $store->prefix . '_saml_LogoutStore',
                        'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore_new RENAME TO ' .
                        $store->prefix . '_saml_LogoutStore',
                        'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_expire ON ' .
                        $store->prefix . '_saml_LogoutStore (_expire)',
                        'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON ' .
                        $store->prefix . '_saml_LogoutStore (_authSource, _nameId)'
                    ];
                    break;
                case 'mysql':
                    $update = [
                        'ALTER TABLE ' . $store->prefix .
                        '_saml_LogoutStore MODIFY _authSource VARCHAR(191) NOT NULL'
                    ];
                    break;
                default:
                    $update = [
                        'ALTER TABLE ' . $store->prefix .
                        '_saml_LogoutStore MODIFY _authSource VARCHAR(255) NOT NULL'
                    ];
                    break;
            }

            try {
                foreach ($update as $query) {
                    $store->pdo->exec($query);
                }
            } catch (\Exception $e) {
                Logger::warning('Database error: ' . var_export($store->pdo->errorInfo(), true));
                return;
            }
            $store->setTableVersion('saml_LogoutStore', 2);
            return;
        }

        $query = 'CREATE TABLE ' . $store->prefix . '_saml_LogoutStore (
            _authSource VARCHAR(' . ($store->driver === 'mysql' ? '191' : '255') . ') NOT NULL,
            _nameId VARCHAR(40) NOT NULL,
            _sessionIndex VARCHAR(50) NOT NULL,
            _expire ' . ($store->driver === 'pgsql' ? 'TIMESTAMP' : 'DATETIME') . ' NOT NULL,
            _sessionId VARCHAR(50) NOT NULL,
            UNIQUE (_authSource' . ($store->driver === 'mysql' ? '(191)' : '') . ', _nameID, _sessionIndex)
        )';
        $store->pdo->exec($query);

        $query = 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_expire ON ';
        $query .= $store->prefix . '_saml_LogoutStore (_expire)';
        $store->pdo->exec($query);

        $query = 'CREATE INDEX ' . $store->prefix . '_saml_LogoutStore_nameId ON ';
        $query .= $store->prefix . '_saml_LogoutStore (_authSource' . ($store->driver === 'mysql' ? '(191)' : '') .
        ', _nameId)';
        $store->pdo->exec($query);

        $store->setTableVersion('saml_LogoutStore', 4);
    }


    /**
     * Clean the logout table of expired entries.
     *
     * @param \SimpleSAML\Store\SQL $store  The datastore.
     * @return void
     */
    private static function cleanLogoutStore(Store\SQL $store): void
    {
        Logger::debug('saml.LogoutStore: Cleaning logout store.');

        $query = 'DELETE FROM ' . $store->prefix . '_saml_LogoutStore WHERE _expire < :now';
        $params = ['now' => gmdate('Y-m-d H:i:s')];

        $query = $store->pdo->prepare($query);
        $query->execute($params);
    }


    /**
     * Register a session in the SQL datastore.
     *
     * @param \SimpleSAML\Store\SQL $store  The datastore.
     * @param string $authId  The authsource ID.
     * @param string $nameId  The hash of the users NameID.
     * @param string $sessionIndex  The SessionIndex of the user.
     * @param int $expire
     * @param string $sessionId
     * @return void
     */
    private static function addSessionSQL(
        Store\SQL $store,
        string $authId,
        string $nameId,
        string $sessionIndex,
        int $expire,
        string $sessionId
    ): void {
        self::createLogoutTable($store);

        if (rand(0, 1000) < 10) {
            self::cleanLogoutStore($store);
        }

        $data = [
            '_authSource' => $authId,
            '_nameId' => $nameId,
            '_sessionIndex' => $sessionIndex,
            '_expire' => gmdate('Y-m-d H:i:s', $expire),
            '_sessionId' => $sessionId,
        ];
        $store->insertOrUpdate(
            $store->prefix . '_saml_LogoutStore',
            ['_authSource', '_nameId', '_sessionIndex'],
            $data
        );
    }


    /**
     * Retrieve sessions from the SQL datastore.
     *
     * @param \SimpleSAML\Store\SQL $store  The datastore.
     * @param string $authId  The authsource ID.
     * @param string $nameId  The hash of the users NameID.
     * @return array  Associative array of SessionIndex =>  SessionId.
     */
    private static function getSessionsSQL(Store\SQL $store, string $authId, string $nameId): array
    {
        self::createLogoutTable($store);

        $params = [
            '_authSource' => $authId,
            '_nameId' => $nameId,
            'now' => gmdate('Y-m-d H:i:s'),
        ];

        // We request the columns in lowercase in order to be compatible with PostgreSQL
        $query = 'SELECT _sessionIndex AS _sessionindex, _sessionId AS _sessionid FROM ' . $store->prefix;
        $query .= '_saml_LogoutStore WHERE _authSource = :_authSource AND _nameId = :_nameId AND _expire >= :now';
        $query = $store->pdo->prepare($query);
        $query->execute($params);

        $res = [];
        while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== false) {
            $res[$row['_sessionindex']] = $row['_sessionid'];
        }

        return $res;
    }


    /**
     * Retrieve all session IDs from a key-value store.
     *
     * @param \SimpleSAML\Store $store  The datastore.
     * @param string $authId  The authsource ID.
     * @param string $nameId  The hash of the users NameID.
     * @param array $sessionIndexes  The session indexes.
     * @return array  Associative array of SessionIndex =>  SessionId.
     */
    private static function getSessionsStore(
        Store $store,
        string $authId,
        string $nameId,
        array $sessionIndexes
    ): array {
        $res = [];
        foreach ($sessionIndexes as $sessionIndex) {
            $sessionId = $store->get('saml.LogoutStore', $nameId . ':' . $sessionIndex);
            if ($sessionId === null) {
                continue;
            }
            assert(is_string($sessionId));
            $res[$sessionIndex] = $sessionId;
        }

        return $res;
    }


    /**
     * Register a new session in the datastore.
     *
     * Please observe the change of the signature in this method. Previously, the second parameter ($nameId) was forced
     * to be an array. However, it has no type restriction now, and the documentation states it must be a
     * \SAML2\XML\saml\NameID object. Currently, this function still accepts an array passed as $nameId, and will
     * silently convert it to a \SAML2\XML\saml\NameID object. This is done to keep backwards-compatibility, though will
     * no longer be possible in the future as the $nameId parameter will be required to be an object.
     *
     * @param string $authId  The authsource ID.
     * @param \SAML2\XML\saml\NameID $nameId The NameID of the user.
     * @param string|null $sessionIndex  The SessionIndex of the user.
     * @param int $expire
     * @return void
     */
    public static function addSession($authId, $nameId, $sessionIndex, $expire)
    {
        assert(is_string($authId));
        assert(is_string($sessionIndex) || $sessionIndex === null);
        assert(is_int($expire));

        $session = Session::getSessionFromRequest();
        if ($session->isTransient()) {
            // transient sessions are useless for this purpose, nothing to do
            return;
        }

        if ($sessionIndex === null) {
            /* This IdP apparently did not include a SessionIndex, and thus probably does not
             * support SLO. We still want to add the session to the data store just in case
             * it supports SLO, but we don't want an LogoutRequest with a specific
             * SessionIndex to match this session. We therefore generate our own session index.
             */
            $sessionIndex = Utils\Random::generateID();
        }

        $store = Store::getInstance();
        if ($store === false) {
            // We don't have a datastore.
            return;
        }

        // serialize and anonymize the NameID
        // TODO: remove this conditional statement
        if (is_array($nameId)) {
            /** @psalm-suppress UndefinedMethod */
            $nameId = NameID::fromArray($nameId);
        }
        $strNameId = serialize($nameId);
        $strNameId = sha1($strNameId);

        // Normalize SessionIndex
        if (strlen($sessionIndex) > 50) {
            $sessionIndex = sha1($sessionIndex);
        }

        /** @var string $sessionId */
        $sessionId = $session->getSessionId();

        if ($store instanceof Store\SQL) {
            self::addSessionSQL($store, $authId, $strNameId, $sessionIndex, $expire, $sessionId);
        } else {
            $store->set('saml.LogoutStore', $strNameId . ':' . $sessionIndex, $sessionId, $expire);
        }
    }


    /**
     * Log out of the given sessions.
     *
     * @param string $authId  The authsource ID.
     * @param \SAML2\XML\saml\NameID $nameId The NameID of the user.
     * @param array $sessionIndexes  The SessionIndexes we should log out of. Logs out of all if this is empty.
     * @return int|false  Number of sessions logged out, or FALSE if not supported.
     */
    public static function logoutSessions($authId, $nameId, array $sessionIndexes)
    {
        assert(is_string($authId));

        $store = Store::getInstance();
        if ($store === false) {
            // We don't have a datastore
            return false;
        }

        // serialize and anonymize the NameID
        // TODO: remove this conditional statement
        if (is_array($nameId)) {
            /** @psalm-suppress UndefinedMethod */
            $nameId = NameID::fromArray($nameId);
        }
        $strNameId = serialize($nameId);
        $strNameId = sha1($strNameId);

        // Normalize SessionIndexes
        foreach ($sessionIndexes as &$sessionIndex) {
            assert(is_string($sessionIndex));
            if (strlen($sessionIndex) > 50) {
                $sessionIndex = sha1($sessionIndex);
            }
        }

        // Remove reference
        unset($sessionIndex);

        if ($store instanceof Store\SQL) {
            $sessions = self::getSessionsSQL($store, $authId, $strNameId);
        } else {
            if (empty($sessionIndexes)) {
                // We cannot fetch all sessions without a SQL store
                return false;
            }
            /** @var array $sessions At this point the store cannot be false */
            $sessions = self::getSessionsStore($store, $authId, $strNameId, $sessionIndexes);
        }

        if (empty($sessionIndexes)) {
            $sessionIndexes = array_keys($sessions);
        }

        $numLoggedOut = 0;
        foreach ($sessionIndexes as $sessionIndex) {
            if (!isset($sessions[$sessionIndex])) {
                Logger::info('saml.LogoutStore: Logout requested for unknown SessionIndex.');
                continue;
            }

            $sessionId = $sessions[$sessionIndex];

            $session = Session::getSession($sessionId);
            if ($session === null) {
                Logger::info('saml.LogoutStore: Skipping logout of missing session.');
                continue;
            }

            if (!$session->isValid($authId)) {
                Logger::info(
                    'saml.LogoutStore: Skipping logout of session because it isn\'t authenticated.'
                );
                continue;
            }

            Logger::info(
                'saml.LogoutStore: Logging out of session with trackId [' . $session->getTrackID() . '].'
            );
            $session->doLogout($authId);
            $numLoggedOut += 1;
        }

        return $numLoggedOut;
    }
}