Merge pull request #1 from djpbessems/development

Development
This commit is contained in:
Danny Bessems 2019-01-28 14:29:31 +01:00 committed by GitHub
commit a25cbb5c16
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 136 additions and 52 deletions

View File

@ -1,10 +1,24 @@
<?php <?php
$confFile = '../lucidAuth.config.php'; $configurationFile = '../lucidAuth.config.php';
if (!file_exists($confFile)) { if (!file_exists($configurationFile)) {
throw 'Missing config file. Please rename lucidAuth.config.php.example to lucidAuth.config.php and edit it to reflect your setup.' . PHP_EOL; throw new Exception(sprintf('Missing config file. Please rename \'%1$s.example\' to \'%1$s\' and edit it to reflect your setup.', explode('../', $configurationFile)[1]));
}
$settings = include_once($configurationFile);
try {
# switch ($settings->Database['Driver']) {
# case 'sqlite':
# $database = new PDO('sqlite:' . $settings->Database['Path']);
if (is_writable($settings->Sqlite['Path'])) {
$pdoDB = new PDO('sqlite:' . $settings->Sqlite['Path']);
} else {
throw new Exception(sprintf('Database file \'%1$s\' is not writable', $settings->Sqlite['Path']));
}
# }
}
catch (Exception $e) {
throw new Exception(sprintf('Unable to connect to database \'%1$s\'', $settings->Sqlite['Path']));
} }
$settings = include_once('../lucidAuth.config.php');
function authenticateLDAP (string $username, string $password) { function authenticateLDAP (string $username, string $password) {
global $settings; global $settings;
@ -15,22 +29,23 @@ function authenticateLDAP (string $username, string $password) {
$ds = ldap_connect($settings->LDAP['Server'], $settings->LDAP['Port']); $ds = ldap_connect($settings->LDAP['Server'], $settings->LDAP['Port']);
// Strict namingconvention: only allow alphabetic characters // Strict namingconvention: only allow alphabetic characters
$strGivenname = preg_replace('([^a-zA-Z]*)', '', $_POST['username']); $sanitizedUsername = preg_replace('([^a-zA-Z]*)', '', $_POST['username']);
$strUsername = $settings->LDAP['Domain'] . '\\' . $strGivenname; $qualifiedUsername = $settings->LDAP['Domain'] . '\\' . $sanitizedUsername;
if (@ldap_bind($ds, $strUsername, utf8_encode($_POST['password']))) { if (@ldap_bind($ds, $qualifiedUsername, utf8_encode($_POST['password']))) {
// Successful auth; get additional userdetails from Active Directory // Successful authentication; get additional userdetails from authenticationsource
$ldapSearchResults = ldap_search($ds, $settings->LDAP['BaseDN'], "sAMAccountName=$strGivenname"); $ldapSearchResults = ldap_search($ds, $settings->LDAP['BaseDN'], "sAMAccountName=$sanitizedUsername");
$strFullname = ldap_get_entries($ds, $ldapSearchResults)[0]['cn'][0]; $commonName = ldap_get_entries($ds, $ldapSearchResults)[0]['cn'][0];
// Create JWT-payload // Create JWT-payload
$jwtPayload = [ $jwtPayload = [
'iat' => time(), // Issued at: time when the token was generated 'iat' => time(), // Issued at: time when the token was generated
'iss' => $_SERVER['SERVER_NAME'], // Issuer 'iss' => $_SERVER['SERVER_NAME'], // Issuer
'sub' => $strGivenname, // Subject (ie. username) 'sub' => $qualifiedUsername, // Subject (ie. username)
'name' => $strFullname // Full name (as retrieved from AD) 'name' => $commonName // Common name (as retrieved from AD)
]; ];
$secureToken = JWT::encode($jwtPayload, base64_decode($settings->JWT['PrivateKey_base64'])); $secureToken = JWT::encode($jwtPayload, base64_decode($settings->JWT['PrivateKey_base64']));
return ['status' => 'Success', 'token' => $secureToken]; return ['status' => 'Success', 'token' => $secureToken];
} else { } else {
// LDAP authentication failed! // LDAP authentication failed!
@ -45,20 +60,54 @@ function authenticateLDAP (string $username, string $password) {
function storeToken (string $username, string $password, object $cookie) { function storeToken (string $username, string $password, object $cookie) {
global $settings; global $settings;
} }
function retrieveToken (string $username, string $foo) { function retrieveTokenFromDB (string $username, string $foo) {
global $settings; global $settings;
} }
function validateCookie (int $expiration, string $username, string $securetoken) { function validateToken (string $secureToken) {
# $_COOKIE['Exp'], $_COOKIE['Sub'], $_COOKIE['JWT'] global $settings, $pdoDB;
global $settings;
If ($expiration > time()) { try {
#moo $jwtPayload = JWT::decode($secureToken, base64_decode($settings->JWT['PrivateKey_base64']), $settings->JWT['Algorithm']);
} catch (Exception $e) {
// Invalid token
return ['status' => 'Fail', 'reason' => '1'];
}
if ((int)$jwtPayload->iat < (time() - (int)$settings->Session['Duration'])) {
// Expired token
return ['status' => 'Fail', 'reason' => '3'];
}
$pdoQuery = $pdoDB->prepare('
SELECT SecureToken.Value
FROM SecureToken
LEFT JOIN User
ON (User.Id=SecureToken.UserId)
WHERE User.Username = :username
');
$pdoQuery->execute([
':username' => (string)$jwtPayload->sub
]);
foreach($pdoQuery->fetchAll(PDO::FETCH_ASSOC) as $row) {
try {
$storedTokens[] = JWT::decode($row['Value'], base64_decode($settings->JWT['PrivateKey_base64']), $settings->JWT['Algorithm']);
} catch (Exception $e) {
continue;
}
}
if (!empty($storedTokens) && sizeof(array_filter($storedTokens, function ($value) use ($jwtPayload) {
return $value->iat === $jwtPayload->iat;
})) === 1) {
// At least one of the database-stored tokens match
return ['status' => 'Success', 'token' => $jwtPayload];
} else {
// No matching token in database
return ['status' => 'Fail', 'reason' => '2'];
} }
} }

View File

@ -69,7 +69,8 @@ $contentLayout['login'] = <<<LOGIN
<input type="password" id="password" name="password" tabindex="200" /> <input type="password" id="password" name="password" tabindex="200" />
</li> </li>
<li> <li>
<button id="btnlogin" class="bttn-simple bttn-xs bttn-primary" tabindex="300" data-translation="button_login">login</button> <input type="hidden" id="ref" name="ref" value="{$_GET['ref']}" />
<button id="btnlogin" class="bttn-simple bttn-xs bttn-primary" tabindex="300" data-translation="button_login">login</button>
</li> </li>
<li class="misc"> <li class="misc">
<span class="indent">&nbsp;</span> <span class="indent">&nbsp;</span>
@ -79,7 +80,7 @@ $contentLayout['login'] = <<<LOGIN
</li> </li>
</ul> </ul>
</fieldset> </fieldset>
<img src="/images/tag_pvr.png" style="position: absolute; top: 135px; left: -10px; transform: scale(0.6, 0.6)" alt="PVR [Secure]" /> <img src="/images/tag_lock.png" style="position: absolute; top: 175px; left: 20px;" alt="Secure!" />
LOGIN; LOGIN;
$contentLayout['manage'] = <<<MANAGE $contentLayout['manage'] = <<<MANAGE

View File

@ -18,10 +18,8 @@ return (object) array(
// Specify the NetBios name of the domain; to allow users to log on with just their usernames. // Specify the NetBios name of the domain; to allow users to log on with just their usernames.
], ],
'DomainNames' => ['*.subdomain.domain.{(tld1|tld2)}'],
'Sqlite' => [ 'Sqlite' => [
'Path' => '../config/lucidAuth.sqlite.db' 'Path' => '../data/lucidAuth.sqlite.db'
// Relative path to the location where the database should be stored // Relative path to the location where the database should be stored
], ],
@ -29,16 +27,21 @@ return (object) array(
// File containing your <externalresource> token // File containing your <externalresource> token
'JWT' => [ 'JWT' => [
'PrivateKey_base64' => 'result of base64_encode(<longrandomstring>)', 'PrivateKey_base64' => '',
// A base64-encoded random (preferably long) string (see https://www.base64encode.org/)
'Algorithm' => [ 'Algorithm' => [
'HS256', 'HS256',
] ]
], ],
'Cookie' => [ 'Session' => [
'Duration' => 2592000, 'Duration' => 2592000,
// In seconds (2592000 is equivalent to 30 days) // In seconds (2592000 is equivalent to 30 days)
# 'Prefix' => 'lucidAuth_' 'CookieDomains' => [
'domain1.tld' #, 'domain2.tld', 'subdomain.domain3.tld'
]
// Domain(s) that will be used to set cookie-domains to
// (multiple domains are allowed; remove the '#' above)
], ],
'Debug' => [ 'Debug' => [

Binary file not shown.

Before

Width:  |  Height:  |  Size: 299 B

After

Width:  |  Height:  |  Size: 318 B

BIN
public/images/tag_lock.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

View File

@ -3,13 +3,41 @@
include_once('../include/lucidAuth.functions.php'); include_once('../include/lucidAuth.functions.php');
echo $settings->Debug['Verbose']; 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
$pdoQuery = $pdoDB->prepare('
INSERT INTO SecureToken (UserId, Value)
SELECT User.Id, :securetoken
FROM User
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;
// forcing it into an associative array (instead of javascript's default StdClass object)
try {
$proxyHeaders = json_decode(base64_decode($_POST['ref']), JSON_OBJECT_AS_ARRAY);
}
catch (Exception $e) {
// Since this request is only ever called through an AJAX-request; return JSON object
echo '{"Result":"Fail","Reason":"Original request URI lost in transition"}' . PHP_EOL;
exit;
}
$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 request is only ever called through an AJAX-request; return JSON object
echo '{"Result":"Success","Location":"<originalurl>"}' . PHP_EOL; echo '{"Result":"Success","Location":"' . $originalUri . '"}' . PHP_EOL;
} else { } else {
switch ($result['reason']) { switch ($result['reason']) {
case '1': case '1':

View File

@ -16,25 +16,27 @@
}, ARRAY_FILTER_USE_KEY); }, ARRAY_FILTER_USE_KEY);
// For debugging purposes - enable it in ../lucidAuth.config.php // For debugging purposes - enable it in ../lucidAuth.config.php
if ($settings->Debug['LogToFile']) 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 ($settings->Debug['LogToFile']) {
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) {
if (False) {
// 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;
} }
# if (validateToken($_COOKIE['Exp'], $_COOKIE['Sub'], $_COOKIE['JWT']) != True) { if (!empty($_COOKIE['JWT']) && validateToken($_COOKIE['JWT'])['status'] == "Success") {
if (False) {
// No or invalid authentication token found, redirecting to loginpage
header("HTTP/1.1 401 Unauthorized");
#remember to include cookies/headers/something
header("Location: lucidAuth.login.php");
} else {
// Valid authentication token found // Valid authentication token found
header("HTTP/1.1 202 Accepted"); header("HTTP/1.1 202 Accepted");
exit; exit;
} else {
// No cookie containing valid authentication token found;
// explicitly deleting any remaining cookie, then redirecting to loginpage
setcookie('JWT', FALSE);
header("HTTP/1.1 401 Unauthorized");
header("Location: lucidAuth.login.php?ref=" . base64_encode(json_encode($proxyHeaders)));
} }
?> ?>

View File

@ -16,7 +16,8 @@ $(document).ready(function(){
$.post("lucidAuth.login.php", { $.post("lucidAuth.login.php", {
do: "login", do: "login",
username: $('#username').val(), username: $('#username').val(),
password: $('#password').val() password: $('#password').val(),
ref: $('#ref').val()
}) })
.done(function(data,status) { .done(function(data,status) {
try { try {

View File

@ -115,7 +115,7 @@
background: rgba(255,255,255,0.4); background: rgba(255,255,255,0.4);
} }
.bttn-simple.bttn-primary { .bttn-simple.bttn-primary {
background: #550055; background: #003399;
background-image: linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0) 50%, rgba(255,255,255,0.25) 51%); background-image: linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0) 50%, rgba(255,255,255,0.25) 51%);
} }
.bttn-simple.bttn-warning { .bttn-simple.bttn-warning {

View File

@ -121,7 +121,7 @@ body {
content: ' '; content: ' ';
} }
.main fieldset input { .main fieldset input {
border: 1px solid #550055; border: 1px solid #003399;
padding: 2px; padding: 2px;
width: 100px; width: 100px;
} }
@ -135,7 +135,7 @@ body {
text-transform: uppercase; text-transform: uppercase;
} }
.main fieldset select { .main fieldset select {
border: 1px solid #550055; border: 1px solid #003399;
padding: 2px; padding: 2px;
width: 375px; width: 375px;
} }
@ -172,7 +172,7 @@ body {
margin-left: 10px; margin-left: 10px;
} }
.main a:link, .main a:visited { .main a:link, .main a:visited {
color: #550055; color: #003399;
text-decoration: none; text-decoration: none;
} }
.main a:hover, .main a:active { .main a:hover, .main a:active {
@ -188,7 +188,7 @@ body {
font-size: 12px; font-size: 12px;
} }
.main span#user a:link, .main span#user a:visited { .main span#user a:link, .main span#user a:visited {
color: #CC1111; color: #001177;
text-decoration: none; text-decoration: none;
} }
.main span#user a:hover, .main span#user a:active { .main span#user a:hover, .main span#user a:active {
@ -218,7 +218,7 @@ body {
right: 10px; right: 10px;
height: 112px; height: 112px;
width: 250px; width: 250px;
border: 1px solid rgb(181, 0, 0); border: 1px solid rgb(0, 51, 153);
box-shadow: black 0px 0px 20px; box-shadow: black 0px 0px 20px;
box-sizing: border-box; box-sizing: border-box;
padding-top: 5px; padding-top: 5px;