Debian Codegraph @

extensions/OATHAuth/src/HTMLForm/TOTPEnableForm.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\OATHAuth\HTMLForm;
4
5 use Endroid\QrCode\Builder\Builder;
6 use Endroid\QrCode\Encoding\Encoding;
7 use Endroid\QrCode\ErrorCorrectionLevel;
8 use Endroid\QrCode\RoundBlockSizeMode;
9 use Endroid\QrCode\Writer\SvgWriter;
10 use MediaWiki\Config\ConfigException;
11 use MediaWiki\Extension\OATHAuth\Key\TOTPKey;
12 use MediaWiki\Html\Html;
13 use MediaWiki\Logger\LoggerFactory;
14 use MediaWiki\Status\Status;
15 use MWException;
16
17 class TOTPEnableForm extends OATHAuthOOUIHTMLForm {
18 /**
19 * @param array|bool|Status|string $submitResult
20 * @return string
21 */
22 public function getHTML( $submitResult ) {
23 $out = $this->getOutput();
24 $out->addModuleStyles( 'ext.oath.styles' );
25 $out->addModules( 'ext.oath' );
26
27 return parent::getHTML( $submitResult );
28 }
29
30 /**
31 * Add content to output when operation was successful
32 */
33 public function onSuccess() {
34 $this->getOutput()->addWikiMsg( 'oathauth-validatedoath' );
35 }
36
37 /**
38 * @return array
39 */
40 protected function getDescriptors() {
41 $keyData = $this->getRequest()->getSessionData( 'oathauth_totp_key' ) ?? [];
42 $key = TOTPKey::newFromArray( $keyData );
43 if ( !$key instanceof TOTPKey ) {
44 $key = TOTPKey::newFromRandom();
45 $this->getRequest()->setSessionData(
46 'oathauth_totp_key',
47 $key->jsonSerialize()
48 );
49 }
50
51 $secret = $key->getSecret();
52 $issuer = $this->oathUser->getIssuer();
53 $account = $this->oathUser->getAccount();
54 $label = "{$issuer}:{$account}";
55 $qrcodeUrl = "otpauth://totp/"
56 . rawurlencode( $label )
57 . "?secret="
58 . rawurlencode( $secret )
59 . "&issuer="
60 . rawurlencode( $issuer );
61
62 $qrCode = Builder::create()
63 ->writer( new SvgWriter() )
64 ->writerOptions( [ SvgWriter::WRITER_OPTION_EXCLUDE_XML_DECLARATION => true ] )
65 ->data( $qrcodeUrl )
66 ->encoding( new Encoding( 'UTF-8' ) )
67 ->errorCorrectionLevel( ErrorCorrectionLevel::High )
68 ->roundBlockSizeMode( RoundBlockSizeMode::None )
69 ->size( 256 )
70 ->margin( 0 )
71 ->build();
72
73 $now = wfTimestampNow();
74 $recoveryCodes = $this->getScratchTokensForDisplay( $key );
75 $this->getOutput()->addJsConfigVars( 'oathauth-recoverycodes', $this->createTextList( $recoveryCodes ) );
76
77 // messages used: oathauth-step1, oathauth-step2, oathauth-step3, oathauth-step4
78 return [
79 'app' => [
80 'type' => 'info',
81 'default' => $this->msg( 'oathauth-step1-test' )->parse(),
82 'raw' => true,
83 'section' => 'step1',
84 ],
85 'qrcode' => [
86 'type' => 'info',
87 'default' =>
88 $this->msg( 'oathauth-step2-qrcode' )->escaped() . '<br/>'
89 . Html::element( 'img', [
90 'class' => 'mw-oauth-qrcode',
91 'src' => $qrCode->getDataUri(),
92 'alt' => $this->msg( 'oathauth-qrcode-alt' ),
93 'width' => 256,
94 'height' => 256,
95 ] ),
96 'raw' => true,
97 'section' => 'step2',
98 ],
99 'manual' => [
100 'type' => 'info',
101 'label-message' => 'oathauth-step2alt',
102 'default' =>
103 '<strong>' . $this->msg( 'oathauth-secret' )->escaped() . '</strong><br/>'
104 . '<kbd>' . $this->getSecretForDisplay( $key ) . '</kbd><br/>'
105 . '<strong>' . $this->msg( 'oathauth-account' )->escaped() . '</strong><br/>'
106 . htmlspecialchars( $label ) . '<br/><br/>',
107 'raw' => true,
108 'section' => 'step2',
109 ],
110 'scratchtokens' => [
111 'type' => 'info',
112 'default' =>
113 '<strong>' . $this->msg( 'oathauth-recoverycodes-important' )->escaped() . '</strong><br/>' .
114 $this->msg( 'oathauth-recoverycodes' )->escaped() . '<br/><br/>' .
115 $this->msg( 'rawmessage' )->rawParams(
116 $this->msg(
117 'oathauth-recoverytokens-createdat',
118 $this->getLanguage()->userTimeAndDate( $now, $this->oathUser->getUser() )
119 )->parse()
120 . $this->msg( 'word-separator' )->escaped()
121 . $this->msg( 'parentheses' )->rawParams( wfTimestamp( TS_ISO_8601, $now ) )->escaped()
122 ) . '<br/>' .
123 $this->createResourceList( $recoveryCodes ) . '<br/>' .
124 '<strong>' . $this->msg( 'oathauth-recoverycodes-neveragain' )->escaped() . '</strong><br/>' .
125 $this->createCopyButton() .
126 $this->createDownloadLink( $recoveryCodes ),
127 'raw' => true,
128 'section' => 'step3',
129 ],
130 'token' => [
131 'type' => 'text',
132 'default' => '',
133 'label-message' => 'oathauth-entertoken',
134 'name' => 'token',
135 'section' => 'step4',
136 'dir' => 'ltr',
137 'autocomplete' => 'one-time-code',
138 'spellcheck' => false,
139 ]
140 ];
141 }
142
143 /**
144 * @param array $resources
145 * @return string
146 */
147 private function createResourceList( $resources ) {
148 $resourceList = '';
149 foreach ( $resources as $resource ) {
150 $resourceList .= Html::rawElement( 'li', [], Html::rawElement( 'kbd', [], $resource ) );
151 }
152 return Html::rawElement( 'ul', [], $resourceList );
153 }
154
155 /**
156 * @param array $items
157 *
158 * @return string
159 */
160 private function createTextList( $items ) {
161 return "* " . implode( "\n* ", $items );
162 }
163
164 private function createDownloadLink( array $scratchTokensForDisplay ): string {
165 $icon = Html::element( 'span', [
166 'class' => [ 'mw-oathauth-recoverycodes-download-icon', 'cdx-button__icon' ],
167 'aria-hidden' => 'true',
168 ] );
169 return Html::rawElement(
170 'a',
171 [
172 'href' => 'data:text/plain;charset=utf-8,'
173 // https://bugzilla.mozilla.org/show_bug.cgi?id=1895687
174 . rawurlencode( implode( PHP_EOL, $scratchTokensForDisplay ) ),
175 'download' => 'recovery-codes.txt',
176 'class' => [
177 'mw-oathauth-recoverycodes-download',
178 'cdx-button', 'cdx-button--fake-button', 'cdx-button--fake-button--enabled',
179 ],
180 ],
181 $icon . $this->msg( 'oathauth-recoverycodes-download' )->escaped()
182 );
183 }
184
185 private function createCopyButton(): string {
186 return Html::rawElement( 'button', [
187 'class' => 'cdx-button mw-oathauth-recoverycodes-copy-button',
188 'type' => 'button',
189 ], Html::element( 'span', [
190 'class' => 'cdx-button__icon',
191 'aria-hidden' => 'true',
192 ] ) . $this->msg( 'oathauth-recoverycodes-copy' )->escaped()
193 );
194 }
195
196 /**
197 * Retrieve the current secret for display purposes
198 *
199 * The characters of the token are split in groups of 4
200 *
201 * @param TOTPKey $key
202 * @return string
203 */
204 protected function getSecretForDisplay( TOTPKey $key ) {
205 return $this->tokenFormatterFunction( $key->getSecret() );
206 }
207
208 /**
209 * Retrieve current recovery codes for display purposes
210 *
211 * The characters of the token are split in groups of 4
212 *
213 * @param TOTPKey $key
214 * @return string[]
215 */
216 protected function getScratchTokensForDisplay( TOTPKey $key ) {
217 return array_map( [ $this, 'tokenFormatterFunction' ], $key->getScratchTokens() );
218 }
219
220 /**
221 * Formats a key or recovery code by creating groups of 4 separated by space characters
222 *
223 * @param string $token Token to format
224 * @return string The token formatted for display
225 */
226 private function tokenFormatterFunction( $token ) {
227 return implode( ' ', str_split( $token, 4 ) );
228 }
229
230 /**
231 * @param array $formData
232 * @return array|bool
233 * @throws ConfigException
234 * @throws MWException
235 */
236 public function onSubmit( array $formData ) {
237 $keyData = $this->getRequest()->getSessionData( 'oathauth_totp_key' ) ?? [];
238 $key = TOTPKey::newFromArray( $keyData );
239 if ( !$key instanceof TOTPKey ) {
240 return [ 'oathauth-invalidrequest' ];
241 }
242
243 if ( $key->isScratchToken( $formData['token'] ) ) {
244 // A recovery code is not allowed for enrollment
245 LoggerFactory::getInstance( 'authentication' )->info(
246 'OATHAuth {user} attempted to enable 2FA using a recovery code from {clientip}', [
247 'user' => $this->getUser()->getName(),
248 'clientip' => $this->getRequest()->getIP(),
249 ]
250 );
251 return [ 'oathauth-noscratchforvalidation' ];
252 }
253 if ( !$key->verify( [ 'token' => $formData['token'] ], $this->oathUser ) ) {
254 LoggerFactory::getInstance( 'authentication' )->info(
255 'OATHAuth {user} failed to provide a correct token while enabling 2FA from {clientip}', [
256 'user' => $this->getUser()->getName(),
257 'clientip' => $this->getRequest()->getIP(),
258 ]
259 );
260 return [ 'oathauth-failedtovalidateoath' ];
261 }
262
263 $this->getRequest()->setSessionData( 'oathauth_totp_key', null );
264 $this->oathRepo->createKey(
265 $this->oathUser,
266 $this->module,
267 $key->jsonSerialize(),
268 $this->getRequest()->getIP()
269 );
270
271 return true;
272 }
273 }