This repository has been archived by the owner on Jul 28, 2022. It is now read-only.
forked from rande/GoogleAuthenticator
-
Notifications
You must be signed in to change notification settings - Fork 122
/
GoogleAuthenticator.php
198 lines (168 loc) · 6.07 KB
/
GoogleAuthenticator.php
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
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Sonata\GoogleAuthenticator;
/**
* @see https://github.com/google/google-authenticator/wiki/Key-Uri-Format
*/
final class GoogleAuthenticator
{
/**
* @var int
*/
private $passCodeLength;
/**
* @var int
*/
private $secretLength;
/**
* @var int
*/
private $pinModulo;
/**
* @var \DateTimeInterface
*/
private $now;
/**
* @var int
*/
private $codePeriod = 30;
/**
* @param int $passCodeLength
* @param int $secretLength
* @param \DateTimeInterface|null $now
*/
public function __construct(int $passCodeLength = 6, int $secretLength = 10, \DateTimeInterface $now = null)
{
$this->passCodeLength = $passCodeLength;
$this->secretLength = $secretLength;
$this->pinModulo = 10 ** $passCodeLength;
$this->now = $now ?? new \DateTimeImmutable();
}
/**
* @param string $secret
* @param string $code
*
* @return bool
*/
public function checkCode($secret, $code): bool
{
/**
* The result of each comparison is accumulated here instead of using a guard clause
* (https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html). This is to implement
* constant time comparison to make side-channel attacks harder. See
* https://cryptocoding.net/index.php/Coding_rules#Compare_secret_strings_in_constant_time for details.
* Each comparison uses hash_equals() instead of an operator to implement constant time equality comparison
* for each code.
*/
$result = 0;
// current period
$result += hash_equals($this->getCode($secret, $this->now), $code);
// previous period, happens if the user was slow to enter or it just crossed over
$dateTime = new \DateTimeImmutable('@'.($this->now->getTimestamp() - $this->codePeriod));
$result += hash_equals($this->getCode($secret, $dateTime), $code);
// next period, happens if the user is not completely synced and possibly a few seconds ahead
$dateTime = new \DateTimeImmutable('@'.($this->now->getTimestamp() + $this->codePeriod));
$result += hash_equals($this->getCode($secret, $dateTime), $code);
return $result > 0;
}
/**
* NEXT_MAJOR: add the interface typehint to $time and remove deprecation.
*
* @param string $secret
* @param float|string|int|null|\DateTimeInterface $time
*
* @return string
*/
public function getCode($secret, /* \DateTimeInterface */$time = null): string
{
if (null === $time) {
$time = $this->now;
}
if ($time instanceof \DateTimeInterface) {
$timeForCode = floor($time->getTimestamp() / $this->codePeriod);
} else {
@trigger_error(
'Passing anything other than null or a DateTimeInterface to $time is deprecated as of 2.0 '.
'and will not be possible as of 3.0.',
E_USER_DEPRECATED
);
$timeForCode = $time;
}
$base32 = new FixedBitNotation(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', true, true);
$secret = $base32->decode($secret);
$timeForCode = str_pad(pack('N', $timeForCode), 8, chr(0), STR_PAD_LEFT);
$hash = hash_hmac('sha1', $timeForCode, $secret, true);
$offset = ord(substr($hash, -1));
$offset &= 0xF;
$truncatedHash = $this->hashToInt($hash, $offset) & 0x7FFFFFFF;
return str_pad((string) ($truncatedHash % $this->pinModulo), $this->passCodeLength, '0', STR_PAD_LEFT);
}
/**
* NEXT_MAJOR: Remove this method.
*
* @param string $user
* @param string $hostname
* @param string $secret
*
* @return string
*
* @deprecated deprecated as of 2.1 and will be removed in 3.0. Use Sonata\GoogleAuthenticator\GoogleQrUrl::generate() instead.
*/
public function getUrl($user, $hostname, $secret): string
{
@trigger_error(sprintf(
'Using %s() is deprecated as of 2.1 and will be removed in 3.0. '.
'Use Sonata\GoogleAuthenticator\GoogleQrUrl::generate() instead.',
__METHOD__
), E_USER_DEPRECATED);
$issuer = func_get_args()[3] ?? null;
$accountName = sprintf('%s@%s', $user, $hostname);
// manually concat the issuer to avoid a change in URL
$url = GoogleQrUrl::generate($accountName, $secret);
if ($issuer) {
$url .= '%26issuer%3D'.$issuer;
}
return $url;
}
/**
* @return string
*/
public function generateSecret(): string
{
return (new FixedBitNotation(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', true, true))
->encode(random_bytes($this->secretLength));
}
/**
* @param string $bytes
* @param int $start
*
* @return int
*/
private function hashToInt(string $bytes, int $start): int
{
return unpack('N', substr(substr($bytes, $start), 0, 4))[1];
}
}
// NEXT_MAJOR: Remove class alias
class_alias('Sonata\GoogleAuthenticator\GoogleAuthenticator', 'Google\Authenticator\GoogleAuthenticator', false);