Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TwoFactorAuthentication.php « TwoFactorAuth « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6139e62dd78fc61b455ceb495a42967539dde04e (plain)
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
<?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\Common;
use Piwik\Db;
use Piwik\Option;
use Piwik\Piwik;
use Piwik\Plugins\TwoFactorAuth\Dao\RecoveryCodeDao;
use Piwik\Plugins\TwoFactorAuth\Dao\TwoFaSecretRandomGenerator;
use Piwik\Plugins\UsersManager\Model;
use Exception;
use Piwik\SettingsPiwik;

require_once PIWIK_DOCUMENT_ROOT . '/libs/Authenticator/TwoFactorAuthenticator.php';

class TwoFactorAuthentication
{
    const OPTION_PREFIX_TWO_FA_CODE_USED = 'twofa_codes_used_';

    /**
     * Make sure the same fa code was not used in the last X minutes.
     * Technically, even 2 minutes be fine since every token is only valid for 30 sec and we only allow the 2 most
     * recent tokens.
     */
    const BLOCK_TWOFA_CODE_MINUTES = 10;

    /**
     * @var SystemSettings
     */
    private $settings;

    /**
     * @var RecoveryCodeDao
     */
    private $recoveryCodeDao;

    /**
     * @var TwoFaSecretRandomGenerator
     */
    private $secretGenerator;

    public function __construct(SystemSettings $systemSettings, RecoveryCodeDao $recoveryCodeDao, TwoFaSecretRandomGenerator $twoFaSecretRandomGenerator)
    {
        $this->settings = $systemSettings;
        $this->recoveryCodeDao = $recoveryCodeDao;
        $this->secretGenerator = $twoFaSecretRandomGenerator;
    }

    private static function getUserModel()
    {
        return new Model();
    }

    public function generateSecret()
    {
        return $this->secretGenerator->generateSecret();
    }

    public function disable2FAforUser($login)
    {
        $this->saveSecret($login, '');
        $this->recoveryCodeDao->deleteAllRecoveryCodesForLogin($login);

        Piwik::postEvent('TwoFactorAuth.disabled', array($login));
    }

    private static function isAnonymous($login)
    {
        return strtolower($login) === 'anonymous';
    }

    public function saveSecret($login, $secret)
    {
        if (self::isAnonymous($login)) {
            throw new Exception('Anonymous cannot use two-factor authentication');
        }

        if (!empty($secret) && !$this->recoveryCodeDao->getAllRecoveryCodesForLogin($login)) {
            // ensures the user has seen and ideally backuped the recovery codes... we don't create them here on demand
            throw new Exception('Cannot enable two-factor authentication, no recovery codes have been created');
        }

        $model = self::getUserModel();
        $model->updateUserFields($login, array('twofactor_secret' => $secret));
    }

    public function isUserRequiredToHaveTwoFactorEnabled()
    {
        return $this->settings->twoFactorAuthRequired->getValue();
    }

    public static function isUserUsingTwoFactorAuthentication($login)
    {
        if (self::isAnonymous($login)) {
            return false; // not possible to use auth code with anonymous
        }

        $user = self::getUser($login);
        return !empty($user['twofactor_secret']);
    }

    private static function getUser($login)
    {
        $model = self::getUserModel();
        return $model->getUser($login);
    }

    private function wasTwoFaCodeUsedRecently($login, $authCode)
    {
        $time = Option::get($this->gettwoFaCodeUsedKey($login, $authCode));
        if (empty($time)) {
            return false;
        }
        $fiveMinutes = 60 * self::BLOCK_TWOFA_CODE_MINUTES;
        if (time() - $fiveMinutes >= (int)$time) {
            return true;
        }
        return false;
    }

    private function gettwoFaCodeUsedKey($login, $authCode)
    {
        return self::OPTION_PREFIX_TWO_FA_CODE_USED . md5($login . $authCode . SettingsPiwik::getSalt());
    }

    private function setTwoFaCodeWasUsed($login, $authCode)
    {
        $table = Common::prefixTable('option');
        $bind = array($this->gettwoFaCodeUsedKey($login, $authCode), time(), 0);
        try {
            Db::query('INSERT INTO `' . $table . '` (option_name, option_value, autoload) VALUES (?, ?, ?) ', $bind);
            return true;
        } catch (Exception $e) {
            // when 2 process try to insert at same time should result in duplicate error
            return false;
        }
    }

    public function cleanupTwoFaCodesUsedRecently()
    {
        $values = Option::getLike(TwoFactorAuthentication::OPTION_PREFIX_TWO_FA_CODE_USED . '%');
        if (!empty($values)) {
            foreach ($values as $optionName => $timeCodeWasUsed) {
                $fiveMinutesAgo = time() - (60 * self::BLOCK_TWOFA_CODE_MINUTES);
                if ($timeCodeWasUsed < $fiveMinutesAgo) {
                    // delete any entry created more than 5 min ago
                    Option::delete($optionName);
                }
            }
        }
    }

    public function validateAuthCode($login, $authCode)
    {
        if (!self::isUserUsingTwoFactorAuthentication($login)) {
            return false;
        }

        $user = self::getUser($login);

        if ($this->wasTwoFaCodeUsedRecently($user['login'], $authCode)) {
            return false;
        }

        if (!$this->setTwoFaCodeWasUsed($user['login'], $authCode)) {
            return false;
        }

        if (!empty($user['twofactor_secret'])
            && $this->validateAuthCodeDuringSetup($authCode, $user['twofactor_secret'])) {
            return true;
        }

        if ($this->recoveryCodeDao->useRecoveryCode($user['login'], $authCode)) {
            return true;
        }

        return false;
    }

    public function validateAuthCodeDuringSetup($authCode, $secret)
    {
        $twoFactorAuth = $this->makeAuthenticator();

        if (!empty($secret) && $twoFactorAuth->verifyCode($secret, $authCode, 2)) {
            return true;
        }
        return false;
    }

    private function makeAuthenticator()
    {
        return new \TwoFactorAuthenticator();
    }

}