Debian Codegraph @

vendor/spomky-labs/otphp/src/OTP.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace OTPHP;
6
7 use function array_key_exists;
8 use function chr;
9 use function count;
10 use Exception;
11 use function in_array;
12 use function is_int;
13 use function is_string;
14 use OTPHP\Exception\InvalidLabelException;
15 use OTPHP\Exception\InvalidParameterException;
16 use OTPHP\Exception\ParameterNotFoundException;
17 use OTPHP\Exception\SecretDecodingException;
18 use ParagonIE\ConstantTime\Base32;
19 use function sprintf;
20 use const STR_PAD_LEFT;
21 use function strlen;
22
23 /**
24 * @readonly
25 */
26 abstract class OTP implements OTPInterface
27 {
28 private const DEFAULT_SECRET_SIZE = 64;
29
30 /**
31 * Minimum digest size, in bytes, required by the RFC 4226 dynamic truncation.
32 *
33 * The truncation reads four bytes starting at an offset taken from the low
34 * nibble of the last digest byte, i.e. an offset in the range [0, 15]. It
35 * therefore reads up to index "offset + 3" = 18 and needs at least 19 bytes.
36 * A shorter digest (e.g. MD5, 16 bytes) makes the truncation read past the
37 * end of the hash, collapsing the output to a small, secret-independent set
38 * of values. Such algorithms are also outside RFC 4226/6238 and are not
39 * interoperable with authenticator apps. See {@see self::generateOTP()}.
40 */
41 private const MINIMUM_DIGEST_SIZE = 19;
42
43 /**
44 * @var array<non-empty-string, mixed>
45 */
46 private array $parameters = [];
47
48 /**
49 * @var non-empty-string|null
50 */
51 private null|string $issuer = null;
52
53 /**
54 * @var non-empty-string|null
55 */
56 private null|string $label = null;
57
58 private bool $issuer_included_as_parameter = true;
59
60 /**
61 * @param non-empty-string $secret
62 */
63 protected function __construct(string $secret)
64 {
65 $this->setSecret($secret);
66 }
67
68 public function getQrCodeUri(string $uri, string $placeholder): string
69 {
70 $provisioning_uri = urlencode($this->getProvisioningUri());
71
72 return str_replace($placeholder, $provisioning_uri, $uri);
73 }
74
75 /**
76 * @param 0|positive-int $input
77 */
78 public function at(int $input): string
79 {
80 return $this->generateOTP($input);
81 }
82
83 /**
84 * @return array<non-empty-string, mixed>
85 */
86 public function getParameters(): array
87 {
88 $parameters = $this->parameters;
89
90 if ($this->getIssuer() !== null && $this->isIssuerIncludedAsParameter() === true) {
91 $parameters['issuer'] = $this->getIssuer();
92 }
93
94 return $parameters;
95 }
96
97 public function getSecret(): string
98 {
99 $value = $this->getParameter('secret');
100 (is_string($value) && $value !== '') || throw new InvalidParameterException(
101 'Invalid "secret" parameter.',
102 'secret',
103 $value
104 );
105
106 return $value;
107 }
108
109 public function getLabel(): null|string
110 {
111 return $this->label;
112 }
113
114 public function setLabel(string $label): void
115 {
116 $this->setParameter('label', $label);
117 }
118
119 public function withLabel(string $label): static
120 {
121 $otp = clone $this;
122 $otp->setParameter('label', $label);
123
124 return $otp;
125 }
126
127 public function getIssuer(): null|string
128 {
129 return $this->issuer;
130 }
131
132 public function setIssuer(string $issuer): void
133 {
134 $this->setParameter('issuer', $issuer);
135 }
136
137 public function withIssuer(string $issuer): static
138 {
139 $otp = clone $this;
140 $otp->setParameter('issuer', $issuer);
141
142 return $otp;
143 }
144
145 public function isIssuerIncludedAsParameter(): bool
146 {
147 return $this->issuer_included_as_parameter;
148 }
149
150 public function setIssuerIncludedAsParameter(bool $issuer_included_as_parameter): void
151 {
152 $this->issuer_included_as_parameter = $issuer_included_as_parameter;
153 }
154
155 public function withIssuerIncludedAsParameter(bool $issuer_included_as_parameter): static
156 {
157 $otp = clone $this;
158 $otp->issuer_included_as_parameter = $issuer_included_as_parameter;
159
160 return $otp;
161 }
162
163 public function getDigits(): int
164 {
165 $value = $this->getParameter('digits');
166 (is_int($value) && $value >= 1 && $value <= self::MAX_DIGITS) || throw new InvalidParameterException(
167 'Invalid "digits" parameter.',
168 'digits',
169 $value
170 );
171
172 return $value;
173 }
174
175 public function getDigest(): string
176 {
177 $value = $this->getParameter('algorithm');
178 (is_string($value) && $value !== '') || throw new InvalidParameterException(
179 'Invalid "algorithm" parameter.',
180 'algorithm',
181 $value
182 );
183
184 return $value;
185 }
186
187 public function hasParameter(string $parameter): bool
188 {
189 return array_key_exists($parameter, $this->parameters);
190 }
191
192 public function getParameter(string $parameter): mixed
193 {
194 if ($this->hasParameter($parameter)) {
195 return $this->getParameters()[$parameter];
196 }
197
198 throw new ParameterNotFoundException(sprintf('Parameter "%s" does not exist', $parameter), $parameter);
199 }
200
201 public function setParameter(string $parameter, mixed $value): void
202 {
203 $map = $this->getParameterMap();
204
205 if (array_key_exists($parameter, $map) === true) {
206 $callback = $map[$parameter];
207 $value = $callback($value);
208 }
209
210 if (in_array($parameter, ['label', 'issuer'], true)) {
211 $this->{$parameter} = $value;
212 } else {
213 $this->parameters[$parameter] = $value;
214 }
215 }
216
217 public function withParameter(string $parameter, mixed $value): static
218 {
219 $otp = clone $this;
220 $otp->setParameter($parameter, $value);
221
222 return $otp;
223 }
224
225 public function setSecret(string $secret): void
226 {
227 $this->setParameter('secret', $secret);
228 }
229
230 public function withSecret(string $secret): static
231 {
232 $otp = clone $this;
233 $otp->setParameter('secret', $secret);
234
235 return $otp;
236 }
237
238 public function setDigits(int $digits): void
239 {
240 $this->setParameter('digits', $digits);
241 }
242
243 public function withDigits(int $digits): static
244 {
245 $otp = clone $this;
246 $otp->setParameter('digits', $digits);
247
248 return $otp;
249 }
250
251 public function setDigest(string $digest): void
252 {
253 $this->setParameter('algorithm', $digest);
254 }
255
256 public function withDigest(string $digest): static
257 {
258 $otp = clone $this;
259 $otp->setParameter('algorithm', $digest);
260
261 return $otp;
262 }
263
264 /**
265 * @param positive-int|null $secretSize
266 *
267 * @return non-empty-string
268 */
269 final protected static function generateSecret(?int $secretSize = null): string
270 {
271 $secretSize ??= self::DEFAULT_SECRET_SIZE;
272 $secretSize > 0 || throw new InvalidParameterException(
273 'Secret size must be at least 1.',
274 'secretSize',
275 $secretSize
276 );
277
278 return Base32::encodeUpper(random_bytes($secretSize));
279 }
280
281 /**
282 * The OTP at the specified input.
283 *
284 * @param 0|positive-int $input
285 *
286 * @return non-empty-string
287 */
288 protected function generateOTP(int $input): string
289 {
290 $hash = hash_hmac($this->getDigest(), $this->intToByteString($input), $this->getDecodedSecret(), true);
291 $unpacked = unpack('C*', $hash);
292 $unpacked !== false || throw new InvalidParameterException('Invalid data.', 'hash', $hash);
293 /** @var list<int> $hmac */
294 $hmac = array_values($unpacked);
295
296 $offset = ($hmac[count($hmac) - 1] & 0xF);
297 $code = ($hmac[$offset] & 0x7F) << 24 | ($hmac[$offset + 1] & 0xFF) << 16 | ($hmac[$offset + 2] & 0xFF) << 8 | ($hmac[$offset + 3] & 0xFF);
298 $otp = $code % (10 ** $this->getDigits());
299
300 return str_pad((string) $otp, $this->getDigits(), '0', STR_PAD_LEFT);
301 }
302
303 /**
304 * @param array<non-empty-string, mixed> $options
305 */
306 protected function filterOptions(array &$options): void
307 {
308 foreach ([
309 'algorithm' => 'sha1',
310 'period' => 30,
311 'digits' => 6,
312 ] as $key => $default) {
313 if (isset($options[$key]) && $default === $options[$key]) {
314 unset($options[$key]);
315 }
316 }
317
318 ksort($options);
319 }
320
321 /**
322 * @param non-empty-string $type
323 * @param array<non-empty-string, mixed> $options
324 *
325 * @return non-empty-string
326 */
327 protected function generateURI(string $type, array $options): string
328 {
329 $options = [...$options, ...$this->getParameters()];
330 $this->filterOptions($options);
331 $params = str_replace(['+', '%7E'], ['%20', '~'], http_build_query($options, '', '&'));
332
333 return sprintf('otpauth://%s/%s?%s', $type, rawurlencode($this->buildProvisioningUriLabel()), $params);
334 }
335
336 /**
337 * @param non-empty-string $safe
338 * @param non-empty-string $user
339 */
340 protected function compareOTP(string $safe, string $user): bool
341 {
342 return hash_equals($safe, $user);
343 }
344
345 /**
346 * @return array<non-empty-string, callable>
347 */
348 protected function getParameterMap(): array
349 {
350 return [
351 'label' => function (string $value): string {
352 $value !== '' || throw new InvalidLabelException('Label must not be empty.', 'label', $value);
353 $this->validateLabel($value);
354
355 return $value;
356 },
357 'secret' => static fn (string $value): string => strtoupper(trim($value, '=')),
358 'algorithm' => static function (string $value): string {
359 $value = strtolower($value);
360 in_array($value, hash_hmac_algos(), true) || throw new InvalidParameterException(
361 sprintf('The "%s" digest is not supported.', $value),
362 'algorithm',
363 $value
364 );
365 $size = strlen(hash($value, '', true));
366 $size >= self::MINIMUM_DIGEST_SIZE || throw new InvalidParameterException(
367 sprintf(
368 'The "%s" digest produces a %d-byte hash which is too short for the RFC 4226 dynamic truncation; at least %d bytes are required.',
369 $value,
370 $size,
371 self::MINIMUM_DIGEST_SIZE
372 ),
373 'algorithm',
374 $value
375 );
376
377 return $value;
378 },
379 'digits' => static function ($value): int {
380 $value = (int) $value;
381 ($value >= 1 && $value <= self::MAX_DIGITS) || throw new InvalidParameterException(
382 sprintf('Digits must be between 1 and %d.', self::MAX_DIGITS),
383 'digits',
384 $value
385 );
386
387 return $value;
388 },
389 'issuer' => function (string $value): string {
390 $value !== '' || throw new InvalidLabelException('Issuer must not be empty.', 'issuer', $value);
391 $this->hasColon($value) === false || throw new InvalidLabelException(
392 'Issuer must not contain a colon.',
393 'issuer',
394 $value
395 );
396
397 return $value;
398 },
399 ];
400 }
401
402 /**
403 * @return non-empty-string
404 */
405 private function getDecodedSecret(): string
406 {
407 try {
408 $decoded = Base32::decodeUpper($this->getSecret());
409 } catch (Exception) {
410 throw new SecretDecodingException('Unable to decode the secret. Is it correctly base32 encoded?');
411 }
412 $decoded !== '' || throw new SecretDecodingException('The decoded secret must not be empty.');
413
414 return $decoded;
415 }
416
417 private function intToByteString(int $int): string
418 {
419 $result = [];
420 while ($int !== 0) {
421 $result[] = chr($int & 0xFF);
422 $int >>= 8;
423 }
424
425 return str_pad(implode('', array_reverse($result)), 8, "\000", STR_PAD_LEFT);
426 }
427
428 /**
429 * @return non-empty-string
430 */
431 private function buildProvisioningUriLabel(): string
432 {
433 $issuer = $this->getIssuer();
434 $label = $this->getLabel();
435
436 return match (true) {
437 $issuer === null && $label === null => throw new InvalidLabelException(
438 'The label is not set. Either label or issuer must be set.',
439 'label'
440 ),
441 $label !== null && $this->hasColon($label) => throw new InvalidLabelException(
442 'Label must not contain a colon.',
443 'label',
444 $label
445 ),
446 $issuer !== null && $label !== null => $issuer . ':' . $label,
447 $issuer !== null => $issuer,
448 default => $label,
449 };
450 }
451
452 /**
453 * Validates a label according to Google Authenticator spec:
454 * label = accountname / issuer (":" / "%3A") *"%20" accountname
455 * Neither issuer nor account name may themselves contain a colon.
456 *
457 * Valid examples:
458 * - [email protected]
459 * - Provider1:Alice%20Smith
460 * - Big%20Corporation%3A%20alice%40bigco.com
461 *
462 * @param non-empty-string $value
463 */
464 private function validateLabel(string $value): void
465 {
466 // Check for colon separators (literal or URL-encoded)
467 $hasLiteralColon = str_contains($value, ':');
468 $hasEncodedColon = str_contains($value, '%3A') || str_contains($value, '%3a');
469
470 if (! $hasLiteralColon && ! $hasEncodedColon) {
471 // Simple label (account name only) - no colons allowed anywhere
472 return;
473 }
474
475 // Label contains a separator - validate issuer:account format
476 // Split by literal or encoded colon
477 $parts = match (true) {
478 $hasLiteralColon => explode(':', $value, 2),
479 default => preg_split('/%3[Aa]/', $value, 2),
480 };
481
482 if ($parts === false || count($parts) !== 2) {
483 throw new InvalidLabelException('Label must not contain a colon.', 'label', $value);
484 }
485
486 [$issuerPart, $accountPart] = $parts;
487
488 // Remove leading %20 (spaces) from account part per spec: *"%20" accountname
489 $accountPart = ltrim($accountPart, '%20');
490
491 // Validate that neither part contains additional colons
492 if ($this->hasColon($issuerPart) || $this->hasColon($accountPart)) {
493 throw new InvalidLabelException(
494 'Neither issuer nor account name in label may contain a colon.',
495 'label',
496 $value
497 );
498 }
499 }
500
501 /**
502 * @param non-empty-string $value
503 */
504 private function hasColon(string $value): bool
505 {
506 $colons = [':', '%3A', '%3a'];
507 foreach ($colons as $colon) {
508 if (str_contains($value, $colon)) {
509 return true;
510 }
511 }
512
513 return false;
514 }
515 }