web-base/Core/Objects/TwoFactor/KeyBasedTwoFactorToken.class.php

94 lines
2.6 KiB
PHP
Raw Normal View History

2022-02-20 16:53:26 +01:00
<?php
2022-11-18 18:06:46 +01:00
namespace Core\Objects\TwoFactor;
2022-02-20 16:53:26 +01:00
2022-11-27 15:58:44 +01:00
use Core\Driver\SQL\SQL;
2022-02-20 16:53:26 +01:00
use Cose\Algorithm\Signature\ECDSA\ECSignature;
2022-11-18 18:06:46 +01:00
use Core\Objects\DatabaseEntity\TwoFactorToken;
2022-02-20 16:53:26 +01:00
class KeyBasedTwoFactorToken extends TwoFactorToken {
const TYPE = "fido";
2022-11-27 12:33:27 +01:00
private ?string $challenge;
private ?string $credentialId;
private ?PublicKey $publicKey;
2022-02-20 16:53:26 +01:00
2022-11-27 15:58:44 +01:00
public function __construct(string $challenge) {
parent::__construct(self::TYPE);
$this->challenge = $challenge;
}
2022-06-20 19:52:31 +02:00
protected function readData(string $data) {
2022-11-27 15:58:44 +01:00
if (!$this->isConfirmed()) {
2022-02-20 16:53:26 +01:00
$this->challenge = base64_decode($data);
$this->credentialId = null;
$this->publicKey = null;
} else {
$jsonData = json_decode($data, true);
$this->challenge = base64_decode($_SESSION["challenge"] ?? "");
$this->credentialId = base64_decode($jsonData["credentialID"]);
$this->publicKey = PublicKey::fromJson($jsonData["publicKey"]);
}
}
public function getData(): string {
2022-11-27 15:58:44 +01:00
if ($this->isConfirmed()) {
return base64_encode($this->challenge);
} else {
return json_encode([
"credentialId" => $this->credentialId,
"publicKey" => $this->publicKey->jsonSerialize()
]);
}
}
public function confirmKeyBased(SQL $sql, string $credentialId, PublicKey $publicKey): bool {
$this->credentialId = $credentialId;
$this->publicKey = $publicKey;
return parent::confirm($sql);
2022-02-20 16:53:26 +01:00
}
2022-11-27 15:58:44 +01:00
2022-02-20 16:53:26 +01:00
public function getPublicKey(): ?PublicKey {
return $this->publicKey;
}
2022-06-20 19:52:31 +02:00
public function getCredentialId(): ?string {
2022-02-20 16:53:26 +01:00
return $this->credentialId;
}
public function jsonSerialize(): array {
$json = parent::jsonSerialize();
if (!empty($this->challenge) && !$this->isAuthenticated()) {
$json["challenge"] = base64_encode($this->challenge);
}
if (!empty($this->credentialId)) {
$json["credentialID"] = base64_encode($this->credentialId);
}
return $json;
}
// TODO: algorithms, hardcoded values, ...
public function verify(string $signature, string $data): bool {
switch ($this->publicKey->getUsedAlgorithm()) {
case -7: // EC2
if (strlen($signature) !== 64) {
$signature = \Cose\Algorithm\Signature\ECDSA\ECSignature::fromAsn1($signature, 64);
}
$coseKey = new \Cose\Key\Key($this->publicKey->getNormalizedData());
$ec2key = new \Cose\Key\Ec2Key($coseKey->getData());
$publicKey = $ec2key->toPublic();
$signature = ECSignature::toAsn1($signature, 64);
return openssl_verify($data, $signature, $publicKey->asPEM(), "sha256") === 1;
default:
// Not implemented :(
return false;
}
}
}