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
;
27 * Value object representing a CSRF token
33 /** CSRF token suffix. Plus and terminal backslash are included to stop
34 * editing from certain broken proxies.
48 * @param string $secret Token secret
49 * @param string $salt Token salt
50 * @param bool $new Whether the secret was newly-created
52 public function __construct( $secret, $salt, $new = false ) {
53 $this->secret
= $secret;
59 * Decode the timestamp from a token string
61 * Does not validate the token beyond the syntactic checks necessary to
62 * be able to extract the timestamp.
64 * @param string $token
67 public static function getTimestamp( $token ) {
68 $suffixLen = strlen( self
::SUFFIX
);
69 $len = strlen( $token );
70 if ( $len <= 32 +
$suffixLen ||
71 substr( $token, -$suffixLen ) !== self
::SUFFIX ||
72 strspn( $token, '0123456789abcdef' ) +
$suffixLen !== $len
77 return hexdec( substr( $token, 32, -$suffixLen ) );
81 * Get the string representation of the token at a timestamp
82 * @param int $timestamp
85 protected function toStringAtTimestamp( $timestamp ) {
86 return hash_hmac( 'md5', $timestamp . $this->salt
, $this->secret
, false ) .
87 dechex( $timestamp ) .
92 * Get the string representation of the token
95 public function toString() {
96 return $this->toStringAtTimestamp( wfTimestamp() );
99 public function __toString() {
100 return $this->toString();
104 * Test if the token-string matches this token
105 * @param string $userToken
106 * @param int|null $maxAge Return false if $userToken is older than this many seconds
109 public function match( $userToken, $maxAge = null ) {
110 $timestamp = self
::getTimestamp( $userToken );
111 if ( $timestamp === null ) {
114 if ( $maxAge !== null && $timestamp < wfTimestamp() - $maxAge ) {
119 $sessionToken = $this->toStringAtTimestamp( $timestamp );
120 return hash_equals( $sessionToken, $userToken );
124 * Indicate whether this token was just created
127 public function wasNew() {