|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Copyright (c) Christoph M. Becker |
| 5 | + * |
| 6 | + * This file is part of Plib_XH. |
| 7 | + * |
| 8 | + * Plib_XH is free software: you can redistribute it and/or modify |
| 9 | + * it under the terms of the GNU General Public License as published by |
| 10 | + * the Free Software Foundation, either version 3 of the License, or |
| 11 | + * (at your option) any later version. |
| 12 | + * |
| 13 | + * Plib_XH is distributed in the hope that it will be useful, |
| 14 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | + * GNU General Public License for more details. |
| 17 | + * |
| 18 | + * You should have received a copy of the GNU General Public License |
| 19 | + * along with Plib_XH. If not, see <http://www.gnu.org/licenses/>. |
| 20 | + */ |
| 21 | + |
| 22 | +namespace Plib; |
| 23 | + |
| 24 | +/** |
| 25 | + * Flexible and unintrusive CSRF protection |
| 26 | + * |
| 27 | + * This class maintains an unguessable random CSRF token in `$_SESSION`, |
| 28 | + * but does not actually start the session. So it will only work if a |
| 29 | + * session is started somewhere else (that is the case for administrators |
| 30 | + * of CMSimple_XH, and users of Register_XH and Memberpages, and maybe some |
| 31 | + * other plugins). |
| 32 | + * |
| 33 | + * @final |
| 34 | + * @since 1.5 |
| 35 | + */ |
| 36 | +class CsrfProtector |
| 37 | +{ |
| 38 | + /** |
| 39 | + * Retrieves the CSRF token |
| 40 | + */ |
| 41 | + public function token(): string |
| 42 | + { |
| 43 | + if (isset($_SESSION["plib_csrf_token"])) { |
| 44 | + return $_SESSION["plib_csrf_token"]; |
| 45 | + } |
| 46 | + $token = base64_encode(random_bytes(15)); |
| 47 | + $_SESSION["plib_csrf_token"] = $token; |
| 48 | + return $token; |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Wether the given `$token` matches the CSRF token |
| 53 | + */ |
| 54 | + public function check(?string $token): bool |
| 55 | + { |
| 56 | + return $token !== null |
| 57 | + && isset($_SESSION["plib_csrf_token"]) |
| 58 | + && hash_equals($_SESSION["plib_csrf_token"], $token); |
| 59 | + } |
| 60 | +} |
0 commit comments