|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Copyright (C) 2016 SURFnet. |
|
4
|
|
|
* |
|
5
|
|
|
* This program is free software: you can redistribute it and/or modify |
|
6
|
|
|
* it under the terms of the GNU Affero General Public License as |
|
7
|
|
|
* published by the Free Software Foundation, either version 3 of the |
|
8
|
|
|
* License, or (at your option) any later version. |
|
9
|
|
|
* |
|
10
|
|
|
* This program is distributed in the hope that it will be useful, |
|
11
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
13
|
|
|
* GNU Affero General Public License for more details. |
|
14
|
|
|
* |
|
15
|
|
|
* You should have received a copy of the GNU Affero General Public License |
|
16
|
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
17
|
|
|
*/ |
|
18
|
|
|
|
|
19
|
|
|
namespace SURFnet\VPN\Server; |
|
20
|
|
|
|
|
21
|
|
|
use Base32\Base32; |
|
22
|
|
|
use Otp\Otp; |
|
23
|
|
|
use SURFnet\VPN\Server\Exception\TotpException; |
|
24
|
|
|
|
|
25
|
|
|
class Totp |
|
26
|
|
|
{ |
|
27
|
|
|
/** @var Storage */ |
|
28
|
|
|
private $storage; |
|
29
|
|
|
|
|
30
|
|
|
public function __construct(Storage $storage) |
|
31
|
|
|
{ |
|
32
|
|
|
$this->storage = $storage; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function verify($userId, $totpKey, $totpSecret = null) |
|
36
|
|
|
{ |
|
37
|
|
|
// for the enroll phase totpSecret is also provided, use that then |
|
38
|
|
|
// instead of fetching one from the DB |
|
39
|
|
|
if (is_null($totpSecret)) { |
|
40
|
|
|
if (!$this->storage->hasTotpSecret($userId)) { |
|
41
|
|
|
throw new TotpException('user has no TOTP secret'); |
|
42
|
|
|
} |
|
43
|
|
|
$totpSecret = $this->storage->getTotpSecret($userId); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
// store the attempt even before validating it, to be able to count |
|
47
|
|
|
// the (failed) attempts |
|
48
|
|
|
if (false === $this->storage->recordTotpKey($userId, $totpKey)) { |
|
49
|
|
|
throw new TotpException('TOTP key replay'); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
if (10 < $this->storage->getTotpAttemptCount($userId)) { |
|
53
|
|
|
throw new TotpException('too many attempts at TOTP'); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
$otp = new Otp(); |
|
57
|
|
|
if (!$otp->checkTotp(Base32::decode($totpSecret), $totpKey)) { |
|
58
|
|
|
throw new TotpException('invalid TOTP key'); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|