Debian Codegraph @

extensions/OATHAuth/src/Key/TOTPKey.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\OATHAuth\Key;
4
5 /**
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 */
21
22 use Base32\Base32;
23 use DomainException;
24 use Exception;
25 use jakobo\HOTP\HOTP;
26 use MediaWiki\Context\RequestContext;
27 use MediaWiki\Extension\OATHAuth\IAuthKey;
28 use MediaWiki\Extension\OATHAuth\Module\TOTP;
29 use MediaWiki\Extension\OATHAuth\Notifications\Manager;
30 use MediaWiki\Extension\OATHAuth\OATHAuthServices;
31 use MediaWiki\Extension\OATHAuth\OATHUser;
32 use MediaWiki\Logger\LoggerFactory;
33 use MediaWiki\MediaWikiServices;
34 use MWException;
35 use Psr\Log\LoggerInterface;
36 use Wikimedia\ObjectCache\EmptyBagOStuff;
37
38 /**
39 * Class representing a two-factor key
40 *
41 * Keys can be tied to OATHUsers
42 *
43 * @ingroup Extensions
44 */
45 class TOTPKey implements IAuthKey {
46 /** @var int|null */
47 private ?int $id;
48
49 /** @var array Two factor binary secret */
50 private $secret;
51
52 /** @var string[] List of recovery codes */
53 private $recoveryCodes = [];
54
55 /**
56 * The upper threshold number of recovery codes that if a user has less than, we'll try and notify them...
57 */
58 private const RECOVERY_CODES_NOTIFICATION_NUMBER = 2;
59
60 /**
61 * Number of recovery codes to be generated
62 */
63 public const RECOVERY_CODES_COUNT = 10;
64
65 /**
66 * Length (in bytes) that recovery codes should be
67 */
68 private const RECOVERY_CODE_LENGTH = 10;
69
70 /**
71 * @return TOTPKey
72 * @throws Exception
73 */
74 public static function newFromRandom() {
75 $object = new self(
76 null,
77 // 26 bytes to give at least 128 bits (26 * 8 = 208 bits of entropy)
78 // https://phabricator.wikimedia.org/T396951
79 self::removeBase32Padding( Base32::encode( random_bytes( 26 ) ) ),
80 []
81 );
82
83 $object->regenerateScratchTokens();
84
85 return $object;
86 }
87
88 /**
89 * @see T408225, T401393
90 */
91 private static function removeBase32Padding( string $paddedBase32String ): string {
92 return rtrim( $paddedBase32String, '=' );
93 }
94
95 /**
96 * @param array $data
97 * @return TOTPKey|null on invalid data
98 */
99 public static function newFromArray( array $data ) {
100 if ( !isset( $data['secret'] ) || !isset( $data['scratch_tokens'] ) ) {
101 return null;
102 }
103 return new static( $data['id'] ?? null, $data['secret'], $data['scratch_tokens'] );
104 }
105
106 /**
107 * @param int|null $id the database id of this key
108 * @param string $secret
109 * @param array $recoveryCodes
110 */
111 public function __construct( ?int $id, $secret, array $recoveryCodes ) {
112 $this->id = $id;
113
114 // Currently hardcoded values; might be used in the future
115 $this->secret = [
116 'mode' => 'hotp',
117 'secret' => $secret,
118 'period' => 30,
119 'algorithm' => 'SHA1',
120 ];
121 $this->recoveryCodes = array_values( $recoveryCodes );
122 }
123
124 /**
125 * @return int|null
126 */
127 public function getId(): ?int {
128 return $this->id;
129 }
130
131 /**
132 * @return string
133 */
134 public function getSecret() {
135 return $this->secret['secret'];
136 }
137
138 /**
139 * @return string[]
140 */
141 public function getScratchTokens() {
142 return $this->recoveryCodes;
143 }
144
145 /**
146 * @param array $data
147 * @param OATHUser $user
148 * @return bool
149 * @throws MWException
150 */
151 public function verify( $data, OATHUser $user ) {
152 global $wgOATHAuthWindowRadius;
153
154 $token = $data['token'];
155
156 if ( $this->secret['mode'] !== 'hotp' ) {
157 throw new DomainException( 'OATHAuth extension does not support non-HOTP tokens' );
158 }
159
160 // Prevent replay attacks
161 $services = MediaWikiServices::getInstance();
162 $store = $services->getMainObjectStash();
163
164 if ( $store instanceof EmptyBagOStuff ) {
165 // Try and find some usable cache if the MainObjectStash isn't useful
166 $store = $services->getObjectCacheFactory()->getLocalServerInstance( CACHE_ANYTHING );
167 }
168
169 $key = $store->makeKey( 'oathauth-totp', 'usedtokens', $user->getCentralId() );
170 $lastWindow = (int)$store->get( $key );
171
172 $results = HOTP::generateByTimeWindow(
173 Base32::decode( $this->secret['secret'] ),
174 $this->secret['period'],
175 -$wgOATHAuthWindowRadius,
176 $wgOATHAuthWindowRadius
177 );
178
179 // Remove any whitespace from the received token, which can be an intended group separator
180 $token = preg_replace( '/\s+/', '', $token );
181
182 $clientIP = RequestContext::getMain()->getRequest()->getIP();
183
184 $logger = $this->getLogger();
185
186 // Check to see if the user's given token is in the list of tokens generated
187 // for the time window.
188 foreach ( $results as $window => $result ) {
189 if ( $window > $lastWindow && hash_equals( $result->toHOTP( 6 ), $token ) ) {
190 $lastWindow = $window;
191
192 $logger->info( 'OATHAuth user {user} entered a valid OTP from {clientip}', [
193 'user' => $user->getAccount(),
194 'clientip' => $clientIP,
195 ] );
196
197 $store->set(
198 $key,
199 $lastWindow,
200 $this->secret['period'] * ( 1 + 2 * $wgOATHAuthWindowRadius )
201 );
202
203 return true;
204 }
205 }
206
207 // See if the user is using a recovery code
208 foreach ( $this->recoveryCodes as $i => $recoveryCode ) {
209 if ( hash_equals( $token, $recoveryCode ) ) {
210 // If we used a recovery code, remove it from the recovery code list.
211 // This is saved below via OATHUserRepository::persist
212 array_splice( $this->recoveryCodes, $i, 1 );
213
214 // TODO: Probably a better home for this...
215 // It could go in OATHUserRepository::persist(), but then we start having to hard code checks
216 // for Keys being TOTPKey...
217 // And eventually we want to do T232336 to split them to their own 2FA method...
218 if ( count( $this->recoveryCodes ) <= self::RECOVERY_CODES_NOTIFICATION_NUMBER ) {
219 Manager::notifyRecoveryTokensRemaining(
220 $user,
221 self::RECOVERY_CODES_NOTIFICATION_NUMBER,
222 self::RECOVERY_CODES_COUNT
223 );
224 }
225
226 $logger->info( 'OATHAuth user {user} used a recovery token from {clientip}', [
227 'user' => $user->getAccount(),
228 'clientip' => $clientIP,
229 ] );
230
231 OATHAuthServices::getInstance()
232 ->getUserRepository()
233 ->updateKey( $user, $this );
234 return true;
235 }
236 }
237
238 return false;
239 }
240
241 public function regenerateScratchTokens() {
242 $codes = [];
243 for ( $i = 0; $i < self::RECOVERY_CODES_COUNT; $i++ ) {
244 $codes[] = Base32::encode( random_bytes( self::RECOVERY_CODE_LENGTH ) );
245 }
246 $this->recoveryCodes = $codes;
247 }
248
249 /**
250 * Check if a token is one of the recovery codes for this two-factor key.
251 *
252 * @param string $token Token to verify
253 *
254 * @return bool true if this is a recovery code.
255 */
256 public function isScratchToken( $token ) {
257 $token = preg_replace( '/\s+/', '', $token );
258 return in_array( $token, $this->recoveryCodes, true );
259 }
260
261 /** @inheritDoc */
262 public function getModule(): string {
263 return TOTP::MODULE_NAME;
264 }
265
266 /**
267 * @return LoggerInterface
268 */
269 private function getLogger() {
270 return LoggerFactory::getInstance( 'authentication' );
271 }
272
273 public function jsonSerialize(): array {
274 return [
275 'secret' => $this->getSecret(),
276 'scratch_tokens' => $this->getScratchTokens()
277 ];
278 }
279 }