3 * MediaWiki session token
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Session
;
29 * Value object representing a CSRF token
34 class Token
implements Stringable
{
35 /** CSRF token suffix. Plus and terminal backslash are included to stop
36 * editing from certain broken proxies.
38 public const SUFFIX
= '+\\';
50 * @param string $secret Token secret
51 * @param string $salt Token salt
52 * @param bool $new Whether the secret was newly-created
54 public function __construct( $secret, $salt, $new = false ) {
55 $this->secret
= $secret;
61 * Decode the timestamp from a token string
63 * Does not validate the token beyond the syntactic checks necessary to
64 * be able to extract the timestamp.
66 * @param string $token
69 public static function getTimestamp( $token ) {
70 $suffixLen = strlen( self
::SUFFIX
);
71 $len = strlen( $token );
72 if ( $len <= 32 +
$suffixLen ||
73 substr( $token, -$suffixLen ) !== self
::SUFFIX ||
74 strspn( $token, '0123456789abcdef' ) +
$suffixLen !== $len
79 return hexdec( substr( $token, 32, -$suffixLen ) );
83 * Get the string representation of the token at a timestamp
84 * @param int $timestamp
87 protected function toStringAtTimestamp( $timestamp ) {
88 return hash_hmac( 'md5', $timestamp . $this->salt
, $this->secret
, false ) .
89 dechex( $timestamp ) .
94 * Get the string representation of the token
97 public function toString() {
98 return $this->toStringAtTimestamp( (int)wfTimestamp( TS_UNIX
) );
101 public function __toString() {
102 return $this->toString();
106 * Test if the token-string matches this token
107 * @param string|null $userToken
108 * @param int|null $maxAge Return false if $userToken is older than this many seconds
111 public function match( $userToken, $maxAge = null ) {
115 $timestamp = self
::getTimestamp( $userToken );
116 if ( $timestamp === null ) {
119 if ( $maxAge !== null && $timestamp < (int)wfTimestamp( TS_UNIX
) - $maxAge ) {
124 $sessionToken = $this->toStringAtTimestamp( $timestamp );
125 return hash_equals( $sessionToken, $userToken );
129 * Indicate whether this token was just created
132 public function wasNew() {