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
$confFile = '../lucidAuth.config.php';
if (!file_exists($confFile)) {
throw 'Missing config file. Please rename lucidAuth.config.php.example to lucidAuth.config.php and edit it to reflect your setup.' . PHP_EOL;
$configurationFile = '../lucidAuth.config.php';
if (!file_exists($configurationFile)) {
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) {
global $settings;
@ -15,22 +29,23 @@ function authenticateLDAP (string $username, string $password) {
$ds = ldap_connect($settings->LDAP['Server'], $settings->LDAP['Port']);
// Strict namingconvention: only allow alphabetic characters
$strGivenname = preg_replace('([^a-zA-Z]*)', '', $_POST['username']);
$strUsername = $settings->LDAP['Domain'] . '\\' . $strGivenname;
$sanitizedUsername = preg_replace('([^a-zA-Z]*)', '', $_POST['username']);
$qualifiedUsername = $settings->LDAP['Domain'] . '\\' . $sanitizedUsername;
if (@ldap_bind($ds, $strUsername, utf8_encode($_POST['password']))) {
// Successful auth; get additional userdetails from Active Directory
$ldapSearchResults = ldap_search($ds, $settings->LDAP['BaseDN'], "sAMAccountName=$strGivenname");
$strFullname = ldap_get_entries($ds, $ldapSearchResults)[0]['cn'][0];
if (@ldap_bind($ds, $qualifiedUsername, utf8_encode($_POST['password']))) {
// Successful authentication; get additional userdetails from authenticationsource
$ldapSearchResults = ldap_search($ds, $settings->LDAP['BaseDN'], "sAMAccountName=$sanitizedUsername");
$commonName = ldap_get_entries($ds, $ldapSearchResults)[0]['cn'][0];
// Create JWT-payload
$jwtPayload = [
'iat' => time(), // Issued at: time when the token was generated
'iss' => $_SERVER['SERVER_NAME'], // Issuer
'sub' => $strGivenname, // Subject (ie. username)
'name' => $strFullname // Full name (as retrieved from AD)
'iat' => time(), // Issued at: time when the token was generated
'iss' => $_SERVER['SERVER_NAME'], // Issuer
'sub' => $qualifiedUsername, // Subject (ie. username)
'name' => $commonName // Common name (as retrieved from AD)
];
$secureToken = JWT::encode($jwtPayload, base64_decode($settings->JWT['PrivateKey_base64']));
return ['status' => 'Success', 'token' => $secureToken];
} else {
// LDAP authentication failed!
@ -45,20 +60,54 @@ function authenticateLDAP (string $username, string $password) {
function storeToken (string $username, string $password, object $cookie) {
global $settings;
}
function retrieveToken (string $username, string $foo) {
function retrieveTokenFromDB (string $username, string $foo) {
global $settings;
}
function validateCookie (int $expiration, string $username, string $securetoken) {
# $_COOKIE['Exp'], $_COOKIE['Sub'], $_COOKIE['JWT']
global $settings;
function validateToken (string $secureToken) {
global $settings, $pdoDB;
If ($expiration > time()) {
#moo
try {
$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" />
</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 class="misc">
<span class="indent">&nbsp;</span>
@ -79,7 +80,7 @@ $contentLayout['login'] = <<<LOGIN
</li>
</ul>
</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;
$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.
],
'DomainNames' => ['*.subdomain.domain.{(tld1|tld2)}'],
'Sqlite' => [
'Path' => '../config/lucidAuth.sqlite.db'
'Path' => '../data/lucidAuth.sqlite.db'
// Relative path to the location where the database should be stored
],
@ -29,16 +27,21 @@ return (object) array(
// File containing your <externalresource> token
'JWT' => [
'PrivateKey_base64' => 'result of base64_encode(<longrandomstring>)',
'PrivateKey_base64' => '',
// A base64-encoded random (preferably long) string (see https://www.base64encode.org/)
'Algorithm' => [
'HS256',
]
],
'Cookie' => [
'Duration' => 2592000,
'Session' => [
'Duration' => 2592000,
// 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' => [

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');
echo $settings->Debug['Verbose'];
if ($_POST['do'] == 'login') {
if ($_POST['do'] === 'login') {
$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
echo '{"Result":"Success","Location":"<originalurl>"}' . PHP_EOL;
echo '{"Result":"Success","Location":"' . $originalUri . '"}' . PHP_EOL;
} else {
switch ($result['reason']) {
case '1':

View File

@ -16,25 +16,27 @@
}, ARRAY_FILTER_USE_KEY);
// 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 (False) {
if (sizeof($proxyHeaders) == 0) {
// Non-proxied request; this is senseless, go fetch!
header("HTTP/1.1 403 Forbidden");
exit;
}
# if (validateToken($_COOKIE['Exp'], $_COOKIE['Sub'], $_COOKIE['JWT']) != True) {
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 {
if (!empty($_COOKIE['JWT']) && validateToken($_COOKIE['JWT'])['status'] == "Success") {
// Valid authentication token found
header("HTTP/1.1 202 Accepted");
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", {
do: "login",
username: $('#username').val(),
password: $('#password').val()
password: $('#password').val(),
ref: $('#ref').val()
})
.done(function(data,status) {
try {

View File

@ -115,7 +115,7 @@
background: rgba(255,255,255,0.4);
}
.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%);
}
.bttn-simple.bttn-warning {

View File

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