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
|
<?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 Piwik\API\Request;
use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\FrontController;
use Piwik\Piwik;
use Piwik\Plugins\TwoFactorAuth\Dao\RecoveryCodeDao;
use Piwik\Plugins\UsersManager\Model;
use Piwik\Session;
use Piwik\Session\SessionFingerprint;
use Exception;
use Piwik\SettingsPiwik;
class TwoFactorAuth extends \Piwik\Plugin
{
/**
* @see \Piwik\Plugin::registerEvents
*/
public function registerEvents()
{
return array(
'Request.dispatch' => array('function' => 'onRequestDispatch', 'after' => true),
'AssetManager.getJavaScriptFiles' => 'getJsFiles',
'AssetManager.getStylesheetFiles' => 'getStylesheetFiles',
'API.UsersManager.deleteUser.end' => 'deleteRecoveryCodes',
'API.UsersManager.getTokenAuth.end' => 'onApiGetTokenAuth',
'Request.dispatch.end' => array('function' => 'onRequestDispatchEnd', 'after' => true),
'Template.userSettings.afterTokenAuth' => 'render2FaUserSettings',
'Login.authenticate.processSuccessfulSession.end' => 'onSuccessfulSession'
);
}
public function getStylesheetFiles(&$stylesheets)
{
$stylesheets[] = "plugins/TwoFactorAuth/stylesheets/twofactorauth.less";
}
public function getJsFiles(&$jsFiles)
{
$jsFiles[] = "plugins/TwoFactorAuth/javascripts/twofactorauth.js";
$jsFiles[] = "plugins/TwoFactorAuth/angularjs/setuptwofactor/setuptwofactor.controller.js";
}
public function deleteRecoveryCodes($returnedValue, $params)
{
$model = new Model();
if (!empty($params['parameters']['userLogin'])
&& !$model->userExists($params['parameters']['userLogin'])) {
// we delete only if the deletion was really successful
$dao = StaticContainer::get(RecoveryCodeDao::class);
$dao->deleteAllRecoveryCodesForLogin($params['parameters']['userLogin']);
}
}
public function render2FaUserSettings(&$out)
{
$validator = $this->getValidator();
if ($validator->canUseTwoFa()) {
$content = FrontController::getInstance()->dispatch('TwoFactorAuth', 'userSettings');
if (!empty($content)) {
$out .= $content;
}
}
}
public function onSuccessfulSession($login)
{
if (Piwik::getModule() === 'Login' && Piwik::getAction() === 'logme' && $login) {
// we allow user to send an "authCode" along logme to directly log in... if not, user will see the
// auth code verification screen after logme
$authCode = Common::getRequestVar('authCode', '', 'string');
$twoFa = $this->getTwoFa();
if ($authCode
&& $twoFa->isUserUsingTwoFactorAuthentication($login)
&& $twoFa->validateAuthCode($login, $authCode)) {
$sessionFingerprint = new SessionFingerprint();
$sessionFingerprint->setTwoFactorAuthenticationVerified();
}
}
}
private function getTwoFa()
{
return StaticContainer::get(TwoFactorAuthentication::class);
}
private function getValidator()
{
return StaticContainer::get(Validator::class);
}
private function isValidTokenAuth($tokenAuth)
{
$model = new Model();
$user = $model->getUserByTokenAuth($tokenAuth);
return !empty($user);
}
public function onApiGetTokenAuth($returnedValue, $params)
{
if (!SettingsPiwik::isPiwikInstalled()) {
return;
}
if (!empty($returnedValue) && !empty($params['parameters']['userLogin'])) {
$login = $params['parameters']['userLogin'];
$twoFa = $this->getTwoFa();
if ($twoFa->isUserUsingTwoFactorAuthentication($login) && $this->isValidTokenAuth($returnedValue)) {
$authCode = Common::getRequestVar('authCode', '', 'string');
// we only return an error when the login/password combo was correct. otherwise you could brute force
// auth tokens
if (!$authCode) {
http_response_code(401);
throw new Exception(Piwik::translate('TwoFactorAuth_MissingAuthCodeAPI'));
}
if (!$twoFa->validateAuthCode($login, $authCode)) {
http_response_code(401);
throw new Exception(Piwik::translate('TwoFactorAuth_InvalidAuthCode'));
}
} else if ($twoFa->isUserRequiredToHaveTwoFactorEnabled()
&& !$twoFa->isUserUsingTwoFactorAuthentication($login)) {
throw new Exception(Piwik::translate('TwoFactorAuth_RequiredAuthCodeNotConfiguredAPI'));
}
}
}
public function onRequestDispatch(&$module, &$action, $parameters)
{
$validator = $this->getValidator();
if (!$validator->canUseTwoFa()) {
return;
}
if ($module === 'Proxy') {
return;
}
if ($module === 'TwoFactorAuth' && $action === 'showQrCode') {
return;
}
if ($module === 'CoreUpdater') {
return;
}
if ($module === Piwik::getLoginPluginName() && $action === 'logout') {
return;
}
if (Piwik::getModule() === 'Widgetize') {
// we cannot use $module as it would be different when dispatching other requests within the widgetized request
$auth = StaticContainer::get('Piwik\Auth');
if ($auth && !$auth->getLogin() && method_exists($auth, 'getTokenAuth') && $auth->getTokenAuth()) {
// when authenticated by token only, we do not require 2fa
// needed eg for rendering exported widgets authenticated by token
return;
}
}
$requiresAuth = true;
Piwik::postEvent('TwoFactorAuth.requiresTwoFactorAuthentication', array(&$requiresAuth, $module, $action, $parameters));
if (!$requiresAuth) {
return;
}
$twoFa = $this->getTwoFa();
$isUsing2FA = $twoFa->isUserUsingTwoFactorAuthentication(Piwik::getCurrentUserLogin());
if ($isUsing2FA && !Request::isRootRequestApiRequest() && Session::isStarted()) {
$sessionFingerprint = new SessionFingerprint();
if (!$sessionFingerprint->hasVerifiedTwoFactor()) {
$module = 'TwoFactorAuth';
$action = 'loginTwoFactorAuth';
}
} elseif (!$isUsing2FA && $twoFa->isUserRequiredToHaveTwoFactorEnabled()) {
$module = 'TwoFactorAuth';
$action = 'onLoginSetupTwoFactorAuth';
}
}
public function onRequestDispatchEnd(&$result, $module, $action, $parameters)
{
$validator = $this->getValidator();
if (!$validator->canUseTwoFa()) {
return;
}
$twoFa = $this->getTwoFa();
$isUsing2FA = $twoFa->isUserUsingTwoFactorAuthentication(Piwik::getCurrentUserLogin());
if ($isUsing2FA && !Request::isRootRequestApiRequest()) {
$sessionFingerprint = new SessionFingerprint();
if (!$sessionFingerprint->hasVerifiedTwoFactor()) {
$result = $this->removeTokenFromOutput($result);
}
} elseif (!$isUsing2FA && $twoFa->isUserRequiredToHaveTwoFactorEnabled()) {
$result = $this->removeTokenFromOutput($result);
}
}
private function removeTokenFromOutput($output)
{
$token = Piwik::getCurrentUserTokenAuth();
// make sure to not leak the token... otherwise someone could log in using someone's credentials...
// and then maybe in the auth screen look into the DOM to find the token... and then bypass the
// auth code using API
return str_replace($token, md5('') . '2fareplaced', $output);
}
}
|