Credentials makeover: rebuilt credentials list with kind icons, username copy, password show/copy and live 2FA code buttons fetched on demand, where it opens, what it is for (asset, contact, vendors, licenses, services), password age pills and last used, filters for Starred, With 2FA, No 2FA, Not changed in 90 days and Shared with counts, search across notes, second link, tags, asset and contact, open straight to a credential with ?open=ID; new credential quick look with login, age, last viewed by, links with unlink, notes, open share links with turn off, and history; tabbed new/edit form with password generator (passphrase or random), strength meter, 2FA secret that accepts spaces or an otpauth:// link and shows the current code to check, copy buttons on both links, prefill from asset, contact or vendor; new Change password window that dates and logs the change; new Share window from anywhere (contact or email, 1 hour to 1 month, gone after opened once by default, link copied); same login controls on asset and contact pages and quick looks, vendor Logins tab, license page and quick look, service quick look, client overview favourites and search; credential pickers show icons and say when a credential moves from another asset or contact; client overview Passwords due for a change attention item and Active share links limited to live links; rotation report with selectable span, per client counts and oldest first; more export columns; demo data gets 2FA secrets, varied password ages and logins attached to their assets. Fixes passwords being blanked when the vault session had expired, other clients' assets, contacts and tags accepted on save, bulk star using the wrong permission, credential links to assets and contacts not checking the client, the edit or link permission, or which asset or contact an unlink was for, credentials left pointing at deleted assets and contacts, share links left open after a credential was deleted, import carrying values between rows and accepting any file type, 2FA secrets saved with spaces or lowercase giving no code, the service quick look listing credentials without credential access and repeating assets, an asset login with only a username being lost, and the API not dating new passwords. Adds functions/credential.php and js/credentials.js; removes credential_model.php and the old credential show password/OTP scripts. No DB change.

This commit is contained in:
johnnyq
2026-10-14 23:33:29 -04:00
parent 9e55d52432
commit fecd1cabff
47 changed files with 2643 additions and 1786 deletions

View File

@@ -367,6 +367,17 @@ function demoFirstId($mysqli, $table, $id_column, $archived_column = '') {
// Deterministic stand-in for a serial number - same input, same serial, so a
// reload after a removal does not produce a whole new set of numbers
/** A 2FA seed that comes out the same on every run - 32 base32 characters from the seed. */
function demoTotpSeed($seed) {
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$bytes = md5('itflow-demo-totp-' . $seed, true) . md5('itflow-demo-totp-2-' . $seed, true);
$out = '';
for ($i = 0; $i < 32; $i++) {
$out .= $alphabet[ord($bytes[$i]) % 32];
}
return $out;
}
function demoSerial($seed, $length = 10) {
return strtoupper(substr(md5('itflow-demo-' . $seed), 0, $length));
}
@@ -1342,9 +1353,12 @@ function demoBuildClient($mysqli, $profile, $index, $context, &$counts) {
'credential_password' => encryptCredentialEntry(demoSerial($profile['abbreviation'] . $credential[0], 14) . '!aA1'),
'credential_note' => $credential[4],
'credential_favorite' => $credential[6],
// A 2FA seed on the logins that have one, so the codes count down like the real thing
'credential_otp_secret' => !empty($credential[7]) ? demoTotpSeed($profile['abbreviation'] . $credential[0]) : '',
'credential_client_id' => $client_id,
'credential_created_at' => demoMonthDateTime($months, 8, 16, 10),
'credential_password_changed_at' => demoMonthDateTime(max(0, min(4, $months)), 8, 16, 10),
// Some changed lately, some due, one well over a year - never before the client was taken on
'credential_password_changed_at' => demoDateTime(min($credential[8] ?? 30, max(0, $months * 30 - 10)), 16, 10),
'credential_accessed_at' => demoDateTime(($index + 2) % 15, 11, 30),
]);
$credential_ids[$credential[0]] = $credential_id;
@@ -1480,6 +1494,8 @@ function demoBuildClient($mysqli, $profile, $index, $context, &$counts) {
foreach ($assets as $asset) {
if (!empty($asset['credential']) && $asset['credential'] === $credential_name) {
demoLink($mysqli, 'asset_credentials', 'credential_id', $credential_id, 'asset_id', $asset['id']);
// The credential's own asset - what the asset's Credentials tab and the credential show
mysqli_query($mysqli, "UPDATE credentials SET credential_asset_id = " . intval($asset['id']) . " WHERE credential_id = " . intval($credential_id) . " AND credential_asset_id = 0");
}
}
}
@@ -4500,13 +4516,14 @@ function demoExpandProfile($spec) {
// Credentials - names line up with demoAssetCredentialName so the vault
// entries attach to the kit they actually open
$mail_admin_uri = $mail === 'Google Workspace' ? 'https://admin.google.com' : 'https://admin.microsoft.com';
// [name, description, uri, username, note, tags, starred, has 2FA, password last changed (days ago)]
$credentials = [
['Firewall Administrator', 'Edge firewall management interface', 'https://192.168.10.1', 'msp-admin', 'Local administrator on the edge firewall. Rotated at every quarterly review.', ['Firewall', 'Local Admin', 'Rotate Quarterly'], 1],
[$mail . ' Administrator', 'Tenant administration for mail and identity', $mail_admin_uri, 'msp-admin@' . $domain, 'Break glass administrator. MFA enforced - the token lives with the on call phone.', ['Microsoft 365', 'Domain Admin', 'Break Glass'], 1],
['Hypervisor and Storage Administrator', $foss ? 'Proxmox VE and TrueNAS management' : 'Hypervisor and NAS management', 'https://192.168.20.10:8006', 'msp-admin', 'Root equivalent. Use the individual accounts for day to day work and this only for maintenance.', ['Hypervisor', 'Local Admin', 'Break Glass'], 0],
['Network Controller', 'UniFi controller for switching and wireless', 'https://192.168.10.12', 'msp-' . strtolower($short), 'Controller runs on the management stack, not on site.', ['Switch', 'Wireless', 'Shared'], 0],
['Backup Console', $foss ? 'Proxmox Backup Server and Synology Active Backup' : 'Backup platform for servers and endpoints', 'https://backup.example', 'msp-' . strtolower($short), 'Console login for restore requests and job monitoring.', ['Backup Console', 'Service Account'], 0],
['Registrar and DNS', 'Domain registrar and DNS control panel', 'https://registrar.example', 'billing@' . $domain, 'Registrar account is in the client name with us as technical contact.', ['Registrar and DNS', 'Shared'], 0],
['Firewall Administrator', 'Edge firewall management interface', 'https://192.168.10.1', 'msp-admin', 'Local administrator on the edge firewall. Rotated at every quarterly review.', ['Firewall', 'Local Admin', 'Rotate Quarterly'], 1, 0, 25],
[$mail . ' Administrator', 'Tenant administration for mail and identity', $mail_admin_uri, 'msp-admin@' . $domain, 'Break glass administrator. MFA enforced - the token lives with the on call phone.', ['Microsoft 365', 'Domain Admin', 'Break Glass'], 1, 1, 120],
['Hypervisor and Storage Administrator', $foss ? 'Proxmox VE and TrueNAS management' : 'Hypervisor and NAS management', 'https://192.168.20.10:8006', 'msp-admin', 'Root equivalent. Use the individual accounts for day to day work and this only for maintenance.', ['Hypervisor', 'Local Admin', 'Break Glass'], 0, 0, 430],
['Network Controller', 'UniFi controller for switching and wireless', 'https://192.168.10.12', 'msp-' . strtolower($short), 'Controller runs on the management stack, not on site.', ['Switch', 'Wireless', 'Shared'], 0, 0, 60],
['Backup Console', $foss ? 'Proxmox Backup Server and Synology Active Backup' : 'Backup platform for servers and endpoints', 'https://backup.example', 'msp-' . strtolower($short), 'Console login for restore requests and job monitoring.', ['Backup Console', 'Service Account'], 0, 1, 210],
['Registrar and DNS', 'Domain registrar and DNS control panel', 'https://registrar.example', 'billing@' . $domain, 'Registrar account is in the client name with us as technical contact.', ['Registrar and DNS', 'Shared'], 0, 1, 15],
];
// Services - the last two entries say which asset types run it and which

View File

@@ -817,6 +817,10 @@ if (isset($_GET['share_generate_link'])) {
// Logging
logAudit("Share", "Create", "$session_name created shared link for $item_type - $item_name", $client_id, $item_id);
// ...and on the credential itself, so its history says who it went out to
if ($item_type == "Credential") {
logAudit("Credential", "Share", "$session_name shared credential $item_name" . ($item_email ? " with $item_email" : '') . ", expiring in $item_expires_friendly", $client_id, $item_id);
}
}
@@ -1167,13 +1171,19 @@ if (isset($_GET['get_totp_token_via_id'])) {
$credential_id = intval($_GET['credential_id']);
$sql = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT credential_name, credential_otp_secret, credential_client_id FROM credentials WHERE credential_id = $credential_id"));
if (!$sql) {
echo json_encode('');
exit;
}
$name = escapeSql($sql['credential_name']);
$totp_secret = $sql['credential_otp_secret'];
$client_id = intval($sql['credential_client_id']);
enforceClientAccess();
$otp = TokenAuth6238::getTokenCode(strtoupper($totp_secret));
// Seeds saved before they were tidied on save may still carry spaces, dashes or the whole otpauth:// link
$totp_seed = credentialOtpSeed($totp_secret);
$otp = $totp_seed ? TokenAuth6238::getTokenCode($totp_seed) : '';
echo json_encode($otp);
// Logging
@@ -1816,6 +1826,10 @@ if (isset($_GET['get_credential_via_id'])) {
$credential_id = intval($_GET['credential_id']);
$sql = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT credential_name, credential_username, credential_password, credential_client_id FROM credentials WHERE credential_id = $credential_id"));
if (!$sql) {
echo json_encode(['error' => 'That credential no longer exists.']);
exit;
}
$name = escapeSql($sql['credential_name']);
$client_id = intval($sql['credential_client_id']);
@@ -1827,6 +1841,9 @@ if (isset($_GET['get_credential_via_id'])) {
);
echo json_encode($response);
// When it was last used - the credentials list sorts by it. Kept off the updated date, which means an edit
mysqli_query($mysqli, "UPDATE credentials SET credential_accessed_at = NOW(), credential_updated_at = credential_updated_at WHERE credential_id = $credential_id");
// Only log if this user hasn't viewed this credential recently (mirrors TOTP dedup)
$check_recent_view = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT(log_id) AS recent_view FROM logs WHERE log_type = 'Credential' AND log_action = 'View' AND log_user_id = $session_user_id AND log_entity_id = $credential_id AND log_client_id = $client_id AND log_created_at > (NOW() - INTERVAL 5 MINUTE)"));

View File

@@ -103,6 +103,7 @@ if (mysqli_num_rows($sql) == 0) {
$can_edit = lookupUserPermission('module_support') >= 2;
$can_delete = lookupUserPermission('module_support') >= 3;
$can_credentials = lookupUserPermission('module_credential') >= 1;
$can_credentials_edit = lookupUserPermission('module_credential') >= 2;
// The rack it sits in, if any
$asset_rack = rackPositionForAsset($asset_id);
@@ -211,18 +212,8 @@ if (mysqli_num_rows($sql) == 0) {
$document_count = mysqli_num_rows($sql_related_documents);
// Credentials
$credential_count = 0;
if ($can_credentials) {
$sql_related_credentials = mysqli_query($mysqli, "
SELECT credential_id, credential_name, credential_description, credential_uri,
credential_username, credential_otp_secret
FROM credentials
WHERE credential_asset_id = $asset_id
AND credential_archived_at IS NULL
ORDER BY credential_name ASC
");
$credential_count = mysqli_num_rows($sql_related_credentials);
}
$related_credentials = $can_credentials ? credentialRows("credential_asset_id = $asset_id AND credential_client_id = $client_id") : [];
$credential_count = count($related_credentials);
// Licenses it holds a seat on, with each one's seats in use and the key it was given
$held_software = softwareHeldBy('asset', $asset_id);
@@ -337,8 +328,8 @@ if (mysqli_num_rows($sql) == 0) {
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/recurring_ticket/recurring_ticket_add.php?<?= $client_url ?>&asset_id=<?= $asset_id ?>" data-modal-size="lg">
<i class="fa fa-fw fa-redo-alt text-secondary me-2"></i>Recurring Ticket
</a>
<?php if ($can_credentials) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>asset_id=<?= $asset_id ?>">
<?php if ($can_credentials_edit) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>asset_id=<?= $asset_id ?>">
<i class="fa fa-fw fa-key text-secondary me-2"></i>Credential
</a>
<?php } ?>
@@ -365,7 +356,7 @@ if (mysqli_num_rows($sql) == 0) {
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/link/link.php?from=asset&id=<?= $asset_id ?>&to=software">
<i class="fa fa-fw fa-cube text-secondary me-2"></i>License
</a>
<?php if ($can_credentials) { ?>
<?php if ($can_credentials_edit) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/asset/asset_link_credential.php?id=<?= $asset_id ?>">
<i class="fa fa-fw fa-key text-secondary me-2"></i>Credential
</a>
@@ -734,98 +725,24 @@ if (mysqli_num_rows($sql) == 0) {
<div class="tab-pane fade" id="asset-pane-credentials" role="tabpanel">
<div class="itflow-asset-pane-bar">
<span class="text-body-secondary small">Logins for this asset. Passwords and codes are fetched only when you ask for them.</span>
<?php if ($can_edit) { ?>
<?php if ($can_edit && $can_credentials_edit) { ?>
<div class="d-flex gap-2">
<button type="button" class="btn btn-sm btn-outline-secondary ajax-modal" data-modal-url="modals/asset/asset_link_credential.php?id=<?= $asset_id ?>">
<i class="fas fa-link me-2"></i>Link
</button>
<button type="button" class="btn btn-sm btn-primary ajax-modal" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>asset_id=<?= $asset_id ?>">
<button type="button" class="btn btn-sm btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>asset_id=<?= $asset_id ?>">
<i class="fas fa-plus me-2"></i>New Credential
</button>
</div>
<?php } ?>
</div>
<?php if ($credential_count) { ?>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="text-nowrap table-light">
<tr>
<th>Name</th>
<th>Username</th>
<th>Password</th>
<th>OTP</th>
<th>URI</th>
<th></th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($sql_related_credentials)) {
$credential_id = intval($row['credential_id']);
$credential_name = escapeHtml($row['credential_name']);
$credential_description = escapeHtml($row['credential_description']);
$credential_uri = escapeHtml($row['credential_uri']);
$credential_username = escapeHtml(decryptCredentialEntry($row['credential_username']));
$credential_has_otp = !empty($row['credential_otp_secret']);
?>
<tr>
<td>
<a class="text-body fw-semibold ajax-modal" href="#" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>"><?= $credential_name ?></a>
<?php if ($credential_description) { ?><div class="small text-body-secondary"><?= $credential_description ?></div><?php } ?>
</td>
<td class="text-nowrap">
<?php if ($credential_username) { ?>
<?= $credential_username ?><button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="<?= $credential_username ?>"><i class="far fa-copy"></i></button>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<td class="text-nowrap">
<button class="btn btn-sm btn-light" aria-label="Show password" title="Show password" type="button" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-ellipsis-h"></i><i class="fas fa-ellipsis-h"></i></button>
<button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
</td>
<td class="text-nowrap">
<?php if ($credential_has_otp) { ?>
<span onmouseenter="showOTPViaCredentialID(<?= $credential_id ?>)"><i class="far fa-clock text-secondary me-1"></i><span id="otp_<?= $credential_id ?>"><i>Hover...</i></span></span>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<td class="text-nowrap">
<?php if ($credential_uri) { ?>
<a href="<?= $credential_uri ?>" target="_blank" rel="noopener" title="<?= $credential_uri ?>"><?= truncate($credential_uri, 26) ?></a><button type="button" class="itflow-copy clipboardjs" title="Copy URI" data-clipboard-text="<?= $credential_uri ?>"><i class="far fa-copy"></i></button>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<td class="text-end">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#shareModal" onclick="populateShareModal(<?= "$client_id, 'Credential', $credential_id" ?>)">
<i class="fas fa-fw fa-share-alt text-secondary me-2"></i>Share
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="post.php?unlink_credential_from_asset&asset_id=<?= $asset_id ?>&credential_id=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-unlink text-secondary me-2"></i>Unlink
</a>
<?php if (lookupUserPermission('module_credential') >= 3) { ?>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_credential=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php if ($related_credentials) { ?>
<?= credentialTableHtml($related_credentials, [
'for' => false,
'unlink' => function ($row) use ($asset_id, $can_edit) {
return $can_edit && credentialCan(2) ? "post.php?unlink_credential_from_asset&asset_id=$asset_id&credential_id=" . intval($row['credential_id']) . "&csrf_token=" . $_SESSION['csrf_token'] : '';
},
]) ?>
<?php } else { ?>
<div class="itflow-asset-empty">No credentials for this asset.</div>
<?php } ?>
@@ -1213,7 +1130,6 @@ if (mysqli_num_rows($sql) == 0) {
</div>
<?php
require_once "modals/share_modal.php";
require_once "modals/asset/asset_interface_multiple_add.php";
require_once "modals/asset/asset_interface_import.php";
require_once "modals/asset/asset_interface_export.php";
@@ -1261,10 +1177,6 @@ if (mysqli_num_rows($sql) == 0) {
});
</script>
<!-- Fetch TOTP codes and passwords only when asked for -->
<script src="js/credential_show_otp_via_id.js"></script>
<script src="js/credential_show_password_via_id.js"></script>
<script src="../js/bulk_actions.js"></script>
<?php

View File

@@ -241,24 +241,19 @@ $money_format = function ($amount) use ($currency_format, $client_currency_code,
<?php } ?>
<?php foreach ($favorites['credentials'] as $credential) {
$credential_id = intval($credential['credential_id']);
$credential_username = escapeHtml(decryptCredentialEntry($credential['credential_username']));
$credential_username = credentialUsername($credential);
?>
<div class="list-group-item d-flex align-items-center gap-2 py-2">
<i class="fas fa-fw fa-key text-body-secondary" title="Credential"></i>
<span class="flex-grow-1 overflow-hidden">
<a class="ajax-modal d-block text-truncate" href="#" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>"><?= escapeHtml($credential['credential_name']) ?></a>
<?php if ($credential_username) { ?>
<span class="d-flex align-items-center small text-body-secondary">
<span class="text-truncate"><?= $credential_username ?></span>
<button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="<?= $credential_username ?>"><i class="far fa-copy"></i></button>
</span>
<?php } ?>
</span>
<?php if ($credential['credential_otp_secret']) { ?>
<span class="small text-body-secondary text-nowrap" onmouseenter="showOTPViaCredentialID(<?= $credential_id ?>)" title="Hover for the current code"><i class="far fa-clock me-1" aria-hidden="true"></i><span id="otp_<?= $credential_id ?>">OTP</span></span>
<?php } ?>
<span class="text-nowrap">
<button class="btn btn-sm btn-link text-body-secondary p-1" type="button" title="Show password" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-fw fa-eye" aria-hidden="true"></i></button><button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
<?= credentialTile($credential, 'sm') ?>
<span class="flex-grow-1 min-w-0">
<a class="ajax-modal d-block text-truncate" href="#" data-modal-url="modals/credential/credential.php?id=<?= $credential_id ?>"><?= escapeHtml($credential['credential_name']) ?></a>
<span class="d-flex flex-wrap align-items-center column-gap-3 row-gap-1 small text-body-secondary">
<?php if ($credential_username !== '') { ?>
<span class="d-inline-flex align-items-center min-w-0"><?= credentialUsernameHtml($credential_username) ?></span>
<?php } ?>
<?= credentialPasswordHtml($credential_id) ?>
<?= credentialOtpHtml($credential_id, trim((string) $credential['credential_otp_secret']) !== '') ?>
</span>
</span>
</div>
<?php } ?>
@@ -378,6 +373,10 @@ $money_format = function ($amount) use ($currency_format, $client_currency_code,
} elseif ($item['item_type'] === 'File') {
$item_tile = fileTypeTile($item['file_ext'], 'sm');
$item_label = "<a class=\"ajax-modal\" href=\"#\" data-modal-size=\"lg\" data-modal-url=\"modals/file/file.php?id=$item_related_id\">$item_label</a>";
} elseif ($item['item_type'] === 'Credential' && $item['item_name']) {
// Its tile, opening its quick look - with the password and 2FA there for whoever may see them
$item_tile = credentialTile(['credential_name' => $item['item_name'], 'credential_uri' => $item['credential_uri'], 'credential_description' => $item['credential_description']], 'sm');
$item_label = $access['credentials'] ? "<a class=\"ajax-modal\" href=\"#\" data-modal-url=\"modals/credential/credential.php?id=$item_related_id\">$item_label</a>" : $item_label;
} else {
$item_tile = '<span class="itflow-link-icon" title="' . escapeHtml($item['item_type']) . '" aria-hidden="true"><i class="fas fa-fw fa-' . ($item['item_type'] === 'Credential' ? 'key' : 'share-square') . '"></i></span>';
}
@@ -547,8 +546,6 @@ $money_format = function ($amount) use ($currency_format, $client_currency_code,
</div>
<script src="js/credential_show_otp_via_id.js"></script>
<script src="js/credential_show_password_via_id.js"></script>
<?php require_once "../includes/footer.php"; ?>

View File

@@ -72,6 +72,7 @@ $contact_role_line = implode(' &middot; ', array_filter([$contact_title, $contac
$can_edit = lookupUserPermission('module_client') >= 2;
$can_delete = lookupUserPermission('module_client') >= 3;
$can_credentials = lookupUserPermission('module_credential') >= 1;
$can_credentials_edit = lookupUserPermission('module_credential') >= 2;
$can_support = lookupUserPermission('module_support') >= 1;
$can_support_edit = lookupUserPermission('module_support') >= 2;
@@ -93,17 +94,8 @@ $sql_related_assets = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_
$asset_count = mysqli_num_rows($sql_related_assets);
// Credentials - only for agents who may see them
$credential_count = 0;
if ($can_credentials) {
$sql_related_credentials = mysqli_query($mysqli, "SELECT credential_id, credential_name, credential_description, credential_uri,
credential_username, credential_otp_secret
FROM credentials
WHERE credential_contact_id = $contact_id
AND credential_archived_at IS NULL
ORDER BY credential_name ASC"
);
$credential_count = mysqli_num_rows($sql_related_credentials);
}
$related_credentials = $can_credentials ? credentialRows("credential_contact_id = $contact_id AND credential_client_id = $client_id") : [];
$credential_count = count($related_credentials);
// Tickets they raised or are the contact on - open ones first
$related_tickets = [];
@@ -276,8 +268,8 @@ if (!$can_support) {
<i class="fa fa-fw fa-desktop text-secondary me-2"></i>Asset
</a>
<?php } ?>
<?php if ($can_credentials) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>&contact_id=<?= $contact_id ?>">
<?php if ($can_credentials_edit) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>&contact_id=<?= $contact_id ?>">
<i class="fa fa-fw fa-key text-secondary me-2"></i>Credential
</a>
<?php } ?>
@@ -303,7 +295,7 @@ if (!$can_support) {
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/contact/contact_link_asset.php?id=<?= $contact_id ?>">
<i class="fa fa-fw fa-desktop text-secondary me-2"></i>Asset
</a>
<?php if ($can_credentials) { ?>
<?php if ($can_credentials_edit) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/contact/contact_link_credential.php?id=<?= $contact_id ?>">
<i class="fa fa-fw fa-key text-secondary me-2"></i>Credential
</a>
@@ -531,75 +523,23 @@ if (!$can_support) {
<div class="tab-pane fade" id="contact-pane-credentials" role="tabpanel">
<div class="itflow-asset-pane-bar">
<span class="text-body-secondary small">Their logins. Passwords and codes are fetched only when you ask for them.</span>
<?php if ($can_edit) { ?>
<?php if ($can_edit && $can_credentials_edit) { ?>
<div class="d-flex gap-2">
<button type="button" class="btn btn-sm btn-outline-secondary ajax-modal" data-modal-url="modals/contact/contact_link_credential.php?id=<?= $contact_id ?>">
<i class="fas fa-link me-2"></i>Link
</button>
<button type="button" class="btn btn-sm btn-primary ajax-modal" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>&contact_id=<?= $contact_id ?>">
<button type="button" class="btn btn-sm btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>&contact_id=<?= $contact_id ?>">
<i class="fas fa-plus me-2"></i>New Credential
</button>
</div>
<?php } ?>
</div>
<?php if ($credential_count) { ?>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="text-nowrap table-light">
<tr><th>Name</th><th>Username</th><th>Password</th><th>OTP</th><th>URI</th><th></th></tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($sql_related_credentials)) {
$credential_id = intval($row['credential_id']);
$credential_description = escapeHtml($row['credential_description']);
$credential_uri = escapeHtml($row['credential_uri']);
$credential_username = escapeHtml(decryptCredentialEntry($row['credential_username'])); ?>
<tr>
<td>
<a class="text-body fw-semibold ajax-modal" href="#" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>"><?= escapeHtml($row['credential_name']) ?></a>
<?php if ($credential_description) { ?><div class="small text-body-secondary"><?= $credential_description ?></div><?php } ?>
</td>
<td class="text-nowrap"><?php if ($credential_username) { ?><?= $credential_username ?><button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="<?= $credential_username ?>"><i class="far fa-copy"></i></button><?php } else { ?><span class="text-body-secondary">-</span><?php } ?></td>
<td class="text-nowrap">
<button class="btn btn-sm btn-light" aria-label="Show password" title="Show password" type="button" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-ellipsis-h"></i><i class="fas fa-ellipsis-h"></i></button><button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
</td>
<td class="text-nowrap">
<?php if (!empty($row['credential_otp_secret'])) { ?>
<span onmouseenter="showOTPViaCredentialID(<?= $credential_id ?>)"><i class="far fa-clock text-secondary me-1"></i><span id="otp_<?= $credential_id ?>"><i>Hover...</i></span></span>
<?php } else { ?><span class="text-body-secondary">-</span><?php } ?>
</td>
<td class="text-nowrap">
<?php if ($credential_uri) { ?><a href="<?= escapeUrl($row['credential_uri']) ?>" target="_blank" rel="noopener" title="<?= $credential_uri ?>"><?= truncate($credential_uri, 26) ?></a><button type="button" class="itflow-copy clipboardjs" title="Copy URI" data-clipboard-text="<?= $credential_uri ?>"><i class="far fa-copy"></i></button><?php } else { ?><span class="text-body-secondary">-</span><?php } ?>
</td>
<td class="text-end">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#shareModal" onclick="populateShareModal(<?= "$client_id, 'Credential', $credential_id" ?>)">
<i class="fas fa-fw fa-share-alt text-secondary me-2"></i>Share
</a>
<?php if ($can_edit) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="post.php?unlink_credential_from_contact&contact_id=<?= $contact_id ?>&credential_id=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-unlink text-secondary me-2"></i>Unlink
</a>
<?php } ?>
<?php if (lookupUserPermission('module_credential') >= 3) { ?>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_credential=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php if ($related_credentials) { ?>
<?= credentialTableHtml($related_credentials, [
'unlink' => function ($row) use ($contact_id, $can_edit) {
return $can_edit && credentialCan(2) ? "post.php?unlink_credential_from_contact&contact_id=$contact_id&credential_id=" . intval($row['credential_id']) . "&csrf_token=" . $_SESSION['csrf_token'] : '';
},
]) ?>
<?php } else { ?>
<div class="itflow-asset-empty">No credentials for <?= $contact_name ?>.</div>
<?php } ?>
@@ -897,8 +837,6 @@ if (!$can_support) {
</div>
<?php require_once "modals/share_modal.php"; ?>
<script>
function updateContactNotes(contact_id) {
itflowPost("ajax.php", {
@@ -941,9 +879,5 @@ if (!$can_support) {
});
</script>
<!-- Fetch TOTP codes and passwords only when asked for -->
<script src="js/credential_show_otp_via_id.js"></script>
<script src="js/credential_show_password_via_id.js"></script>
<?php
require_once "../includes/footer.php";

View File

@@ -1,5 +1,17 @@
<?php
/*
* Credentials - one client's logins, or every login the agent can see from
* All Client Docs. Starred first. Each row has what is needed to log in -
* the username, the password and 2FA code on asking, where it opens - what
* it is for (asset, contact, vendors, licenses), and how old the password is.
* The pills along the top count and filter the ones to look at: no 2FA,
* due for a change, shared out.
*
* Passwords and codes are never in the page; js/credentials.js fetches them
* when asked for, and agent/ajax.php logs each view.
*/
// Default Column Sortby Filter
$sort = "credential_name";
$order = "ASC";
@@ -9,14 +21,8 @@ if (isset($_GET['client_id'])) {
require_once "includes/inc_all_client.php";
$client_query = "AND credential_client_id = $client_id";
$client_url = "client_id=$client_id&";
// Overide Filter Header Archived
if (isset($_GET['archived']) && $_GET['archived'] == 1) {
$archived = 1;
$archive_query = "credential_archived_at IS NOT NULL";
} else {
$archived = 0;
$archive_query = "credential_archived_at IS NULL";
}
$archived = isset($_GET['archived']) && $_GET['archived'] == 1 ? 1 : 0;
$archive_query = $archived ? "credential_archived_at IS NOT NULL" : "credential_archived_at IS NULL";
// Log when users load the Credentials page
logAudit("Credential", "View", "$session_name viewed the Credentials page for client", $client_id);
@@ -25,14 +31,9 @@ if (isset($_GET['client_id'])) {
require_once "includes/inc_client_overview_all.php";
$client_query = '';
$client_url = '';
// Overide Filter Header Archived
if (isset($_GET['archived']) && $_GET['archived'] == 1) {
$archived = 1;
$archive_query = "(client_archived_at IS NOT NULL OR credential_archived_at IS NOT NULL)";
} else {
$archived = 0;
$archive_query = "(client_archived_at IS NULL AND credential_archived_at IS NULL)";
}
$archived = isset($_GET['archived']) && $_GET['archived'] == 1 ? 1 : 0;
$archive_query = $archived ? "(client_archived_at IS NOT NULL OR credential_archived_at IS NOT NULL)" : "(client_archived_at IS NULL AND credential_archived_at IS NULL)";
// Log when users load the Credentials page
logAudit("Credential", "View", "$session_name viewed the All Credentials page");
}
@@ -40,83 +41,128 @@ if (isset($_GET['client_id'])) {
// Perms
enforceUserPermission('module_credential');
// Tags Filter
$can_edit = credentialCan(2);
$can_delete = credentialCan(3) && !empty($config_destructive_deletes_enable);
$can_share = lookupUserPermission('module_support') >= 2;
// Client Filter (all clients)
$client = '';
if (!$client_url && !empty($_GET['client'])) {
$client = intval($_GET['client']);
$client_query = "AND credential_client_id = $client";
}
// Location Filter (one client) - credentials for the assets at a site
$location_filter = $client_url ? intval($_GET['location'] ?? 0) : 0;
$location_query = $location_filter ? "AND c.credential_asset_id IN (SELECT asset_id FROM assets WHERE asset_location_id = $location_filter)" : '';
// Tags Filter - a credential with any of them
if (isset($_GET['tags']) && is_array($_GET['tags']) && !empty($_GET['tags'])) {
// Sanitize each element of the tags array
$sanitizedTags = array_map('intval', $_GET['tags']);
// Convert the sanitized tags into a comma-separated string
$tag_filter = implode(",", $sanitizedTags);
$tag_query = "AND tags.tag_id IN ($tag_filter)";
$tag_filter = implode(",", array_map('intval', $_GET['tags']));
$tag_query = "AND c.credential_id IN (SELECT credential_id FROM credential_tags WHERE tag_id IN ($tag_filter))";
} else {
$tag_filter = 0;
$tag_query = '';
}
if (!$client_url) {
// Client Filter
if (isset($_GET['client']) & !empty($_GET['client'])) {
$client_query = 'AND (credential_client_id = ' . intval($_GET['client']) . ')';
$client = intval($_GET['client']);
} else {
// Default - any
$client_query = '';
$client = '';
}
}
// Which ones - the pills along the top
$rotate_days = CREDENTIAL_ROTATE_DAYS;
$shows = [
'' => ['label' => 'All', 'where' => ''],
'starred' => ['label' => 'Starred', 'icon' => 'fa-star', 'where' => 'c.credential_favorite = 1'],
'otp' => ['label' => 'With 2FA', 'icon' => 'fa-clock', 'where' => "c.credential_otp_secret <> ''"],
'nootp' => ['label' => 'No 2FA', 'icon' => 'fa-unlock', 'where' => "(c.credential_otp_secret IS NULL OR c.credential_otp_secret = '')"],
'due' => ['label' => "Not changed in $rotate_days days", 'icon' => 'fa-history', 'where' => "(c.credential_password_changed_at IS NULL OR c.credential_password_changed_at < NOW() - INTERVAL $rotate_days DAY)"],
'shared' => ['label' => 'Shared', 'icon' => 'fa-share-alt', 'where' => "c.credential_id IN (SELECT item_related_id FROM shared_items WHERE item_type = 'Credential' AND item_active = 1 AND item_expire_at > NOW() AND (COALESCE(item_view_limit, 0) = 0 OR item_views < item_view_limit))"],
];
$show = isset($shows[$_GET['show'] ?? '']) ? ($_GET['show'] ?? '') : '';
$show_query = $shows[$show]['where'] ? 'AND ' . $shows[$show]['where'] : '';
// Location Filter
if ($client_url && isset($_GET['location']) && !empty($_GET['location'])) {
$location_query = 'AND (a.asset_location_id = ' . intval($_GET['location']) . ')';
$location_query_innerjoin = 'INNER JOIN assets a on a.asset_id = c.credential_asset_id ';
$location_filter = intval($_GET['location']);
} else {
// Default - any
$location_query_innerjoin = '';
$location_query = '';
$location_filter = '';
// Only these sort - filter_header.php will hand through any lowercase word, and
// an unknown column takes the page down with a mysqli exception
$sortable_columns = ['credential_name', 'credential_uri', 'credential_password_changed_at', 'credential_accessed_at', 'client_name', 'credential_created_at'];
if (!in_array($sort, $sortable_columns, true)) {
$sort = 'credential_name';
}
$sort_column = $sort === 'client_name' ? 'client_name' : "c.$sort";
$search_query = "AND (c.credential_name LIKE '%$q%' OR c.credential_description LIKE '%$q%' OR c.credential_uri LIKE '%$q%' OR c.credential_uri_2 LIKE '%$q%'
OR c.credential_note LIKE '%$q%' OR client_name LIKE '%$q%' OR asset_name LIKE '%$q%' OR contact_name LIKE '%$q%'
OR c.credential_id IN (SELECT credential_id FROM credential_tags JOIN tags USING (tag_id) WHERE tag_name LIKE '%$q%'))";
$scope_query = clientScopeSql('credential_client_id');
$sql = mysqli_query(
$mysqli,
"SELECT SQL_CALC_FOUND_ROWS c.credential_id AS c_credential_id, c.*, credential_tags.*, tags.*, clients.*, contacts.*, assets.*
"SELECT SQL_CALC_FOUND_ROWS c.credential_id, c.credential_name, c.credential_description, c.credential_uri, c.credential_uri_2, c.credential_username,
c.credential_otp_secret, c.credential_favorite, c.credential_archived_at, c.credential_password_changed_at, c.credential_accessed_at,
c.credential_client_id, client_name, contact_id, contact_name, contact_photo, contact_archived_at, asset_id, asset_name, asset_type, asset_archived_at
FROM credentials c
LEFT JOIN credential_tags ON credential_tags.credential_id = c.credential_id
LEFT JOIN tags ON tags.tag_id = credential_tags.tag_id
LEFT JOIN clients ON client_id = credential_client_id
LEFT JOIN contacts ON contact_id = credential_contact_id
LEFT JOIN assets ON asset_id = credential_asset_id
$location_query_innerjoin
LEFT JOIN contacts ON contact_id = credential_contact_id AND contact_client_id = credential_client_id
LEFT JOIN assets ON asset_id = credential_asset_id AND asset_client_id = credential_client_id
WHERE $archive_query
$tag_query
AND (c.credential_name LIKE '%$q%' OR c.credential_description LIKE '%$q%' OR c.credential_uri LIKE '%$q%' OR tag_name LIKE '%$q%' OR client_name LIKE '%$q%')
$search_query
$location_query
" . clientScopeSql('credential_client_id') . "
$show_query
$scope_query
$client_query
GROUP BY c.credential_id
ORDER BY c.credential_favorite DESC, $sort $order LIMIT $record_from, $record_to"
ORDER BY c.credential_favorite DESC, $sort_column $order, c.credential_name ASC LIMIT $record_from, $record_to"
);
$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$credentials = [];
while ($row = mysqli_fetch_assoc($sql)) {
$credentials[intval($row['credential_id'])] = $row;
}
// Tags, links and share links for the whole page at once, not per row
$credentials_tags = tagsForRecords('credential', array_keys($credentials));
$credentials_links = credentialLinks(array_keys($credentials));
$credentials_shares = credentialShares(array_keys($credentials));
// How many of each, for the pills - everything in scope, before the pill itself
$counts = ['' => 0];
$count_sql = [];
foreach ($shows as $key => $s) {
$count_sql[] = $key === '' ? 'COUNT(*)' : "COALESCE(SUM({$s['where']}), 0)";
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', $count_sql) . "
FROM credentials c
LEFT JOIN clients ON client_id = credential_client_id
LEFT JOIN contacts ON contact_id = credential_contact_id AND contact_client_id = credential_client_id
LEFT JOIN assets ON asset_id = credential_asset_id AND asset_client_id = credential_client_id
WHERE $archive_query $tag_query $search_query $location_query $scope_query $client_query"));
foreach (array_keys($shows) as $i => $key) {
$counts[$key] = intval($row[$i]);
}
$filter_url = function ($changes) use ($client_url) {
$params = array_merge($_GET, $changes);
unset($params['page']);
return '?' . http_build_query(array_filter($params, function ($v) { return $v !== '' && $v !== null; }));
};
?>
<div class="card">
<div class="card-header bg-dark py-2">
<h3 class="card-title mt-2"><i class="fa fa-fw fa-key me-2"></i>Credentials</h3>
<div class="card-tools">
<?php if (lookupUserPermission("module_credential") >= 2) { ?>
<div class="btn-group">
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>" <?php if (!isset($_COOKIE['user_encryption_session_key'])) { echo "disabled"; } ?>>
<i class="fas fa-plus me-2"></i>New Credential
</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown"></button>
<div class="dropdown-menu">
<?php if ($client_url) { ?>
<a class="dropdown-item text-dark ajax-modal" href="#"
data-modal-url="modals/credential/credential_import.php?<?= $client_url ?>">
<i class="fa fa-fw fa-upload me-2"></i>Import
</a>
<div class="dropdown-divider"></div>
<?php if ($can_edit || $num_rows[0]) { ?>
<div class="btn-group">
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/credential/credential_add.php?<?= $client_url ?>">
<i class="fas fa-plus me-2"></i>New Credential
</button>
<?php } ?>
<button type="button" class="btn btn-primary dropdown-toggle <?= $can_edit ? 'dropdown-toggle-split' : '' ?>" data-bs-toggle="dropdown"><?= $can_edit ? '' : '<i class="fas fa-ellipsis-h"></i>' ?></button>
<div class="dropdown-menu dropdown-menu-end">
<?php if ($client_url && $can_edit) { ?>
<a class="dropdown-item text-dark ajax-modal" href="#" data-modal-url="modals/credential/credential_import.php?<?= $client_url ?>">
<i class="fa fa-fw fa-upload me-2"></i>Import
</a>
<?php } ?>
<?php if ($num_rows[0] > 0) { ?>
<a class="dropdown-item text-dark ajax-modal" href="#"
@@ -124,6 +170,9 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
<i class="fa fa-fw fa-download me-2"></i>Export
</a>
<?php } ?>
<a class="dropdown-item text-dark" href="reports/credential_rotation.php">
<i class="fa fa-fw fa-history me-2"></i>Rotation report
</a>
</div>
</div>
<?php } ?>
@@ -135,67 +184,48 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<input type="hidden" name="archived" value="<?= $archived ?>">
<input type="hidden" name="show" value="<?= escapeHtml($show) ?>">
<div class="row g-2 align-items-center">
<div class="col-md-4">
<div class="col-lg-4 col-md-6">
<div class="input-group">
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search Credentials">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search name, link, notes, asset...">
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<select onchange="this.form.submit()" class="form-select select2" name="tags[]" data-placeholder="- Select Tags -" multiple>
<?php
$sql_tags_filter = mysqli_query($mysqli, "
SELECT tags.tag_id, tags.tag_name, MAX(tags.tag_color) AS tag_color, MAX(tags.tag_icon) AS tag_icon
FROM tags
LEFT JOIN credential_tags ON credential_tags.tag_id = tags.tag_id
LEFT JOIN credentials ON credential_tags.credential_id = credentials.credential_id
WHERE tag_type = 4
$client_query OR tags.tag_id IN ($tag_filter)
GROUP BY tags.tag_id
HAVING COUNT(credential_tags.credential_id) > 0 OR tags.tag_id IN ($tag_filter)
");
while ($row = mysqli_fetch_assoc($sql_tags_filter)) {
$tag_id = intval($row['tag_id']);
$tag_name = escapeHtml($row['tag_name']); ?>
<option value="<?= $tag_id ?>" <?php if (isset($_GET['tags']) && is_array($_GET['tags']) && in_array($tag_id, $_GET['tags'])) { echo 'selected'; } ?><?= selectOptionColor($row['tag_color'] ?? '', $row['tag_icon'] ?? '') ?>> <?= $tag_name ?> </option>
<?php } ?>
</select>
</div>
<div class="col-lg-3 col-md-6">
<select onchange="this.form.submit()" class="form-select select2" name="tags[]" data-placeholder="- Tags -" multiple>
<?php
// Tags in use on credentials in this scope, plus any already picked
$sql_tags_filter = mysqli_query($mysqli, "
SELECT tag_id, tag_name, tag_color, tag_icon FROM tags
WHERE tag_type = 4
AND (
EXISTS (SELECT 1 FROM credential_tags JOIN credentials ON credentials.credential_id = credential_tags.credential_id
WHERE credential_tags.tag_id = tags.tag_id " . clientScopeSql('credential_client_id') . " $client_query)
OR tag_id IN ($tag_filter)
)
ORDER BY tag_name ASC
");
while ($row = mysqli_fetch_assoc($sql_tags_filter)) {
$tag_id = intval($row['tag_id']); ?>
<option value="<?= $tag_id ?>" <?php if (isset($_GET['tags']) && is_array($_GET['tags']) && in_array($tag_id, $_GET['tags'])) { echo 'selected'; } ?><?= selectOptionColor($row['tag_color'] ?? '', $row['tag_icon'] ?? '') ?>><?= escapeHtml($row['tag_name']) ?></option>
<?php } ?>
</select>
</div>
<?php if ($client_url) { ?>
<div class="col-md-2">
<div class="input-group">
<div class="col-lg-3 col-md-6">
<?php if ($client_url) { ?>
<select class="form-select select2" name="location" onchange="this.form.submit()">
<option value="">- All Asset Locations -</option>
<?php
$sql_locations_filter = mysqli_query($mysqli, "SELECT location_id, location_name FROM locations WHERE location_client_id = $client_id AND location_archived_at IS NULL ORDER BY location_name ASC");
while ($row = mysqli_fetch_assoc($sql_locations_filter)) {
$location_id = intval($row['location_id']);
$location_name = escapeHtml($row['location_name']);
?>
<option <?php if ($location_filter == $location_id) { echo "selected"; } ?> value="<?= $location_id ?>"><?= $location_name ?></option>
<?php
}
?>
$location_id = intval($row['location_id']); ?>
<option <?php if ($location_filter == $location_id) { echo "selected"; } ?> value="<?= $location_id ?>"><?= escapeHtml($row['location_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } else { ?>
<div class="col-md-2">
<div class="input-group">
<?php } else { ?>
<select class="form-select select2" name="client" onchange="this.form.submit()">
<option value="" <?php if ($client == "") { echo "selected"; } ?>>- All Clients -</option>
<?php
$sql_clients_filter = mysqli_query($mysqli, "
SELECT DISTINCT client_id, client_name, client_abbreviation
@@ -206,317 +236,256 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
ORDER BY client_name ASC
");
while ($row = mysqli_fetch_assoc($sql_clients_filter)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
?>
<option <?php if ($client == $client_id) { echo "selected"; } ?> value="<?= $client_id ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= $client_name ?></option>
<?php
}
?>
$client_id_filter = intval($row['client_id']); ?>
<option <?php if ($client == $client_id_filter) { echo "selected"; } ?> value="<?= $client_id_filter ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= escapeHtml($row['client_name']) ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
</div>
<?php } ?>
<div class="col-md-3">
<div class="btn-group float-end">
<a href="?<?= $client_url ?>&archived=<?php if($archived == 1){ echo 0; } else { echo 1; } ?>"
class="btn btn-<?php if($archived == 1){ echo"primary"; } else { echo "default"; } ?>">
<i class="fa fa-fw fa-archive me-2"></i>Archived
<div class="col-lg-2 col-md-6">
<div class="d-flex justify-content-end gap-2">
<a href="<?= escapeHtml($filter_url(['archived' => $archived ? '' : 1])) ?>"
class="btn <?= $archived ? 'btn-dark' : 'btn-outline-dark' ?>" title="<?= $archived ? 'Back to active credentials' : 'Show archived credentials' ?>">
<i class="fa fa-fw fa-archive"></i><span class="d-lg-none ms-2">Archived</span>
</a>
<div class="dropdown ms-2" id="bulkActionButton" hidden>
<?php if ($can_edit) { ?>
<div class="dropdown" id="bulkActionButton" hidden>
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
<i class="fas fa-fw fa-layer-group me-2"></i>Bulk Action (<span id="selectedCount">0</span>)
</button>
<div class="dropdown-menu">
<button class="dropdown-item"
type="submit" form="bulkActions" name="bulk_favorite_credentials">
<i class="fas fa-fw fa-star text-warning me-2"></i>Favorite
</button>
<div class="dropdown-divider"></div>
<button class="dropdown-item"
type="submit" form="bulkActions" name="bulk_unfavorite_credentials">
<i class="far fa-fw fa-star me-2"></i>Unfavorite
</button>
<?php if ($archived) { ?>
<div class="dropdown-divider"></div>
<button class="dropdown-item text-info"
type="submit" form="bulkActions" name="bulk_restore_credentials">
<i class="fas fa-fw fa-redo me-2"></i>Restore
</button>
<div class="dropdown-divider"></div>
<button class="dropdown-item text-danger text-bold"
type="submit" form="bulkActions" name="bulk_delete_credentials">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</button>
<?php } else { ?>
<div class="dropdown-divider"></div>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="#" data-tag-picker data-tag-entity="credential" data-tag-bulk data-csrf="<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-tags me-2"></i>Tags
</a>
<div class="dropdown-divider"></div>
<button class="dropdown-item text-danger confirm-link"
type="submit" form="bulkActions" name="bulk_archive_credentials">
<i class="fas fa-fw fa-archive me-2"></i>Archive
<button class="dropdown-item" type="submit" form="bulkActions" name="bulk_favorite_credentials">
<i class="fas fa-fw fa-star text-warning me-2"></i>Star
</button>
<button class="dropdown-item" type="submit" form="bulkActions" name="bulk_unfavorite_credentials">
<i class="far fa-fw fa-star me-2"></i>Unstar
</button>
<div class="dropdown-divider"></div>
<?php if ($archived) { ?>
<button class="dropdown-item text-info" type="submit" form="bulkActions" name="bulk_restore_credentials">
<i class="fas fa-fw fa-redo me-2"></i>Restore
</button>
<?php if ($can_delete) { ?>
<button class="dropdown-item text-danger text-bold confirm-link" type="submit" form="bulkActions" name="bulk_delete_credentials"
data-confirm-text="The credentials go for good, with any share links still open.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</button>
<?php } ?>
<?php } else { ?>
<button class="dropdown-item text-danger confirm-link" type="submit" form="bulkActions" name="bulk_archive_credentials">
<i class="fas fa-fw fa-archive me-2"></i>Archive
</button>
<?php } ?>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</form>
<!-- Which ones - counted over what the filters above leave -->
<nav class="nav nav-pills itflow-asset-tabs mt-2 flex-nowrap overflow-auto">
<?php foreach ($shows as $key => $s) { ?>
<a class="nav-link text-nowrap <?= $show === $key ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['show' => $key])) ?>">
<?php if (!empty($s['icon'])) { ?><i class="fas fa-fw <?= $s['icon'] ?> me-1"></i><?php } ?><?= $s['label'] ?>
<span class="badge rounded-pill ms-1 <?= $key === 'due' && $counts[$key] ? 'text-bg-warning' : '' ?>"><?= $counts[$key] ?></span>
</a>
<?php } ?>
</nav>
</div>
<form id="bulkActions" action="post.php" method="post">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<div class="table-responsive">
<table class="table table-striped table-borderless table-hover mb-0">
<thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?> text-nowrap">
<tr>
<td class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" id="selectAllCheckbox" type="checkbox" onclick="checkAll(this)">
</div>
</td>
<th>
<a class="text-secondary" href="?<?= $url_query_strings_sort ?>&sort=credential_name&order=<?= $disp ?>">
Name <?php if ($sort == 'credential_name') { echo $order_icon; } ?>
</a>
</th>
<th>Username / ID</th>
<th>Password / Key</th>
<th>OTP</th>
<th>
<a class="text-secondary" href="?<?= $url_query_strings_sort ?>&sort=credential_uri&order=<?= $disp ?>">
URI <?php if ($sort == 'credential_uri') { echo $order_icon; } ?>
</a>
</th>
<th></th>
<?php if (!$client_url) { ?>
<th>
<a class="text-secondary" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">
Client <?php if ($sort == 'client_name') { echo $order_icon; } ?>
</a>
</th>
<?php } ?>
<th class="text-center">Action</th>
</tr>
<table class="table table-hover align-middle mb-0 itflow-asset-table">
<thead class="<?php if (!$num_rows[0]) { echo "d-none"; } ?> text-nowrap table-light">
<tr>
<?php if ($can_edit) { ?>
<th class="checkbox-column border-end">
<div class="form-check">
<input class="form-check-input" id="selectAllCheckbox" type="checkbox" onclick="checkAll(this)" title="Select all on this page">
</div>
</th>
<?php } ?>
<th>
<a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=credential_name&order=<?= $disp ?>">
Credential <?php if ($sort == 'credential_name') { echo $order_icon; } ?>
</a>
</th>
<th>Login</th>
<th>For</th>
<th>
<a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=credential_password_changed_at&order=<?= $disp ?>">
Changed <?php if ($sort == 'credential_password_changed_at') { echo $order_icon; } ?>
</a>
</th>
<?php if (!$client_url) { ?>
<th>
<a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">
Client <?php if ($sort == 'client_name') { echo $order_icon; } ?>
</a>
</th>
<?php } ?>
<th></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($sql)) {
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
$credential_id = intval($row['c_credential_id']);
$credential_name = escapeHtml($row['credential_name']);
$credential_description = escapeHtml($row['credential_description']);
$credential_uri = escapeUrl($row['credential_uri']);
if (empty($credential_uri)) {
$credential_uri_display = "-";
} else {
$credential_uri_display = "<a href='$credential_uri'>" . truncate($credential_uri,40) . "</a><button type='button' class='itflow-copy clipboardjs' title='Copy URI' data-clipboard-text='$credential_uri'><i class='far fa-copy'></i></button>";
}
$credential_uri_2 = escapeUrl($row['credential_uri_2']);
$credential_username = escapeHtml(decryptCredentialEntry($row['credential_username']));
if (empty($credential_username)) {
$credential_username_display = "-";
} else {
$credential_username_display = "$credential_username<button type='button' class='itflow-copy clipboardjs' title='Copy username' data-clipboard-text='$credential_username'><i class='far fa-copy'></i></button>";
}
$credential_otp_secret = escapeHtml($row['credential_otp_secret']);
if (empty($credential_otp_secret)) {
$otp_display = "-";
} else {
$otp_display = "<span onmouseenter='showOTPViaCredentialID($credential_id)'><i class='far fa-clock'></i> <span id='otp_$credential_id'><i>Hover..</i></span></span>";
}
$credential_note = escapeHtml($row['credential_note']);
$credential_created_at = escapeHtml($row['credential_created_at']);
$credential_archived_at = escapeHtml($row['credential_archived_at']);
$credential_favorite = intval($row['credential_favorite']);
$credential_contact_id = intval($row['credential_contact_id']);
$contact_name = escapeHtml($row['contact_name']);
$credential_asset_id = intval($row['credential_asset_id']);
$asset_name = escapeHtml($row['asset_name']);
// Tags
$credential_tags = tagsForRecord('credential', $credential_id);
if ($credential_contact_id) {
// Their avatar, the size of the asset pill beside it
$credential_contact_display = "<a href='#' class='me-2 mb-1 d-inline-flex align-middle ajax-modal' title='$contact_name'
data-modal-size='lg'
data-modal-url='modals/contact/contact.php?id=$credential_contact_id'>"
. contactAvatar($row['credential_client_id'], $credential_contact_id, $row['contact_name'], $row['contact_photo'], 'md') . "</a>";
} else {
$credential_contact_display = '';
}
if ($credential_asset_id) {
$credential_asset_display = "<a href='#' class='me-2 mb-1 badge rounded-pill bg-secondary p-2 ajax-modal' title='$asset_name' data-toggle=''
data-modal-size='lg'
data-modal-url='modals/asset/asset.php?id=$credential_asset_id'>
<i class='fas fa-fw fa-desktop'></i></a>";
} else {
$credential_asset_display = '';
}
// Check if shared
$sql_shared = mysqli_query(
$mysqli,
"SELECT item_active, item_created_at, item_expire_at, item_id, item_key, item_note, item_recipient,
item_related_id, item_type, item_view_limit, item_views FROM shared_items
WHERE item_client_id = $client_id
AND item_active = 1
AND (COALESCE(item_view_limit, 0) = 0 OR item_views < item_view_limit)
AND item_expire_at > NOW()
AND item_type = 'Credential'
AND item_related_id = $credential_id
LIMIT 1"
);
if (mysqli_num_rows($sql_shared) > 0) {
$row = mysqli_fetch_assoc($sql_shared);
$item_id = intval($row['item_id']);
$item_active = escapeHtml($row['item_active']);
$item_key = escapeHtml($row['item_key']);
$item_type = escapeHtml($row['item_type']);
$item_related_id = intval($row['item_related_id']);
$item_note = escapeHtml($row['item_note']);
$item_recipient = escapeHtml($row['item_recipient']);
$item_views = escapeHtml($row['item_views']);
$item_view_limit = escapeHtml($row['item_view_limit']);
$item_created_at = escapeHtml($row['item_created_at']);
$item_expire_at = escapeHtml($row['item_expire_at']);
$item_expire_at_human = timeAgo($row['item_expire_at']);
}
<?php
foreach ($credentials as $credential_id => $row) {
$row_client_id = intval($row['credential_client_id']);
$credential_name = escapeHtml($row['credential_name']);
$credential_description = escapeHtml($row['credential_description']);
$credential_favorite = intval($row['credential_favorite']);
$credential_archived_at = escapeHtml($row['credential_archived_at']);
$credential_tags = $credentials_tags[$credential_id] ?? [];
$credential_links = $credentials_links[$credential_id] ?? [];
$credential_shares = $credentials_shares[$credential_id] ?? [];
$has_otp = trim((string) $row['credential_otp_secret']) !== '';
$age = credentialAge($row['credential_password_changed_at']);
$quick_url = "modals/credential/credential.php?id=$credential_id";
?>
<tr class="<?php if ($credential_favorite) { echo "text-bold"; } ?>">
<td class="checkbox-column bg-light border-end">
<div class="form-check">
<input class="form-check-input bulk-select" type="checkbox" name="credential_ids[]" value="<?= $credential_id ?>">
</div>
</td>
<!-- The whole cell opens the credential (stretched-link); the tag pills sit above it -->
<td class="position-relative">
<div class="d-flex">
<i class="fa fa-fw fa-2x fa-key me-3"></i>
<div class="flex-grow-1">
<a class="text-dark stretched-link ajax-modal" href="#" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>"><?= $credential_name ?> <?php if ($credential_favorite) { echo "<i class='fas fa-fw fa-star text-warning' title='Favorite'></i>"; } ?></a>
<div><small class="text-secondary"><?= $credential_description ?></small></div>
<?php if ($credential_tags || lookupUserPermission('module_credential') >= 2) { ?>
<div class="mt-1"><?= tagPills('credential', $credential_id, $credential_tags, "credentials.php?$client_url") ?></div>
<?php } ?>
</div>
</div>
</td>
<td class="text-nowrap"><?= $credential_username_display ?></td>
<td class="text-nowrap">
<button class="btn p-0" aria-label="Show password" type="button" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-2x fa-ellipsis-h text-secondary"></i><i class="fas fa-2x fa-ellipsis-h text-secondary"></i></button><button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
</td>
<td class="text-nowrap"><?= $otp_display ?></td>
<td><?= $credential_uri_display ?></td>
<td>
<?= "$credential_contact_display$credential_asset_display" ?>
<?php if (mysqli_num_rows($sql_shared) > 0) { ?>
<div class="d-flex" title="Expires <?= $item_expire_at_human ?>">
<i class="fas fa-link me-2 mt-1"></i>
<div class="flex-grow-1">Shared
<br>
<small class="text-secondary"><?= $item_recipient ?></small>
</div>
</div>
<?php } ?>
</td>
<?php if (!$client_url) { ?>
<td><a href="credentials.php?client_id=<?= $client_id ?>"><?= $client_name ?></a></td>
<?php } ?>
<td class="text-center">
<div class="btn-group">
<?php if ( !empty($credential_uri) || !empty($credential_uri_2) ) { ?>
<div class="dropdown dropstart text-center">
<button class="btn btn-default btn-sm" title="Open link" type="button" data-bs-toggle="dropdown">
<i class="fa fa-fw fa-external-link-alt"></i>
</button>
<div class="dropdown-menu">
<?php if ($credential_uri) { ?>
<a href="<?= $credential_uri ?>" alt="<?= $credential_uri ?>" target="_blank" class="dropdown-item" >
<i class="fa fa-fw fa-external-link-alt"></i> <?= truncate($credential_uri,40) ?>
</a>
<?php } ?>
<?php if ($credential_uri_2) { ?>
<div class="dropdown-divider"></div>
<a href="<?= $credential_uri_2 ?>" target="_blank" class="dropdown-item" >
<i class="fa fa-fw fa-external-link-alt"></i> <?= truncate($credential_uri_2,40) ?>
</a>
<?php } ?>
</div>
</div>
<tr>
<?php if ($can_edit) { ?>
<td class="checkbox-column bg-light border-end">
<div class="form-check">
<input class="form-check-input bulk-select" type="checkbox" name="credential_ids[]" value="<?= $credential_id ?>" aria-label="Select <?= $credential_name ?>">
</div>
</td>
<?php } ?>
<td class="itflow-asset-name-cell">
<div class="d-flex align-items-center gap-3">
<?= credentialTile($row) ?>
<div class="min-w-0">
<a class="fw-semibold text-body ajax-modal" href="#" data-modal-url="<?= $quick_url ?>"><?= $credential_name ?></a>
<?php if ($credential_favorite) { ?><i class="fas fa-star text-warning small ms-1" title="Starred"></i><?php } ?>
<?php if ($credential_shares) { ?><span class="badge rounded-pill bg-info-subtle text-info-emphasis fw-normal ms-1" title="Shared with <?= escapeHtml(implode(', ', array_filter(array_column($credential_shares, 'item_recipient'))) ?: 'a link') ?>"><i class="fas fa-share-alt me-1"></i>Shared</span><?php } ?>
<?php if ($credential_archived_at) { ?><span class="badge rounded-pill text-bg-secondary fw-normal ms-1">Archived</span><?php } ?>
<?php if ($credential_description) { ?>
<div class="small text-body-secondary text-truncate itflow-asset-desc" title="<?= $credential_description ?>"><?= $credential_description ?></div>
<?php } ?>
<?php if ($credential_tags || $can_edit) { ?>
<div class="mt-1"><?= tagPills('credential', $credential_id, $credential_tags, "credentials.php?$client_url") ?></div>
<?php } ?>
<div class="dropdown dropstart text-center">
<button class="btn btn-secondary btn-sm" title="More actions" type="button" data-bs-toggle="dropdown">
<i class="fas fa-ellipsis-h"></i>
</button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#"
data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>">
<i class="fas fa-fw fa-edit me-2"></i>Edit
</a>
<div class="dropdown-divider"></div>
<?php if ($client_url) { ?>
<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#shareModal" onclick="populateShareModal(<?= "$client_id, 'Credential', $credential_id" ?>)">
<i class="fas fa-fw fa-share me-2"></i>Share
</a>
<?php } ?>
<?php if (lookupUserPermission("module_credential") >= 2) { ?>
<?php if ($credential_archived_at) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-info confirm-link" href="post.php?restore_credential=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-redo me-2"></i>Restore
</a>
<?php if (lookupUserPermission("module_credential") >= 3) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_credential=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-trash me-2"></i>Delete
<?php } ?>
</a>
<?php } else { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger confirm-link" href="post.php?archive_credential=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-archive me-2"></i>Archive
</a>
<?php } ?>
<?php } ?>
</div>
</div>
</div>
</td>
</tr>
</div>
</td>
<td>
<div class="d-flex align-items-center small"><i class="fas fa-fw fa-user text-body-secondary me-1"></i><?= credentialUsernameHtml(credentialUsername($row)) ?></div>
<div class="d-flex align-items-center flex-wrap gap-2 mt-1 small">
<?= credentialPasswordHtml($credential_id) ?>
<?= credentialOtpHtml($credential_id, $has_otp) ?>
</div>
<?php foreach (array_filter([$row['credential_uri'], $row['credential_uri_2']]) as $uri) { ?>
<div class="small text-nowrap mt-1"><?= credentialUriHtml($uri, 34) ?></div>
<?php } ?>
</td>
<td class="small itflow-credential-for">
<div class="d-flex flex-column gap-1">
<?= implode('', credentialOwnersHtml($row)) ?>
<?php foreach (array_slice($credential_links, 0, 2) as [$type, $id, $name]) { ?>
<?php if ($type === 'vendor') { ?>
<?= vendorLink($id, $name) ?>
<?php } else { ?>
<span class="itflow-contact-ref"><i class="fas fa-fw fa-<?= $type === 'software' ? 'cube' : 'stream' ?> text-body-secondary"></i><a class="ajax-modal text-truncate" href="#" data-modal-size="lg" data-modal-url="modals/<?= $type === 'software' ? 'software/software' : 'service/service' ?>.php?id=<?= $id ?>"><?= escapeHtml($name) ?></a></span>
<?php } ?>
<?php } ?>
<?php if (count($credential_links) > 2) { ?>
<a class="ajax-modal text-body-secondary" href="#" data-modal-url="<?= $quick_url ?>">+<?= count($credential_links) - 2 ?> more</a>
<?php } ?>
<?php if (!$row['asset_id'] && !$row['contact_id'] && !$credential_links) { ?><span class="text-body-secondary">-</span><?php } ?>
</div>
</td>
<td class="text-nowrap">
<?= credentialAgePill($age, true) ?: '<span class="text-body-secondary">-</span>' ?>
<?php if ($row['credential_accessed_at']) { ?><div class="small text-body-secondary mt-1" title="Password last shown or copied <?= escapeHtml($row['credential_accessed_at']) ?>">Used <?= timeAgo($row['credential_accessed_at']) ?></div><?php } ?>
</td>
<?php if (!$client_url) { ?>
<td><a href="credentials.php?client_id=<?= $row_client_id ?>"><?= escapeHtml($row['client_name']) ?></a></td>
<?php } ?>
<td class="text-end">
<div class="dropdown dropstart">
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= $quick_url ?>">
<i class="fas fa-fw fa-eye text-secondary me-2"></i>Quick look
</a>
<?php if ($can_edit && !$credential_archived_at) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>">
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
</a>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_rotate.php?id=<?= $credential_id ?>">
<i class="fas fa-fw fa-sync-alt text-secondary me-2"></i>Change password
</a>
<?php } ?>
<?php if ($can_share && !$credential_archived_at) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_share.php?id=<?= $credential_id ?>">
<i class="fas fa-fw fa-share-alt text-secondary me-2"></i>Share
</a>
<?php } ?>
<?php if ($can_edit) { ?>
<?php if (!$credential_archived_at) { ?>
<a class="dropdown-item" href="post.php?<?= $credential_favorite ? 'unfavorite_credential' : 'favorite_credential' ?>=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="<?= $credential_favorite ? 'far' : 'fas' ?> fa-fw fa-star text-secondary me-2"></i><?= $credential_favorite ? 'Unstar' : 'Star' ?>
</a>
<?php } ?>
<div class="dropdown-divider"></div>
<?php if ($credential_archived_at) { ?>
<a class="dropdown-item" href="post.php?restore_credential=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-redo text-secondary me-2"></i>Restore
</a>
<?php if ($can_delete) { ?>
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_credential=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
data-confirm-text="<?= $credential_name ?> goes for good, with any share links still open.">
<i class="fas fa-fw fa-trash me-2"></i>Delete
</a>
<?php } ?>
<?php } else { ?>
<a class="dropdown-item text-danger confirm-link" href="post.php?archive_credential=<?= $credential_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
<i class="fas fa-fw fa-archive me-2"></i>Archive
</a>
<?php } ?>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php
}
?>
<?php } ?>
</tbody>
</table>
</div>
</form>
<?php if (!$num_rows[0]) { ?>
<div class="itflow-asset-empty">
<i class="fas fa-key fa-2x mb-2 opacity-50"></i>
<div><?= $q || $tag_query || $show ? 'No credentials match.' : 'No credentials yet.' ?></div>
</div>
<?php } ?>
<?php require_once "../includes/filter_footer.php"; ?>
</div>
<!-- Include script to get TOTP code via the login ID -->
<script src="js/credential_show_otp_via_id.js"></script>
<script src="js/credential_show_password_via_id.js"></script>
<?php if (!empty($_GET['open'])) { ?>
<script>
// Opened from search - straight to that credential's quick look
document.addEventListener('DOMContentLoaded', function () {
var open = document.createElement('a');
open.className = 'ajax-modal';
open.href = '#';
open.dataset.modalUrl = 'modals/credential/credential.php?id=<?= intval($_GET['open']) ?>';
document.body.appendChild(open);
open.click();
open.remove();
});
</script>
<?php } ?>
<script src="../js/bulk_actions.js"></script>
<?php
if ($client_url) {
require_once "modals/share_modal.php";
}
require_once "../includes/footer.php";

View File

@@ -25,15 +25,15 @@ $search_total = array_sum(array_column($search_results, 'total'));
// Usernames for the credentials shown - decrypted here, the same as the
// credentials list does, and only for rows that already passed the search's gates
$search_has_credentials = false;
$credential_usernames = [];
$credential_has_otp = [];
foreach ($search_results as $search_group) {
if ($search_group['key'] === 'credentials') {
$search_has_credentials = true;
$credential_ids = implode(',', array_map('intval', array_column($search_group['items'], 'id')));
$sql_credential_usernames = mysqli_query($mysqli, "SELECT credential_id, credential_username FROM credentials WHERE credential_id IN ($credential_ids)");
$sql_credential_usernames = mysqli_query($mysqli, "SELECT credential_id, credential_username, credential_otp_secret FROM credentials WHERE credential_id IN ($credential_ids)");
while ($row = mysqli_fetch_assoc($sql_credential_usernames)) {
$credential_usernames[intval($row['credential_id'])] = decryptCredentialEntry($row['credential_username']);
$credential_usernames[intval($row['credential_id'])] = credentialUsername($row);
$credential_has_otp[intval($row['credential_id'])] = trim((string) $row['credential_otp_secret']) !== '';
}
}
}
@@ -192,15 +192,16 @@ function searchResultBadge($badge) {
<?php if ($search_group['key'] === 'credentials') {
$credential_id = intval($item['id']);
$credential_username = escapeHtml($credential_usernames[$credential_id] ?? '');
$credential_username = $credential_usernames[$credential_id] ?? '';
?>
<div class="text-nowrap d-none d-md-block">
<div class="text-nowrap d-none d-md-flex align-items-center small">
<?php if ($credential_username !== '') { ?>
<span class="small"><?= $credential_username ?></span><button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="<?= $credential_username ?>"><i class="far fa-copy"></i></button>
<?= credentialUsernameHtml($credential_username) ?>
<?php } ?>
</div>
<div class="text-nowrap">
<button class="btn p-0" aria-label="Show password" type="button" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-ellipsis-h text-secondary"></i><i class="fas fa-ellipsis-h text-secondary"></i></button><button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
<div class="text-nowrap d-flex align-items-center gap-2 small">
<?= credentialPasswordHtml($credential_id) ?>
<?= credentialOtpHtml($credential_id, !empty($credential_has_otp[$credential_id])) ?>
</div>
<?php } ?>
@@ -234,9 +235,5 @@ function searchResultBadge($badge) {
</div>
</div>
<?php if ($search_has_credentials) { ?>
<script src="js/credential_show_password_via_id.js"></script>
<?php } ?>
<?php
require_once "../includes/footer.php";

View File

@@ -1,16 +0,0 @@
function showOTPViaCredentialID(credential_id) {
// Send a GET request to ajax.php as ajax.php?get_totp_token_via_id=true&credential_id=ID
itflowGet(
"ajax.php", {
get_totp_token_via_id: 'true',
credential_id: credential_id
},
function(data) {
//If we get a response from post.php, parse it as JSON
const token = JSON.parse(data);
document.getElementById("otp_" + credential_id).innerText = token
}
);
}

View File

@@ -1,40 +0,0 @@
function showPasswordViaCredentialID(button, credential_id) {
// Send a GET request to ajax.php as ajax.php?get_credential_via_id=true&credential_id=ID
itflowGet(
"ajax.php", {
get_credential_via_id: 'true',
credential_id: credential_id
},
function(data) {
const credential = JSON.parse(data);
// (Re)create the popover with the fetched password and show it
// trigger: focus dismisses it when the user clicks away
bootstrap.Popover.getInstance(button)?.dispose();
new bootstrap.Popover(button, {
content: credential.password,
placement: 'top',
trigger: 'focus'
}).show();
}
);
}
function copyPasswordViaCredentialID(button, credential_id) {
itflowGet(
"ajax.php", {
get_credential_via_id: 'true',
credential_id: credential_id
},
function(data) {
const credential = JSON.parse(data);
// itflowCopyText (js/app.js) also works on a plain-HTTP install,
// where navigator.clipboard does not exist and this used to throw
itflowCopyText(credential.password, button).then(
function () { flashTooltip(button, 'Copied!'); },
function () { flashTooltip(button, 'Failed!'); }
);
}
);
}

View File

@@ -71,7 +71,7 @@ if (!$license || ($client_url && intval($license['software_client_id']) !== intv
$keys_free = count(array_filter($keys, function ($key) {
return !$key['assets'] && !$key['contacts'];
}));
$credentials = $can_credentials ? linkedRecords('software', $software_id, 'credential') : [];
$credentials = $can_credentials ? credentialRows("credential_id IN (SELECT credential_id FROM software_credentials WHERE software_id = $software_id)") : [];
$documents = linkedRecords('software', $software_id, 'document');
$files = linkedRecords('software', $software_id, 'file');
$history = softwareHistory($software_id, 100);
@@ -79,7 +79,7 @@ if (!$license || ($client_url && intval($license['software_client_id']) !== intv
$license_tabs = [
'seats' => ['label' => 'Seats', 'icon' => 'fa-users', 'count' => $seats['used']],
'keys' => ['label' => 'Keys', 'icon' => 'fa-key', 'count' => count($keys) + ($software_key ? 1 : 0)],
'credentials' => ['label' => 'Credentials', 'icon' => 'fa-lock', 'count' => count($credentials)],
'credentials' => ['label' => 'Credentials', 'icon' => 'fa-key', 'count' => count($credentials)],
'documents' => ['label' => 'Documents', 'icon' => 'fa-file-alt', 'count' => count($documents)],
'files' => ['label' => 'Files', 'icon' => 'fa-paperclip', 'count' => count($files)],
'history' => ['label' => 'History', 'icon' => 'fa-history', 'count' => count($history)],
@@ -510,50 +510,12 @@ if (!$license || ($client_url && intval($license['software_client_id']) !== intv
<?php } ?>
</div>
<?php if ($credentials) { ?>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="text-nowrap table-light">
<tr><th>Name</th><th>Username</th><th>Password</th><th>OTP</th><th></th></tr>
</thead>
<tbody>
<?php foreach ($credentials as $credential) {
$credential_id = intval($credential['id']);
$credential_uri = escapeHtml($credential['credential_uri']);
$credential_username = escapeHtml(decryptCredentialEntry($credential['credential_username'])); ?>
<tr>
<td>
<a class="text-body fw-semibold ajax-modal" href="#" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>"><?= escapeHtml($credential['name']) ?></a>
<?php if ($credential_uri) { ?><a class="ms-1 small" href="<?= escapeUrl($credential['credential_uri']) ?>" target="_blank" rel="noopener" title="<?= $credential_uri ?>"><i class="fas fa-external-link-alt"></i></a><?php } ?>
<?php if ($credential['credential_description']) { ?><div class="small text-body-secondary"><?= escapeHtml($credential['credential_description']) ?></div><?php } ?>
</td>
<td class="text-nowrap">
<?php if ($credential_username) { ?>
<?= $credential_username ?><button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="<?= $credential_username ?>"><i class="far fa-copy"></i></button>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<td class="text-nowrap">
<button class="btn btn-sm btn-light" aria-label="Show password" title="Show password" type="button" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-ellipsis-h"></i><i class="fas fa-ellipsis-h"></i></button>
<button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
</td>
<td class="text-nowrap">
<?php if (!empty($credential['credential_otp_secret'])) { ?>
<span onmouseenter="showOTPViaCredentialID(<?= $credential_id ?>)"><i class="far fa-clock text-secondary me-1"></i><span id="otp_<?= $credential_id ?>"><i>Hover...</i></span></span>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
<td class="text-end">
<?php if ($can_link_credentials) { ?>
<a href="<?= $unlink_url('credential', $credential_id) ?>" class="btn btn-sm btn-light" title="Unlink"><i class="fas fa-fw fa-unlink"></i></a>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?= credentialTableHtml($credentials, [
'for' => true,
'unlink' => function ($row) use ($unlink_url, $can_link_credentials) {
return $can_link_credentials ? $unlink_url('credential', $row['credential_id']) : '';
},
]) ?>
<?php } else { ?>
<div class="itflow-asset-empty">No credentials linked.</div>
<?php } ?>
@@ -684,11 +646,6 @@ if (!$license || ($client_url && intval($license['software_client_id']) !== intv
});
</script>
<?php if ($credentials) { ?>
<!-- Fetch TOTP codes and passwords only when asked for -->
<script src="js/credential_show_otp_via_id.js"></script>
<script src="js/credential_show_password_via_id.js"></script>
<?php } ?>
<?php
}

View File

@@ -93,17 +93,8 @@ $sql_related_interfaces = mysqli_query($mysqli, "
$interface_count = mysqli_num_rows($sql_related_interfaces);
// Credentials - only for agents who may see them
$credential_count = 0;
if ($can_credentials) {
$sql_related_credentials = mysqli_query($mysqli, "
SELECT credential_id, credential_name, credential_uri, credential_username, credential_otp_secret
FROM credentials
WHERE credential_asset_id = $asset_id
AND credential_archived_at IS NULL
ORDER BY credential_name ASC
");
$credential_count = mysqli_num_rows($sql_related_credentials);
}
$related_credentials = $can_credentials ? credentialRows("credential_asset_id = $asset_id AND credential_client_id = $client_id") : [];
$credential_count = count($related_credentials);
// Tickets - open ones first; the most recent few here, the rest on the asset page
$quick_ticket_limit = 8;
@@ -365,41 +356,8 @@ ob_start();
<?php if ($credential_count) { ?>
<div class="tab-pane fade <?= $first_tab === 'credentials' ? 'show active' : '' ?>" id="asset-quick-<?= $asset_id ?>-credentials" role="tabpanel">
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0">
<thead class="text-nowrap"><tr><th>Name</th><th>Username</th><th>Password</th><th>OTP</th></tr></thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($sql_related_credentials)) {
$credential_id = intval($row['credential_id']);
$credential_uri = escapeHtml($row['credential_uri']);
$credential_username = escapeHtml(decryptCredentialEntry($row['credential_username'])); ?>
<tr>
<td>
<?= escapeHtml($row['credential_name']) ?>
<?php if ($credential_uri) { ?><a class="ms-1 small" href="<?= escapeUrl($row['credential_uri']) ?>" target="_blank" rel="noopener" title="<?= $credential_uri ?>"><i class="fas fa-external-link-alt"></i></a><?php } ?>
</td>
<td class="text-nowrap"><?php if ($credential_username) { ?><?= $credential_username ?><button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="<?= $credential_username ?>"><i class="far fa-copy"></i></button><?php } else { ?><span class="text-body-secondary">-</span><?php } ?></td>
<td class="text-nowrap">
<button class="btn btn-sm btn-light" aria-label="Show password" title="Show password" type="button" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-ellipsis-h"></i><i class="fas fa-ellipsis-h"></i></button>
<button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
</td>
<td class="text-nowrap">
<?php if (!empty($row['credential_otp_secret'])) { ?>
<span onmouseenter="showOTPViaCredentialID(<?= $credential_id ?>)"><i class="far fa-clock text-secondary me-1"></i><span id="otp_<?= $credential_id ?>"><i>Hover...</i></span></span>
<?php } else { ?>
<span class="text-body-secondary">-</span>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?= credentialListHtml($related_credentials) ?>
</div>
<?php /* js/, not ../js/ - this file is injected by js/ajax_modal.js, so a
relative src resolves against the host page's URL (/agent/...) */ ?>
<script src="js/credential_show_otp_via_id.js"></script>
<script src="js/credential_show_password_via_id.js"></script>
<?php } ?>
<?php if ($ticket_count) { ?>

View File

@@ -1,65 +1,66 @@
<?php
/*
* Link one of the client's credentials to an asset. A credential sits on one
* asset, so picking one that is on another asset moves it here - the picker
* says where each one is now. Ones whose asset was deleted count as free.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_support', 2);
enforceUserPermission('module_credential', 2);
$asset_id = intval($_GET['id']);
$asset_id = intval($_GET['id'] ?? 0);
$sql = mysqli_query($mysqli, "SELECT asset_client_id, asset_name FROM assets
WHERE asset_id = $asset_id
LIMIT 1
");
$row = mysqli_fetch_assoc($sql);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT asset_client_id, asset_name FROM assets WHERE asset_id = $asset_id LIMIT 1"));
if (!$row) {
echo json_encode(['error' => 'That asset no longer exists.']);
exit;
}
$asset_name = escapeHtml($row['asset_name']);
$client_id = intval($row['asset_client_id']);
enforceClientAccess();
$choices = credentialRows("credential_client_id = $client_id AND credential_asset_id <> $asset_id");
// Free ones first, then the ones that would move from another asset
uasort($choices, function ($a, $b) {
return [empty($a['asset_id']) ? 0 : 1, strtolower($a['credential_name'])] <=> [empty($b['asset_id']) ? 0 : 1, strtolower($b['credential_name'])];
});
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-key me-2"></i>Link Credential to <strong><?= $asset_name ?></strong></h5>
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-key me-2"></i>Link a credential to <strong><?= $asset_name ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="asset_id" value="<?= $asset_id ?>">
<div class="modal-body">
<div class="mb-3">
<?php if ($choices) { ?>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<select class="form-select select2" name="credential_id">
<option value="">- Select a Credential -</option>
<?php
$sql_credentials_select = mysqli_query($mysqli, "
SELECT credentials.credential_id, credentials.credential_name
FROM credentials
LEFT JOIN assets ON credentials.credential_asset_id = assets.asset_id
AND credentials.credential_asset_id = $asset_id
WHERE credentials.credential_client_id = $client_id
AND credentials.credential_asset_id = 0
AND credentials.credential_archived_at IS NULL
ORDER BY credentials.credential_name ASC
");
while ($row = mysqli_fetch_assoc($sql_credentials_select)) {
$credential_id = intval($row['credential_id']);
$credential_name = escapeHtml($row['credential_name']);
?>
<option value="<?= $credential_id ?>"><?= $credential_name ?></option>
<?php
}
?>
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<select class="form-select select2" name="credential_id" required data-placeholder="Pick a credential">
<option value=""></option>
<?php foreach ($choices as $credential_id => $choice) {
$where_now = !empty($choice['asset_id']) ? 'On ' . $choice['asset_name'] . ' - moves here' : ($choice['credential_description'] ?: $choice['credential_uri']); ?>
<option value="<?= $credential_id ?>"<?= selectOptionCredential($choice, $where_now) ?>><?= escapeHtml($choice['credential_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-text">A credential belongs to one asset - one already on another asset moves here.</div>
<?php } else { ?>
<p class="text-body-secondary mb-0">This client has no other credentials to link - make a new one instead.</p>
<?php } ?>
</div>
<div class="modal-footer">
<button type="submit" name="link_asset_to_credential" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Link</button>
<?php if ($choices) { ?>
<button type="submit" name="link_asset_to_credential" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Link</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -65,16 +65,8 @@ $sql_related_assets = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_
$asset_count = mysqli_num_rows($sql_related_assets);
// Credentials - only for agents who may see them
$credential_count = 0;
if ($can_credentials) {
$sql_related_credentials = mysqli_query($mysqli, "SELECT credential_id, credential_name, credential_uri, credential_username, credential_otp_secret
FROM credentials
WHERE credential_contact_id = $contact_id
AND credential_archived_at IS NULL
ORDER BY credential_name ASC"
);
$credential_count = mysqli_num_rows($sql_related_credentials);
}
$related_credentials = $can_credentials ? credentialRows("credential_contact_id = $contact_id AND credential_client_id = $client_id") : [];
$credential_count = count($related_credentials);
// Tickets - open ones first; the most recent few here, the rest on the contact page
$quick_ticket_limit = 8;
@@ -291,38 +283,8 @@ ob_start();
<?php if ($credential_count) { ?>
<div class="tab-pane fade <?= $first_tab === 'credentials' ? 'show active' : '' ?>" id="contact-quick-<?= $contact_id ?>-credentials" role="tabpanel">
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0">
<thead class="text-nowrap"><tr><th>Name</th><th>Username</th><th>Password</th><th>OTP</th></tr></thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($sql_related_credentials)) {
$credential_id = intval($row['credential_id']);
$credential_uri = escapeHtml($row['credential_uri']);
$credential_username = escapeHtml(decryptCredentialEntry($row['credential_username'])); ?>
<tr>
<td>
<?= escapeHtml($row['credential_name']) ?>
<?php if ($credential_uri) { ?><a class="ms-1 small" href="<?= escapeUrl($row['credential_uri']) ?>" target="_blank" rel="noopener" title="<?= $credential_uri ?>"><i class="fas fa-external-link-alt"></i></a><?php } ?>
</td>
<td class="text-nowrap"><?php if ($credential_username) { ?><?= $credential_username ?><button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="<?= $credential_username ?>"><i class="far fa-copy"></i></button><?php } else { ?><span class="text-body-secondary">-</span><?php } ?></td>
<td class="text-nowrap">
<button class="btn btn-sm btn-light" aria-label="Show password" title="Show password" type="button" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-ellipsis-h"></i><i class="fas fa-ellipsis-h"></i></button><button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
</td>
<td class="text-nowrap">
<?php if (!empty($row['credential_otp_secret'])) { ?>
<span onmouseenter="showOTPViaCredentialID(<?= $credential_id ?>)"><i class="far fa-clock text-secondary me-1"></i><span id="otp_<?= $credential_id ?>"><i>Hover...</i></span></span>
<?php } else { ?><span class="text-body-secondary">-</span><?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?= credentialListHtml($related_credentials) ?>
</div>
<?php /* js/, not ../js/ - this file is injected by js/ajax_modal.js, so a
relative src resolves against the host page's URL (/agent/...) */ ?>
<script src="js/credential_show_otp_via_id.js"></script>
<script src="js/credential_show_password_via_id.js"></script>
<?php } ?>
<?php if ($ticket_count) { ?>

View File

@@ -1,61 +1,66 @@
<?php
/*
* Link one of the client's credentials to a contact - whose login it is. A
* credential belongs to one contact, so picking one that is someone else's
* moves it - the picker says whose each one is now.
*/
require_once '../../../includes/modal_header.php';
$contact_id = intval($_GET['id']);
enforceUserPermission('module_client', 2);
enforceUserPermission('module_credential', 2);
$sql = mysqli_query($mysqli, "SELECT contact_client_id, contact_name FROM contacts
WHERE contact_id = $contact_id
LIMIT 1
");
$contact_id = intval($_GET['id'] ?? 0);
$row = mysqli_fetch_assoc($sql);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_client_id, contact_name FROM contacts WHERE contact_id = $contact_id LIMIT 1"));
if (!$row) {
echo json_encode(['error' => 'That contact no longer exists.']);
exit;
}
$contact_name = escapeHtml($row['contact_name']);
$client_id = intval($row['contact_client_id']);
enforceClientAccess();
$choices = credentialRows("credential_client_id = $client_id AND credential_contact_id <> $contact_id");
// Nobody's first, then the ones that would move from someone else
uasort($choices, function ($a, $b) {
return [empty($a['contact_id']) ? 0 : 1, strtolower($a['credential_name'])] <=> [empty($b['contact_id']) ? 0 : 1, strtolower($b['credential_name'])];
});
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-key me-2"></i>Link Credential to <strong><?= $contact_name ?></strong></h5>
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-key me-2"></i>Link a credential to <strong><?= $contact_name ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="contact_id" value="<?= $contact_id ?>">
<div class="modal-body">
<div class="mb-3">
<?php if ($choices) { ?>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<select class="form-select select2" name="credential_id">
<option value="">- Select a Credential -</option>
<?php
$sql_credentials_select = mysqli_query($mysqli, "
SELECT credential_id, credential_name
FROM credentials
WHERE credential_client_id = $client_id
AND credential_contact_id = 0
AND credential_archived_at IS NULL
ORDER BY credential_name ASC
");
while ($row = mysqli_fetch_assoc($sql_credentials_select)) {
$credential_id = intval($row['credential_id']);
$credential_name = escapeHtml($row['credential_name']);
?>
<option value="<?= $credential_id ?>"><?= $credential_name ?></option>
<?php
}
?>
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<select class="form-select select2" name="credential_id" required data-placeholder="Pick a credential">
<option value=""></option>
<?php foreach ($choices as $credential_id => $choice) {
$whose_now = !empty($choice['contact_id']) ? $choice['contact_name'] . "'s - moves to " . html_entity_decode($contact_name, ENT_QUOTES, 'UTF-8') : ($choice['credential_description'] ?: $choice['credential_uri']); ?>
<option value="<?= $credential_id ?>"<?= selectOptionCredential($choice, $whose_now) ?>><?= escapeHtml($choice['credential_name']) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-text">A credential belongs to one person - one that is someone else's moves to <?= $contact_name ?>.</div>
<?php } else { ?>
<p class="text-body-secondary mb-0">This client has no other credentials to link - make a new one instead.</p>
<?php } ?>
</div>
<div class="modal-footer">
<button type="submit" name="link_contact_to_credential" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Link</button>
<?php if ($choices) { ?>
<button type="submit" name="link_contact_to_credential" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Link</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -0,0 +1,188 @@
<?php
/*
* Credential quick look - opened from the credentials list, assets,
* contacts, vendors, licenses, the client overview and search. The login
* (username, the password on asking, the 2FA code, where it opens), how old
* the password is and who last looked at it, what it belongs to and is
* linked to, the notes, the share links still open, and its history.
* Anyone who may see credentials gets this; changing one takes edit rights.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_credential');
$credential_id = intval($_GET['id'] ?? 0);
$credential = credentialRow($credential_id);
if (!$credential) {
echo json_encode(['error' => 'That credential no longer exists.']);
exit;
}
$client_id = intval($credential['credential_client_id']);
enforceClientAccess();
$credential_name = escapeHtml($credential['credential_name']);
$credential_archived = !empty($credential['credential_archived_at']);
$can_edit = credentialCan(2) && !$credential_archived;
// Making a share link is a support action as well as a credential one (agent/ajax.php share_generate_link)
$can_share = !$credential_archived && lookupUserPermission('module_support') >= 2;
$age = credentialAge($credential['credential_password_changed_at']);
$last_viewed = credentialLastViewed($credential_id);
$links = credentialLinks([$credential_id])[$credential_id];
$shares = credentialShares([$credential_id])[$credential_id];
$history = credentialHistory($credential_id, 8);
$tags = tagsForRecord('credential', $credential_id);
$has_otp = trim((string) $credential['credential_otp_secret']) !== '';
$link_types = linkTypesFor('credential');
ob_start();
?>
<div class="modal-header bg-dark" data-bs-theme="dark">
<div class="d-flex align-items-center gap-3 min-w-0">
<?= credentialTile($credential) ?>
<div class="min-w-0">
<h5 class="modal-title d-flex flex-wrap align-items-center column-gap-2 row-gap-1">
<span class="fw-semibold text-break"><?= $credential_name ?></span>
<?php if (intval($credential['credential_favorite'])) { ?><i class="fas fa-star text-warning small" title="Starred"></i><?php } ?>
<?php if ($credential_archived) { ?><span class="badge rounded-pill text-bg-secondary fw-normal fs-6">Archived</span><?php } ?>
</h5>
<div class="small text-body-secondary d-flex flex-wrap column-gap-3 mt-1">
<span><?= escapeHtml($credential['client_name']) ?></span>
<?php if ($credential['credential_description']) { ?><span><?= escapeHtml($credential['credential_description']) ?></span><?php } ?>
</div>
</div>
</div>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<!-- The login -->
<dl class="itflow-asset-dl itflow-credential-dl mb-0">
<dt>Username</dt>
<dd class="d-flex align-items-center min-w-0"><?= credentialUsernameHtml(credentialUsername($credential), 'None') ?></dd>
<dt>Password</dt>
<dd><?= credentialPasswordHtml($credential_id) ?></dd>
<?php if ($has_otp) { ?>
<dt>2FA code</dt>
<dd><?= credentialOtpHtml($credential_id, true) ?></dd>
<?php } ?>
<?php if ($credential['credential_uri'] || $credential['credential_uri_2']) { ?>
<dt>Opens at</dt>
<dd class="min-w-0">
<?php foreach (array_filter([$credential['credential_uri'], $credential['credential_uri_2']]) as $uri) { ?>
<div class="text-truncate"><?= credentialUriHtml($uri, 60) ?></div>
<?php } ?>
</dd>
<?php } ?>
</dl>
<div class="d-flex flex-wrap align-items-center gap-2 mt-3 small text-body-secondary">
<?= credentialAgePill($age) ?>
<?php if ($last_viewed) { ?>
<span title="<?= escapeHtml($last_viewed['log_created_at']) ?>"><i class="far fa-eye me-1"></i>Last looked at by <?= escapeHtml($last_viewed['user_name'] ?: 'someone') ?>, <?= timeAgo($last_viewed['log_created_at']) ?></span>
<?php } ?>
<?php if ($tags) { ?><span><?= tagPills('credential', $credential_id, $tags, "credentials.php?client_id=$client_id&", false) ?></span><?php } ?>
</div>
<!-- What it belongs to and is linked to -->
<?php if ($credential['asset_id'] || $credential['contact_id'] || $links || ($can_edit && $link_types)) { ?>
<div class="d-flex align-items-center mt-3 mb-1">
<span class="small text-body-secondary fw-semibold text-uppercase me-auto">For</span>
<?php if ($can_edit && $link_types) { ?>
<a class="small ajax-modal" href="#" data-modal-url="modals/link/link.php?from=credential&id=<?= $credential_id ?>&to=vendor"><i class="fas fa-link me-1"></i>Link a vendor or license</a>
<?php } ?>
</div>
<ul class="list-unstyled mb-0 itflow-links">
<?php if ($credential['asset_id']) { ?>
<li class="itflow-link-row">
<span class="itflow-asset-icon itflow-asset-icon-sm itflow-asset-tone-<?= assetTypeTone($credential['asset_type']) ?>" aria-hidden="true"><i class="fas fa-fw fa-<?= getAssetIcon($credential['asset_type']) ?>"></i></span>
<div class="min-w-0 flex-grow-1"><div class="d-flex"><a class="ajax-modal text-truncate" href="#" data-modal-size="lg" data-modal-url="modals/asset/asset.php?id=<?= intval($credential['asset_id']) ?>"><?= escapeHtml($credential['asset_name']) ?></a></div><div class="small text-body-secondary">Asset</div></div>
</li>
<?php } ?>
<?php if ($credential['contact_id']) { ?>
<li class="itflow-link-row">
<?= contactAvatar($client_id, $credential['contact_id'], $credential['contact_name'], $credential['contact_photo'], 'sm') ?>
<div class="min-w-0 flex-grow-1"><div class="d-flex"><a class="ajax-modal text-truncate" href="#" data-modal-size="lg" data-modal-url="modals/contact/contact.php?id=<?= intval($credential['contact_id']) ?>"><?= escapeHtml($credential['contact_name']) ?></a></div><div class="small text-body-secondary">Contact<?= $credential['contact_title'] ? ' · ' . escapeHtml($credential['contact_title']) : '' ?></div></div>
</li>
<?php } ?>
<?php foreach ($links as [$type, $id, $name]) { ?>
<li class="itflow-link-row">
<?php if ($type === 'vendor') { ?>
<?= vendorTile($name, 'sm') ?>
<div class="min-w-0 flex-grow-1"><div class="d-flex"><a class="ajax-modal text-truncate" href="#" data-modal-size="lg" data-modal-url="modals/vendor/vendor.php?id=<?= $id ?>"><?= escapeHtml($name) ?></a></div><div class="small text-body-secondary">Vendor</div></div>
<?php } elseif ($type === 'software') { ?>
<span class="itflow-link-icon" aria-hidden="true"><i class="fas fa-fw fa-cube"></i></span>
<div class="min-w-0 flex-grow-1"><div class="d-flex"><a class="ajax-modal text-truncate" href="#" data-modal-size="lg" data-modal-url="modals/software/software.php?id=<?= $id ?>"><?= escapeHtml($name) ?></a></div><div class="small text-body-secondary">License</div></div>
<?php } else { ?>
<span class="itflow-link-icon" aria-hidden="true"><i class="fas fa-fw fa-stream"></i></span>
<div class="min-w-0 flex-grow-1"><div class="d-flex"><a class="ajax-modal text-truncate" href="#" data-modal-size="lg" data-modal-url="modals/service/service.php?id=<?= $id ?>"><?= escapeHtml($name) ?></a></div><div class="small text-body-secondary">Service</div></div>
<?php } ?>
<?php if ($can_edit && $type !== 'service') { ?>
<a class="itflow-link-remove" href="post.php?unlink_item&from=credential&id=<?= $credential_id ?>&to=<?= $type ?>&other=<?= $id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" title="Unlink"><i class="fas fa-unlink"></i></a>
<?php } ?>
</li>
<?php } ?>
<?php if (!$credential['asset_id'] && !$credential['contact_id'] && !$links) { ?>
<li class="small text-body-secondary">Not linked to anything yet.</li>
<?php } ?>
</ul>
<?php } ?>
<?php if (trim((string) $credential['credential_note']) !== '') { ?>
<div class="small text-body-secondary fw-semibold text-uppercase mt-3 mb-1">Notes</div>
<div class="itflow-credential-note small"><?= nl2br(escapeHtml($credential['credential_note'])) ?></div>
<?php } ?>
<!-- Share links still open -->
<?php if ($shares) { ?>
<div class="small text-body-secondary fw-semibold text-uppercase mt-3 mb-1">Shared</div>
<ul class="list-unstyled mb-0 itflow-links">
<?php foreach ($shares as $share) {
$views = intval($share['item_views']);
$limit = intval($share['item_view_limit']); ?>
<li class="itflow-link-row">
<span class="itflow-link-icon" aria-hidden="true"><i class="fas fa-fw fa-share-alt"></i></span>
<div class="min-w-0 flex-grow-1">
<div class="text-truncate"><?= escapeHtml($share['item_recipient'] ?: 'A share link') ?></div>
<div class="small text-body-secondary"><?= $views ?><?= $limit ? " of $limit" : '' ?> view<?= ($limit ?: $views) === 1 ? '' : 's' ?>, expires <?= timeAgo($share['item_expire_at']) ?></div>
</div>
<a class="btn btn-sm btn-link text-danger confirm-link" href="post.php?deactivate_shared_item=<?= intval($share['item_id']) ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" title="Turn off this link"><i class="fas fa-fw fa-unlink"></i></a>
</li>
<?php } ?>
</ul>
<?php } ?>
<!-- History -->
<?php if ($history) { ?>
<details class="mt-3">
<summary class="small text-body-secondary fw-semibold text-uppercase">History</summary>
<ul class="list-unstyled small mt-2 mb-0">
<?php foreach ($history as $entry) { ?>
<li class="d-flex gap-2 py-1 border-bottom">
<span class="flex-grow-1 min-w-0"><?= escapeHtml($entry['log_description']) ?></span>
<span class="text-body-secondary text-nowrap" title="<?= escapeHtml($entry['log_created_at']) ?>"><?= timeAgo($entry['log_created_at']) ?></span>
</li>
<?php } ?>
</ul>
</details>
<?php } ?>
</div>
<div class="modal-footer">
<?php if ($can_share) { ?>
<button type="button" class="btn btn-outline-secondary ajax-modal me-auto" data-modal-url="modals/credential/credential_share.php?id=<?= $credential_id ?>"><i class="fas fa-share-alt me-2"></i>Share</button>
<?php } ?>
<?php if ($can_edit) { ?>
<button type="button" class="btn btn-outline-secondary ajax-modal" data-modal-url="modals/credential/credential_rotate.php?id=<?= $credential_id ?>"><i class="fas fa-sync-alt me-2"></i>Change password</button>
<button type="button" class="btn btn-primary text-bold ajax-modal" data-modal-size="lg" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>"><i class="fas fa-edit me-2"></i>Edit</button>
<?php } ?>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Close</button>
</div>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -1,238 +1,64 @@
<?php
/*
* New credential - for the client it was opened from, or pick the client
* here. Opened from an asset or a contact (?asset_id= / ?contact_id=) it
* starts belonging to them; from a vendor's page (?vendor_id=) it is linked
* to that vendor once saved.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_credential', 2);
$client_id = intval($_GET['client_id'] ?? 0);
$contact_id = intval($_GET['contact_id'] ?? 0);
$asset_id = intval($_GET['asset_id'] ?? 0);
if ($client_id) {
enforceClientAccess();
}
$credential_form_mode = 'add';
$credential_id = 0;
$credential_name = $credential_description = $credential_username = $credential_password = $credential_otp_secret = '';
$credential_uri = $credential_uri_2 = $credential_note = '';
$credential_favorite = 0;
$credential_tag_ids = [];
$credential_contact_id = $client_id ? assetClientOwnedId('contact', $_GET['contact_id'] ?? 0, $client_id) : 0;
$credential_asset_id = $client_id ? assetClientOwnedId('asset', $_GET['asset_id'] ?? 0, $client_id) : 0;
// Opened from a vendor's page - their portal login, linked to them
$vendor_id = $client_id ? assetClientOwnedId('vendor', $_GET['vendor_id'] ?? 0, $client_id) : 0;
$vendor_name = $vendor_id ? getFieldById('vendors', $vendor_id, 'vendor_name') : '';
$for_name = $vendor_id ? getFieldById('vendors', $vendor_id, 'vendor_name')
: ($credential_asset_id ? getFieldById('assets', $credential_asset_id, 'asset_name')
: ($credential_contact_id ? getFieldById('contacts', $credential_contact_id, 'contact_name') : ''));
// Without the vault open there is nothing to encrypt with - say so before anything is typed
$vault_open = encryptCredentialEntry('') !== false;
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class="fa fa-fw fa-key me-2"></i>New Credential<?php if ($vendor_name) { ?> <small class="opacity-75 ms-1">for <?= escapeHtml($vendor_name) ?></small><?php } ?></h5>
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-key me-2"></i>New Credential<?php if ($for_name) { ?> <small class="opacity-75 ms-1">for <?= escapeHtml($for_name) ?></small><?php } ?></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="vendor_id" value="<?= $vendor_id ?>">
<?php if ($client_id) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } ?>
<div class="modal-body">
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#pills-credential-details">Details</a>
</li>
<?php if ($client_id) { ?>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-credential-relation">Relation</a>
</li>
<?php } ?>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-credential-notes">Notes</a>
</li>
</ul>
<hr>
<div class="tab-content">
<div class="tab-pane fade show active" id="pills-credential-details">
<?php if ($client_id) { ?>
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<?php } else { ?>
<div class="mb-3">
<label>Client <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="client_id" required>
<option value="">- Select Client -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$client_id_select = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']); ?>
<option <?php if ($client_id == $client_id_select) { echo "selected"; } ?> value="<?= $client_id_select ?>"<?= selectOptionClient($row['client_id'], $row['client_name'], $row['client_abbreviation'] ?? '') ?>><?= $client_name ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } ?>
<div class="mb-3">
<label>Name <strong class="text-danger">*</strong> / <span class="text-secondary">Important?</span></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<input type="text" class="form-control" name="name" placeholder="Name of Login" maxlength="200" required autofocus>
<div class="input-group-text">
<label class="star-toggle mb-0" title="Favorite">
<input class="form-check-input" type="checkbox" name="favorite" value="1"><i class="far fa-star"></i>
</label>
</div>
</div>
</div>
<div class="mb-3">
<label>Description</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description" placeholder="Description" maxlength="500">
</div>
</div>
<div class="mb-3">
<label>Username / ID</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<input type="text" class="form-control" name="username" placeholder="Username or ID" maxlength="350"> <!-- DB field is 500, 350 un-encrypted chars -->
</div>
</div>
<div class="mb-3">
<label>Password / Key <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-lock"></i></span>
<input type="password" class="form-control" data-toggle="password" id="password" name="password" placeholder="Password or Key" required maxlength="350" autocomplete="new-password">
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
<span class="btn btn-default"><i class="fa fa-fw fa-question" onclick="generatePassword()"></i></span>
</div>
</div>
<div class="mb-3">
<label>TOTP Seed</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<input type="password" class="form-control" data-toggle="password" name="otp_secret" placeholder="Insert secret key" maxlength="200">
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
</div>
</div>
<div class="mb-3">
<label>URI</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-link"></i></span>
<input type="text" class="form-control" name="uri" placeholder="http://192.168.1.1" maxlength="500">
</div>
</div>
<div class="mb-3">
<label>URI 2</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-link"></i></span>
<input type="text" class="form-control" name="uri_2" placeholder="https://server.company.com:5001" maxlength="500">
</div>
</div>
</div>
<?php if ($client_id) { ?>
<div class="tab-pane fade" id="pills-credential-relation">
<div class="mb-3">
<label>Contact</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="contact">
<option value="">- Select Contact -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_client_id, contact_photo, contact_title FROM contacts WHERE contact_client_id = $client_id ORDER BY contact_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$contact_id_select = intval($row['contact_id']);
$contact_name = escapeHtml($row['contact_name']);
?>
<option
<?php if ($contact_id == $contact_id_select) { echo "selected"; } ?>
value="<?= $contact_id_select ?>"<?= selectOptionContact($row['contact_client_id'] ?? 0, $row['contact_name'], $row['contact_photo'] ?? '', $row['contact_title'] ?? '', $row['contact_id'] ?? 0) ?>><?= $contact_name ?>
</option>
<?php
}
?>
</select>
</div>
</div>
<div class="mb-3">
<label>Asset</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="asset">
<option value="">- Select Asset -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_make, asset_model, location_name FROM assets LEFT JOIN locations on asset_location_id = location_id WHERE asset_client_id = $client_id AND asset_archived_at IS NULL ORDER BY asset_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$asset_id_select = intval($row['asset_id']);
$asset_name = escapeHtml($row['asset_name']);
$asset_location = escapeHtml($row['location_name']);
$asset_display_string = $asset_name;
if (!empty($asset_location)) {
$asset_display_string = "$asset_name ($asset_location)";
}
?>
<option <?php if ($asset_id == $asset_id_select) { echo "selected"; } ?>
value="<?= $asset_id_select ?>"<?= selectOptionAsset($row['asset_type'] ?? '', trim(($row['asset_make'] ?? '') . ' ' . ($row['asset_model'] ?? ''))) ?>><?= $asset_display_string ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<?php } ?>
<div class="tab-pane fade" id="pills-credential-notes">
<div class="mb-3">
<textarea class="form-control" rows="12" placeholder="Enter some notes" name="note"></textarea>
</div>
<div class="mb-3">
<label>Tags</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tags"></i></span>
<select class="form-select select2" name="tags[]" data-placeholder="Add some tags" multiple>
<?php
$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 4 ORDER BY tag_name ASC");
while ($row = mysqli_fetch_assoc($sql_tags_select)) {
$tag_id_select = intval($row['tag_id']);
$tag_name_select = escapeHtml($row['tag_name']);
?>
<option value="<?= $tag_id_select ?>"<?= selectOptionColor($row['tag_color'] ?? '', $row['tag_icon'] ?? '') ?>><?= $tag_name_select ?></option>
<?php } ?>
</select>
<button class="btn btn-secondary ajax-modal" title="New tag" type="button"
data-modal-url="../admin/modals/tag/tag_add.php?type=4">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<?php if (!$vault_open) { ?>
<div class="alert alert-warning small"><i class="fas fa-lock me-2"></i>Your vault session has expired, so a new login cannot be encrypted. Sign out and back in first.</div>
<?php } ?>
<?php require 'credential_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="add_credential" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Create</button>
<button type="submit" name="add_credential" class="btn btn-primary text-bold" <?= $vault_open ? '' : 'disabled' ?>><i class="fa fa-check me-2"></i>Create</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<script src="/agent/js/generate_password.js"></script>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -4,49 +4,43 @@ require_once '../../../includes/modal_header.php';
enforceUserPermission('module_credential', 2);
$credential_id = intval($_GET['id']);
$sql = mysqli_query($mysqli, "SELECT credential_archived_at, credential_asset_id, credential_client_id, credential_contact_id,
credential_created_at, credential_description, credential_favorite, credential_name,
credential_note, credential_otp_secret, credential_password, credential_uri,
credential_uri_2, credential_username FROM credentials WHERE credential_id = $credential_id LIMIT 1");
$row = mysqli_fetch_assoc($sql);
$client_id = intval($row['credential_client_id']);
$credential_name = escapeHtml($row['credential_name']);
$credential_description = escapeHtml($row['credential_description']);
$credential_uri = escapeHtml($row['credential_uri']);
$credential_uri_2 = escapeHtml($row['credential_uri_2']);
$credential_uri_link = escapeUrl($row['credential_uri']);
$credential_uri_2_link = escapeUrl($row['credential_uri_2']);
$credential_username = escapeHtml(decryptCredentialEntry($row['credential_username']));
$credential_password = escapeHtml(decryptCredentialEntry($row['credential_password']));
$credential_otp_secret = escapeHtml($row['credential_otp_secret']);
$credential_note = escapeHtml($row['credential_note']);
$credential_created_at = escapeHtml($row['credential_created_at']);
$credential_archived_at = escapeHtml($row['credential_archived_at']);
$credential_favorite = intval($row['credential_favorite']);
$credential_contact_id = intval($row['credential_contact_id']);
$credential_asset_id = intval($row['credential_asset_id']);
// Tags
$credential_tag_id_array = array();
$sql_credential_tags = mysqli_query($mysqli, "SELECT tag_id FROM credential_tags WHERE credential_id = $credential_id");
while ($row = mysqli_fetch_assoc($sql_credential_tags)) {
$credential_tag_id = intval($row['tag_id']);
$credential_tag_id_array[] = $credential_tag_id;
$credential_id = intval($_GET['id'] ?? 0);
$credential = credentialRow($credential_id);
if (!$credential) {
echo json_encode(['error' => 'That credential no longer exists.']);
exit;
}
$client_id = intval($credential['credential_client_id']);
enforceClientAccess();
logAudit("Credential", "View", "$session_name viewed credential $credential_name (edit)", $client_id, $credential_id);
// The form shows the password, so opening it counts as a view
logAudit("Credential", "View", "$session_name viewed credential " . escapeSql($credential['credential_name']) . " (edit)", $client_id, $credential_id);
$credential_form_mode = 'edit';
$credential_name = escapeHtml($credential['credential_name']);
$credential_description = escapeHtml($credential['credential_description']);
$credential_username = escapeHtml(credentialUsername($credential));
$credential_password = escapeHtml((string) decryptCredentialEntry($credential['credential_password']));
$credential_otp_secret = escapeHtml($credential['credential_otp_secret']);
$credential_uri = escapeHtml($credential['credential_uri']);
$credential_uri_2 = escapeHtml($credential['credential_uri_2']);
$credential_note = escapeHtml($credential['credential_note']);
$credential_favorite = intval($credential['credential_favorite']);
$credential_contact_id = intval($credential['credential_contact_id']);
$credential_asset_id = intval($credential['credential_asset_id']);
$credential_tag_ids = array_map(function ($tag) {
return intval($tag['tag_id']);
}, tagsForRecord('credential', $credential_id));
// Without the vault open the password shows blank and would be saved back blank - stop that here
$vault_open = encryptCredentialEntry('') !== false;
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title"><i class='fas fa-fw fa-key me-2'></i>Editing credential: <strong><?= $credential_name ?></strong></h5>
<h5 class="modal-title text-truncate"><i class="fas fa-fw fa-key me-2"></i>Editing credential: <strong><?= $credential_name ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
@@ -54,185 +48,13 @@ ob_start();
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="credential_id" value="<?= $credential_id ?>">
<div class="modal-body">
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#pills-credential-details<?= $credential_id ?>">Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-credential-relation<?= $credential_id ?>">Relation</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#pills-credential-notes<?= $credential_id ?>">Notes</a>
</li>
</ul>
<hr>
<div class="tab-content" <?php if (lookupUserPermission('module_credential') <= 1) { echo 'inert'; } ?>>
<div class="tab-pane fade show active" id="pills-credential-details<?= $credential_id ?>">
<div class="mb-3">
<label>Name <strong class="text-danger">*</strong> / <span class="text-secondary">Important?</span></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<input type="text" class="form-control" name="name" placeholder="Name of Credential" maxlength="200" value="<?= $credential_name ?>" required>
<div class="input-group-text">
<label class="star-toggle mb-0" title="Favorite">
<input class="form-check-input" type="checkbox"
name="favorite"
value="1"
<?php if($credential_favorite) { echo 'checked'; } ?>>
<i class="far fa-star"></i>
</label>
</div>
</div>
</div>
<div class="mb-3">
<label>Description</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description" placeholder="Description" maxlength="500" value="<?= $credential_description ?>">
</div>
</div>
<div class="mb-3">
<label>Username / ID</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<input type="text" class="form-control" name="username" placeholder="Username or ID" maxlength="350" value="<?= $credential_username ?>">
</div>
</div>
<div class="mb-3">
<label>Password / Key <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-lock"></i></span>
<input type="password" class="form-control" data-toggle="password" name="password" placeholder="Password or Key" maxlength="350" value="<?= $credential_password ?>" required autocomplete="new-password">
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
<button class="input-group-text clipboardjs" title="Copy password" type="button" data-clipboard-target="input[name=password]"><i class="far fa-fw fa-copy"></i></button>
</div>
</div>
<div class="mb-3">
<label>OTP</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
<input type="password" class="form-control" data-toggle="password" name="otp_secret" maxlength="200" value="<?= $credential_otp_secret ?>" placeholder="Insert secret key">
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
</div>
</div>
<div class="mb-3">
<label>URI</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-link"></i></span>
<input type="text" class="form-control" name="uri" placeholder="ex. http://192.168.1.1" maxlength="500" value="<?= $credential_uri ?>">
<a href="<?= $credential_uri_link ?>" target="_blank" class="input-group-text"><i class="fa fa-fw fa-link"></i></a>
<button class="input-group-text clipboardjs" title="Copy URI" type="button" data-clipboard-target="input[name=uri]"><i class="far fa-fw fa-copy"></i></button>
</div>
</div>
<div class="mb-3">
<label>URI 2</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-link"></i></span>
<input type="text" class="form-control" name="uri_2" placeholder="ex. https://server.company.com:5001" maxlength="500" value="<?= $credential_uri_2 ?>">
<a href="<?= $credential_uri_2_link ?>" target="_blank" class="input-group-text"><i class="fa fa-fw fa-link"></i></a>
<button class="input-group-text clipboardjs" title="Copy URI 2" type="button" data-clipboard-target="input[name=uri_2]"><i class="far fa-fw fa-copy"></i></button>
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-credential-relation<?= $credential_id ?>">
<div class="mb-3">
<label>Contact</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="contact">
<option value="">- Select Contact -</option>
<?php
$sql_contacts = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_client_id, contact_photo, contact_title FROM contacts WHERE contact_client_id = $client_id ORDER BY contact_name ASC");
while ($row = mysqli_fetch_assoc($sql_contacts)) {
$contact_id_select = intval($row['contact_id']);
$contact_name_select = escapeHtml($row['contact_name']);
?>
<option <?php if ($credential_contact_id == $contact_id_select) { echo "selected"; } ?> value="<?= $contact_id_select ?>"<?= selectOptionContact($row['contact_client_id'] ?? 0, $row['contact_name'], $row['contact_photo'] ?? '', $row['contact_title'] ?? '', $row['contact_id'] ?? 0) ?>><?= $contact_name_select ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="mb-3">
<label>Asset</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
<select class="form-select select2" name="asset">
<option value="0">- Select Asset -</option>
<?php
$sql_assets = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_make, asset_model, location_name FROM assets LEFT JOIN locations on asset_location_id = location_id WHERE asset_client_id = $client_id AND asset_archived_at IS NULL ORDER BY asset_name ASC");
while ($row = mysqli_fetch_assoc($sql_assets)) {
$asset_id_select = intval($row['asset_id']);
$asset_name_select = escapeHtml($row['asset_name']);
$asset_location_select = escapeHtml($row['location_name']);
$asset_select_display_string = $asset_name_select;
if (!empty($asset_location_select)) {
$asset_select_display_string = "$asset_name_select ($asset_location_select)";
}
?>
<option <?php if ($credential_asset_id == $asset_id_select) { echo "selected"; } ?> value="<?= $asset_id_select ?>"<?= selectOptionAsset($row['asset_type'] ?? '', trim(($row['asset_make'] ?? '') . ' ' . ($row['asset_model'] ?? ''))) ?>><?= $asset_select_display_string ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-credential-notes<?= $credential_id ?>">
<div class="mb-3">
<textarea class="form-control" rows="12" placeholder="Enter some notes" name="note"><?= $credential_note ?></textarea>
</div>
<div class="mb-3">
<label>Tags</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tags"></i></span>
<select class="form-select select2" name="tags[]" data-placeholder="Add some tags" multiple>
<?php
$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 4 ORDER BY tag_name ASC");
while ($row = mysqli_fetch_assoc($sql_tags_select)) {
$tag_id_select = intval($row['tag_id']);
$tag_name_select = escapeHtml($row['tag_name']);
?>
<option value="<?= $tag_id_select ?>" <?php if (in_array($tag_id_select, $credential_tag_id_array)) { echo "selected"; } ?><?= selectOptionColor($row['tag_color'] ?? '', $row['tag_icon'] ?? '') ?>><?= $tag_name_select ?></option>
<?php } ?>
</select>
<button class="btn btn-secondary ajax-modal" title="New tag" type="button"
data-modal-url="../admin/modals/tag/tag_add.php?type=4">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<?php if (!$vault_open) { ?>
<div class="alert alert-warning small"><i class="fas fa-lock me-2"></i>Your vault session has expired, so this login cannot be read or saved. Sign out and back in first.</div>
<?php } ?>
<?php require 'credential_form.php'; ?>
</div>
<div class="modal-footer">
<button type="submit" name="edit_credential" class="btn btn-primary text-bold"><i class="fa fa-check me-2"></i>Save</button>
<button type="submit" name="edit_credential" class="btn btn-primary text-bold" <?= $vault_open ? '' : 'disabled' ?>><i class="fa fa-check me-2"></i>Save</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>

View File

@@ -0,0 +1,375 @@
<?php
/*
* Credential form fields - shared by credential_add.php and
* credential_edit.php, which set $credential_form_mode ('add' | 'edit'),
* $client_id (0 = pick the client here), $credential_id and the
* $credential_* values (escaped; the username, password and 2FA seed already
* decrypted for an edit, empty for a new one), $credential_tag_ids,
* $credential_contact_id and $credential_asset_id, before including this.
* Posts what credentialFormSet() (functions/credential.php) reads.
*
* Tabs: Login (name, star, username, password with a generator and how
* strong it is, the 2FA secret with the code it makes, where it opens),
* Belongs to (the asset and contact it is for), Details (what it is, tags)
* and Notes.
*
* Should not be accessed directly.
*/
isset($mysqli) || die("Direct file access is not allowed");
$client_options = $contact_options = $asset_options = [];
if ($client_id) {
$sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_title, contact_photo, contact_client_id, contact_archived_at FROM contacts
WHERE contact_client_id = $client_id AND (contact_archived_at IS NULL OR contact_id = " . intval($credential_contact_id) . ")
ORDER BY contact_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$contact_options[] = $row;
}
$sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_make, asset_model, asset_archived_at, location_name FROM assets
LEFT JOIN locations ON location_id = asset_location_id
WHERE asset_client_id = $client_id AND (asset_archived_at IS NULL OR asset_id = " . intval($credential_asset_id) . ")
ORDER BY asset_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$asset_options[] = $row;
}
} else {
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$client_options[] = $row;
}
}
$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 4 ORDER BY tag_name ASC");
$form_id = 'credentialForm' . ($credential_form_mode === 'edit' ? $credential_id : 'New');
?>
<ul class="nav nav-pills nav-fill flex-nowrap overflow-auto mb-3 itflow-asset-form-tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="pill" href="#<?= $form_id ?>Login"><i class="fas fa-fw fa-key me-2 d-none d-lg-inline"></i>Login</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#<?= $form_id ?>Belongs"><i class="fas fa-fw fa-link me-2 d-none d-lg-inline"></i>Belongs to</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#<?= $form_id ?>Details"><i class="fas fa-fw fa-tags me-2 d-none d-lg-inline"></i>Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="pill" href="#<?= $form_id ?>Notes"><i class="fas fa-fw fa-sticky-note me-2 d-none d-lg-inline"></i>Notes</a>
</li>
</ul>
<div class="tab-content" id="<?= $form_id ?>">
<!-- The login itself -->
<div class="tab-pane fade show active" id="<?= $form_id ?>Login">
<div class="row g-3">
<?php if (!$client_id) { ?>
<div class="col-12">
<label class="form-label">Client <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="client_id" required>
<option value="">- Select Client -</option>
<?php foreach ($client_options as $client_option) { ?>
<option value="<?= intval($client_option['client_id']) ?>"<?= selectOptionClient($client_option['client_id'], $client_option['client_name'], $client_option['client_abbreviation'] ?? '') ?>><?= escapeHtml($client_option['client_name']) ?></option>
<?php } ?>
</select>
</div>
<div class="form-text">Pick the asset and contact it belongs to once it's saved.</div>
</div>
<?php } ?>
<div class="col-md-8">
<label class="form-label">Name <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-fw fa-key"></i></span>
<input type="text" class="form-control" name="name" placeholder="Firewall admin, Microsoft 365 break glass, Guest Wi-Fi" maxlength="200" value="<?= $credential_name ?>" required <?= $credential_form_mode === 'edit' ? '' : 'autofocus' ?>>
</div>
</div>
<div class="col-md-4">
<label class="form-label d-none d-md-block">&nbsp;</label>
<div class="form-check form-switch mt-md-2">
<input class="form-check-input" type="checkbox" role="switch" name="favorite" value="1" id="<?= $form_id ?>Favorite" <?= $credential_favorite ? 'checked' : '' ?>>
<label class="form-check-label" for="<?= $form_id ?>Favorite"><i class="fas fa-star text-warning me-1"></i>Starred</label>
</div>
</div>
<div class="col-12">
<label class="form-label">Username / ID</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<input type="text" class="form-control" name="username" placeholder="Username, email or ID" maxlength="350" value="<?= $credential_username ?>" autocomplete="off">
</div>
</div>
<div class="col-12">
<label class="form-label">Password / key</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-lock"></i></span>
<input type="password" class="form-control font-monospace" data-toggle="password" name="password" placeholder="Password, key or PSK" maxlength="350" value="<?= $credential_password ?>" autocomplete="new-password" data-credential-password>
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
<button class="btn btn-outline-secondary clipboardjs" title="Copy password" type="button" data-clipboard-target="input[name=password]"><i class="far fa-fw fa-copy"></i></button>
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" title="Make one up"><i class="fas fa-fw fa-magic"></i></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="#" data-credential-generate="passphrase"><i class="fas fa-fw fa-font text-secondary me-2"></i>Passphrase <small class="text-body-secondary">easy to read out</small></a>
<a class="dropdown-item" href="#" data-credential-generate="20"><i class="fas fa-fw fa-random text-secondary me-2"></i>Random, 20 characters</a>
<a class="dropdown-item" href="#" data-credential-generate="32"><i class="fas fa-fw fa-random text-secondary me-2"></i>Random, 32 characters</a>
</div>
</div>
<div class="d-flex align-items-center gap-2 mt-1 small" data-credential-strength hidden>
<div class="progress flex-grow-1" style="height: .35rem;"><div class="progress-bar" role="progressbar"></div></div>
<span class="text-body-secondary text-nowrap" data-credential-strength-label></span>
</div>
</div>
<div class="col-12">
<label class="form-label">2FA secret</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-clock"></i></span>
<input type="password" class="form-control font-monospace" data-toggle="password" name="otp_secret" placeholder="The key behind the QR code, or the otpauth:// link" maxlength="200" value="<?= $credential_otp_secret ?>" autocomplete="off" data-credential-otp-input>
<span class="input-group-text"><i class="fa fa-fw fa-eye"></i></span>
</div>
<div class="form-text" data-credential-otp-check>Every agent who can see this credential gets the current code, so nobody needs the phone.</div>
</div>
<div class="col-md-6">
<label class="form-label">Opens at</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-link"></i></span>
<input type="text" class="form-control" name="uri" placeholder="https://192.168.1.1, rdp://server" maxlength="500" value="<?= $credential_uri ?>">
<button class="btn btn-outline-secondary clipboardjs" title="Copy URI" type="button" data-clipboard-target="input[name=uri]"><i class="far fa-fw fa-copy"></i></button>
</div>
</div>
<div class="col-md-6">
<label class="form-label">Also at</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-link"></i></span>
<input type="text" class="form-control" name="uri_2" placeholder="https://server.company.com:5001" maxlength="500" value="<?= $credential_uri_2 ?>">
<button class="btn btn-outline-secondary clipboardjs" title="Copy URI 2" type="button" data-clipboard-target="input[name=uri_2]"><i class="far fa-fw fa-copy"></i></button>
</div>
</div>
</div>
</div>
<!-- What it is for -->
<div class="tab-pane fade" id="<?= $form_id ?>Belongs">
<?php if ($client_id) { ?>
<div class="row g-3">
<div class="col-12">
<label class="form-label">Asset</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-desktop"></i></span>
<select class="form-select select2" name="asset">
<option value="0">- No asset -</option>
<?php foreach ($asset_options as $asset_option) {
$asset_option_id = intval($asset_option['asset_id']); ?>
<option value="<?= $asset_option_id ?>" <?= intval($credential_asset_id) === $asset_option_id ? 'selected' : '' ?><?= selectOptionAsset($asset_option['asset_type'], implode(' · ', array_filter([trim($asset_option['asset_make'] . ' ' . $asset_option['asset_model']), $asset_option['location_name']]))) ?>><?= escapeHtml($asset_option['asset_name']) ?><?= $asset_option['asset_archived_at'] ? ' (archived)' : '' ?></option>
<?php } ?>
</select>
</div>
<div class="form-text">The device this login is for - it shows on the asset's Credentials tab.</div>
</div>
<div class="col-12">
<label class="form-label">Contact</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
<select class="form-select select2" name="contact">
<option value="0">- Nobody -</option>
<?php foreach ($contact_options as $contact_option) {
$contact_option_id = intval($contact_option['contact_id']); ?>
<option value="<?= $contact_option_id ?>" <?= intval($credential_contact_id) === $contact_option_id ? 'selected' : '' ?><?= selectOptionContact($contact_option['contact_client_id'], $contact_option['contact_name'], $contact_option['contact_photo'], $contact_option['contact_title'], $contact_option_id) ?>><?= escapeHtml($contact_option['contact_name']) ?><?= $contact_option['contact_archived_at'] ? ' (archived)' : '' ?></option>
<?php } ?>
</select>
</div>
<div class="form-text">Whose login it is - it shows on their contact page.</div>
</div>
<div class="col-12">
<div class="form-text mt-0"><i class="fas fa-info-circle me-1"></i>Vendors and licenses link from the credential's quick look, or from the vendor or license itself.</div>
</div>
</div>
<?php } else { ?>
<div class="itflow-asset-empty">Pick the client first - the asset and contact are theirs.</div>
<?php } ?>
</div>
<!-- What it is -->
<div class="tab-pane fade" id="<?= $form_id ?>Details">
<div class="row g-3">
<div class="col-12">
<label class="form-label">Description</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-align-left"></i></span>
<input type="text" class="form-control" name="description" placeholder="What it opens, and who uses it" maxlength="500" value="<?= $credential_description ?>">
</div>
</div>
<div class="col-12">
<label class="form-label">Tags</label>
<input type="hidden" name="tags_form" value="1">
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-tags"></i></span>
<select class="form-select select2" name="tags[]" data-placeholder="Domain Admin, Break Glass, Vendor Portal" multiple>
<?php while ($row = mysqli_fetch_assoc($sql_tags_select)) {
$tag_id_select = intval($row['tag_id']); ?>
<option value="<?= $tag_id_select ?>" <?= in_array($tag_id_select, $credential_tag_ids, true) ? 'selected' : '' ?><?= selectOptionColor($row['tag_color'] ?? '', $row['tag_icon'] ?? '') ?>><?= escapeHtml($row['tag_name']) ?></option>
<?php } ?>
</select>
<?php if (!empty($session_is_admin)) { ?>
<button class="btn btn-secondary ajax-modal" title="New tag" type="button" data-modal-url="../admin/modals/tag/tag_add.php?type=4">
<i class="fas fa-plus"></i>
</button>
<?php } ?>
</div>
</div>
</div>
<?php if ($credential_form_mode === 'edit') { ?>
<p class="text-body-secondary small text-end mt-3 mb-0">Credential ID <span class="font-monospace"><?= $credential_id ?></span></p>
<?php } ?>
</div>
<!-- Everything else -->
<div class="tab-pane fade" id="<?= $form_id ?>Notes">
<label class="form-label">Notes</label>
<textarea class="form-control" rows="10" name="note" placeholder="What it is for, who may use it, when it was last rotated and by whom"><?= $credential_note ?></textarea>
<div class="form-text">Notes are not encrypted - keep recovery codes and second passwords in their own credential.</div>
</div>
</div>
<script>
itflowReady(function () {
var form = document.getElementById(<?= json_encode($form_id) ?>).closest('form');
if (form.dataset.credentialFormWired) {
return;
}
form.dataset.credentialFormWired = '1';
// A required field on a tab that isn't showing: show that tab and point at it
var reported = false;
form.addEventListener('invalid', function (e) {
var pane = e.target.closest('.tab-pane');
var tab = pane && form.querySelector('[data-bs-toggle="pill"][href="#' + pane.id + '"]');
if (!tab || pane.classList.contains('active') || reported) {
return;
}
reported = true;
tab.addEventListener('shown.bs.tab', function () {
reported = false;
e.target.reportValidity();
}, { once: true });
bootstrap.Tab.getOrCreateInstance(tab).show();
}, true);
var password = form.querySelector('[data-credential-password]');
var meter = form.querySelector('[data-credential-strength]');
var bar = meter.querySelector('.progress-bar');
var label = meter.querySelector('[data-credential-strength-label]');
// How strong it is - length and the kinds of character in it, roughly in bits
function strength() {
var value = password.value;
meter.hidden = value === '';
if (!value) {
return;
}
var pool = 0;
if (/[a-z]/.test(value)) pool += 26;
if (/[A-Z]/.test(value)) pool += 26;
if (/[0-9]/.test(value)) pool += 10;
if (/[^a-zA-Z0-9]/.test(value)) pool += 32;
var bits = Math.round(value.length * Math.log2(Math.max(pool, 2)));
var levels = [[40, 'Weak', 'danger', 25], [60, 'Fair', 'warning', 50], [80, 'Good', 'info', 75], [Infinity, 'Strong', 'success', 100]];
var level = levels.find(function (l) { return bits < l[0]; });
bar.className = 'progress-bar bg-' + level[2];
bar.style.width = level[3] + '%';
label.textContent = level[1] + ' · ' + value.length + ' characters';
}
password.addEventListener('input', strength);
strength();
// Make one up - a passphrase from the server, or random characters made here
function randomPassword(length) {
var chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*-_=+?';
var bytes = new Uint32Array(length);
window.crypto.getRandomValues(bytes);
return Array.prototype.map.call(bytes, function (b) { return chars[b % chars.length]; }).join('');
}
form.querySelectorAll('[data-credential-generate]').forEach(function (item) {
item.addEventListener('click', function (e) {
e.preventDefault();
var kind = item.dataset.credentialGenerate;
function set(value) {
password.value = value;
password.type = 'text';
password.dispatchEvent(new Event('input'));
}
if (kind === 'passphrase') {
itflowGet('ajax.php', { get_readable_pass: 'true' }, function (data) {
set(JSON.parse(data));
});
} else {
set(randomPassword(parseInt(kind, 10)));
}
});
});
// The 2FA secret: say whether it is one, and show the code it makes now - worked
// out here (where the browser allows it), so a mistyped secret is caught before saving
var otp = form.querySelector('[data-credential-otp-input]');
var check = form.querySelector('[data-credential-otp-check]');
var checkDefault = check.textContent;
function seed(value) {
value = value.trim();
if (/^otpauth:\/\//i.test(value)) {
var match = value.match(/[?&]secret=([^&]+)/i);
value = match ? decodeURIComponent(match[1]) : '';
}
value = value.replace(/[\s-]+/g, '').toUpperCase().replace(/=+$/, '');
return /^[A-Z2-7]{16,}$/.test(value) ? value : null;
}
function base32(value) {
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', bits = '', bytes = [];
value.split('').forEach(function (c) { bits += alphabet.indexOf(c).toString(2).padStart(5, '0'); });
for (var i = 0; i + 8 <= bits.length; i += 8) {
bytes.push(parseInt(bits.substr(i, 8), 2));
}
return new Uint8Array(bytes);
}
function totp(secret) {
var counter = Math.floor(Date.now() / 30000);
var message = new Uint8Array(8);
for (var i = 7; i >= 0; i--) {
message[i] = counter & 0xff;
counter = Math.floor(counter / 256);
}
return crypto.subtle.importKey('raw', base32(secret), { name: 'HMAC', hash: 'SHA-1' }, false, ['sign'])
.then(function (key) { return crypto.subtle.sign('HMAC', key, message); })
.then(function (signature) {
var h = new Uint8Array(signature), o = h[h.length - 1] & 0xf;
var code = ((h[o] & 0x7f) << 24 | h[o + 1] << 16 | h[o + 2] << 8 | h[o + 3]) % 1000000;
return String(code).padStart(6, '0');
});
}
function checkOtp() {
var value = otp.value.trim();
check.classList.remove('text-danger', 'text-success');
if (!value) {
check.textContent = checkDefault;
return;
}
var secret = seed(value);
if (!secret) {
check.classList.add('text-danger');
check.textContent = 'That is not a 2FA secret - it is the long key shown under "can\'t scan the code", or the otpauth:// link.';
return;
}
if (!window.crypto || !crypto.subtle) {
check.textContent = 'Looks like a 2FA secret.';
return;
}
totp(secret).then(function (code) {
check.classList.add('text-success');
check.textContent = 'The code now is ' + code.slice(0, 3) + ' ' + code.slice(3) + ' - check it matches the app.';
});
}
otp.addEventListener('input', checkOtp);
checkOtp();
});
</script>

View File

@@ -0,0 +1,103 @@
<?php
/*
* Change a credential's password - the rotation every MSP owes its clients.
* Make one up (a passphrase, or random characters), copy it to set it on
* the device or site, and save it: the password and the date it changed are
* updated and the change is logged. Nothing else about the credential moves.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_credential', 2);
$credential_id = intval($_GET['id'] ?? 0);
$credential = credentialRow($credential_id);
if (!$credential) {
echo json_encode(['error' => 'That credential no longer exists.']);
exit;
}
$client_id = intval($credential['credential_client_id']);
enforceClientAccess();
$age = credentialAge($credential['credential_password_changed_at']);
$vault_open = encryptCredentialEntry('') !== false;
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-sync-alt me-2"></i>Change password: <strong><?= escapeHtml($credential['credential_name']) ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form action="post.php" method="post" autocomplete="off" data-credential-rotate>
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="credential_id" value="<?= $credential_id ?>">
<div class="modal-body">
<?php if (!$vault_open) { ?>
<div class="alert alert-warning small"><i class="fas fa-lock me-2"></i>Your vault session has expired, so the new password cannot be encrypted. Sign out and back in first.</div>
<?php } ?>
<div class="d-flex flex-wrap align-items-center gap-2 mb-3 small text-body-secondary">
<?= credentialAgePill($age) ?>
<?php $username = credentialUsername($credential); if ($username !== '') { ?>
<span class="d-inline-flex align-items-center"><i class="fas fa-user me-1"></i><?= credentialUsernameHtml($username) ?></span>
<?php } ?>
</div>
<label class="form-label">New password <strong class="text-danger">*</strong></label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-lock"></i></span>
<input type="text" class="form-control font-monospace" name="password" maxlength="350" required autocomplete="new-password" data-rotate-password>
<button class="btn btn-outline-secondary" type="button" title="Copy" data-rotate-copy><i class="far fa-fw fa-copy"></i></button>
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" title="Make one up"><i class="fas fa-fw fa-magic"></i></button>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="#" data-rotate-generate="passphrase"><i class="fas fa-fw fa-font text-secondary me-2"></i>Passphrase</a>
<a class="dropdown-item" href="#" data-rotate-generate="20"><i class="fas fa-fw fa-random text-secondary me-2"></i>Random, 20 characters</a>
<a class="dropdown-item" href="#" data-rotate-generate="32"><i class="fas fa-fw fa-random text-secondary me-2"></i>Random, 32 characters</a>
</div>
</div>
<div class="form-text">Set it on the device or site first, then save it here - the old one is gone once you do.</div>
</div>
<div class="modal-footer">
<button type="submit" name="rotate_credential" class="btn btn-primary text-bold" <?= $vault_open ? '' : 'disabled' ?>><i class="fa fa-check me-2"></i>Save new password</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Cancel</button>
</div>
</form>
<script>
itflowReady(function () {
var form = document.querySelector('form[data-credential-rotate]:not([data-wired])');
if (!form) {
return;
}
form.dataset.wired = '1';
var input = form.querySelector('[data-rotate-password]');
var copy = form.querySelector('[data-rotate-copy]');
function randomPassword(length) {
var chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*-_=+?';
var bytes = new Uint32Array(length);
window.crypto.getRandomValues(bytes);
return Array.prototype.map.call(bytes, function (b) { return chars[b % chars.length]; }).join('');
}
form.querySelectorAll('[data-rotate-generate]').forEach(function (item) {
item.addEventListener('click', function (e) {
e.preventDefault();
if (item.dataset.rotateGenerate === 'passphrase') {
itflowGet('ajax.php', { get_readable_pass: 'true' }, function (data) {
input.value = JSON.parse(data);
});
} else {
input.value = randomPassword(parseInt(item.dataset.rotateGenerate, 10));
}
});
});
copy.addEventListener('click', function () {
itflowCopyText(input.value, copy).then(
function () { flashTooltip(copy, 'Copied!'); },
function () {}
);
});
});
</script>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -0,0 +1,132 @@
<?php
/*
* Share a credential - a link that opens it once, or until it expires, for
* someone outside (a client's new starter, a vendor's engineer). The same
* share links as the page share modal (agent/modals/share_modal.php), made
* through agent/ajax.php share_generate_link, as an ajax modal so it opens
* from anywhere the credential does.
*/
require_once '../../../includes/modal_header.php';
enforceUserPermission('module_credential');
enforceUserPermission('module_support', 2);
$credential_id = intval($_GET['id'] ?? 0);
$credential = credentialRow($credential_id);
if (!$credential) {
echo json_encode(['error' => 'That credential no longer exists.']);
exit;
}
$client_id = intval($credential['credential_client_id']);
enforceClientAccess();
// Who it might go to - the client's people with an email, or anyone typed in
$recipients = [];
$sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_title, contact_photo, contact_client_id FROM contacts
WHERE contact_client_id = $client_id AND contact_email <> '' AND contact_archived_at IS NULL ORDER BY contact_name ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$recipients[] = $row;
}
ob_start();
?>
<div class="modal-header bg-dark">
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-share-alt me-2"></i>Share <strong><?= escapeHtml($credential['credential_name']) ?></strong></h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form data-credential-share autocomplete="off">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<input type="hidden" name="client_id" value="<?= $client_id ?>">
<input type="hidden" name="id" value="<?= $credential_id ?>">
<div class="modal-body">
<div data-share-form>
<div class="mb-3">
<label class="form-label">Send it to</label>
<div class="input-group">
<span class="input-group-text"><i class="fa fa-fw fa-envelope"></i></span>
<select class="form-select select2" name="contact_email" data-placeholder="Pick a contact or type an email - or leave it and copy the link" data-tags="true">
<option value=""></option>
<?php foreach ($recipients as $recipient) { ?>
<option value="<?= escapeHtml($recipient['contact_email']) ?>"<?= selectOptionContact($recipient['contact_client_id'], $recipient['contact_name'], $recipient['contact_photo'], $recipient['contact_email'], $recipient['contact_id']) ?>><?= escapeHtml($recipient['contact_name']) ?></option>
<?php } ?>
</select>
</div>
<div class="form-text">They get an email with the link. Leave it empty to just copy the link.</div>
</div>
<label class="form-label">Works for</label>
<div class="btn-group w-100 mb-3" role="group">
<?php foreach ([1 => '1 hour', 24 => '1 day', 168 => '1 week', 730 => '1 month'] as $hours => $label) { ?>
<input class="btn-check" id="credentialShare<?= $credential_id ?>_<?= $hours ?>" type="radio" name="expires" value="<?= $hours ?>" <?= $hours === 24 ? 'checked' : '' ?>>
<label class="btn btn-outline-secondary" for="credentialShare<?= $credential_id ?>_<?= $hours ?>"><?= $label ?></label>
<?php } ?>
</div>
<div class="form-check form-switch mb-3">
<input type="checkbox" class="form-check-input" name="views" value="1" id="credentialShareOnce<?= $credential_id ?>" checked>
<label class="form-check-label" for="credentialShareOnce<?= $credential_id ?>">Gone after it is opened once</label>
</div>
<label class="form-label">Note for them</label>
<textarea class="form-control" rows="3" name="note" maxlength="255" placeholder="Shown with the login - what it is for, and to change it once they are in"></textarea>
</div>
<div data-share-done hidden>
<p class="mb-2"><i class="fas fa-check-circle text-success me-2"></i>The link is made, and copied.</p>
<div class="input-group">
<input type="text" class="form-control" readonly data-share-link onclick="this.select();">
<button class="btn btn-outline-secondary" type="button" data-share-copy title="Copy link"><i class="far fa-fw fa-copy"></i></button>
</div>
<div class="form-text">Turn it off any time from the credential's quick look.</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary text-bold" data-share-make><i class="fas fa-link me-2"></i>Make the link</button>
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fa fa-times me-2"></i>Close</button>
</div>
</form>
<script>
itflowReady(function () {
var form = document.querySelector('form[data-credential-share]:not([data-wired])');
if (!form) {
return;
}
form.dataset.wired = '1';
var output = form.querySelector('[data-share-link]');
var copy = form.querySelector('[data-share-copy]');
function copyLink() {
itflowCopyText(output.value, copy).then(
function () { flashTooltip(copy, 'Copied!'); },
function () {}
);
}
copy.addEventListener('click', copyLink);
form.addEventListener('submit', function (e) {
e.preventDefault();
var make = form.querySelector('[data-share-make]');
make.disabled = true;
itflowGet('ajax.php', {
share_generate_link: 'true',
csrf_token: form.csrf_token.value,
client_id: form.client_id.value,
type: 'Credential',
id: form.querySelector('input[name="id"]').value,
note: form.note.value,
views: form.views.checked ? 1 : 0,
expires: form.querySelector('input[name="expires"]:checked').value,
contact_email: form.contact_email.value
}, function (data) {
output.value = JSON.parse(data);
form.querySelector('[data-share-form]').hidden = true;
form.querySelector('[data-share-done]').hidden = false;
make.hidden = true;
copyLink();
}, function () {
make.disabled = false;
});
});
});
</script>
<?php
require_once '../../../includes/modal_footer.php';

View File

@@ -58,7 +58,7 @@ function linkOptionData($to, $row, $client_id) {
: $seats['free'] . ' of ' . $seats['total'] . ' seats free');
return selectOptionData(['icon' => 'fas ' . softwareTypeStyle($row['software_type'])['icon'], 'description' => implode(' · ', array_filter([$row['software_license_type'], $seat_text, $row['software_version']]))]);
case 'credential':
return selectOptionData(['icon' => 'fas fa-key', 'description' => $row['credential_description'] ?: $row['credential_uri']]);
return selectOptionCredential(['credential_name' => $row['name'], 'credential_description' => $row['credential_description'], 'credential_uri' => $row['credential_uri']], $row['credential_description'] ?: $row['credential_uri']);
case 'location':
return selectOptionData(['icon' => 'fas fa-' . (intval($row['location_primary']) ? 'building' : 'map-marker-alt'), 'description' => implode(' · ', array_filter([intval($row['location_primary']) ? 'Primary' : '', locationAddressText($row)]))]);
case 'vendor':

View File

@@ -34,25 +34,22 @@ if ($service_importance == "High") {
$service_importance_display = "-";
}
// Associated Assets (and their credentials/networks/locations)
// Associated Assets (and their networks/locations) - one row each, their credentials come below
$sql_assets = mysqli_query(
$mysqli,
"SELECT * FROM service_assets
LEFT JOIN assets ON service_assets.asset_id = assets.asset_id
LEFT JOIN asset_interfaces ON interface_asset_id = assets.asset_id AND interface_primary = 1
LEFT JOIN credentials ON service_assets.asset_id = credentials.credential_asset_id
LEFT JOIN networks ON interface_network_id = networks.network_id
LEFT JOIN locations ON assets.asset_location_id = locations.location_id
WHERE service_id = $service_id"
);
// Associated credentials
$sql_credentials = mysqli_query(
$mysqli,
"SELECT * FROM service_credentials
LEFT JOIN credentials ON service_credentials.credential_id = credentials.credential_id
WHERE service_id = $service_id"
);
// Its credentials - the ones linked to it and the ones on its assets - for those who may see credentials
$service_credentials = lookupUserPermission('module_credential') >= 1
? credentialRows("credential_client_id = $client_id AND (credential_id IN (SELECT credential_id FROM service_credentials WHERE service_id = $service_id)
OR credential_asset_id IN (SELECT asset_id FROM service_assets WHERE service_id = $service_id))")
: [];
// Associated Domains
$sql_domains = mysqli_query(
@@ -247,34 +244,15 @@ ob_start();
?>
<!-- Credentials -->
<?php
if (mysqli_num_rows($sql_assets) > 0 || mysqli_num_rows($sql_credentials) > 0) {
echo "<h5><i class='fas fa-fw fa-key me-2'></i>Credentials</h5><ul>";
// Credentials linked to assets
mysqli_data_seek($sql_assets, 0);
while ($row = mysqli_fetch_assoc($sql_assets)) {
$credential_name = escapeHtml($row['credential_name']);
if (!empty($credential_name)) {
echo "<li><a href='credentials.php?client_id=$client_id&q=$credential_name'>$credential_name</a></li>";
}
}
// Explicitly linked credentials
mysqli_data_seek($sql_credentials, 0);
while ($row = mysqli_fetch_assoc($sql_credentials)) {
$credential_name = escapeHtml($row['credential_name']);
if (!empty($credential_name)) {
echo "<li><a href='credentials.php?client_id=$client_id&q=$credential_name'>$credential_name</a></li>";
}
}
echo "</ul>";
}
?>
<?php if ($service_credentials) { ?>
<h5><i class="fas fa-fw fa-key me-2"></i>Credentials</h5>
<div class="mb-3"><?= credentialListHtml($service_credentials) ?></div>
<?php } ?>
<!-- URLs -->
<?php
$urls = [];
mysqli_data_seek($sql_credentials, 0);
while ($row = mysqli_fetch_assoc($sql_credentials)) {
foreach ($service_credentials as $row) {
if (!empty($row['credential_uri'])) {
$urls[] = escapeUrl($row['credential_uri']);
}

View File

@@ -40,7 +40,7 @@ $can_credentials = lookupUserPermission('module_credential') >= 1;
$holders = softwareSeatHolders($software_id);
$keys = softwareKeys($software_id);
$credentials = $can_credentials ? linkedRecords('software', $software_id, 'credential') : [];
$credentials = $can_credentials ? credentialRows("credential_id IN (SELECT credential_id FROM software_credentials WHERE software_id = $software_id)") : [];
$documents = linkedRecords('software', $software_id, 'document');
$files = linkedRecords('software', $software_id, 'file');
@@ -216,31 +216,8 @@ ob_start();
<?php if ($credentials) { ?>
<div class="tab-pane fade <?= $first_tab === 'credentials' ? 'show active' : '' ?>" id="<?= $quick_id ?>-credentials" role="tabpanel">
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0">
<tbody>
<?php foreach ($credentials as $credential) {
$credential_id = intval($credential['id']);
$credential_username = escapeHtml(decryptCredentialEntry($credential['credential_username'])); ?>
<tr>
<td>
<a class="ajax-modal" href="#" data-modal-url="modals/credential/credential_edit.php?id=<?= $credential_id ?>"><?= escapeHtml($credential['name']) ?></a>
<?php if ($credential['credential_uri']) { ?><a class="ms-1 small" href="<?= escapeUrl($credential['credential_uri']) ?>" target="_blank" rel="noopener" title="<?= escapeHtml($credential['credential_uri']) ?>"><i class="fas fa-external-link-alt"></i></a><?php } ?>
</td>
<td class="text-nowrap"><?php if ($credential_username) { ?><?= $credential_username ?><button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="<?= $credential_username ?>"><i class="far fa-copy"></i></button><?php } else { ?><span class="text-body-secondary">-</span><?php } ?></td>
<td class="text-nowrap">
<button class="btn btn-sm btn-light" aria-label="Show password" title="Show password" type="button" onclick="showPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="fas fa-ellipsis-h"></i><i class="fas fa-ellipsis-h"></i></button>
<button type="button" class="itflow-copy" title="Copy password" onclick="copyPasswordViaCredentialID(this, <?= $credential_id ?>)"><i class="far fa-copy"></i></button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?= credentialListHtml($credentials) ?>
</div>
<?php /* js/, not ../js/ - this file is injected by js/ajax_modal.js, so a
relative src resolves against the host page's URL (/agent/...) */ ?>
<script src="js/credential_show_password_via_id.js"></script>
<?php } ?>
<?php foreach (['documents' => ['document', $documents], 'files' => ['file', $files]] as $pane => [$to, $linked]) {

View File

@@ -72,17 +72,26 @@ if (isset($_POST['add_asset'])) {
// Add Primary Interface
mysqli_query($mysqli,"INSERT INTO asset_interfaces SET interface_name = '01', interface_mac = '$mac', interface_ip = '$ip', interface_nat_ip = '$nat_ip', interface_ipv6 = '$ipv6', interface_primary = 1, interface_network_id = $network, interface_asset_id = $asset_id");
if (!empty($_POST['password'])) {
$username = trim(mysqli_real_escape_string($mysqli, encryptCredentialEntry($_POST['username'])));
$password = trim(mysqli_real_escape_string($mysqli, encryptCredentialEntry($_POST['password'])));
// A username or a password on its own is enough to keep
if (trim((string) ($_POST['username'] ?? '')) !== '' || trim((string) ($_POST['password'] ?? '')) !== '') {
$username = encryptCredentialEntry(trim((string) ($_POST['username'] ?? '')));
$password = encryptCredentialEntry(trim((string) ($_POST['password'] ?? '')));
mysqli_query($mysqli,"INSERT INTO credentials SET credential_name = '$name', credential_username = '$username', credential_password = '$password', credential_asset_id = $asset_id, credential_client_id = $client_id");
// A vault session that didn't open encrypts to nothing - better no login than one that can never be read
if ($username === false || $password === false) {
$alert_extended = ", but not its login - your vault session has expired, so sign in again and add it from the asset";
} else {
$username = escapeSql($username);
$password = escapeSql($password);
$credential_id = mysqli_insert_id($mysqli);
mysqli_query($mysqli,"INSERT INTO credentials SET credential_name = '$name', credential_username = '$username', credential_password = '$password', credential_password_changed_at = NOW(), credential_asset_id = $asset_id, credential_client_id = $client_id");
logAudit("Credential", "Create", "$session_name created login credential for asset $name", $client_id, $credential_id);
$credential_id = mysqli_insert_id($mysqli);
$alert_extended = " along with login credentials";
logAudit("Credential", "Create", "$session_name created login credential for asset $name", $client_id, $credential_id);
$alert_extended = " along with login credentials";
}
}
@@ -91,7 +100,7 @@ if (isset($_POST['add_asset'])) {
logAudit("Asset", "Create", "$session_name created asset $name", $client_id, $asset_id);
flashAlert("Asset <strong>$name</strong> created $alert_extended");
flashAlert("Asset <strong>$name</strong> created$alert_extended");
redirect();
@@ -256,6 +265,9 @@ if (isset($_GET['delete_asset'])) {
// Out of whatever rack it was in - an item pointing at a deleted asset draws as nothing
mysqli_query($mysqli,"DELETE FROM rack_units WHERE unit_asset_id = $asset_id");
// Its logins stay with the client, no longer pointing at an asset that is gone
credentialsForget('asset', $asset_id);
logAudit("Asset", "Delete", "$session_name deleted asset $asset_name", $client_id);
flashAlert("Asset <strong>$asset_name</strong> deleted");
@@ -841,6 +853,7 @@ if (isset($_POST['bulk_delete_assets'])) {
mysqli_query($mysqli,"DELETE FROM assets WHERE asset_id = $asset_id");
mysqli_query($mysqli,"DELETE FROM rack_units WHERE unit_asset_id = $asset_id");
credentialsForget('asset', $asset_id);
logAudit("Asset", "Delete", "$session_name deleted asset $asset_name", $client_id, $asset_id);
}
@@ -864,6 +877,8 @@ if (isset($_POST['link_asset_to_credential'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
// It changes the credential, so it takes credential edit rights too
enforceUserPermission('module_credential', 2);
$credential_id = intval($_POST['credential_id']);
$asset_id = intval($_POST['asset_id']);
@@ -871,11 +886,21 @@ if (isset($_POST['link_asset_to_credential'])) {
// Get credential Name and Client ID for logging
$sql_credential = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql_credential);
if (!$row) {
flashAlert("That credential no longer exists", 'error');
redirect();
}
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
// Only to one of the same client's assets
if (!assetClientOwnedId('asset', $asset_id, $client_id)) {
flashAlert("That asset isn't one of this client's", 'error');
redirect();
}
// Get Asset Name for logging
$asset_name = escapeSql(getFieldById('assets', $asset_id, 'asset_name'));
@@ -894,6 +919,7 @@ if (isset($_GET['unlink_credential_from_asset'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
enforceUserPermission('module_credential', 2);
$asset_id = intval($_GET['asset_id']);
$credential_id = intval($_GET['credential_id']);
@@ -909,11 +935,12 @@ if (isset($_GET['unlink_credential_from_asset'])) {
// Get Asset Name for logging
$asset_name = escapeSql(getFieldById('assets', $asset_id, 'asset_name'));
mysqli_query($mysqli,"UPDATE credentials SET credential_asset_id = 0 WHERE credential_id = $credential_id");
// Only if it is this asset's - an old link can't unpick a newer one
mysqli_query($mysqli,"UPDATE credentials SET credential_asset_id = 0 WHERE credential_id = $credential_id AND credential_asset_id = $asset_id");
logAudit("Credential", "Unlink", "$session_name unlinked asset $asset_name from credential $credential_name", $client_id, $credential_id);
flashAlert("Credential <strong>$credential_name</strong> unlinked from Asset <strong>$asset_name</strong>", 'errpr');
flashAlert("Credential <strong>$credential_name</strong> unlinked from Asset <strong>$asset_name</strong>");
redirect();

View File

@@ -713,6 +713,7 @@ if (isset($_POST['bulk_delete_contacts'])) {
}
mysqli_query($mysqli, "DELETE FROM contacts WHERE contact_id = $contact_id AND contact_client_id = $client_id");
credentialsForget('contact', $contact_id);
logAudit("Contact", "Delete", "$session_name deleted $contact_name", $client_id);
@@ -922,6 +923,9 @@ if (isset($_GET['delete_contact'])) {
mysqli_query($mysqli,"DELETE FROM contacts WHERE contact_id = $contact_id");
// Their logins stay with the client, no longer pointing at a contact that is gone
credentialsForget('contact', $contact_id);
logAudit("Contact", "Delete", "$session_name deleted contact $contact_name", $client_id);
flashAlert("Contact <strong>$contact_name</strong> has been deleted.", 'error');
@@ -997,6 +1001,8 @@ if (isset($_POST['link_contact_to_credential'])) {
validateCSRFToken();
enforceUserPermission('module_client', 2);
// It changes the credential, so it takes credential edit rights too
enforceUserPermission('module_credential', 2);
$credential_id = intval($_POST['credential_id']);
$contact_id = intval($_POST['contact_id']);
@@ -1004,17 +1010,27 @@ if (isset($_POST['link_contact_to_credential'])) {
// Get credential Name and Client ID for logging
$sql_credential = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql_credential);
if (!$row) {
flashAlert("That credential no longer exists", 'error');
redirect();
}
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
// Only to one of the same client's people
if (!assetClientOwnedId('contact', $contact_id, $client_id)) {
flashAlert("That contact isn't one of this client's", 'error');
redirect();
}
// Get Contact Name for logging
$contact_name = escapeSql(getFieldById('contacts', $contact_id, 'contact_name'));
mysqli_query($mysqli,"UPDATE credentials SET credential_contact_id = $contact_id WHERE credential_id = $credential_id");
logAudit("Asset", "Link", "$session_name linked credential $credential_name to contact $contact_name", $client_id, $credential_id);
logAudit("Credential", "Link", "$session_name linked credential $credential_name to contact $contact_name", $client_id, $credential_id);
flashAlert("Contact <strong>$contact_name</strong> linked with credential <strong>$credential_name</strong>");
@@ -1027,6 +1043,7 @@ if (isset($_GET['unlink_credential_from_contact'])) {
validateCSRFToken();
enforceUserPermission('module_client', 2);
enforceUserPermission('module_credential', 2);
$contact_id = intval($_GET['contact_id']);
$credential_id = intval($_GET['credential_id']);
@@ -1042,11 +1059,12 @@ if (isset($_GET['unlink_credential_from_contact'])) {
// Get Contact Name for logging
$contact_name = escapeSql(getFieldById('contacts', $contact_id, 'contact_name'));
mysqli_query($mysqli,"UPDATE credentials SET credential_contact_id = 0 WHERE credential_id = $credential_id");
// Only if it is this contact's - an old link can't unpick a newer one
mysqli_query($mysqli,"UPDATE credentials SET credential_contact_id = 0 WHERE credential_id = $credential_id AND credential_contact_id = $contact_id");
logAudit("Credential", "Unlink", "$session_name unlinked contact $contact_name from credential $credential_name", $client_id, $credential_id);
flashAlert("Credential <strong>$credential_name</strong> unlinked from Contact <strong>$contact_name</strong>", 'error');
flashAlert("Credential <strong>$credential_name</strong> unlinked from Contact <strong>$contact_name</strong>");
redirect();

View File

@@ -2,41 +2,82 @@
/*
* ITFlow - GET/POST request handler for client credentials
*
* Every handler checks the credential module and the credential's own client;
* anything a form names - the asset, the contact, the tags, a vendor to link
* to - must be that client's. Usernames and passwords are encrypted with the
* session's vault key (credentialFormSet() in functions/credential.php), and
* nothing is saved when the vault did not open, rather than writing an empty
* password over the real one. Vendors and licenses link through post/link.php.
*/
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
/** The credential a request names, after the module and client checks - or back with an error if it is gone. */
function credentialForRequest($credential_id, $level) {
global $client_id;
enforceUserPermission('module_credential', $level);
$row = credentialRow($credential_id);
if (!$row) {
flashAlert('That credential no longer exists.', 'error');
redirect();
}
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
return $row;
}
/** The credentials a bulk action names that this agent may act on - [id => row]. */
function credentialsForBulk($level) {
global $client_id;
enforceUserPermission('module_credential', $level);
$rows = [];
foreach (array_unique(array_map('intval', (array) ($_POST['credential_ids'] ?? []))) as $credential_id) {
$row = credentialRow($credential_id);
if (!$row) {
continue;
}
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
$rows[$credential_id] = $row;
}
return $rows;
}
if (isset($_POST['add_credential'])) {
validateCSRFToken();
enforceUserPermission('module_credential', 2);
require_once 'credential_model.php';
$client_id = intval($_POST['client_id']);
$client_id = intval($_POST['client_id'] ?? 0);
enforceClientAccess();
mysqli_query($mysqli,"INSERT INTO credentials SET credential_name = '$name', credential_description = '$description', credential_uri = '$uri', credential_uri_2 = '$uri_2', credential_username = '$username', credential_password = '$password', credential_otp_secret = '$otp_secret', credential_note = '$note', credential_favorite = $favorite, credential_contact_id = $contact_id, credential_asset_id = $asset_id, credential_client_id = $client_id");
if (!$client_id || !getFieldById('clients', $client_id, 'client_name')) {
flashAlert('Pick the client this credential is for.', 'error');
redirect();
}
$set = credentialFormSet($_POST, $client_id, $error);
if ($set === null) {
flashAlert($error, 'error');
redirect();
}
mysqli_query($mysqli, "INSERT INTO credentials SET $set, credential_password_changed_at = NOW(), credential_client_id = $client_id");
$credential_id = mysqli_insert_id($mysqli);
credentialSetTags($credential_id, $_POST['tags'] ?? []);
// Made from a vendor's page - linked to that vendor, if it is the same client's
$vendor_id = assetClientOwnedId('vendor', $_POST['vendor_id'] ?? 0, $client_id);
if ($vendor_id) {
mysqli_query($mysqli, "INSERT IGNORE INTO vendor_credentials SET vendor_id = $vendor_id, credential_id = $credential_id");
}
// Add Tags
if (isset($_POST['tags'])) {
foreach($_POST['tags'] as $tag) {
$tag = intval($tag);
mysqli_query($mysqli, "INSERT INTO credential_tags SET credential_id = $credential_id, tag_id = $tag");
}
}
logAudit("Credential", "Create", "$session_name created credential $name", $client_id, $credential_id);
$name = trim($_POST['name']);
logAudit("Credential", "Create", "$session_name created credential " . escapeSql($name), $client_id, $credential_id);
flashAlert("Credential <strong>$name</strong> created");
@@ -48,94 +89,112 @@ if (isset($_POST['edit_credential'])) {
validateCSRFToken();
enforceUserPermission('module_credential', 2);
$row = credentialForRequest($_POST['credential_id'] ?? 0, 2);
$credential_id = intval($row['credential_id']);
require_once 'credential_model.php';
$credential_id = intval($_POST['credential_id']);
$client_id = intval(getFieldById('credentials', $credential_id, 'credential_client_id'));
enforceClientAccess();
// Determine if the password has actually changed (salt is rotated on all updates, so have to dencrypt both and compare)
$current_password = decryptCredentialEntry(mysqli_fetch_row(mysqli_query($mysqli, "SELECT credential_password FROM credentials WHERE credential_id = $credential_id"))[0]); // Get current credential password
$new_password = decryptCredentialEntry($password); // Get the new password being set (already encrypted by the credential model)
if ($current_password !== $new_password) {
// The password has been changed - update the DB to track
mysqli_query($mysqli, "UPDATE credentials SET credential_password_changed_at = NOW() WHERE credential_id = $credential_id");
$set = credentialFormSet($_POST, $client_id, $error);
if ($set === null) {
flashAlert($error, 'error');
redirect();
}
// Update the credential entry with the new details
mysqli_query($mysqli,"UPDATE credentials SET credential_name = '$name', credential_description = '$description', credential_uri = '$uri', credential_uri_2 = '$uri_2', credential_username = '$username', credential_password = '$password', credential_otp_secret = '$otp_secret', credential_note = '$note', credential_favorite = $favorite, credential_contact_id = $contact_id, credential_asset_id = $asset_id WHERE credential_id = $credential_id");
// Changed password - record when, for the rotation report and the age shown everywhere
$password_changed = trim((string) ($_POST['password'] ?? '')) !== (string) decryptCredentialEntry($row['credential_password']);
// Tags
// Delete existing tags
mysqli_query($mysqli, "DELETE FROM credential_tags WHERE credential_id = $credential_id");
mysqli_query($mysqli, "UPDATE credentials SET $set" . ($password_changed ? ", credential_password_changed_at = NOW()" : '') . " WHERE credential_id = $credential_id");
// Add new tags
if(isset($_POST['tags'])) {
foreach($_POST['tags'] as $tag) {
$tag = intval($tag);
mysqli_query($mysqli, "INSERT INTO credential_tags SET credential_id = $credential_id, tag_id = $tag");
}
// Only a form that showed the tags changes them
if (isset($_POST['tags_form'])) {
credentialSetTags($credential_id, $_POST['tags'] ?? []);
}
logAudit("Credential", "Edit", "$session_name edited credential $name", $client_id, $credential_id);
$name = trim($_POST['name']);
logAudit("Credential", "Edit", "$session_name edited credential " . escapeSql($name) . ($password_changed ? ' and changed its password' : ''), $client_id, $credential_id);
flashAlert("Credential <strong>$name</strong> edited");
flashAlert("Credential <strong>$name</strong> updated");
redirect();
}
if(isset($_GET['archive_credential'])){
// A new password and nothing else - the rotation
if (isset($_POST['rotate_credential'])) {
validateCSRFToken();
enforceUserPermission('module_credential', 2);
$row = credentialForRequest($_POST['credential_id'] ?? 0, 2);
$credential_id = intval($row['credential_id']);
$credential_id = intval($_GET['archive_credential']);
$password = trim((string) ($_POST['password'] ?? ''));
if ($password === '') {
flashAlert('Type or make up the new password.', 'error');
redirect();
}
if (checkCredentialLengths(['password' => $password])) {
flashAlert('That password is too long to store.', 'error');
redirect();
}
$encrypted = encryptCredentialEntry($password);
if ($encrypted === false) {
flashAlert('Your vault session has expired, so the password could not be encrypted - sign out and back in, then try again.', 'error');
redirect();
}
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql);
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
mysqli_query($mysqli, "UPDATE credentials SET credential_password = '" . escapeSql($encrypted) . "', credential_password_changed_at = NOW() WHERE credential_id = $credential_id");
enforceClientAccess();
logAudit("Credential", "Rotate", "$session_name changed the password on credential " . escapeSql($row['credential_name']), $client_id, $credential_id);
mysqli_query($mysqli,"UPDATE credentials SET credential_archived_at = NOW() WHERE credential_id = $credential_id");
logAudit("Credential", "Archive", "$session_name archived credential $credential_name", $client_id, $credential_id);
flashAlert("Credential <strong>$credential_name</strong> archived", 'error');
flashAlert("Password changed on <strong>{$row['credential_name']}</strong>");
redirect();
}
if(isset($_GET['restore_credential'])){
if (isset($_GET['favorite_credential']) || isset($_GET['unfavorite_credential'])) {
validateCSRFToken();
enforceUserPermission('module_credential', 2);
$favorite = isset($_GET['favorite_credential']) ? 1 : 0;
$row = credentialForRequest($favorite ? $_GET['favorite_credential'] : $_GET['unfavorite_credential'], 2);
$credential_id = intval($row['credential_id']);
$credential_id = intval($_GET['restore_credential']);
mysqli_query($mysqli, "UPDATE credentials SET credential_favorite = $favorite WHERE credential_id = $credential_id");
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql);
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
logAudit("Credential", "Edit", "$session_name " . ($favorite ? 'starred' : 'unstarred') . " credential " . escapeSql($row['credential_name']), $client_id, $credential_id);
enforceClientAccess();
redirect();
mysqli_query($mysqli,"UPDATE credentials SET credential_archived_at = NULL WHERE credential_id = $credential_id");
}
logAudit("Credential", "Restore", "$session_name restored credential $credential_name", $client_id, $credential_id);
if (isset($_GET['archive_credential'])) {
flashAlert("Credential <strong>$credential_name</strong> restored");
validateCSRFToken();
$row = credentialForRequest($_GET['archive_credential'], 2);
$credential_id = intval($row['credential_id']);
mysqli_query($mysqli, "UPDATE credentials SET credential_archived_at = NOW() WHERE credential_id = $credential_id");
logAudit("Credential", "Archive", "$session_name archived credential " . escapeSql($row['credential_name']), $client_id, $credential_id);
flashAlert("Credential <strong>{$row['credential_name']}</strong> archived", 'error');
redirect();
}
if (isset($_GET['restore_credential'])) {
validateCSRFToken();
$row = credentialForRequest($_GET['restore_credential'], 2);
$credential_id = intval($row['credential_id']);
mysqli_query($mysqli, "UPDATE credentials SET credential_archived_at = NULL WHERE credential_id = $credential_id");
logAudit("Credential", "Restore", "$session_name restored credential " . escapeSql($row['credential_name']), $client_id, $credential_id);
flashAlert("Credential <strong>{$row['credential_name']}</strong> restored");
redirect();
@@ -145,99 +204,31 @@ if (isset($_GET['delete_credential'])) {
validateCSRFToken();
enforceUserPermission('module_credential', 3);
$row = credentialForRequest($_GET['delete_credential'], 3);
$credential_id = intval($_GET['delete_credential']);
credentialDeleteForGood($row['credential_id']);
// Get Credential Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql);
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
logAudit("Credential", "Delete", "$session_name deleted credential " . escapeSql($row['credential_name']), $client_id);
enforceClientAccess();
mysqli_query($mysqli,"DELETE FROM credentials WHERE credential_id = $credential_id");
logAudit("Credential", "Delete", "$session_name deleted credential $credential_name", $client_id);
flashAlert("Credential <strong>$credential_name</strong> deleted", 'error');
flashAlert("Credential <strong>{$row['credential_name']}</strong> deleted", 'error');
redirect();
}
if (isset($_POST['bulk_favorite_credentials'])) {
if (isset($_POST['bulk_favorite_credentials']) || isset($_POST['bulk_unfavorite_credentials'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
if (isset($_POST['credential_ids'])) {
$count = count($_POST['credential_ids']);
foreach ($_POST['credential_ids'] as $credential_id) {
$credential_id = intval($credential_id);
// Get Asset Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql);
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE credentials SET credential_favorite = 1 WHERE credential_id = $credential_id");
logAudit("Credential", "Edit", "$session_name marked credential $credential_name a favorite", $client_id, $credential_id);
}
logAudit("Credential", "Bulk Edit", "$session_name favorited $count credentials", $client_id);
flashAlert("Favorited <strong>$count</strong> credential(s)");
$favorite = isset($_POST['bulk_favorite_credentials']) ? 1 : 0;
$count = 0;
foreach (credentialsForBulk(2) as $credential_id => $row) {
mysqli_query($mysqli, "UPDATE credentials SET credential_favorite = $favorite WHERE credential_id = $credential_id");
logAudit("Credential", "Edit", "$session_name " . ($favorite ? 'starred' : 'unstarred') . " credential " . escapeSql($row['credential_name']), intval($row['credential_client_id']), $credential_id);
$count++;
}
redirect();
}
if (isset($_POST['bulk_unfavorite_credentials'])) {
validateCSRFToken();
enforceUserPermission('module_support', 2);
if (isset($_POST['credential_ids'])) {
$count = count($_POST['credential_ids']);
foreach ($_POST['credential_ids'] as $credential_id) {
$credential_id = intval($credential_id);
// Get Asset Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql);
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE credentials SET credential_favorite = 0 WHERE credential_id = $credential_id");
logAudit("Credential", "Edit", "$session_name unfavorited credential $credential_name", $client_id, $credential_id);
}
logAudit("Crednetial", "Bulk Edit", "$session_name unfavorited $count credentials", $client_id);
flashAlert("Unfavorited <strong>$count</strong> credential(s)");
}
flashAlert(($favorite ? 'Starred' : 'Unstarred') . " <strong>$count</strong> credential" . ($count === 1 ? '' : 's'));
redirect();
@@ -247,37 +238,15 @@ if (isset($_POST['bulk_archive_credentials'])) {
validateCSRFToken();
enforceUserPermission('module_credential', 2);
if (isset($_POST['credential_ids'])) {
// Get Selected Credential Count
$count = count($_POST['credential_ids']);
// Cycle through array and archive each record
foreach ($_POST['credential_ids'] as $credential_id) {
$credential_id = intval($credential_id);
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql);
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE credentials SET credential_archived_at = NOW() WHERE credential_id = $credential_id");
logAudit("Credential", "Archive", "$session_name archived credential $credential_name", $client_id, $credential_id);
}
logAudit("Credential", "Bulk Archive", "$session_name archived $count credentials", $client_id);
flashAlert("Archived <strong>$count</strong> credential(s)", 'error');
$count = 0;
foreach (credentialsForBulk(2) as $credential_id => $row) {
mysqli_query($mysqli, "UPDATE credentials SET credential_archived_at = NOW() WHERE credential_id = $credential_id");
logAudit("Credential", "Archive", "$session_name archived credential " . escapeSql($row['credential_name']), intval($row['credential_client_id']), $credential_id);
$count++;
}
flashAlert("Archived <strong>$count</strong> credential" . ($count === 1 ? '' : 's'), 'error');
redirect();
}
@@ -286,38 +255,15 @@ if (isset($_POST['bulk_restore_credentials'])) {
validateCSRFToken();
enforceUserPermission('module_credential', 2);
if (isset($_POST['credential_ids'])) {
// Get Selected Credential Count
$count = count($_POST['credential_ids']);
// Cycle through array and restore
foreach ($_POST['credential_ids'] as $credential_id) {
$credential_id = intval($credential_id);
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql);
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
mysqli_query($mysqli,"UPDATE credentials SET credential_archived_at = NULL WHERE credential_id = $credential_id");
logAudit("Credential", "Restore", "$session_name restored credential $credential_name", $client_id, $credential_id);
}
logAudit("Credential", "Bulk Restore", "$session_name restored $count credential(s)", $client_id);
flashAlert("Restored <strong>$count</strong> credential(s)");
$count = 0;
foreach (credentialsForBulk(2) as $credential_id => $row) {
mysqli_query($mysqli, "UPDATE credentials SET credential_archived_at = NULL WHERE credential_id = $credential_id");
logAudit("Credential", "Restore", "$session_name restored credential " . escapeSql($row['credential_name']), intval($row['credential_client_id']), $credential_id);
$count++;
}
flashAlert("Restored <strong>$count</strong> credential" . ($count === 1 ? '' : 's'));
redirect();
}
@@ -326,38 +272,15 @@ if (isset($_POST['bulk_delete_credentials'])) {
validateCSRFToken();
enforceUserPermission('module_credential', 3);
if (isset($_POST['credential_ids'])) {
// Get Selected Credential Count
$count = count($_POST['credential_ids']);
// Cycle through array and delete each record
foreach ($_POST['credential_ids'] as $credential_id) {
$credential_id = intval($credential_id);
// Get Name and Client ID for logging and alert message
$sql = mysqli_query($mysqli,"SELECT credential_name, credential_client_id FROM credentials WHERE credential_id = $credential_id");
$row = mysqli_fetch_assoc($sql);
$credential_name = escapeSql($row['credential_name']);
$client_id = intval($row['credential_client_id']);
enforceClientAccess();
mysqli_query($mysqli, "DELETE FROM credentials WHERE credential_id = $credential_id AND credential_client_id = $client_id");
logAudit("Credential", "Delete", "$session_name deleted credential $credential_name", $client_id);
}
logAudit("Credential", "Bulk Delete", "$session_name deleted $count credential(s)", $client_id);
flashAlert("Deleted <strong>$count</strong> credential(s)", 'error');
$count = 0;
foreach (credentialsForBulk(3) as $credential_id => $row) {
credentialDeleteForGood($credential_id);
logAudit("Credential", "Delete", "$session_name deleted credential " . escapeSql($row['credential_name']), intval($row['credential_client_id']));
$count++;
}
flashAlert("Deleted <strong>$count</strong> credential" . ($count === 1 ? '' : 's'), 'error');
redirect();
}
@@ -405,10 +328,11 @@ if (isExportRequest('export_credentials')) {
$archive_query = $archived ? "(client_archived_at IS NOT NULL OR credential_archived_at IS NOT NULL)" : "(client_archived_at IS NULL AND credential_archived_at IS NULL)";
}
// Tags Filter
// Tags Filter - a credential with any of them
$tag_query = '';
if (isset($_POST['tags']) && is_array($_POST['tags']) && !empty($_POST['tags'])) {
$tag_filter = implode(",", array_map('intval', $_POST['tags']));
$tag_query = "AND tags.tag_id IN ($tag_filter)";
$tag_query = "AND c.credential_id IN (SELECT credential_id FROM credential_tags WHERE tag_id IN ($tag_filter))";
$tag_names = [];
$sql_tags = mysqli_query($mysqli, "SELECT tag_name FROM tags WHERE tag_id IN ($tag_filter) ORDER BY tag_name ASC");
@@ -416,9 +340,6 @@ if (isExportRequest('export_credentials')) {
$tag_names[] = $tag_row['tag_name'];
}
$filter_summary['Tags'] = implode(', ', $tag_names);
} else {
// Default - any
$tag_query = '';
}
// Search Filter
@@ -429,20 +350,20 @@ if (isExportRequest('export_credentials')) {
$sql = mysqli_query(
$mysqli,
"SELECT c.*, clients.*, contacts.*, assets.*
"SELECT c.*, client_name, contact_name, asset_name,
(SELECT GROUP_CONCAT(tag_name ORDER BY tag_name SEPARATOR ', ') FROM credential_tags ct JOIN tags t ON t.tag_id = ct.tag_id WHERE ct.credential_id = c.credential_id) AS credential_tags,
DATE(c.credential_password_changed_at) AS credential_password_changed
FROM credentials c
LEFT JOIN credential_tags ON credential_tags.credential_id = c.credential_id
LEFT JOIN tags ON tags.tag_id = credential_tags.tag_id
LEFT JOIN clients ON client_id = credential_client_id
LEFT JOIN contacts ON contact_id = credential_contact_id
LEFT JOIN assets ON asset_id = credential_asset_id
WHERE $archive_query
$tag_query
AND (c.credential_name LIKE '%$q%' OR c.credential_description LIKE '%$q%' OR c.credential_uri LIKE '%$q%' OR tag_name LIKE '%$q%' OR client_name LIKE '%$q%')
AND (c.credential_name LIKE '%$q%' OR c.credential_description LIKE '%$q%' OR c.credential_uri LIKE '%$q%' OR c.credential_note LIKE '%$q%' OR client_name LIKE '%$q%'
OR c.credential_id IN (SELECT credential_id FROM credential_tags JOIN tags USING (tag_id) WHERE tag_name LIKE '%$q%'))
" . clientScopeSql('credential_client_id') . "
$client_query
GROUP BY c.credential_id
ORDER BY c.credential_name ASC"
ORDER BY client_name ASC, c.credential_name ASC"
);
$num_rows = mysqli_num_rows($sql);
@@ -478,111 +399,80 @@ if (isset($_POST["import_credentials_csv"])) {
enforceClientAccess();
$error = false;
if (!empty($_FILES["file"]["tmp_name"])) {
$file_name = $_FILES["file"]["tmp_name"];
} else {
if (empty($_FILES["file"]["tmp_name"])) {
flashAlert("Please select a file to upload.", 'error');
redirect();
}
$file_name = $_FILES["file"]["tmp_name"];
//Check file is CSV
$file_extension = strtolower(end(explode('.',$_FILES['file']['name'])));
$allowed_file_extensions = array('csv');
if (in_array($file_extension,$allowed_file_extensions) === false){
$error = true;
if (strtolower(pathinfo((string) $_FILES['file']['name'], PATHINFO_EXTENSION)) !== 'csv') {
flashAlert("Bad file extension", 'error');
redirect();
}
//Check file isn't empty
elseif ($_FILES["file"]["size"] < 1){
$error = true;
if ($_FILES["file"]["size"] < 1) {
flashAlert("Bad file size (empty?)", 'error');
redirect();
}
//(Else)Check column count
$f = fopen($file_name, "r");
$f_columns = fgetcsv($f, 1000, ",");
if (!$error & count($f_columns) != 6) {
$error = true;
flashAlert("Bad column count.", 'error');
}
//Else, parse the file
if (!$error){
$file = fopen($file_name, "r");
fgetcsv($file, 1000, ","); // Skip first line
$row_count = 0;
$duplicate_count = 0;
$too_long_count = 0;
while(($column = fgetcsv($file, 1000, ",")) !== false){
$duplicate_detect = 0;
// Nothing client-side guards an uploaded file, and an overlong value is a hard
// MySQL error - skip the row and report it rather than losing the whole import
if (checkCredentialLengths([
'name' => $column[0] ?? null,
'description' => $column[1] ?? null,
'username' => $column[2] ?? null,
'password' => $column[3] ?? null,
'otp_secret' => $column[4] ?? null,
'uri' => $column[5] ?? null,
])) {
$too_long_count = $too_long_count + 1;
continue;
}
// Name
if (isset($column[0])) {
$name = escapeSql($column[0]);
if (mysqli_num_rows(mysqli_query($mysqli,"SELECT 1 FROM credentials WHERE credential_name = '$name' AND credential_client_id = $client_id")) > 0){
$duplicate_detect = 1;
}
}
// Desc
if (isset($column[1])) {
$description = escapeSql($column[1]);
}
// User
if (isset($column[2])) {
$username = escapeSql(encryptCredentialEntry($column[2]));
}
// Pass
if (isset($column[3])) {
$password = escapeSql(encryptCredentialEntry($column[3]));
}
// OTP
if (isset($column[4])) {
$totp = escapeSql($column[4]);
}
// URL
if (isset($column[5])) {
$uri = escapeSql($column[5]);
}
// Check if duplicate was detected
if ($duplicate_detect == 0){
//Add
mysqli_query($mysqli,"INSERT INTO credentials SET credential_name = '$name', credential_description = '$description', credential_uri = '$uri', credential_username = '$username', credential_password = '$password', credential_otp_secret = '$totp', credential_client_id = $client_id");
$row_count = $row_count + 1;
} else {
$duplicate_count = $duplicate_count + 1;
}
}
$file = fopen($file_name, "r");
$f_columns = fgetcsv($file, 1000, ",");
if (!is_array($f_columns) || count($f_columns) != 6) {
fclose($file);
logAudit("Credential", "Import", "$session_name imported $row_count credential(s) via CSV file. $duplicate_count duplicate(s) found and not imported, $too_long_count row(s) skipped for over-length fields", $client_id);
flashAlert("<strong>$row_count</strong> credential(s) imported, <strong>$duplicate_count</strong> duplicate(s) detected and not imported, <strong>$too_long_count</strong> row(s) skipped for over-length fields", 'warning');
flashAlert("Bad column count.", 'error');
redirect();
}
//Check for any errors, if there are notify user and redirect
if ($error) {
// The vault must be open, or every imported password would be saved empty
if (encryptCredentialEntry('') === false) {
fclose($file);
flashAlert('Your vault session has expired, so nothing could be encrypted - sign out and back in, then import again.', 'error');
redirect();
}
$row_count = $duplicate_count = $too_long_count = $bad_otp_count = 0;
while (($column = fgetcsv($file, 1000, ",")) !== false) {
// Every row stands alone - a column missing on one row must not take the last row's value
$column = array_pad($column, 6, '');
[$name, $description, $username, $password, $totp, $uri] = array_map(function ($value) {
return trim((string) $value);
}, array_slice($column, 0, 6));
if ($name === '') {
continue;
}
// Nothing client-side guards an uploaded file, and an overlong value is a hard
// MySQL error - skip the row and report it rather than losing the whole import
if (checkCredentialLengths(['name' => $name, 'description' => $description, 'username' => $username, 'password' => $password, 'otp_secret' => $totp, 'uri' => $uri])) {
$too_long_count++;
continue;
}
$otp = credentialOtpSeed($totp);
if ($otp === false) {
$bad_otp_count++;
$otp = '';
}
$name_sql = escapeSql($name);
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM credentials WHERE credential_name = '$name_sql' AND credential_client_id = $client_id"))) {
$duplicate_count++;
continue;
}
mysqli_query($mysqli, "INSERT INTO credentials SET credential_name = '$name_sql', credential_description = '" . escapeSql($description) . "', credential_uri = '" . escapeSql($uri) . "',
credential_username = '" . escapeSql(encryptCredentialEntry($username)) . "', credential_password = '" . escapeSql(encryptCredentialEntry($password)) . "',
credential_otp_secret = '" . escapeSql($otp) . "', credential_password_changed_at = NOW(), credential_client_id = $client_id");
$row_count++;
}
fclose($file);
logAudit("Credential", "Import", "$session_name imported $row_count credential(s) via CSV file. $duplicate_count duplicate(s) found and not imported, $too_long_count row(s) skipped for over-length fields", $client_id);
flashAlert("<strong>$row_count</strong> credential(s) imported, <strong>$duplicate_count</strong> duplicate(s) detected and not imported, <strong>$too_long_count</strong> row(s) skipped for over-length fields" . ($bad_otp_count ? ", <strong>$bad_otp_count</strong> 2FA secret(s) left off - they were not secrets" : ''), 'warning');
redirect();
}
if (isset($_GET['download_credentials_csv_template'])) {

View File

@@ -1,22 +0,0 @@
<?php
// Model of reusable variables for client credentials - not to be confused with the ITFLow login process
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
// The form maxlength is client-side only - a hand-rolled POST gets here without it
if ($credential_field_too_long = checkCredentialLengths($_POST)) {
flashAlert("Credential <strong>$credential_field_too_long</strong> is too long to store", 'error');
redirect();
exit;
}
$name = escapeSql($_POST['name']);
$description = escapeSql($_POST['description']);
$uri = escapeSql($_POST['uri']);
$uri_2 = escapeSql($_POST['uri_2']);
$username = encryptCredentialEntry(trim($_POST['username']));
$password = encryptCredentialEntry(trim($_POST['password']));
$otp_secret = escapeSql($_POST['otp_secret']);
$note = escapeSql($_POST['note']);
$favorite = intval($_POST['favorite'] ?? 0);
$contact_id = intval($_POST['contact'] ?? 0);
$asset_id = intval($_POST['asset'] ?? 0);

View File

@@ -60,7 +60,8 @@ if (isset($_POST['add_service'])) {
if (isset($_POST['credentials'])) {
foreach($_POST['credentials'] as $credential_id) {
$credential_id = intval($credential_id);
mysqli_query($mysqli, "INSERT INTO service_credentials SET service_id = $service_id, credential_id = $credential_id");
// Only the client's own credentials
mysqli_query($mysqli, "INSERT INTO service_credentials (service_id, credential_id) SELECT $service_id, credential_id FROM credentials WHERE credential_id = $credential_id AND credential_client_id = $client_id");
}
}
@@ -148,7 +149,8 @@ if (isset($_POST['edit_service'])) {
if (isset($_POST['credentials'])) {
foreach($_POST['credentials'] as $credential_id) {
$credential_id = intval($credential_id);
mysqli_query($mysqli, "INSERT INTO service_credentials SET service_id = $service_id, credential_id = $credential_id");
// Only the client's own credentials
mysqli_query($mysqli, "INSERT INTO service_credentials (service_id, credential_id) SELECT $service_id, credential_id FROM credentials WHERE credential_id = $credential_id AND credential_client_id = $client_id");
}
}

View File

@@ -1,73 +1,128 @@
<?php
/*
* Credential rotation - every client login whose password hasn't changed in
* a while (90 days unless another span is picked), oldest first, with how
* many each client has. Archived credentials are left out; ones with no
* change date recorded count as due. Each opens on its client's credentials
* page, where it can be changed (credentials.php?open=ID).
*/
require_once "includes/inc_all_reports.php";
enforceUserPermission('module_credential');
// TODO: Default to 90 but allow input field to change this
if (isset($_GET['days'])) {
$days = intval($_GET['days']);
} else {
$days = 90;
$day_options = [30 => '30 days', 60 => '60 days', 90 => '90 days', 180 => '6 months', 365 => 'A year'];
$days = intval($_GET['days'] ?? CREDENTIAL_ROTATE_DAYS);
if (!isset($day_options[$days])) {
$days = CREDENTIAL_ROTATE_DAYS;
}
$passwords_not_rotated_sql = mysqli_query($mysqli,
"SELECT credential_id, credential_name, credential_description, credential_password_changed_at, credential_client_id, client_id, client_name
$sql = mysqli_query($mysqli,
"SELECT credential_id, credential_name, credential_description, credential_uri, credential_password_changed_at, credential_accessed_at,
credential_client_id, client_name
FROM credentials
LEFT JOIN clients ON credential_client_id = client_id
WHERE DATE(credential_password_changed_at) < DATE_SUB(CURDATE(), INTERVAL $days DAY)
JOIN clients ON credential_client_id = client_id
WHERE credential_archived_at IS NULL AND client_archived_at IS NULL
AND (credential_password_changed_at IS NULL OR credential_password_changed_at < NOW() - INTERVAL $days DAY)
" . clientScopeSql('credential_client_id') . "
ORDER BY client_name"
ORDER BY client_name ASC, credential_password_changed_at IS NOT NULL, credential_password_changed_at ASC, credential_name ASC"
);
$credentials = [];
$by_client = [];
while ($row = mysqli_fetch_assoc($sql)) {
$credentials[] = $row;
$client = intval($row['credential_client_id']);
$by_client[$client] = $by_client[$client] ?? ['name' => $row['client_name'], 'count' => 0, 'year' => 0];
$by_client[$client]['count']++;
$age = credentialAge($row['credential_password_changed_at']);
if (!$age || $age['state'] === 'overdue') {
$by_client[$client]['year']++;
}
}
?>
<div class="card card-dark">
<div class="card-header py-2">
<h3 class="card-title mt-2"><i class="fas fa-fw fa-life-ring me-2"></i>Client credentials not changed/rotated in the last 90 days</h3>
<h3 class="card-title mt-2"><i class="fas fa-fw fa-history me-2"></i>Credentials not changed in <?= strtolower($day_options[$days]) ?></h3>
<div class="card-tools">
<button type="button" class="btn btn-primary d-print-none" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
</div>
</div>
<div class="card-body">
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>Client</th>
<th class="text-end">Credential Name</th>
<th class="text-end">Credential Description</th>
<th class="text-end">Credential Password Last Changed</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($passwords_not_rotated_sql)) {
$credential_id = intval($row['credential_id']);
$credential_name = escapeHtml($row['credential_name']);
$credential_description = escapeHtml($row['credential_description']);
$credential_password_changed = escapeHtml($row['credential_password_changed_at']);
$client_id = intval($row['client_id']);
$client_name = escapeHtml($row['client_name']);
?>
<tr>
<td><?= $client_name ?></td>
<td class="text-end"><?= $credential_name ?></td>
<td class="text-end"><?= $credential_description ?></td>
<td class="text-end"><?= timeAgo($credential_password_changed) . " (" . $credential_password_changed . ")" ?></td>
</tr>
<form class="d-flex flex-wrap align-items-center gap-2 mb-3 d-print-none">
<label class="form-label mb-0" for="rotationDays">Not changed in</label>
<select class="form-select w-auto" id="rotationDays" name="days" onchange="this.form.submit()">
<?php foreach ($day_options as $value => $label) { ?>
<option value="<?= $value ?>" <?= $value === $days ? 'selected' : '' ?>><?= $label ?></option>
<?php } ?>
</select>
<span class="text-body-secondary small ms-sm-2"><?= count($credentials) ?> credential<?= count($credentials) === 1 ? '' : 's' ?> across <?= count($by_client) ?> client<?= count($by_client) === 1 ? '' : 's' ?></span>
</form>
</tbody>
</table>
</div>
<?php if (!$credentials) { ?>
<div class="itflow-asset-empty"><i class="fas fa-check-circle fa-2x mb-2 text-success opacity-75"></i><div>Every password has changed in the last <?= strtolower($day_options[$days]) ?>.</div></div>
<?php } else { ?>
<h6 class="text-body-secondary text-uppercase small fw-semibold">By client</h6>
<div class="table-responsive-sm mb-4">
<table class="table table-sm table-hover align-middle">
<thead class="table-light"><tr><th>Client</th><th class="text-end">Due</th><th class="text-end">Over a year or never</th></tr></thead>
<tbody>
<?php foreach ($by_client as $client_id => $client) { ?>
<tr>
<td><a href="../credentials.php?client_id=<?= $client_id ?>&show=due&sort=credential_password_changed_at&order=ASC"><?= escapeHtml($client['name']) ?></a></td>
<td class="text-end"><?= $client['count'] ?></td>
<td class="text-end"><?= $client['year'] ? '<span class="text-danger fw-semibold">' . $client['year'] . '</span>' : '<span class="text-body-secondary">0</span>' ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<h6 class="text-body-secondary text-uppercase small fw-semibold">Credentials, oldest first</h6>
<div class="table-responsive-sm">
<table class="table table-hover align-middle">
<thead class="table-light text-nowrap">
<tr>
<th>Client</th>
<th>Credential</th>
<th>Password last changed</th>
<th>Last used</th>
</tr>
</thead>
<tbody>
<?php foreach ($credentials as $row) {
$client_id = intval($row['credential_client_id']);
$age = credentialAge($row['credential_password_changed_at']); ?>
<tr>
<td class="text-nowrap"><?= escapeHtml($row['client_name']) ?></td>
<td>
<div class="d-flex align-items-center gap-2">
<?= credentialTile($row, 'sm') ?>
<div class="min-w-0">
<a class="fw-semibold" href="../credentials.php?client_id=<?= $client_id ?>&open=<?= intval($row['credential_id']) ?>"><?= escapeHtml($row['credential_name']) ?></a>
<?php if ($row['credential_description']) { ?><div class="small text-body-secondary"><?= escapeHtml($row['credential_description']) ?></div><?php } ?>
</div>
</div>
</td>
<td class="text-nowrap">
<?php if ($age) { ?>
<?= credentialAgePill($age) ?>
<div class="small text-body-secondary mt-1"><?= escapeHtml($age['date']) ?></div>
<?php } else { ?>
<span class="badge rounded-pill bg-danger-subtle text-danger-emphasis border border-danger-subtle fw-normal">Never recorded</span>
<?php } ?>
</td>
<td class="text-nowrap small text-body-secondary"><?= $row['credential_accessed_at'] ? timeAgo($row['credential_accessed_at']) : '-' ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php } ?>
</div>
</div>

View File

@@ -130,7 +130,8 @@ if (!$vendor || (isset($_GET['client_id']) && $vendor_client_id !== intval($clie
}
}
if ($can_credentials && !$is_ours) {
$logins = linkedRecords('vendor', $vendor_id, 'credential');
// The whole credential, so the password and 2FA code are right there to use
$logins = credentialRows("credential_id IN (SELECT credential_id FROM vendor_credentials WHERE vendor_id = $vendor_id)");
}
// What we spend with one of ours
@@ -276,7 +277,7 @@ if (!$vendor || (isset($_GET['client_id']) && $vendor_client_id !== intval($clie
</a>
<?php } ?>
<?php if ($can_credentials_edit) { ?>
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_add.php?client_id=<?= $client_id ?>&vendor_id=<?= $vendor_id ?>">
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/credential/credential_add.php?client_id=<?= $client_id ?>&vendor_id=<?= $vendor_id ?>">
<i class="fa fa-fw fa-key text-secondary me-2"></i>Portal login
</a>
<?php } ?>
@@ -630,7 +631,7 @@ if (!$vendor || (isset($_GET['client_id']) && $vendor_client_id !== intval($clie
<i class="fas fa-link me-2"></i>Link
</button>
<?php if ($to === 'credential') { ?>
<button type="button" class="btn btn-sm btn-primary ajax-modal" data-modal-url="modals/credential/credential_add.php?client_id=<?= $client_id ?>&vendor_id=<?= $vendor_id ?>">
<button type="button" class="btn btn-sm btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/credential/credential_add.php?client_id=<?= $client_id ?>&vendor_id=<?= $vendor_id ?>">
<i class="fas fa-plus me-2"></i>New Login
</button>
<?php } elseif ($to === 'document') { ?>
@@ -645,7 +646,14 @@ if (!$vendor || (isset($_GET['client_id']) && $vendor_client_id !== intval($clie
</div>
<?php } ?>
</div>
<?php if ($linked) { ?>
<?php if ($linked && $to === 'credential') { ?>
<?= credentialTableHtml($linked, [
'for' => true,
'unlink' => function ($row) use ($unlink_url, $can_link) {
return $can_link ? $unlink_url('credential', $row['credential_id']) : '';
},
]) ?>
<?php } elseif ($linked) { ?>
<ul class="list-unstyled mb-0 itflow-links itflow-license-links">
<?php foreach ($linked as $linked_row) { ?>
<li class="itflow-link-row">

View File

@@ -27,6 +27,9 @@ if (!empty($asset_id)) {
// And take it out of any rack
mysqli_query($mysqli,"DELETE FROM rack_units WHERE unit_asset_id = $asset_id");
// Its logins stay with the client, no longer pointing at it
credentialsForget('asset', $asset_id);
// Logging
logAudit("Asset", "Delete", "$asset_name via API ($api_key_name)", $client_id);
}

View File

@@ -21,6 +21,9 @@ if (!empty($contact_id)) {
if ($delete_sql && !empty($contact_name)) {
$delete_count = mysqli_affected_rows($mysqli);
// Their logins stay with the client, no longer pointing at them
credentialsForget('contact', $contact_id);
// Logging
logAudit("Contact", "Delete", "$contact_name via API ($api_key_name)", $client_id);
}

View File

@@ -13,7 +13,7 @@ $insert_id = false;
if (!empty($api_key_decrypt_password) && !empty($name) && !(empty($password))) {
// Add credential
$insert_sql = mysqli_query($mysqli,"INSERT INTO credentials SET credential_name = '$name', credential_description = '$description', credential_uri = '$uri', credential_uri_2 = '$uri_2', credential_username = '$username', credential_password = '$password', credential_otp_secret = '$otp_secret', credential_note = '$note', credential_favorite = $favorite, credential_contact_id = $contact_id, credential_asset_id = $asset_id, credential_client_id = $client_id");
$insert_sql = mysqli_query($mysqli,"INSERT INTO credentials SET credential_name = '$name', credential_description = '$description', credential_uri = '$uri', credential_uri_2 = '$uri_2', credential_username = '$username', credential_password = '$password', credential_password_changed_at = NOW(), credential_otp_secret = '$otp_secret', credential_note = '$note', credential_favorite = $favorite, credential_contact_id = $contact_id, credential_asset_id = $asset_id, credential_client_id = $client_id");
// Check insert & get insert ID
if ($insert_sql) {

View File

@@ -85,7 +85,9 @@ if (isset($_POST['credential_password'])) {
}
if (isset($_POST['credential_otp_secret'])) {
$otp_secret = escapeSql($_POST['credential_otp_secret']);
// Stored the way the agent side stores it - spaces and dashes out, an otpauth:// link down to its secret
$otp_seed = credentialOtpSeed($_POST['credential_otp_secret']);
$otp_secret = escapeSql($otp_seed === false ? trim((string) $_POST['credential_otp_secret']) : $otp_seed);
} elseif (isset($credential_row) && isset($credential_row['credential_otp_secret'])) {
$otp_secret = mysqli_real_escape_string($mysqli, $credential_row['credential_otp_secret']);
} else {

View File

@@ -21,6 +21,9 @@ if (!empty($credential_id)) {
if ($delete_sql && !empty($credential_name)) {
$delete_count = mysqli_affected_rows($mysqli);
// Any share links still open go with it
mysqli_query($mysqli, "DELETE FROM shared_items WHERE item_type = 'Credential' AND item_related_id = $credential_id");
// Logging
logAudit("Credential", "Delete", "$credential_name via API ($api_key_name)", $client_id, $credential_id);
}

View File

@@ -4602,3 +4602,87 @@ img.itflow-contact-avatar {
.itflow-vendor-email {
max-width: 16rem;
}
/* Credentials - agent/credentials.php, agent/modals/credential/ and every
credential row elsewhere (functions/credential.php, js/credentials.js).
The password is dots until the eye fetches it; the 2FA button counts the
code down and turns red for its last five seconds. */
.itflow-credential-pw {
display: inline-flex;
align-items: center;
gap: .15rem;
white-space: nowrap;
}
.itflow-credential-pw-mask {
letter-spacing: .05em;
color: var(--bs-secondary-color);
}
.itflow-credential-pw-value {
user-select: all;
background: var(--bs-tertiary-bg);
border-radius: var(--bs-border-radius-sm);
padding: 0 .3rem;
}
.itflow-credential-reveal {
border: 0;
background: none;
padding: 0 .3rem;
color: var(--bs-secondary-color);
}
.itflow-credential-reveal:hover {
color: var(--bs-emphasis-color);
}
.itflow-credential-otp {
display: inline-flex;
align-items: center;
gap: .25rem;
border: 1px solid var(--bs-border-color);
border-radius: 50rem;
background: var(--bs-body-bg);
padding: .05rem .55rem;
font-size: .85em;
color: var(--bs-secondary-color);
white-space: nowrap;
}
.itflow-credential-otp:hover {
color: var(--bs-emphasis-color);
border-color: var(--bs-secondary-color);
}
.itflow-credential-otp.is-live {
color: var(--bs-emphasis-color);
font-family: var(--bs-font-monospace);
font-weight: 600;
}
.itflow-credential-otp-time {
font-size: .8em;
font-weight: 400;
color: var(--bs-secondary-color);
}
.itflow-credential-otp.is-ending .itflow-credential-otp-time {
color: var(--bs-danger);
}
.itflow-credential-user {
max-width: 14rem;
display: inline-block;
vertical-align: bottom;
}
.itflow-credential-dl dd {
min-height: 1.5rem;
}
.itflow-credential-note {
white-space: normal;
max-height: 10rem;
overflow-y: auto;
padding: .5rem .75rem;
background: var(--bs-tertiary-bg);
border-radius: var(--bs-border-radius);
}
/* The list's "For" column - an asset, a contact and the first links, kept to one width */
.itflow-credential-for {
max-width: 15rem;
}
/* Credentials listed on an asset, contact, vendor or license (credentialTableHtml) */
.itflow-credential-name-cell {
min-width: 12rem;
max-width: 22rem;
}

View File

@@ -24,6 +24,7 @@ require_once __DIR__ . '/functions/contact.php';
require_once __DIR__ . '/functions/software.php';
require_once __DIR__ . '/functions/location.php';
require_once __DIR__ . '/functions/vendor.php';
require_once __DIR__ . '/functions/credential.php';
require_once __DIR__ . '/functions/links.php';
require_once __DIR__ . '/functions/auth.php';
require_once __DIR__ . '/functions/logging.php';

View File

@@ -231,8 +231,8 @@ function assetLinkIcon($url) {
}
/**
* $id if that location / contact / vendor / network belongs to the client,
* else 0. The asset handlers run their picks through this so a hand-edited
* $id if that location / contact / vendor / network / asset belongs to the
* client, else 0. The handlers run their picks through this so a hand-edited
* POST can't hang another client's contact or location off an asset.
*/
function assetClientOwnedId($kind, $id, $client_id) {
@@ -243,6 +243,7 @@ function assetClientOwnedId($kind, $id, $client_id) {
'contact' => ['contacts', 'contact_id', 'contact_client_id'],
'vendor' => ['vendors', 'vendor_id', 'vendor_client_id'],
'network' => ['networks', 'network_id', 'network_client_id'],
'asset' => ['assets', 'asset_id', 'asset_client_id'],
];
$id = intval($id);
$client_id = intval($client_id);

View File

@@ -91,6 +91,17 @@ function clientOverviewAttention($client_id, $access, $renewals) {
];
}
if ($access['credentials']) {
// Logins nobody has changed in a while - the same rule as credentials.php?show=due
$items[] = [
'count' => dashboardCount("SELECT COUNT(credential_id) FROM credentials WHERE credential_client_id = $client_id AND credential_archived_at IS NULL
AND (credential_password_changed_at IS NULL OR credential_password_changed_at < NOW() - INTERVAL " . CREDENTIAL_ROTATE_DAYS . " DAY)"),
'label' => 'Passwords due for a change', 'icon' => 'history', 'tone' => 'warning',
'detail' => 'Not changed in ' . CREDENTIAL_ROTATE_DAYS . ' days',
'url' => "/agent/credentials.php?client_id=$client_id&show=due&sort=credential_password_changed_at&order=ASC",
];
}
if ($access['docs'] && $renewals) {
$expired = count(array_filter($renewals['items'], function ($r) { return $r['days'] < 0; }));
$soon = count($renewals['items']) - $expired;
@@ -181,7 +192,7 @@ function clientOverviewFavorites($client_id, $access) {
}
if ($access['credentials']) {
$sql = mysqli_query($mysqli, "SELECT credential_id, credential_name, credential_username, credential_otp_secret, credential_uri
$sql = mysqli_query($mysqli, "SELECT credential_id, credential_name, credential_description, credential_username, credential_otp_secret, credential_uri, credential_password_changed_at
FROM credentials
WHERE credential_client_id = $client_id AND credential_favorite = 1 AND credential_archived_at IS NULL
ORDER BY credential_name");
@@ -358,12 +369,14 @@ function clientOverviewSharedItems($client_id) {
global $mysqli;
$sql = mysqli_query($mysqli, "SELECT item_id, item_type, item_related_id, item_recipient, item_views, item_view_limit, item_expire_at,
COALESCE(credential_name, document_name, file_name) AS item_name, file_ext
COALESCE(credential_name, document_name, file_name) AS item_name, file_ext, credential_uri, credential_description
FROM shared_items
LEFT JOIN credentials ON item_type = 'Credential' AND credential_id = item_related_id AND credential_client_id = $client_id
LEFT JOIN documents ON item_type = 'Document' AND document_id = item_related_id AND document_client_id = $client_id
LEFT JOIN files ON item_type = 'File' AND file_id = item_related_id AND file_client_id = $client_id
WHERE item_client_id = $client_id AND item_active = 1
-- Still openable: not expired, views not used up (functions/credential.php credentialShares)
AND item_expire_at > NOW() AND (COALESCE(item_view_limit, 0) = 0 OR item_views < item_view_limit)
ORDER BY item_created_at DESC
LIMIT 10");

515
functions/credential.php Normal file
View File

@@ -0,0 +1,515 @@
<?php
/*
* Credentials - a client's logins: the firewall admin, the Microsoft 365
* break-glass account, the registrar, the Wi-Fi key.
*
* Usernames and passwords are encrypted with the vault key that opens with
* the agent's session (functions/security.php); nothing here changes that.
* Passwords and 2FA codes are only ever fetched when asked for, through
* agent/ajax.php (get_credential_via_id, get_totp_token_via_id), which check
* the module and the client and log the view - the HTML these helpers draw
* carries the credential id, never the secret.
*
* A credential belongs to one asset and/or one contact (columns on the
* credential), and is linked to vendors and licenses through link tables
* (functions/links.php) and to services (service_credentials).
*/
/** How long a password can go unchanged before it is called stale - the same 90 days the rotation report uses. */
const CREDENTIAL_ROTATE_DAYS = 90;
/** Changed within this many days is fresh; between this and a year, due; over a year, overdue. */
const CREDENTIAL_OVERDUE_DAYS = 365;
/** May this agent do this with credentials? 1 is to see them (and reveal, copy and share), 2 to change them, 3 to delete them. */
function credentialCan($level) {
return lookupUserPermission('module_credential') >= $level;
}
/** One credential by id with its client, contact and asset - raw, or null. */
function credentialRow($credential_id) {
global $mysqli;
$credential_id = intval($credential_id);
if (!$credential_id) {
return null;
}
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT credentials.*, client_name,
contact_id, contact_name, contact_title, contact_photo, contact_archived_at,
asset_id, asset_name, asset_type, asset_archived_at
FROM credentials
LEFT JOIN clients ON client_id = credential_client_id
LEFT JOIN contacts ON contact_id = credential_contact_id AND contact_client_id = credential_client_id
LEFT JOIN assets ON asset_id = credential_asset_id AND asset_client_id = credential_client_id
WHERE credential_id = $credential_id
LIMIT 1"));
return $row ?: null;
}
/**
* What kind of login it is, from where it opens and what it is called - an
* icon and a tone for its tile: an admin account, Wi-Fi, a remote desktop,
* a shell, a database, a mailbox, a web console, or a plain key.
*/
function credentialKind($row) {
$uri = strtolower(trim((string) ($row['credential_uri'] ?? '')));
$text = strtolower(($row['credential_name'] ?? '') . ' ' . ($row['credential_description'] ?? ''));
$kinds = [
['/wi-?fi|wireless|ssid|psk/', '', 'fa-wifi', 'wireless'],
['/vpn/', '', 'fa-shield-alt', 'firewall'],
['/\b(admin|administrator|root|break ?glass|domain admin)\b/', '', 'fa-user-shield', 'firewall'],
['/database|\bsql\b|mysql|postgres/', '', 'fa-database', 'virtual'],
['/', '#^(rdp|vnc|rustdesk|anydesk|splashtop|connectwise)://#', 'fa-desktop', 'workstation'],
['/', '#^(ssh|telnet|sftp)://#', 'fa-terminal', 'server'],
['/', '#^(smb|file|dav|webdav|ftp|ftps)://#', 'fa-folder-open', 'peripheral'],
['/\b(mail|email|mailbox|365|exchange|workspace)\b/', '', 'fa-envelope', 'phone'],
['/', '#^https?://#', 'fa-globe', 'network'],
];
foreach ($kinds as [$name_match, $uri_match, $icon, $tone]) {
if ($uri_match !== '' && preg_match($uri_match, $uri)) {
return ['icon' => $icon, 'tone' => $tone];
}
if ($uri_match === '' && $name_match !== '/' && preg_match($name_match, $text)) {
return ['icon' => $icon, 'tone' => $tone];
}
}
return ['icon' => 'fa-key', 'tone' => 'other'];
}
/** The credential's tile - its kind's icon on its tone. $size '' | 'sm' | 'lg'. */
function credentialTile($row, $size = '') {
$kind = credentialKind($row);
$size_class = in_array($size, ['sm', 'lg'], true) ? " itflow-asset-icon-$size" : '';
return '<span class="itflow-asset-icon' . $size_class . ' itflow-asset-tone-' . $kind['tone'] . '" aria-hidden="true"><i class="fas fa-fw ' . $kind['icon'] . '"></i></span>';
}
/**
* How old the password is: 'fresh' (changed in the last 90 days), 'due'
* (90 days to a year) or 'overdue' (over a year), with the days and a line
* to show. Null when it has never been recorded.
*/
function credentialAge($changed_at) {
$changed_at = trim((string) $changed_at);
if ($changed_at === '' || strpos($changed_at, '0000-00-00') === 0) {
return null;
}
$changed = strtotime($changed_at);
if (!$changed) {
return null;
}
$days = max(0, intval(floor((time() - $changed) / 86400)));
if ($days >= CREDENTIAL_OVERDUE_DAYS) {
$state = 'overdue';
$tone = 'danger';
} elseif ($days >= CREDENTIAL_ROTATE_DAYS) {
$state = 'due';
$tone = 'warning';
} else {
$state = 'fresh';
$tone = 'success';
}
$text = $days === 0 ? 'Changed today' : ($days === 1 ? 'Changed yesterday' : ($days < 60 ? "Changed $days days ago" : 'Changed ' . timeAgo(date('Y-m-d', $changed))));
return ['state' => $state, 'tone' => $tone, 'days' => $days, 'text' => $text, 'date' => date('Y-m-d', $changed)];
}
/** The age as a soft pill - green, amber when due for rotation, red when overdue. '' when unknown. */
function credentialAgePill($age, $short = false) {
if (!$age) {
return '';
}
$tone = $age['tone'];
$label = $short ? ($age['days'] < 60 ? $age['days'] . 'd' : ($age['days'] < 730 ? round($age['days'] / 30) . 'mo' : round($age['days'] / 365) . 'y')) : $age['text'];
$title = $age['text'] . ($age['state'] === 'fresh' ? '' : ' - due for rotation');
return '<span class="badge rounded-pill bg-' . $tone . '-subtle text-' . $tone . '-emphasis border border-' . $tone . '-subtle fw-normal" title="' . escapeHtml($title) . '">'
. '<i class="fas fa-' . ($age['state'] === 'fresh' ? 'check' : 'history') . ' me-1"></i>' . escapeHtml($label) . '</span>';
}
/**
* A 2FA seed as it is stored - the base32 secret, uppercase, without spaces
* or dashes - from what was pasted: the secret as an app shows it ("abcd efgh
* ...") or a whole otpauth:// link from the QR code. '' for nothing, false
* when it is not a seed.
*/
function credentialOtpSeed($input) {
$input = trim((string) $input);
if ($input === '') {
return '';
}
if (stripos($input, 'otpauth://') === 0) {
$query = [];
parse_str((string) parse_url($input, PHP_URL_QUERY), $query);
$input = (string) ($query['secret'] ?? '');
}
$seed = strtoupper(preg_replace('/[\s\-]+/', '', $input));
$seed = rtrim($seed, '=');
if ($seed === '' || !preg_match('/^[A-Z2-7]+$/', $seed) || strlen($seed) < 16) {
return false;
}
return $seed;
}
/**
* The credential fields a New / Edit form posts, as a SQL SET list - the
* username and password encrypted, the 2FA seed tidied, only the client's
* own contact and asset. Null with $error set when it cannot be saved: no
* name, a field too long, a 2FA seed that is not one, or a vault that did
* not open with this session (encrypting would otherwise write nothing over
* the password).
*/
function credentialFormSet($post, $client_id, &$error = '') {
$error = '';
if (trim((string) ($post['name'] ?? '')) === '') {
$error = 'A credential needs a name.';
return null;
}
if ($too_long = checkCredentialLengths($post)) {
$error = "The $too_long is too long to store.";
return null;
}
$otp = credentialOtpSeed($post['otp_secret'] ?? '');
if ($otp === false) {
$error = "That 2FA secret is not one - paste the key the site shows under \"can't scan the code\", or the otpauth:// link.";
return null;
}
$username = encryptCredentialEntry(trim((string) ($post['username'] ?? '')));
$password = encryptCredentialEntry(trim((string) ($post['password'] ?? '')));
if ($username === false || $password === false) {
$error = 'Your vault session has expired, so the login could not be encrypted - sign out and back in, then try again.';
return null;
}
$text = function ($field, $length) use ($post) {
return "'" . escapeSql(mb_substr(trim((string) ($post[$field] ?? '')), 0, $length)) . "'";
};
$fields = [
'credential_name' => $text('name', 200),
'credential_description' => $text('description', 500),
'credential_uri' => $text('uri', 500),
'credential_uri_2' => $text('uri_2', 500),
'credential_username' => "'" . escapeSql($username) . "'",
'credential_password' => "'" . escapeSql($password) . "'",
'credential_otp_secret' => "'" . escapeSql($otp) . "'",
'credential_note' => "'" . escapeSql(trim((string) ($post['note'] ?? ''))) . "'",
'credential_favorite' => intval($post['favorite'] ?? 0) ? 1 : 0,
'credential_contact_id' => assetClientOwnedId('contact', $post['contact'] ?? 0, $client_id),
'credential_asset_id' => assetClientOwnedId('asset', $post['asset'] ?? 0, $client_id),
];
$set = [];
foreach ($fields as $column => $value) {
$set[] = "$column = $value";
}
return implode(', ', $set);
}
/** Replace a credential's tags with these - credential tags (type 4) only. */
function credentialSetTags($credential_id, $tag_ids) {
global $mysqli;
$credential_id = intval($credential_id);
mysqli_query($mysqli, "DELETE FROM credential_tags WHERE credential_id = $credential_id");
$tag_ids = array_values(array_unique(array_filter(array_map('intval', (array) $tag_ids))));
if (!$tag_ids) {
return;
}
mysqli_query($mysqli, "INSERT IGNORE INTO credential_tags (credential_id, tag_id)
SELECT $credential_id, tag_id FROM tags WHERE tag_type = 4 AND tag_id IN (" . implode(',', $tag_ids) . ")");
}
/** The username as stored, decrypted - '' when there is none or the vault is closed. */
function credentialUsername($row) {
$ciphertext = (string) ($row['credential_username'] ?? '');
if ($ciphertext === '') {
return '';
}
$plain = decryptCredentialEntry($ciphertext);
return $plain === false ? '' : (string) $plain;
}
/** The username with its copy button, or a dash. Raw in. */
function credentialUsernameHtml($username, $empty = '-') {
$username = escapeHtml($username);
if ($username === '') {
return '<span class="text-body-secondary">' . $empty . '</span>';
}
return '<span class="itflow-credential-user text-truncate">' . $username . '</span><button type="button" class="itflow-copy clipboardjs" title="Copy username" data-clipboard-text="' . $username . '"><i class="far fa-copy"></i></button>';
}
/**
* The password as dots, with an eye that fetches and shows it for a little
* while and a copy button that fetches and copies it - both logged as a view
* by agent/ajax.php. Nothing secret is in the page until asked for.
*/
function credentialPasswordHtml($credential_id) {
$credential_id = intval($credential_id);
// Copying is the point here, so its copy button shows all the time (.itflow-copy-always)
return '<span class="itflow-credential-pw itflow-copy-always" data-credential-id="' . $credential_id . '">'
. '<span class="itflow-credential-pw-mask" aria-hidden="true">&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;</span>'
. '<span class="itflow-credential-pw-value font-monospace" hidden></span>'
. '<button type="button" class="itflow-credential-reveal" title="Show password" aria-label="Show password" aria-pressed="false"><i class="fas fa-eye"></i></button>'
. '<button type="button" class="itflow-copy itflow-credential-copy" title="Copy password"><i class="far fa-copy"></i></button>'
. '</span>';
}
/**
* The current 2FA code, fetched when clicked, with how long it has left - it
* follows on to the next code while it is on show, and a second click
* copies it. '' when the credential has no 2FA.
*/
function credentialOtpHtml($credential_id, $has_otp) {
if (!$has_otp) {
return '';
}
$credential_id = intval($credential_id);
return '<button type="button" class="itflow-credential-otp" data-credential-otp="' . $credential_id . '" title="Show the 2FA code">'
. '<i class="far fa-clock me-1"></i><span class="itflow-credential-otp-code">2FA</span><span class="itflow-credential-otp-time"></span></button>';
}
/** Where the login is used - the link, opening in a new tab, and a copy button. '' without one. Raw in. */
function credentialUriHtml($uri, $max = 34) {
$uri = trim((string) $uri);
if ($uri === '') {
return '';
}
$href = escapeUrl($uri);
$label = escapeHtml(truncate(preg_replace('#^https?://#i', '', $uri), $max));
return '<a href="' . $href . '" target="_blank" rel="noopener noreferrer" title="' . escapeHtml($uri) . '">' . $label . '<i class="fas fa-external-link-alt ms-1 small"></i></a>'
. '<button type="button" class="itflow-copy clipboardjs" title="Copy link" data-clipboard-text="' . escapeHtml($uri) . '"><i class="far fa-copy"></i></button>';
}
/** A credential in a picker - its kind's icon and a quieter line under it (functions/format.php selectOptionData). */
function selectOptionCredential($row, $description = '') {
return selectOptionData(['icon' => 'fas ' . credentialKind($row)['icon'], 'description' => $description, 'keywords' => $row['credential_uri'] ?? '']);
}
/**
* A credential wherever a page mentions one: its tile and its name, opening
* its quick look. 'class' goes on the link; 'archived' strikes it through.
*/
function credentialLink($row, $options = []) {
$credential_id = intval($row['credential_id'] ?? $row['id'] ?? 0);
$name = escapeHtml($row['credential_name'] ?? $row['name'] ?? '');
$archived = !empty($options['archived']);
$class = trim('text-truncate ' . ($options['class'] ?? '') . ($archived ? ' text-decoration-line-through text-body-secondary' : ''));
return '<span class="itflow-contact-ref">' . credentialTile($row, 'sm')
. "<a class=\"ajax-modal $class\" href=\"#\" data-modal-url=\"modals/credential/credential.php?id=$credential_id\">$name</a></span>";
}
/**
* Credentials to list somewhere - an asset's, a contact's, a vendor's or a
* license's - each with its client, contact and asset like credentialRow(),
* starred first then by name, keyed by id. $where is SQL the caller built
* from intval'd ids. Archived ones are left out unless asked for.
*/
function credentialRows($where, $include_archived = false) {
global $mysqli;
$sql = mysqli_query($mysqli, "SELECT credentials.*, client_name,
contact_id, contact_name, contact_title, contact_photo, contact_archived_at,
asset_id, asset_name, asset_type, asset_archived_at
FROM credentials
LEFT JOIN clients ON client_id = credential_client_id
LEFT JOIN contacts ON contact_id = credential_contact_id AND contact_client_id = credential_client_id
LEFT JOIN assets ON asset_id = credential_asset_id AND asset_client_id = credential_client_id
WHERE ($where)" . ($include_archived ? '' : ' AND credential_archived_at IS NULL') . "
ORDER BY credential_favorite DESC, credential_name ASC
LIMIT 500");
$rows = [];
while ($sql && $row = mysqli_fetch_assoc($sql)) {
$rows[intval($row['credential_id'])] = $row;
}
return $rows;
}
/** The asset and contact a credential belongs to, each as a small link - HTML pieces, maybe none. */
function credentialOwnersHtml($row) {
$pieces = [];
if (!empty($row['asset_id'])) {
$pieces[] = '<span class="itflow-contact-ref"><span class="itflow-asset-icon itflow-asset-icon-sm itflow-vendor-tile-xs itflow-asset-tone-' . assetTypeTone($row['asset_type']) . '" aria-hidden="true"><i class="fas fa-fw fa-' . getAssetIcon($row['asset_type']) . '"></i></span>'
. '<a class="ajax-modal text-truncate" href="#" data-modal-size="lg" data-modal-url="modals/asset/asset.php?id=' . intval($row['asset_id']) . '">' . escapeHtml($row['asset_name']) . '</a></span>';
}
if (!empty($row['contact_id'])) {
$pieces[] = contactLink(intval($row['credential_client_id']), $row['contact_id'], $row['contact_name'], $row['contact_photo'], ['archived' => !empty($row['contact_archived_at'])]);
}
return $pieces;
}
/**
* Credentials as a table, the same wherever they are listed outside the
* credentials page - an asset's or contact's tab, a vendor's logins, a
* license's: the credential (opening its quick look), the login with the
* password and 2FA code on asking, how old the password is, and the actions.
* Options: 'for' adds the asset and contact it belongs to under its name
* (on a vendor's or license's list, where that differs); 'unlink' is a function
* of the row giving the URL that unlinks it from this page's record ('' for
* none).
*/
function credentialTableHtml(array $rows, array $options = []) {
$can_edit = credentialCan(2);
$can_share = lookupUserPermission('module_support') >= 2;
$show_for = !empty($options['for']);
$unlink = $options['unlink'] ?? null;
$csrf = $_SESSION['csrf_token'] ?? '';
$html = '<div class="table-responsive"><table class="table table-hover align-middle mb-0 itflow-credential-table">'
. '<thead class="text-nowrap table-light"><tr><th>Credential</th><th>Login</th><th>Changed</th><th></th></tr></thead><tbody>';
foreach ($rows as $row) {
$id = intval($row['credential_id']);
$name = escapeHtml($row['credential_name']);
$description = escapeHtml($row['credential_description']);
$archived = !empty($row['credential_archived_at']);
$quick = "modals/credential/credential.php?id=$id";
$has_otp = trim((string) $row['credential_otp_secret']) !== '';
$html .= '<tr><td class="itflow-credential-name-cell"><div class="d-flex align-items-center gap-2">' . credentialTile($row, 'sm') . '<div class="min-w-0">'
. '<a class="fw-semibold text-body ajax-modal" href="#" data-modal-url="' . $quick . '">' . $name . '</a>'
. (intval($row['credential_favorite']) ? '<i class="fas fa-star text-warning small ms-1" title="Starred"></i>' : '')
. ($description !== '' ? '<div class="small text-body-secondary text-truncate itflow-asset-desc" title="' . $description . '">' . $description . '</div>' : '');
$owners = $show_for ? credentialOwnersHtml($row) : [];
if ($owners) {
$html .= '<div class="small d-flex flex-wrap column-gap-3 row-gap-1 mt-1 itflow-credential-owners">' . implode('', $owners) . '</div>';
}
$html .= '</div></div></td>';
$html .= '<td><div class="d-flex align-items-center small"><i class="fas fa-fw fa-user text-body-secondary me-1"></i>' . credentialUsernameHtml(credentialUsername($row)) . '</div>'
. '<div class="d-flex align-items-center flex-wrap gap-2 mt-1 small">' . credentialPasswordHtml($id) . credentialOtpHtml($id, $has_otp) . '</div>';
foreach (array_filter([$row['credential_uri'] ?? '', $row['credential_uri_2'] ?? '']) as $uri) {
$html .= '<div class="small text-nowrap mt-1">' . credentialUriHtml($uri, 34) . '</div>';
}
$html .= '</td>';
$html .= '<td class="text-nowrap">' . (credentialAgePill(credentialAge($row['credential_password_changed_at']), true) ?: '<span class="text-body-secondary">-</span>') . '</td>';
$actions = '<a class="dropdown-item ajax-modal" href="#" data-modal-url="' . $quick . '"><i class="fas fa-fw fa-eye text-secondary me-2"></i>Quick look</a>';
if ($can_edit && !$archived) {
$actions .= '<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/credential/credential_edit.php?id=' . $id . '"><i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit</a>'
. '<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_rotate.php?id=' . $id . '"><i class="fas fa-fw fa-sync-alt text-secondary me-2"></i>Change password</a>';
}
if ($can_share && !$archived) {
$actions .= '<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/credential/credential_share.php?id=' . $id . '"><i class="fas fa-fw fa-share-alt text-secondary me-2"></i>Share</a>';
}
$unlink_url = $unlink ? (string) $unlink($row) : '';
if ($unlink_url !== '' || ($can_edit && !$archived)) {
$actions .= '<div class="dropdown-divider"></div>';
}
if ($unlink_url !== '') {
$actions .= '<a class="dropdown-item" href="' . escapeHtml($unlink_url) . '"><i class="fas fa-fw fa-unlink text-secondary me-2"></i>Unlink</a>';
}
if ($can_edit && !$archived) {
$actions .= '<a class="dropdown-item text-danger confirm-link" href="post.php?archive_credential=' . $id . '&amp;csrf_token=' . escapeHtml($csrf) . '"><i class="fas fa-fw fa-archive me-2"></i>Archive</a>';
}
$html .= '<td class="text-end"><div class="dropdown dropstart"><button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>'
. '<div class="dropdown-menu">' . $actions . '</div></div></td></tr>';
}
return $html . '</tbody></table></div>';
}
/**
* Credentials as a short list for the quick looks (an asset's, a contact's):
* each one's tile and name opening its own quick look, the login with the
* password and 2FA code on asking, and how old the password is. Rows from
* credentialRows().
*/
function credentialListHtml(array $rows) {
$html = '<ul class="list-unstyled mb-0 itflow-links">';
foreach ($rows as $row) {
$link_row = $row + ['id' => $row['credential_id'], 'name' => $row['credential_name']];
$html .= '<li class="itflow-link-row">' . linkRowHtml('credential', $link_row, $row['credential_client_id'])
. credentialAgePill(credentialAge($row['credential_password_changed_at']), true) . '</li>';
}
return $html . '</ul>';
}
/**
* What each credential is linked to beyond its own asset and contact -
* vendors, licenses and services - for the whole page at once:
* [credential_id => [['type', 'id', 'name'], ...]].
*/
function credentialLinks(array $credential_ids) {
global $mysqli;
$credential_ids = array_values(array_unique(array_filter(array_map('intval', $credential_ids))));
$links = array_fill_keys($credential_ids, []);
if (!$credential_ids) {
return $links;
}
$in = implode(',', $credential_ids);
$sources = [
'vendor' => "SELECT l.credential_id, v.vendor_id, v.vendor_name FROM vendor_credentials l JOIN vendors v ON v.vendor_id = l.vendor_id AND v.vendor_archived_at IS NULL WHERE l.credential_id IN ($in) ORDER BY v.vendor_name",
'software' => "SELECT l.credential_id, s.software_id, s.software_name FROM software_credentials l JOIN software s ON s.software_id = l.software_id AND s.software_archived_at IS NULL WHERE l.credential_id IN ($in) ORDER BY s.software_name",
'service' => "SELECT l.credential_id, s.service_id, s.service_name FROM service_credentials l JOIN services s ON s.service_id = l.service_id WHERE l.credential_id IN ($in) ORDER BY s.service_name",
];
foreach ($sources as $type => $query) {
$sql = mysqli_query($mysqli, $query);
while ($row = mysqli_fetch_row($sql)) {
$links[intval($row[0])][] = [$type, intval($row[1]), $row[2]];
}
}
return $links;
}
/** The share links still open for each credential, for the whole page at once: [credential_id => [share rows]]. */
function credentialShares(array $credential_ids) {
global $mysqli;
$credential_ids = array_values(array_unique(array_filter(array_map('intval', $credential_ids))));
$shares = array_fill_keys($credential_ids, []);
if (!$credential_ids) {
return $shares;
}
$sql = mysqli_query($mysqli, "SELECT item_id, item_related_id, item_recipient, item_note, item_views, item_view_limit, item_created_at, item_expire_at
FROM shared_items
WHERE item_type = 'Credential' AND item_active = 1 AND item_expire_at > NOW()
AND (COALESCE(item_view_limit, 0) = 0 OR item_views < item_view_limit)
AND item_related_id IN (" . implode(',', $credential_ids) . ")
ORDER BY item_expire_at ASC");
while ($row = mysqli_fetch_assoc($sql)) {
$shares[intval($row['item_related_id'])][] = $row;
}
return $shares;
}
/**
* Who did what with a credential - its audit log entries (views, 2FA code
* views, edits, rotations, links, shares), newest first.
*/
function credentialHistory($credential_id, $limit = 50) {
global $mysqli;
$credential_id = intval($credential_id);
$limit = max(1, intval($limit));
$sql = mysqli_query($mysqli, "SELECT log_action, log_description, log_created_at, user_name FROM logs
LEFT JOIN users ON user_id = log_user_id
WHERE log_type = 'Credential' AND log_entity_id = $credential_id
ORDER BY log_id DESC LIMIT $limit");
$rows = [];
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
return $rows;
}
/** The last time someone looked at the password or the 2FA code, and who - or null. */
function credentialLastViewed($credential_id) {
global $mysqli;
$credential_id = intval($credential_id);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT log_created_at, user_name FROM logs
LEFT JOIN users ON user_id = log_user_id
WHERE log_type = 'Credential' AND log_entity_id = $credential_id AND log_action IN ('View', 'View TOTP')
ORDER BY log_id DESC LIMIT 1"));
return $row ?: null;
}
/**
* An asset or contact is going for good - its credentials stay, for no asset
* or no contact, rather than pointing at an id that no longer exists.
*/
function credentialsForget($kind, $id) {
global $mysqli;
$column = ['asset' => 'credential_asset_id', 'contact' => 'credential_contact_id'][$kind] ?? null;
$id = intval($id);
if (!$column || !$id) {
return;
}
mysqli_query($mysqli, "UPDATE credentials SET $column = 0 WHERE $column = $id");
}
/** Deleting a credential for good - its open share links go with it. Links and tags cascade. */
function credentialDeleteForGood($credential_id) {
global $mysqli;
$credential_id = intval($credential_id);
mysqli_query($mysqli, "DELETE FROM shared_items WHERE item_type = 'Credential' AND item_related_id = $credential_id");
mysqli_query($mysqli, "DELETE FROM credentials WHERE credential_id = $credential_id");
}

View File

@@ -198,6 +198,13 @@ function getExportColumns($export_type) {
'credential_password' => ['label' => 'Password'],
'credential_otp_secret' => ['label' => 'TOTP'],
'credential_uri' => ['label' => 'URI', 'weight' => 2],
'credential_uri_2' => ['label' => 'URI 2', 'default' => false],
'credential_tags' => ['label' => 'Tags', 'default' => false],
'asset_name' => ['label' => 'Asset', 'default' => false],
'contact_name' => ['label' => 'Contact', 'default' => false],
'credential_password_changed' => ['label' => 'Password Changed', 'default' => false],
'credential_note' => ['label' => 'Notes', 'weight' => 3, 'default' => false],
'client_name' => ['label' => 'Client', 'default' => false],
],
// seats_used, assigned_to_assets / assigned_to_contacts and software_keys_list are built by the handler's query

View File

@@ -112,7 +112,7 @@ function linkDisplayColumns($type) {
'document' => 'document_description, document_updated_at, document_created_at',
'file' => 'file_ext, file_size, file_mime_type, file_description',
'software' => 'software_type, software_version, software_license_type, software_seats, software_expire, ' . softwareSeatsUsedSql('t.software_id') . ' AS seats_used',
'credential' => 'credential_description, credential_uri, credential_username, credential_otp_secret, credential_favorite',
'credential' => 'credential_description, credential_uri, credential_username, credential_otp_secret, credential_favorite, credential_password_changed_at',
'vendor' => 'vendor_description, vendor_account_number, vendor_phone, vendor_phone_country_code, vendor_extension',
'location' => 'location_address, location_city, location_state, location_zip, location_primary, location_photo, location_client_id',
][$type] ?? '';
@@ -288,6 +288,7 @@ function linkRemoveAll($type, $id) {
function linkRowHtml($to, $row, $client_id) {
$id = intval($row['id']);
$name = escapeHtml($row['name']);
$extra = '';
switch ($to) {
case 'asset':
$lead = '<span class="itflow-asset-icon itflow-asset-icon-sm itflow-asset-tone-' . assetTypeTone($row['asset_type']) . '" aria-hidden="true"><i class="fas fa-fw fa-' . getAssetIcon($row['asset_type']) . '"></i></span>';
@@ -321,9 +322,17 @@ function linkRowHtml($to, $row, $client_id) {
]));
break;
case 'credential':
$lead = '<span class="itflow-link-icon" aria-hidden="true"><i class="fas fa-fw fa-key"></i></span>';
$link = "<a class=\"ajax-modal text-truncate\" href=\"#\" data-modal-url=\"modals/credential/credential_edit.php?id=$id\">$name</a>";
$credential = ['credential_name' => $row['name'], 'credential_description' => $row['credential_description'] ?? '', 'credential_uri' => $row['credential_uri'] ?? '', 'credential_username' => $row['credential_username'] ?? ''];
$lead = credentialTile($credential, 'sm');
$link = "<a class=\"ajax-modal text-truncate\" href=\"#\" data-modal-url=\"modals/credential/credential.php?id=$id\">$name</a>"
. (intval($row['credential_favorite'] ?? 0) ? '<i class="fas fa-star text-warning small ms-1 align-self-center" title="Starred"></i>' : '');
$detail = $row['credential_description'] ?: $row['credential_uri'];
// The login itself - username to copy, the password and 2FA code on asking
$username = credentialUsername($credential);
$extra = '<div class="small d-flex flex-wrap align-items-center column-gap-3 row-gap-1 mt-1">'
. ($username !== '' ? '<span class="d-inline-flex align-items-center min-w-0"><i class="fas fa-fw fa-user text-body-secondary me-1"></i>' . credentialUsernameHtml($username) . '</span>' : '')
. credentialPasswordHtml($id) . credentialOtpHtml($id, trim((string) ($row['credential_otp_secret'] ?? '')) !== '')
. '</div>';
break;
case 'location':
$lead = locationTile($row, 'sm');
@@ -339,7 +348,7 @@ function linkRowHtml($to, $row, $client_id) {
return '';
}
$detail = (string) $detail !== '' ? '<div class="small text-body-secondary text-truncate">' . escapeHtml($detail) . '</div>' : '';
return "$lead<div class=\"min-w-0 flex-grow-1\"><div class=\"d-flex\">$link</div>$detail</div>";
return "$lead<div class=\"min-w-0 flex-grow-1\"><div class=\"d-flex\">$link</div>$detail$extra</div>";
}
/**

View File

@@ -269,7 +269,7 @@ function globalSearchGroups($terms, $deep) {
'select' => 'credential_id, credential_name, credential_description, credential_client_id, client_name',
'from' => 'credentials LEFT JOIN clients ON credential_client_id = client_id',
'where' => "credential_archived_at IS NULL
AND (credential_name LIKE '%$like%' OR credential_description LIKE '%$like%' OR credential_uri LIKE '%$like%')",
AND (credential_name LIKE '%$like%' OR credential_description LIKE '%$like%' OR credential_uri LIKE '%$like%' OR credential_uri_2 LIKE '%$like%')",
'scope' => 'credential_client_id',
'order' => "(credential_name = '$eq') DESC, (credential_name LIKE '$like%') DESC, credential_name",
'list_url' => '/agent/credentials.php?' . http_build_query(['q' => $q]),
@@ -279,7 +279,8 @@ function globalSearchGroups($terms, $deep) {
'title' => $row['credential_name'],
'subtitle' => $row['credential_description'],
'context' => $row['client_name'],
'url' => globalSearchClientUrl('credentials.php', $row['credential_client_id'], ['q' => $row['credential_name']]),
// Straight to its quick look on the client's credentials page
'url' => globalSearchClientUrl('credentials.php', $row['credential_client_id'], ['open' => intval($row['credential_id'])]),
];
},
];

View File

@@ -146,14 +146,15 @@ if (isset($_GET['get_share_totp_token'])) {
exit(json_encode(['error' => 'invalid']));
}
$totp_secret = mysqli_fetch_assoc($credential_sql)['credential_otp_secret'];
// Tidied the same way as the agent side - seeds saved with spaces or as an otpauth:// link still work
$totp_secret = credentialOtpSeed(mysqli_fetch_assoc($credential_sql)['credential_otp_secret']);
if (empty($totp_secret)) {
exit(json_encode(['error' => 'invalid']));
}
echo json_encode([
'token' => TokenAuth6238::getTokenCode(strtoupper($totp_secret)),
'token' => TokenAuth6238::getTokenCode($totp_secret),
'expires_in' => 30 - (time() % 30)
]);
exit;

View File

@@ -77,6 +77,7 @@
<script src="/libs/sweetalert2/js/sweetalert2.min.js"></script>
<script src="/js/autocomplete.js"></script>
<script src="/js/app.js"></script>
<script src="/js/credentials.js"></script>
<script src="/js/tag_picker.js"></script>
<script src="/js/quick_pick.js"></script>
<script src="/js/ajax_modal.js"></script>

155
js/credentials.js Normal file
View File

@@ -0,0 +1,155 @@
/*
* Credentials - the password, copy and 2FA buttons functions/credential.php
* draws wherever a credential is listed (the credentials list, assets,
* contacts, vendors, licenses, the quick looks). Bound once on document, so
* they work in ajax modals too.
*
* Nothing secret is in the page until it is asked for: the eye and the copy
* button fetch the password from agent/ajax.php (get_credential_via_id), the
* 2FA button fetches the current code (get_totp_token_via_id) - both check the
* module and the client and log the view.
*/
(function () {
// How long a shown password stays on screen, and how many codes in a row the 2FA button follows on to
var SHOW_FOR = 30000;
var OTP_ROUNDS = 6;
function fetchCredential(id, done) {
itflowGet('/agent/ajax.php', { get_credential_via_id: 'true', credential_id: id }, function (data) {
var credential = null;
try {
credential = JSON.parse(data);
} catch (e) {}
if (credential) {
done(credential);
}
});
}
function hidePassword(box) {
var value = box.querySelector('.itflow-credential-pw-value');
var mask = box.querySelector('.itflow-credential-pw-mask');
var button = box.querySelector('.itflow-credential-reveal');
clearTimeout(box.itflowHide);
value.textContent = '';
value.hidden = true;
mask.hidden = false;
if (button) {
button.querySelector('i').className = 'fas fa-eye';
button.setAttribute('aria-pressed', 'false');
button.title = 'Show password';
}
}
// The eye: show the password for a while, or hide it again
itflowBindOnce('itflowCredentialReveal', 'click', '.itflow-credential-reveal', function (e) {
e.preventDefault();
var button = this;
var box = button.closest('.itflow-credential-pw');
if (!box) {
return;
}
var value = box.querySelector('.itflow-credential-pw-value');
if (!value.hidden) {
hidePassword(box);
return;
}
fetchCredential(box.dataset.credentialId, function (credential) {
value.textContent = credential.password || '';
value.hidden = false;
box.querySelector('.itflow-credential-pw-mask').hidden = true;
button.querySelector('i').className = 'fas fa-eye-slash';
button.setAttribute('aria-pressed', 'true');
button.title = 'Hide password';
clearTimeout(box.itflowHide);
box.itflowHide = setTimeout(function () {
hidePassword(box);
}, SHOW_FOR);
});
});
// Copy: fetch the password and copy it, without showing it
itflowBindOnce('itflowCredentialCopy', 'click', '.itflow-credential-copy', function (e) {
e.preventDefault();
var button = this;
var box = button.closest('[data-credential-id]');
if (!box) {
return;
}
fetchCredential(box.dataset.credentialId, function (credential) {
itflowCopyText(credential.password || '', button).then(
function () { flashTooltip(button, 'Copied!'); },
function () { flashTooltip(button, 'Failed!'); }
);
});
});
function resetOtp(button) {
clearInterval(button.itflowTimer);
delete button.dataset.code;
button.classList.remove('is-live', 'is-ending');
button.querySelector('.itflow-credential-otp-code').textContent = '2FA';
button.querySelector('.itflow-credential-otp-time').textContent = '';
button.title = 'Show the 2FA code';
}
// 2FA: the first click fetches the code and counts it down, following on to
// the next one for a few minutes; clicking it while it shows copies it
itflowBindOnce('itflowCredentialOtp', 'click', '.itflow-credential-otp', function (e) {
e.preventDefault();
var button = this;
if (button.dataset.code) {
itflowCopyText(button.dataset.code, button).then(
function () { flashTooltip(button, 'Copied!'); },
function () { flashTooltip(button, 'Failed!'); }
);
return;
}
var codeEl = button.querySelector('.itflow-credential-otp-code');
var timeEl = button.querySelector('.itflow-credential-otp-time');
var rounds = 0;
var last = 31;
function load() {
itflowGet('/agent/ajax.php', { get_totp_token_via_id: 'true', credential_id: button.dataset.credentialOtp }, function (data) {
var code = '';
try {
code = String(JSON.parse(data) || '');
} catch (err) {}
if (!/^[0-9]{6,8}$/.test(code)) {
resetOtp(button);
codeEl.textContent = 'No code';
return;
}
button.dataset.code = code;
codeEl.textContent = code.length === 6 ? code.slice(0, 3) + ' ' + code.slice(3) : code;
button.classList.add('is-live');
button.title = 'Click to copy the code';
});
}
function tick() {
var left = 30 - Math.floor(Date.now() / 1000) % 30;
timeEl.textContent = left + 's';
button.classList.toggle('is-ending', left <= 5);
// A new period - the next code, for a few rounds, then back to the button
if (left > last) {
rounds++;
if (rounds >= OTP_ROUNDS || !document.body.contains(button)) {
resetOtp(button);
return;
}
load();
}
last = left;
}
clearInterval(button.itflowTimer);
load();
tick();
button.itflowTimer = setInterval(tick, 1000);
});
})();

View File

@@ -32,11 +32,20 @@ if (isset($_GET['deactivate_shared_item'])) {
enforceClientAccess();
// A credential's link is turned off by someone who may see credentials
if ($item_type === 'Credential') {
enforceUserPermission('module_credential');
}
// Deactivate item id
mysqli_query($mysqli, "DELETE FROM shared_items WHERE item_id = $item_id");
// Logging
logAudit("Sharing", "Delete", "$session_name deactivated shared $item_type link Item ID: $item_related_id. Share ID $item_id", $client_id, $item_id);
if ($item_type === 'Credential') {
// In the credential's own history too
logAudit("Credential", "Unshare", "$session_name turned off a share link", $client_id, $item_related_id);
}
$_SESSION['alert_message'] = "Share Link deactivated";