Periodic merge upstream

This commit is contained in:
Danny Bessems 2019-12-30 12:18:42 +00:00
commit 69bb1368cb
15 changed files with 334 additions and 42 deletions

View File

@ -35,13 +35,36 @@ function authenticateLDAP (string $username, string $password) {
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
$commonName = ldap_get_entries($ds, $ldapSearchResults)[0]['cn'][0];
$browserDetails = get_browser(null, True);
$geoLocation = json_decode(file_get_contents("http://ip-api.com/json/{$_SERVER['HTTP_X_REAL_IP']}"));
if ($geoLocation->status === 'fail') {
switch ($geoLocation->message) {
case 'private range':
case 'reserved range':
$geoLocation = json_decode(file_get_contents("http://ip-api.com/json/" . trim(file_get_contents('https://api.ipify.org')) ));
break;
case 'invalid query':
default:
$geoLocation->city = null;
$geoLocation->countryCode = null;
break;
}
}
// Create JWT-payload
$jwtPayload = [
'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)
'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)
'fp' => base64_encode(json_encode((object) [ // Fingerprint
'browser' => $browserDetails['browser'],
'platform' => $browserDetails['platform'],
'city' => $geoLocation->city,
'countrycode' => $geoLocation->countryCode
]))
];
$secureToken = JWT::encode($jwtPayload, base64_decode($settings->JWT['PrivateKey_base64']));
@ -121,8 +144,8 @@ function validateToken (string $secureToken) {
WHERE LOWER(User.Username) = :username
');
$pdoQuery->execute([
':username' => (string) strtolower($jwtPayload->sub)
]);
':username' => (string) strtolower($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']);
@ -136,7 +159,9 @@ function validateToken (string $secureToken) {
if (!empty($storedTokens) && sizeof(array_filter($storedTokens, function ($value) use ($jwtPayload) {
return $value->iat === $jwtPayload->iat;
})) === 1) {
return [
purgeTokens($currentUserId, $settings->Session['Duration']);
return [
'status' => 'Success',
'name' => $jwtPayload->name,
'uid' => $currentUserId
@ -149,4 +174,85 @@ function validateToken (string $secureToken) {
}
}
function purgeTokens(int $userID, int $maximumTokenAge) {
global $settings, $pdoDB;
$defunctTokens = []; $expiredTokens = [];
$pdoQuery = $pdoDB->prepare('
SELECT SecureToken.Id, SecureToken.Value
FROM SecureToken
WHERE SecureToken.UserId = :userid
');
$pdoQuery->execute([
':userid' => (int) $userID
]);
foreach($pdoQuery->fetchAll(PDO::FETCH_ASSOC) as $row) {
try {
$token = JWT::decode($row['Value'], base64_decode($settings->JWT['PrivateKey_base64']), $settings->JWT['Algorithm']);
if ($token->iat < (time() - $maximumTokenAge)) {
$expiredTokens[] = $row['Id'];
}
} catch (Exception $e) {
$defunctTokens[] = $row['Id'];
}
}
try {
// Sadly, PDO does not support named parameters in constructions like 'IN ( :array )'
// instead, the supported syntax is unnamed placeholders like 'IN (?, ?, ?, ...)'
$pdoQuery = $pdoDB->prepare('
DELETE FROM SecureToken
WHERE SecureToken.Id IN (' . implode( ',', array_fill(0, count(array_merge($defunctTokens, $expiredTokens)), '?')) . ')
');
$pdoQuery->execute(array_merge($defunctTokens, $expiredTokens));
if ($settings->Debug['LogToFile']) {
file_put_contents('../purgeToken.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- Garbage collection succeeded (' . $userID . ' => #' . $pdoQuery->rowCount() . ')' . PHP_EOL, FILE_APPEND);
}
return [
'status' => 'Success',
'amount' => $pdoQuery->rowCount()
];
} catch (Exception $e) {
if ($settings->Debug['LogToFile']) {
file_put_contents('../purgeToken.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- Garbage collection failed (' . $userID . ' => ' . $e . ')' . PHP_EOL, FILE_APPEND);
}
return ['status' => 'Fail', 'reason' => $e];
}
}
function deleteToken(array $tokenIDs, int $userID) {
try {
// Sadly, PDO does not support named parameters in constructions like 'IN ( :array )'
// instead, the supported syntax is unnamed placeholders like 'IN (?, ?, ?, ...)'
$pdoQuery = $pdoDB->prepare('
DELETE FROM SecureToken
WHERE SecureToken.Id IN (' . implode( ',', array_fill(0, count($tokenIDs), '?')) . ')
AND SecureToken.UserId = :userid
');
$pdoQuery->execute($tokenIDs,[
':userid' => (int) $userID
]);
if ($settings->Debug['LogToFile']) {
file_put_contents('../deleteToken.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- Successfully deleted specific token(s) (' . $userID . ' => #' . $pdoQuery->rowCount() . ')' . PHP_EOL, FILE_APPEND);
}
return [
'status' => 'Success',
'amount' => $pdoQuery->rowCount()
];
} catch (Exception $e) {
if ($settings->Debug['LogToFile']) {
file_put_contents('../deleteToken.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- Failed deleting specific token(s) (' . $userID . ' => ' . $e . ')' . PHP_EOL, FILE_APPEND);
}
return ['status' => 'Fail', 'reason' => $e];
}
}
?>

View File

@ -130,6 +130,22 @@ $contentLayout['manage']['section'] = <<<'MANAGE_SECTION'
%1$s
</tbody>
</table>
<div id="sessions">
<span data-translation="label_sessions" style="float: left; margin-left: 5px;">Sessions</span>
<br>
<table id="sessiontable">
<thead>
<tr>
<th data-translation="th_timestamp">Timestamp</th>
<th data-translation="th_origin">&lt;origin&gt;</th>
<th data-translation="th_description">Description</th>
<th data-translation="th_manage">Manage</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</li>
</ul>
MANAGE_SECTION;

View File

@ -18,6 +18,16 @@ return (object) array(
// Specify the NetBios name of the domain; to allow users to log on with just their usernames.
],
'2FA' => [
'Protocol' => 'TOTP', // Possible options are HOTP (sequential codes) and TOTP (timebased codes)
'TOTP' => [
'Secret' => 'NULL', // By default, a 512 bits secret is generated. If you need, you can provide your own secret here.
'Age' => '30', // The duration that each OTP code is valid for.
'Length' => '6', // Number of digits the OTP code will consist of.
'Algorithm' => 'SHA256' // The hashing algorithm used.
],
],
'Sqlite' => [
'Path' => '../data/lucidAuth.sqlite.db'
// Relative path to the location where the database should be stored
@ -37,6 +47,9 @@ return (object) array(
'CrossDomainLogin' => False,
// Set this to True if SingleSignOn (albeit rudementary) is desired
// (cookies are inheritently unaware of each other; clearing cookies for one domain does not affect other domains)
// Important!
// If you leave this set to False, the domainname where lucidAuth will be running on,
// needs to match the domainname (*ignoring subdomains, if any*) of the resource utilizing the authentication proxy.
'CookieDomains' => [
'domain1.tld' #, 'domain2.tld', 'subdomain.domain3.tld'
]

1
public/images/README.md Normal file
View File

@ -0,0 +1 @@
Browser logo's obtained from [alrra/browser-logos](https://github.com/alrra/browser-logos).

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@ -8,37 +8,73 @@
}
if ($validateTokenResult['status'] === "Success") {
include_once('../include/lucidAuth.template.php');
if ($_REQUEST['do'] === 'retrievesessions') {
$storedTokens = [];
try {
$allUsers = $pdoDB->query('
SELECT User.Id, User.Username, Role.Rolename
FROM User
LEFT JOIN Role
ON (Role.Id = User.RoleId)
')->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
$pdoQuery = $pdoDB->prepare('
SELECT SecureToken.Id, SecureToken.UserId, SecureToken.Value
FROM SecureToken
WHERE SecureToken.UserId = :userid
');
$pdoQuery->execute([
':userid' => (int) $_REQUEST['userid']
]);
foreach($pdoQuery->fetchAll(PDO::FETCH_ASSOC) as $row) {
try {
$JWTPayload = JWT::decode($row['Value'], base64_decode($settings->JWT['PrivateKey_base64']), $settings->JWT['Algorithm']);
$storedTokens[] = [
'tid' => $row['Id'],
'iat' => $JWTPayload->iat,
'iss' => $JWTPayload->iss,
'fp' => $JWTPayload->fp
];
} catch (Exception $e) {
// Invalid token
continue;
}
}
// Return JSON object
header('Content-Type: application/json');
echo json_encode([
"Result" => "Success",
"SessionCount" => sizeof($storedTokens),
"UserSessions" => json_encode($storedTokens)
]);
} else {
// No action requested, default action
include_once('../include/lucidAuth.template.php');
try {
$allUsers = $pdoDB->query('
SELECT User.Id, User.Username, Role.Rolename
FROM User
LEFT JOIN Role
ON (Role.Id = User.RoleId)
')->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
// Should really do some actual errorhandling here
throw new Exception($e);
}
foreach($allUsers as $row) {
$tableRows[] = sprintf('<tr%1$s><td data-userid="%2$s">%3$s</td><td>%4$s</td><td class="immutable">%5$s</td></tr>',
$validateTokenResult['uid'] === $row['Id'] ? ' class="currentuser"': null,
$row['Id'],
explode('\\', $row['Username'])[1],
$row['Rolename'],
'<button class="bttn-simple bttn-xs bttn-primary" data-translation="button_sessions">Sessions</button>' . ($validateTokenResult['uid'] === $row['Id'] ? null : '&nbsp;<button class="bttn-simple bttn-xs bttn-primary delete" data-translation="button_delete">Delete</button>')
);
}
throw new Exception($e);
}
foreach($allUsers as $row) {
$tableRows[] = sprintf('<tr%1$s><td data-userid="%2$s">%3$s</td><td>%4$s</td><td class="immutable">%5$s</td></tr>',
$validateTokenResult['uid'] === $row['Id'] ? ' class="currentuser"': null,
$row['Id'],
explode('\\', $row['Username'])[1],
$row['Rolename'],
'<button class="bttn-simple bttn-xs bttn-primary session" data-translation="button_sessions">Sessions</button>' . ($validateTokenResult['uid'] === $row['Id'] ? null : '&nbsp;<button class="bttn-simple bttn-xs bttn-primary delete" data-translation="button_delete">Delete</button>')
);
}
echo sprintf($pageLayout['full_alt'],
sprintf($contentLayout['manage']['header'],
$validateTokenResult['name']
),
sprintf($contentLayout['manage']['section'],
implode($tableRows)
)
);
echo sprintf($pageLayout['full_alt'],
sprintf($contentLayout['manage']['header'],
$validateTokenResult['name']
),
sprintf($contentLayout['manage']['section'],
implode($tableRows)
)
);
}
} else {
// No cookie containing valid authentication token found;
// explicitly deleting any remaining cookie, then redirecting to loginpage

View File

@ -49,14 +49,19 @@ $(document).ready(function(){
token: data.SecureToken
}))
}
}).done(function() {
}).done(function(_data, _textStatus, jqXHR) {
NProgress.inc(1 / XHR.length);
console.log('CrossDomain login succeeded for domain `' + domain + '` [' + JSON.stringify(jqXHR) + ']');
}).fail(function(jqXHR) {
console.log('CrossDomain login failed for domain `' + domain + '` [' + JSON.stringify(jqXHR) + ')]');
// Should check why this failed (timeout or bad request?), and if this is the origin domain, take action
}));
});
$.when.apply($, XHR).then(function(){
$.each(arguments, function(_index, _arg) {
// Finished cross-domain logins (either succesfully or through timeout)
// Finished cross-domain logins (either successfully or through timeout)
NProgress.done();
console.log('CrossDomain login completed; forwarding to `' + data.Location + '`');
window.location.replace(data.Location);
});
});

View File

@ -1,7 +1,80 @@
jQuery.fn.inlineConfirm = function() {
return this.on('click', function(event) {
sessionID = $(this).data('sessionid');
// event.preventDefault();
$(this).off('click').parent().empty().append(
$('<button>', {
text: locales[(localStorage.getItem('language') !== null ? localStorage.getItem('language') : 'en')]['button_yes'],
class: 'bttn-simple bttn-xs bttn-primary sessiondeleteconfirm',
style: 'margin-right: 3px;',
'data-translation': 'button_yes',
'data-sessionid': sessionID
})).append(
$('<button>', {
text: locales[(localStorage.getItem('language') !== null ? localStorage.getItem('language') : 'en')]['button_no'],
class: 'bttn-simple bttn-xs bttn-primary sessiondeletecancel',
'data-translation': 'button_no',
'data-sessionid': sessionID
})
);
});
};
$(document).ready(function(){
// Initialize the editable-table functionality
$('#usertable').editableTableWidget();
// Prevent clicking *through* popup-screens
$('#sessions').click(function(event) {
event.stopPropagation();
});
// Add eventhandlers to buttons
$('#usertable button.session').click(function() {
event.stopPropagation();
$('#sessions tbody').empty();
$('#sessions').fadeToggle();
$.post("lucidAuth.manage.php", {
do: "retrievesessions",
userid: $(this).closest('tr').find('td:nth-child(1)').data('userid')
})
.done(function(data,_status) {
if (data.Result === 'Success') {
var Sessions = JSON.parse(data.UserSessions);
for (var i = 0; i < data.SessionCount; i++) {
try {
var fingerPrint = JSON.parse(atob(Sessions[i]['fp']));
var sessionDetails = '<img class="browsericon" src="/images/' + fingerPrint['browser'] + '_256x256.png">';
sessionDetails += fingerPrint['browser'] + ' -- ' + fingerPrint['platform'];
sessionDetails += '<br>' + fingerPrint['city'] + ' (' + fingerPrint['countrycode'] + ')';
} catch(e) {
// Do nothing
}
$('#sessiontable tbody').append($('<tr>')
.append($('<td>', {
text: new Date(Sessions[i]['iat'] * 1000).toLocaleString('en-GB')
}))
.append($('<td>', {
text: Sessions[i]['iss']
}))
.append($('<td>', {
html: sessionDetails ? sessionDetails : ''
}))
.append($('<td>', {
html: $('<button>', {
text: locales[(localStorage.getItem('language') !== null ? localStorage.getItem('language') : 'en')]['button_delete'],
class: 'bttn-simple bttn-xs bttn-primary sessiondelete',
'data-translation': 'button_delete',
'data-sessionid': Sessions[i]['tid']})
}))
);
}
$('#sessiontable .sessiondelete').inlineConfirm();
} else {
}
});
});
$('#usertable button.delete').click(function() {
$(this).closest('tr').addClass('removed');
});
@ -32,6 +105,9 @@ $(document).ready(function(){
// To prevent recreating multiple new editors; reference the already existing `<input>`
$('#usertable').editableTableWidget({editor: $('#editor')});
// Add eventhandlers to buttons of newly added `<tr>`
$('#usertable .new button.session').unbind().click(function() {
console.log('New user, unlikely to have sessions already, lets do nothing for now');
});
$('#usertable .new button.delete').unbind().click(function() {
$(this).closest('tr').remove();
});
@ -92,4 +168,8 @@ console.log({'new': newEntries, 'removed': removedEntries});
}
});
});
$(document).click(function () {
$('#sessions').fadeOut();
});

View File

@ -5,9 +5,12 @@ var locales = {
button_cancel: "cancel",
button_sessions: "sessions",
button_delete: "delete",
button_login: "login",
button_yes: "yes",
button_no: "no",
button_login: "login",
heading_error: "ERROR!",
label_password: "Password:",
label_password: "Password:",
label_sessions: "Sessions",
label_username: "Username:",
link_logout: "Logout",
span_credentialsavailable: "Login credentials available upon request!",
@ -22,9 +25,12 @@ var locales = {
button_cancel: "annuleren",
button_sessions: "sessies",
button_delete: "verwijder",
button_yes: "ja",
button_no: "nee",
button_login: "log in",
heading_error: "FOUT!",
label_password: "Wachtwoord:",
label_password: "Wachtwoord:",
label_sessions: "Sessies",
label_username: "Gebruikersnaam:",
link_logout: "Log uit",
span_credentialsavailable: "Inloggegevens verkrijgbaar op aanvraag!",

View File

@ -129,6 +129,35 @@ body {
.main section .buttons button {
margin-left: inherit;
}
.main section #sessions {
display: none;
position: absolute;
top: calc(50% - 160px);
right: 20%;
height: 320px;
width: 60%;
border: 1px solid rgb(0, 51, 153);
box-shadow: black 0px 0px 20px;
box-sizing: border-box;
padding-top: 5px;
background: white;
font-size: inherit;
z-index: 99;
overflow-y: auto;
}
.main section #sessions .browsericon {
height: 30px;
float: left;
margin-right: 5px;
border: none;
filter: drop-shadow(0px 0px 1px #000);
}
.main section #sessions .sessiondeleteconfirm {
background: crimson linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0) 50%, rgba(255,255,255,0.33) 51%) no-repeat center;
}
.main section #sessions .sessiondeletecancel {
background: green linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0) 50%, rgba(255,255,255,0.25) 51%) no-repeat center;
}
.main section table {
width: 100%;
}