1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\TwoFactorAuth;
use Endroid\QrCode\QrCode;
use Piwik\API\Request;
use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\IP;
use Piwik\Nonce;
use Piwik\Piwik;
use Piwik\Plugins\Login\PasswordVerifier;
use Piwik\Plugins\TwoFactorAuth\Dao\RecoveryCodeDao;
use Piwik\Session\SessionFingerprint;
use Piwik\Session\SessionNamespace;
use Piwik\Url;
use Piwik\View;
use Exception;
class Controller extends \Piwik\Plugin\Controller
{
const AUTH_CODE_NONCE = 'TwoFactorAuth.saveAuthCode';
const LOGIN_2FA_NONCE = 'TwoFactorAuth.loginAuthCode';
const DISABLE_2FA_NONCE = 'TwoFactorAuth.disableAuthCode';
const REGENERATE_CODES_2FA_NONCE = 'TwoFactorAuth.regenerateCodes';
const VERIFY_PASSWORD_NONCE = 'TwoFactorAuth.verifyPassword';
/**
* @var SystemSettings
*/
private $settings;
/**
* @var RecoveryCodeDao
*/
private $recoveryCodeDao;
/**
* @var PasswordVerifier
*/
private $passwordVerify;
/**
* @var TwoFactorAuthentication
*/
private $twoFa;
/**
* @var Validator
*/
private $validator;
public function __construct(SystemSettings $systemSettings, RecoveryCodeDao $recoveryCodeDao, PasswordVerifier $passwordVerify, TwoFactorAuthentication $twoFa, Validator $validator)
{
$this->settings = $systemSettings;
$this->recoveryCodeDao = $recoveryCodeDao;
$this->passwordVerify = $passwordVerify;
$this->twoFa = $twoFa;
$this->validator = $validator;
parent::__construct();
}
public function loginTwoFactorAuth()
{
$this->validator->checkCanUseTwoFa();
$this->validator->check2FaEnabled();
$this->validator->checkNotVerified2FAYet();
$messageNoAccess = null;
$view = new View('@TwoFactorAuth/loginTwoFactorAuth');
$form = new FormTwoFactorAuthCode();
$form->removeAttribute('action'); // remove action attribute, otherwise hash part will be lost
if ($form->validate()) {
$nonce = $form->getSubmitValue('form_nonce');
if ($nonce && Nonce::verifyNonce(self::LOGIN_2FA_NONCE, $nonce) && $form->validate()) {
$authCode = $form->getSubmitValue('form_authcode');
if ($authCode && is_string($authCode)) {
$authCode = str_replace('-', '', $authCode);
$authCode = strtoupper($authCode); // recovery codes are stored upper case, app codes are only numbers
$authCode = trim($authCode);
}
if ($this->twoFa->validateAuthCode(Piwik::getCurrentUserLogin(), $authCode)) {
$sessionFingerprint = new SessionFingerprint();
$sessionFingerprint->setTwoFactorAuthenticationVerified();
Url::redirectToUrl(Url::getCurrentUrl());
} else {
$messageNoAccess = Piwik::translate('TwoFactorAuth_InvalidAuthCode');
try {
$bruteForce = StaticContainer::get('Piwik\Plugins\Login\Security\BruteForceDetection');
if ($bruteForce->isEnabled()) {
$bruteForce->addFailedAttempt(IP::getIpFromHeader());
}
} catch (Exception $e) {
// ignore error eg if login plugin is disabled
}
}
} else {
$messageNoAccess = Piwik::translate('Login_InvalidNonceOrHeadersOrReferrer', array('<a target="_blank" rel="noreferrer noopener" href="https://matomo.org/faq/how-to-install/#faq_98">', '</a>'));
}
}
$superUsers = Request::processRequest('UsersManager.getUsersHavingSuperUserAccess', [], []);
$view->superUserEmails = implode(',', array_column($superUsers, 'email'));
$view->loginModule = Piwik::getLoginPluginName();
$view->AccessErrorString = $messageNoAccess;
$view->addForm($form);
$this->setBasicVariablesView($view);
$view->nonce = Nonce::getNonce(self::LOGIN_2FA_NONCE);
return $view->render();
}
public function userSettings()
{
$this->validator->checkCanUseTwoFa();
return $this->renderTemplate('userSettings', array(
'isEnabled' => $this->twoFa->isUserUsingTwoFactorAuthentication(Piwik::getCurrentUserLogin()),
'isForced' => $this->twoFa->isUserRequiredToHaveTwoFactorEnabled(),
'disableNonce' => Nonce::getNonce(self::DISABLE_2FA_NONCE)
));
}
public function disableTwoFactorAuth()
{
$this->validator->checkCanUseTwoFa();
$this->validator->check2FaEnabled();
$this->validator->checkVerified2FA();
if ($this->twoFa->isUserRequiredToHaveTwoFactorEnabled()) {
throw new Exception('Two-factor authentication cannot be disabled as it is enforced');
}
$nonce = Common::getRequestVar('disableNonce', null, 'string');
$params = array('module' => 'TwoFactorAuth', 'action' => 'disableTwoFactorAuth', 'disableNonce' => $nonce);
if ($this->passwordVerify->requirePasswordVerifiedRecently($params)) {
Nonce::checkNonce(self::DISABLE_2FA_NONCE, $nonce);
$this->twoFa->disable2FAforUser(Piwik::getCurrentUserLogin());
$this->passwordVerify->forgetVerifiedPassword();
$this->redirectToIndex('UsersManager', 'userSecurity', null, null, null, array(
'disableNonce' => false
));
}
}
private function make2faSession()
{
return new SessionNamespace('TwoFactorAuthenticator');
}
public function onLoginSetupTwoFactorAuth()
{
// called when 2fa is required, but user has not yet set up 2fa
return $this->setupTwoFactorAuth($standalone = true);
}
/**
* Action to setup two factor authentication
*
* @return string
* @throws \Exception
*/
public function setupTwoFactorAuth($standalone = false)
{
$this->validator->checkCanUseTwoFa();
if ($standalone) {
$view = new View('@TwoFactorAuth/setupTwoFactorAuthStandalone');
$this->setBasicVariablesView($view);
$view->submitAction = 'onLoginSetupTwoFactorAuth';
} else {
$view = new View('@TwoFactorAuth/setupTwoFactorAuth');
$this->setGeneralVariablesView($view);
$view->submitAction = 'setupTwoFactorAuth';
$redirectParams = array('module' => 'TwoFactorAuth', 'action' => 'setupTwoFactorAuth');
if (!$this->passwordVerify->requirePasswordVerified($redirectParams)) {
// should usually not go in here but redirect instead
throw new Exception('You have to verify your password first.');
}
}
$session = $this->make2faSession();
if (empty($session->secret)) {
$session->secret = $this->twoFa->generateSecret();
}
$secret = $session->secret;
$session->setExpirationSeconds(60 * 15, 'secret');
$authCode = Common::getRequestVar('authCode', '', 'string');
$authCodeNonce = Common::getRequestVar('authCodeNonce', '', 'string');
$hasSubmittedForm = !empty($authCodeNonce) || !empty($authCode);
$accessErrorString = '';
$login = Piwik::getCurrentUserLogin();
if (!empty($secret) && !empty($authCode)
&& Nonce::verifyNonce(self::AUTH_CODE_NONCE, $authCodeNonce)) {
if ($this->twoFa->validateAuthCodeDuringSetup(trim($authCode), $secret)) {
$this->twoFa->saveSecret($login, $secret);
$fingerprint = new SessionFingerprint();
$fingerprint->setTwoFactorAuthenticationVerified();
unset($session->secret);
$this->passwordVerify->forgetVerifiedPassword();
Piwik::postEvent('TwoFactorAuth.enabled', array($login));
if ($standalone) {
$this->redirectToIndex('CoreHome', 'index');
return;
}
$view = new View('@TwoFactorAuth/setupFinished');
$this->setGeneralVariablesView($view);
return $view->render();
} else {
$accessErrorString = Piwik::translate('TwoFactorAuth_WrongAuthCodeTryAgain');
}
} elseif (!$standalone) {
// the user has not posted the form... at least not with a valid nonce... we make sure the password verify
// is valid for at least another 15 minutes and if not, ask for another password confirmation to avoid
// the user may be posting a valid auth code after rendering this screen but the password verify is invalid
// by then.
$redirectParams = array('module' => 'TwoFactorAuth', 'action' => 'setupTwoFactorAuth');
if (!$this->passwordVerify->requirePasswordVerifiedRecently($redirectParams)) {
throw new Exception('You have to verify your password first.');
}
}
if (!$this->recoveryCodeDao->getAllRecoveryCodesForLogin($login)
|| (!$hasSubmittedForm && !$this->twoFa->isUserUsingTwoFactorAuthentication($login))) {
// we cannot generate new codes after form has been submitted and user is not yet using 2fa cause we would
// change recovery codes in the background without the user noticing... we cannot simply do this:
// if !getAllRecoveryCodesForLogin => createRecoveryCodesForLogin. Because it could be a security issue that
// user might start the setup but never finishes. Before setting up 2fa the first time we have to change
// the recovery codes
$this->recoveryCodeDao->createRecoveryCodesForLogin($login);
}
$view->title = $this->settings->twoFactorAuthTitle->getValue();
$view->description = $login;
$view->authCodeNonce = Nonce::getNonce(self::AUTH_CODE_NONCE);
$view->AccessErrorString = $accessErrorString;
$view->isAlreadyUsing2fa = $this->twoFa->isUserUsingTwoFactorAuthentication($login);
$view->newSecret = $secret;
$view->twoFaBarCodeSetupUrl = $this->getTwoFaBarCodeSetupUrl($secret);
$view->codes = $this->recoveryCodeDao->getAllRecoveryCodesForLogin($login);
$view->standalone = $standalone;
return $view->render();
}
public function showRecoveryCodes()
{
$this->validator->checkCanUseTwoFa();
$this->validator->checkVerified2FA();
$this->validator->check2FaEnabled();
$regenerateNonce = Common::getRequestVar('regenerateNonce', '', 'string', $_POST);
$postedValidNonce = !empty($regenerateNonce) && Nonce::verifyNonce(self::REGENERATE_CODES_2FA_NONCE, $regenerateNonce);
$regenerateSuccess = false;
$regenerateError = false;
if ($postedValidNonce && $this->passwordVerify->hasBeenVerified()) {
$this->passwordVerify->forgetVerifiedPassword();
$this->recoveryCodeDao->createRecoveryCodesForLogin(Piwik::getCurrentUserLogin());
$regenerateSuccess = true;
// no need to redirect as password was verified nonce
// if user has posted a valid nonce, we do not need to require password again as nonce must have been generated recent
// avoids use case where eg password verify is only valid for one more minute when opening the page but user regenerates 2min later
} elseif (!$this->passwordVerify->requirePasswordVerifiedRecently(array('module' => 'TwoFactorAuth', 'action' => 'showRecoveryCodes'))) {
// should usually not go in here but redirect instead
throw new Exception('You have to verify your password first.');
}
if (!$postedValidNonce && !empty($regenerateNonce)) {
$regenerateError = true;
}
$recoveryCodes = $this->recoveryCodeDao->getAllRecoveryCodesForLogin(Piwik::getCurrentUserLogin());
return $this->renderTemplate('showRecoveryCodes', array(
'codes' => $recoveryCodes,
'regenerateNonce' => Nonce::getNonce(self::REGENERATE_CODES_2FA_NONCE),
'regenerateError' => $regenerateError,
'regenerateSuccess' => $regenerateSuccess
));
}
private function getTwoFaBarCodeSetupUrl($secret)
{
$title = $this->settings->twoFactorAuthTitle->getValue();
$descr = Piwik::getCurrentUserLogin();
$url = 'otpauth://totp/'.urlencode($descr).'?secret='.$secret;
if(isset($title)) {
$url .= '&issuer='.urlencode($title);
}
return $url;
}
protected function getQRUrl($description, $title)
{
return sprintf('index.php?module=TwoFactorAuth&action=showQrCode&cb=%s&title=%s&descr=%s', Common::getRandomString(8), urlencode($title), urlencode($description));
}
}
|