Tied up code & removed placeholders (#1)

This commit is contained in:
Danny Bessems 2019-02-19 15:31:02 +01:00 committed by Gitea
parent 42505774c1
commit ec7e4b28ec
3 changed files with 40 additions and 29 deletions

View File

@ -57,19 +57,41 @@ function authenticateLDAP (string $username, string $password) {
} }
} }
function storeToken (string $username, string $password, object $cookie) { function storeToken (string $secureToken, string $qualifiedUsername, string $httpHost) {
global $settings; global $settings, $pdoDB;
} // Save authentication token in database serverside
try {
function retrieveTokenFromDB (string $username, string $foo) { $pdoQuery = $pdoDB->prepare('
global $settings; INSERT INTO SecureToken (UserId, Value)
SELECT User.Id, :securetoken
FROM User
WHERE User.Username = :qualifiedusername
');
$pdoQuery->execute([
':securetoken' => $secureToken,
':qualifiedusername' => $qualifiedUsername
]);
}
catch (Exception $e) {
return ['status' => 'Fail', 'reason' => $e];
}
// Save authentication token in cookie clientside
$cookieDomain = array_values(array_filter($settings->Session['CookieDomains'], function ($value) use ($httpHost) {
// Check if $_SERVER['HTTP_HOST'] matches any of the configured domains (either explicitly or as a subdomain)
// This might seem backwards, but relying on $_SERVER directly allows spoofed values with potential security risks
return (strlen($value) > strlen($httpHost)) ? false : (0 === substr_compare($httpHost, $value, -strlen($value)));
}))[0];
if (setcookie('JWT', $secureToken, (time() + $settings->Session['Duration']), '/', '.' . $cookieDomain)) {
return ['status' => 'Success'];
}
} }
function validateToken (string $secureToken) { function validateToken (string $secureToken) {
global $settings, $pdoDB; global $settings, $pdoDB;
// Decode provided authentication token
try { try {
$jwtPayload = JWT::decode($secureToken, base64_decode($settings->JWT['PrivateKey_base64']), $settings->JWT['Algorithm']); $jwtPayload = JWT::decode($secureToken, base64_decode($settings->JWT['PrivateKey_base64']), $settings->JWT['Algorithm']);
} catch (Exception $e) { } catch (Exception $e) {
@ -82,6 +104,7 @@ function validateToken (string $secureToken) {
return ['status' => 'Fail', 'reason' => '3']; return ['status' => 'Fail', 'reason' => '3'];
} }
// Retrieve all authentication tokens from database matching username
$pdoQuery = $pdoDB->prepare(' $pdoQuery = $pdoDB->prepare('
SELECT SecureToken.Value SELECT SecureToken.Value
FROM SecureToken FROM SecureToken
@ -100,13 +123,12 @@ function validateToken (string $secureToken) {
} }
} }
// Compare provided authentication token to all stored tokens in database
if (!empty($storedTokens) && sizeof(array_filter($storedTokens, function ($value) use ($jwtPayload) { if (!empty($storedTokens) && sizeof(array_filter($storedTokens, function ($value) use ($jwtPayload) {
return $value->iat === $jwtPayload->iat; return $value->iat === $jwtPayload->iat;
})) === 1) { })) === 1) {
// At least one of the database-stored tokens match return ['status' => 'Success'];
return ['status' => 'Success', 'token' => $jwtPayload];
} else { } else {
// No matching token in database
return ['status' => 'Fail', 'reason' => '2']; return ['status' => 'Fail', 'reason' => '2'];
} }
} }

View File

@ -6,23 +6,12 @@
if ($_POST['do'] === 'login') { if ($_POST['do'] === 'login') {
$result = authenticateLDAP($_POST['username'], $_POST['password']); $result = authenticateLDAP($_POST['username'], $_POST['password']);
if ($result['status'] === 'Success') { if ($result['status'] === 'Success') {
// Save authentication token in database // Store authentication token; in database serverside & in cookie clientside
$pdoQuery = $pdoDB->prepare(' if (storeToken($result['token'], $settings->LDAP['Domain'] . '\\' . $_POST['username'], $_SERVER['HTTP_HOST'])['status'] !== 'Success') {
INSERT INTO SecureToken (UserId, Value) // Since this action is only ever called through an AJAX-request; return JSON object
SELECT User.Id, :securetoken echo '{"Result":"Fail","Reason":"Failed storing authentication token in database and/or cookie"}' . PHP_EOL;
FROM User exit;
WHERE User.Username = :qualifiedusername }
');
$pdoQuery->execute([
':securetoken' => $result['token'],
':qualifiedusername' => $settings->LDAP['Domain'] . '\\' . $_POST['username']
]);
// Save authentication token in cookie
$httpHost = $_SERVER['HTTP_HOST'];
$cookieDomain = array_values(array_filter($settings->Session['CookieDomains'], function ($value) use ($httpHost) {
return (strlen($value) > strlen($httpHost)) ? false : (0 === substr_compare($httpHost, $value, -strlen($value)));
}))[0];
setcookie('JWT', $result['token'], (time() + $settings->Session['Duration']), '/', '.' . $cookieDomain);
// Convert base64 encoded string back from JSON; // Convert base64 encoded string back from JSON;
// forcing it into an associative array (instead of javascript's default StdClass object) // forcing it into an associative array (instead of javascript's default StdClass object)
@ -30,13 +19,13 @@
$proxyHeaders = json_decode(base64_decode($_POST['ref']), JSON_OBJECT_AS_ARRAY); $proxyHeaders = json_decode(base64_decode($_POST['ref']), JSON_OBJECT_AS_ARRAY);
} }
catch (Exception $e) { catch (Exception $e) {
// Since this request is only ever called through an AJAX-request; return JSON object // Since this action is only ever called through an AJAX-request; return JSON object
echo '{"Result":"Fail","Reason":"Original request URI lost in transition"}' . PHP_EOL; echo '{"Result":"Fail","Reason":"Original request URI lost in transition"}' . PHP_EOL;
exit; exit;
} }
$originalUri = !empty($proxyHeaders) ? $proxyHeaders['XForwardedProto'] . '://' . $proxyHeaders['XForwardedHost'] . $proxyHeaders['XForwardedUri'] : 'lucidAuth.manage.php'; $originalUri = !empty($proxyHeaders) ? $proxyHeaders['XForwardedProto'] . '://' . $proxyHeaders['XForwardedHost'] . $proxyHeaders['XForwardedUri'] : 'lucidAuth.manage.php';
// Since this request is only ever called through an AJAX-request; return JSON object // Since this action is only ever called through an AJAX-request; return JSON object
echo '{"Result":"Success","Location":"' . $originalUri . '"}' . PHP_EOL; echo '{"Result":"Success","Location":"' . $originalUri . '"}' . PHP_EOL;
} else { } else {
switch ($result['reason']) { switch ($result['reason']) {

View File

@ -20,7 +20,7 @@
file_put_contents('../requestHeaders.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- ' . (json_encode($proxyHeaders, JSON_FORCE_OBJECT)) . PHP_EOL, FILE_APPEND); file_put_contents('../requestHeaders.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- ' . (json_encode($proxyHeaders, JSON_FORCE_OBJECT)) . PHP_EOL, FILE_APPEND);
} }
if (sizeof($proxyHeaders) == 0) { if (sizeof($proxyHeaders) === 0) {
// Non-proxied request; this is senseless, go fetch! // Non-proxied request; this is senseless, go fetch!
header("HTTP/1.1 403 Forbidden"); header("HTTP/1.1 403 Forbidden");
exit; exit;