- incs/db.php: db_verbinden() setzt utf8mb4, strikten sql_mode und schaltet die mysqli-Exceptions von PHP 8.1+ ab, damit die bestehenden "or error(mysqli_error())"-Pruefungen weiter greifen. - db_abfrage/db_zeilen/db_zeile/db_wert mit ?-Platzhaltern (mysqli_execute_query, PHP 8.2). - Alle neun kopierten mysqli_connect/select_db-Stellen nutzen jetzt db_verbinden(). Nur zusammen mit der auf utf8mb4 migrierten Datenbank einsetzbar. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
373 lines
15 KiB
PHP
373 lines
15 KiB
PHP
<?php
|
|
|
|
/*
|
|
* Copyright (C) 2022 Lukas Buchs
|
|
* license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
|
*
|
|
* Server test script for WebAuthn library. Saves new registrations in session.
|
|
*
|
|
* JAVASCRIPT | SERVER
|
|
* ------------------------------------------------------------
|
|
*
|
|
* REGISTRATION
|
|
*
|
|
* window.fetch -----------------> getCreateArgs
|
|
* |
|
|
* navigator.credentials.create <-------------'
|
|
* |
|
|
* '-------------------------> processCreate
|
|
* |
|
|
* alert ok or fail <----------------'
|
|
*
|
|
* ------------------------------------------------------------
|
|
*
|
|
* VALIDATION
|
|
*
|
|
* window.fetch ------------------> getGetArgs
|
|
* |
|
|
* navigator.credentials.get <----------------'
|
|
* |
|
|
* '-------------------------> processGet
|
|
* |
|
|
* alert ok or fail <----------------'
|
|
*
|
|
* ------------------------------------------------------------
|
|
*/
|
|
|
|
require_once './incs/WebAuthn/src/WebAuthn.php';
|
|
|
|
|
|
|
|
try {
|
|
require_once("incs/constants.php");
|
|
session_name(SESSION_NAME);
|
|
session_start();
|
|
require_once("incs/authHelper.php");
|
|
require_once("incs/settings.php");
|
|
$settings=readsettings();
|
|
if($settings != "valid")
|
|
$action = "setup";
|
|
|
|
if($settings == "valid")
|
|
{
|
|
if(!$dbconn = db_verbinden($mysql_server, $mysql_user, $mysql_pw, $mysql_db))
|
|
$err = error("Verbindung zur Datenbank fehlgeschlagen: ".htmlspecialchars(mysqli_connect_error()));
|
|
}
|
|
// read get argument and post body
|
|
$fn = filter_input(INPUT_GET, 'fn');
|
|
$requireResidentKey = false;
|
|
$userVerification = false;
|
|
$formats = [];
|
|
$msg="";
|
|
|
|
$formats[] = 'android-key';
|
|
$formats[] = 'android-safetynet';
|
|
$formats[] = 'apple';
|
|
$formats[] = 'fido-u2f';
|
|
$formats[] = 'none';
|
|
$formats[] = 'packed';
|
|
$formats[] = 'tpm';
|
|
$userId = "E071229F004A4CDE";
|
|
$userName = "SmartHomeWagner";
|
|
$userDisplayName = "2025Bym0";
|
|
|
|
$post = trim(file_get_contents('php://input'));
|
|
if ($post) {
|
|
$post = json_decode($post, null, 512, JSON_THROW_ON_ERROR);
|
|
}
|
|
|
|
$rpId = "wm.el-wa.org";
|
|
if ($rpId === false) {
|
|
throw new Exception('invalid relying party ID');
|
|
}
|
|
|
|
// cross-platform: true, if type internal is not allowed
|
|
// false, if only internal is allowed
|
|
// null, if internal and cross-platform is allowed
|
|
$crossPlatformAttachment = null;
|
|
|
|
// new Instance of the server library.
|
|
// make sure that $rpId is the domain name.
|
|
$WebAuthn = new lbuchs\WebAuthn\WebAuthn('WebAuthn Library', $rpId, $formats);
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/isrg-root-x2.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/solo.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/solokey_f1.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/solokey_r1.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/apple.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/yubico.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/hypersecu.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/globalSign.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/googleHardware.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/microsoftTpmCollection.pem');
|
|
$WebAuthn->addRootCertificates('./restricted/WebAuthn/rootCertificates/mds');
|
|
|
|
// ------------------------------------
|
|
// request for create arguments
|
|
// ------------------------------------
|
|
|
|
if ($fn === 'getCreateArgs') {
|
|
$createArgs = $WebAuthn->getCreateArgs(\hex2bin($userId), $userName, $userDisplayName, 60*4, $requireResidentKey, $userVerification, $crossPlatformAttachment);
|
|
|
|
header('Content-Type: application/json');
|
|
print(json_encode($createArgs));
|
|
|
|
// save challange to session. you have to deliver it to processGet later.
|
|
$_SESSION['challenge'] = $WebAuthn->getChallenge();
|
|
|
|
|
|
|
|
// ------------------------------------
|
|
// request for get arguments
|
|
// ------------------------------------
|
|
|
|
} else if ($fn === 'getGetArgs') {
|
|
$result = mysqli_query($dbconn,"SELECT id FROM user WHERE nick = '".mysqli_real_escape_string($dbconn,$_GET["user"])."';");
|
|
if ($result->num_rows > 0) {
|
|
$row = $result->fetch_assoc();
|
|
$userId = $row["id"];
|
|
}else{
|
|
throw new Exception('Username not found');
|
|
}
|
|
$ids = [];
|
|
$result = mysqli_query($dbconn,"SELECT credentialId FROM passkeys WHERE userId = '".$userId."';");
|
|
if(!$result){
|
|
$msg = "Error:<br>".mysqli_error($dbconn)."<br />";
|
|
}
|
|
if ($result->num_rows > 0) {
|
|
while($row = $result->fetch_assoc()) {
|
|
$ids[] = base64_decode($row["credentialId"]);
|
|
}
|
|
}
|
|
|
|
if (count($ids) === 0) {
|
|
throw new Exception('no registrations in session for userId ' . $userId);
|
|
}
|
|
|
|
$getArgs = $WebAuthn->getGetArgs($ids, 60*4, true, true, true, true, true, $userVerification);
|
|
|
|
header('Content-Type: application/json');
|
|
print(json_encode($getArgs));
|
|
|
|
// save challange to session. you have to deliver it to processGet later.
|
|
$_SESSION['challenge'] = $WebAuthn->getChallenge();
|
|
|
|
|
|
|
|
// ------------------------------------
|
|
// process create
|
|
// ------------------------------------
|
|
|
|
} else if ($fn === 'processCreate') {
|
|
//$mysql = new mysqli($mysql_server,$mysql_user,$mysql_pass,$mysql_db);
|
|
$clientDataJSON = !empty($post->clientDataJSON) ? base64_decode($post->clientDataJSON) : null;
|
|
$attestationObject = !empty($post->attestationObject) ? base64_decode($post->attestationObject) : null;
|
|
$challenge = $_SESSION['challenge'] ?? null;
|
|
|
|
// processCreate returns data to be stored for future logins.
|
|
// in this example we store it in the php session.
|
|
// Normally you have to store the data in a database connected
|
|
// with the username.
|
|
$data = $WebAuthn->processCreate($clientDataJSON, $attestationObject, $challenge, $userVerification === 'required', true, false);
|
|
|
|
// add user infos
|
|
$data->userId = $userId;
|
|
$data->userName = $userName;
|
|
$data->userDisplayName = $userDisplayName;
|
|
//set Null to 0
|
|
$data->signatureCounter ??= 0;
|
|
/*
|
|
if (!isset($_SESSION['registrations']) || !array_key_exists('registrations', $_SESSION) || !is_array($_SESSION['registrations'])) {
|
|
$_SESSION['registrations'] = [];
|
|
}*/
|
|
if(!mysqli_query($dbconn,"INSERT INTO passkeys SET credentialId = '".base64_encode($data->credentialId)."', credentialPublicKey = '".base64_encode($data->credentialPublicKey)."', signatureCounter = '".base64_encode($data->signatureCounter)."', name = '".mysqli_real_escape_string($mysql,filter_input(INPUT_GET, 'name'))."', userId = '".mysqli_real_escape_string($mysql,filter_input(INPUT_GET, 'id'))."';")){
|
|
$msg = "Error:<br>".mysqli_error($dbconn)."<br />";
|
|
}
|
|
else{
|
|
if ($data->rootValid === false) {
|
|
$msg = 'registration ok, but certificate does not match any of the selected root ca. NO PROBLEM FOR THIS APP';
|
|
}
|
|
// $msg = "Data: ".json_last_error();//json_encode($data);//'registration success.';
|
|
}
|
|
/*
|
|
$_SESSION['registrations'][] = $data;
|
|
*/
|
|
$return = new stdClass();
|
|
$return->success = true;
|
|
$return->msg = $msg;
|
|
|
|
header('Content-Type: application/json');
|
|
print(json_encode($return));
|
|
|
|
|
|
|
|
// ------------------------------------
|
|
// proccess get
|
|
// ------------------------------------
|
|
|
|
} else if ($fn === 'processGet') {
|
|
$clientDataJSON = !empty($post->clientDataJSON) ? base64_decode($post->clientDataJSON) : null;
|
|
$authenticatorData = !empty($post->authenticatorData) ? base64_decode($post->authenticatorData) : null;
|
|
$signature = !empty($post->signature) ? base64_decode($post->signature) : null;
|
|
$userHandle = !empty($post->userHandle) ? base64_decode($post->userHandle) : null;
|
|
$id = !empty($post->id) ? base64_decode($post->id) : null;
|
|
$challenge = $_SESSION['challenge'] ?? '';
|
|
$credentialPublicKey = null;
|
|
|
|
// looking up correspondending public key of the credential id
|
|
// you should also validate that only ids of the given user name
|
|
// are taken for the login.
|
|
$result = mysqli_query($dbconn,"SELECT credentialPublicKey, userId, name FROM passkeys WHERE credentialId = '".base64_encode($id)."';");
|
|
if(!$result){
|
|
$msg = "Error:<br>".mysqli_error($dbconn)."<br />";
|
|
}
|
|
if ($result->num_rows > 0) {
|
|
$row = $result->fetch_assoc();
|
|
$userId = $row["userId"];
|
|
$credentialPublicKey = base64_decode($row["credentialPublicKey"]);
|
|
$reg = (object) ['userId' => base64_decode($row["userId"])];
|
|
$username = $row["name"];
|
|
} /*else {
|
|
if (isset($_SESSION['registrations']) && is_array($_SESSION['registrations'])) {
|
|
foreach ($_SESSION['registrations'] as $reg) {
|
|
if ($reg->credentialId === $id) {
|
|
$credentialPublicKey = $reg->credentialPublicKey;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}*/
|
|
if ($credentialPublicKey === null) {
|
|
throw new Exception('Public Key for credential ID not found!');
|
|
}
|
|
|
|
// if we have resident key, we have to verify that the userHandle is the provided userId at registration
|
|
if ($requireResidentKey && $userHandle !== hex2bin($reg->userId)) {
|
|
throw new \Exception('userId doesnt match (is ' . bin2hex($userHandle) . ' but expect ' . $reg->userId . ')');
|
|
}
|
|
|
|
// process the get request. throws WebAuthnException if it fails
|
|
$WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $credentialPublicKey, $challenge, null, $userVerification === 'required');
|
|
|
|
|
|
$authKey = strval(random_int(0,99999999));
|
|
$result = mysqli_query($dbconn,"UPDATE passkeys SET authKey=".$authKey.", lastAuth=NOW() WHERE credentialId = '".base64_encode($id)."';");
|
|
$qry= mysqli_query($dbconn, "SELECT * FROM user WHERE id = '".mysqli_real_escape_string($dbconn,$userId)."'");
|
|
if(mysqli_num_rows($qry) == 1)
|
|
{
|
|
$udata = mysqli_fetch_assoc($qry);
|
|
$_SESSION["login"] = "valid";
|
|
$_SESSION["logedout"] = $udata["logedout"];
|
|
$_SESSION["user"] = $udata["id"];
|
|
$_SESSION["nick"] = $udata["nick"];
|
|
$_SESSION["vname"] = $udata["vname"];
|
|
$_SESSION["nname"] = $udata["nname"];
|
|
$_SESSION["rights"] = $udata["rights"];
|
|
$_SESSION["lastlogin"] = $udata["lastlogin"];
|
|
$_SESSION["numlogins"] = $udata["numlogins"];
|
|
$_SESSION["style"] = getUserSetting($dbconn,"style", $udata["id"]);
|
|
if(!is_file("styles/".$_SESSION["style"]))
|
|
{
|
|
updateUserSetting($dbconn,"style", "default.css", $udata["id"]);
|
|
$_SESSION["style"] = getUserSetting($dbconn,"style", $udata["id"]);
|
|
}
|
|
$_SESSION["zoom"] = getUserSetting($dbconn,"zoom", $_SESSION["user"], 1);
|
|
$_SESSION["privateNotes"] = getUserSetting($dbconn,"privnotes", $_SESSION["user"], "");
|
|
|
|
mysqli_query($dbconn, "UPDATE user SET wrongpw = 0, lastlogin = NOW(), numlogins = numlogins + 1, logedout = 0 WHERE id = '".mysqli_real_escape_string($dbconn,$userId)."'");
|
|
}
|
|
$return = new stdClass();
|
|
$return->success = true;
|
|
header('Content-Type: application/json');
|
|
print(json_encode($return));
|
|
|
|
// ------------------------------------
|
|
// proccess clear registrations
|
|
// ------------------------------------
|
|
|
|
} else if ($fn === 'clearRegistrations') {
|
|
$_SESSION['registrations'] = null;
|
|
$_SESSION['challenge'] = null;
|
|
|
|
$return = new stdClass();
|
|
$return->success = true;
|
|
$return->msg = 'all registrations deleted';
|
|
|
|
header('Content-Type: application/json');
|
|
print(json_encode($return));
|
|
|
|
// ------------------------------------
|
|
// display stored data as HTML
|
|
// ------------------------------------
|
|
|
|
} /*else if ($fn === 'getStoredDataHtml') {
|
|
$html = '<!DOCTYPE html>' . "\n";
|
|
$html .= '<html><head><style>tr:nth-child(even){background-color: #f2f2f2;}</style></head>';
|
|
$html .= '<body style="font-family:sans-serif">';
|
|
if (isset($_SESSION['registrations']) && is_array($_SESSION['registrations'])) {
|
|
$html .= '<p>There are ' . count($_SESSION['registrations']) . ' registrations in this session:</p>';
|
|
foreach ($_SESSION['registrations'] as $reg) {
|
|
$html .= '<table style="border:1px solid black;margin:10px 0;">';
|
|
foreach ($reg as $key => $value) {
|
|
|
|
if (is_bool($value)) {
|
|
$value = $value ? 'yes' : 'no';
|
|
|
|
} else if (is_null($value)) {
|
|
$value = 'null';
|
|
|
|
} else if (is_object($value)) {
|
|
$value = chunk_split(strval($value), 64);
|
|
|
|
} else if (is_string($value) && strlen($value) > 0 && htmlspecialchars($value, ENT_QUOTES) === '') {
|
|
$value = chunk_split(bin2hex($value), 64);
|
|
}
|
|
$html .= '<tr><td>' . htmlspecialchars($key) . '</td><td style="font-family:monospace;">' . nl2br(htmlspecialchars($value)) . '</td>';
|
|
}
|
|
$html .= '</table>';
|
|
}
|
|
} else {
|
|
$html .= '<p>There are no registrations.</p>';
|
|
}
|
|
$html .= '</body></html>';
|
|
|
|
header('Content-Type: text/html');
|
|
print $html;
|
|
|
|
// ------------------------------------
|
|
// get root certs from FIDO Alliance Metadata Service
|
|
// ------------------------------------
|
|
|
|
} */else if ($fn === 'queryFidoMetaDataService') {
|
|
|
|
$mdsFolder = './restricted/WebAuthn/rootCertificates/mds';
|
|
$success = false;
|
|
$msg = null;
|
|
|
|
// fetch only 1x / 24h
|
|
$lastFetch = \is_file($mdsFolder . '/lastMdsFetch.txt') ? \strtotime(\file_get_contents($mdsFolder . '/lastMdsFetch.txt')) : 0;
|
|
if ($lastFetch + (3600*48) < \time()) {
|
|
$cnt = $WebAuthn->queryFidoMetaDataService($mdsFolder);
|
|
$success = true;
|
|
\file_put_contents($mdsFolder . '/lastMdsFetch.txt', date('r'));
|
|
$msg = 'successfully queried FIDO Alliance Metadata Service - ' . $cnt . ' certificates downloaded.';
|
|
|
|
} else {
|
|
$msg = 'Fail: last fetch was at ' . date('r', $lastFetch) . ' - fetch only 1x every 48h';
|
|
}
|
|
|
|
$return = new stdClass();
|
|
$return->success = $success;
|
|
$return->msg = $msg;
|
|
|
|
header('Content-Type: application/json');
|
|
print(json_encode($return));
|
|
}
|
|
|
|
} catch (Throwable $ex) {
|
|
$return = new stdClass();
|
|
$return->success = false;
|
|
$return->msg = $ex->getMessage()." File: ".$ex->getFile()." Line: ".$ex->getLine();
|
|
|
|
header('Content-Type: application/json');
|
|
print(json_encode($return));
|
|
} |