Periodic merge upstream #5

Manually merged
djpbessems merged 13 commits from development into master 2019-12-30 12:18:50 +00:00
16 changed files with 397 additions and 73 deletions

View File

@ -1,5 +1,5 @@
# lucidAuth # lucidAuth [![](https://img.shields.io/badge/status-in%20production-%23003399.svg)](#) [![](https://img.shields.io/badge/contributors-1-green.svg) ](#)
[![](https://img.shields.io/badge/status-in%20production-%23003399.svg)](#) [![](https://img.shields.io/badge/contributors-1-green.svg) ](#) > *Respect* the unexpected, mitigate your risks
Forward Authentication for use with proxies (caddy, nginx, traefik, etc) Forward Authentication for use with proxies (caddy, nginx, traefik, etc)
@ -14,15 +14,47 @@ Forward Authentication for use with proxies (caddy, nginx, traefik, etc)
- #### in Traefik - #### in Traefik
Add the following lines (change to reflect your existing configuration): Add the following lines (change to reflect your existing configuration):
##### 1.7
``` ```
[frontends.server1] [frontends.server1]
entrypoints = ["https"] entrypoints = ["https"]
backend = "server1" backend = "server1"
[frontends.server1.auth.forward] [frontends.server1.auth.forward]
address = "https://<fqdn>/lucidAuth.validateRequest.php" address = "https://<fqdn>/lucidAuth.validateRequest.php"
[frontends.server1.routes] [frontends.server1.routes]
[frontends.server1.routes.ext] [frontends.server1.routes.ext]
rule = "Host:<fqdn>" rule = "Host:<fqdn>"
```
##### 2.0
Either whitelist IP's which should be trusted to send `HTTP_X-Forwarded-*` headers, ór enable insecure-mode in your static configuration:
```
entryPoints:
https:
address: :443
forwardedHeaders:
trustedIPs:
- "127.0.0.1/32"
- "192.168.1.0/24"
# insecure: true
```
Define a middleware that tells Traefik to forward requests for authentication in your dynamic file provider:
```
https:
middlewares:
ldap-authentication:
forwardAuth:
address: "https://<fqdn>/lucidAuth.validateRequest.php"
trustForwardHeader: true
```
And finally add the new middleware to your service (different methods; this depends on your configuration):
```
# as a label (when using Docker provider)
traefik.http.routers.router1.middlewares: "ldap-authentication@file"
# as yaml (when using file provider)
routers:
router1:
middlewares:
- "ldap-authentication"
``` ```
- #### Important! - #### Important!

View File

@ -35,13 +35,36 @@ function authenticateLDAP (string $username, string $password) {
if (@ldap_bind($ds, $qualifiedUsername, utf8_encode($_POST['password']))) { if (@ldap_bind($ds, $qualifiedUsername, utf8_encode($_POST['password']))) {
// Successful authentication; get additional userdetails from authenticationsource // Successful authentication; get additional userdetails from authenticationsource
$ldapSearchResults = ldap_search($ds, $settings->LDAP['BaseDN'], "sAMAccountName=$sanitizedUsername"); $ldapSearchResults = ldap_search($ds, $settings->LDAP['BaseDN'], "sAMAccountName=$sanitizedUsername");
$commonName = ldap_get_entries($ds, $ldapSearchResults)[0]['cn'][0]; $commonName = ldap_get_entries($ds, $ldapSearchResults)[0]['cn'][0];
// Create JWT-payload
$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 = [ $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' => $qualifiedUsername, // Subject (ie. username) 'sub' => $qualifiedUsername, // Subject (ie. username)
'name' => $commonName // Common name (as retrieved from AD) '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'])); $secureToken = JWT::encode($jwtPayload, base64_decode($settings->JWT['PrivateKey_base64']));
@ -121,8 +144,8 @@ function validateToken (string $secureToken) {
WHERE LOWER(User.Username) = :username WHERE LOWER(User.Username) = :username
'); ');
$pdoQuery->execute([ $pdoQuery->execute([
':username' => (string) strtolower($jwtPayload->sub) ':username' => (string) strtolower($jwtPayload->sub)
]); ]);
foreach($pdoQuery->fetchAll(PDO::FETCH_ASSOC) as $row) { foreach($pdoQuery->fetchAll(PDO::FETCH_ASSOC) as $row) {
try { try {
$storedTokens[] = JWT::decode($row['Value'], base64_decode($settings->JWT['PrivateKey_base64']), $settings->JWT['Algorithm']); $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) { if (!empty($storedTokens) && sizeof(array_filter($storedTokens, function ($value) use ($jwtPayload) {
return $value->iat === $jwtPayload->iat; return $value->iat === $jwtPayload->iat;
})) === 1) { })) === 1) {
return [ purgeTokens($currentUserId, $settings->Session['Duration']);
return [
'status' => 'Success', 'status' => 'Success',
'name' => $jwtPayload->name, 'name' => $jwtPayload->name,
'uid' => $currentUserId '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 %1$s
</tbody> </tbody>
</table> </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> </li>
</ul> </ul>
MANAGE_SECTION; 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. // 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' => [ 'Sqlite' => [
'Path' => '../data/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
@ -37,6 +47,9 @@ return (object) array(
'CrossDomainLogin' => False, 'CrossDomainLogin' => False,
// Set this to True if SingleSignOn (albeit rudementary) is desired // 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) // (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' => [ 'CookieDomains' => [
'domain1.tld' #, 'domain2.tld', 'subdomain.domain3.tld' '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") { if ($validateTokenResult['status'] === "Success") {
include_once('../include/lucidAuth.template.php'); if ($_REQUEST['do'] === 'retrievesessions') {
$storedTokens = [];
try { $pdoQuery = $pdoDB->prepare('
$allUsers = $pdoDB->query(' SELECT SecureToken.Id, SecureToken.UserId, SecureToken.Value
SELECT User.Id, User.Username, Role.Rolename FROM SecureToken
FROM User WHERE SecureToken.UserId = :userid
LEFT JOIN Role ');
ON (Role.Id = User.RoleId) $pdoQuery->execute([
')->fetchAll(PDO::FETCH_ASSOC); ':userid' => (int) $_REQUEST['userid']
} catch (Exception $e) { ]);
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 // Should really do some actual errorhandling here
throw new Exception($e); throw new Exception($e);
} }
foreach($allUsers as $row) { 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>', $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, $validateTokenResult['uid'] === $row['Id'] ? ' class="currentuser"': null,
$row['Id'], $row['Id'],
explode('\\', $row['Username'])[1], explode('\\', $row['Username'])[1],
$row['Rolename'], $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>') '<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'], echo sprintf($pageLayout['full_alt'],
sprintf($contentLayout['manage']['header'], sprintf($contentLayout['manage']['header'],
$validateTokenResult['name'] $validateTokenResult['name']
), ),
sprintf($contentLayout['manage']['section'], sprintf($contentLayout['manage']['section'],
implode($tableRows) implode($tableRows)
) )
); );
}
} else { } else {
// No cookie containing valid authentication token found; // No cookie containing valid authentication token found;
// explicitly deleting any remaining cookie, then redirecting to loginpage // explicitly deleting any remaining cookie, then redirecting to loginpage

View File

@ -49,14 +49,19 @@ $(document).ready(function(){
token: data.SecureToken token: data.SecureToken
})) }))
} }
}).done(function() { }).done(function(_data, _textStatus, jqXHR) {
NProgress.inc(1 / XHR.length); 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(){ $.when.apply($, XHR).then(function(){
$.each(arguments, function(_index, _arg) { $.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(); NProgress.done();
console.log('CrossDomain login completed; forwarding to `' + data.Location + '`');
window.location.replace(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(){ $(document).ready(function(){
// Initialize the editable-table functionality // Initialize the editable-table functionality
$('#usertable').editableTableWidget(); $('#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() { $('#usertable button.delete').click(function() {
$(this).closest('tr').addClass('removed'); $(this).closest('tr').addClass('removed');
}); });
@ -32,6 +105,9 @@ $(document).ready(function(){
// To prevent recreating multiple new editors; reference the already existing `<input>` // To prevent recreating multiple new editors; reference the already existing `<input>`
$('#usertable').editableTableWidget({editor: $('#editor')}); $('#usertable').editableTableWidget({editor: $('#editor')});
// Add eventhandlers to buttons of newly added `<tr>` // 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() { $('#usertable .new button.delete').unbind().click(function() {
$(this).closest('tr').remove(); $(this).closest('tr').remove();
}); });
@ -93,3 +169,7 @@ console.log({'new': newEntries, 'removed': removedEntries});
}); });
}); });
$(document).click(function () {
$('#sessions').fadeOut();
});

View File

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

View File

@ -129,6 +129,35 @@ body {
.main section .buttons button { .main section .buttons button {
margin-left: inherit; 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 { .main section table {
width: 100%; width: 100%;
} }