mirror of
https://github.com/itflow-org/itflow
synced 2026-12-01 00:29:02 +00:00
Certificates: Check now connects to the host and saves what it serves - issuer, issued and expiry dates, names covered, SHA-256 fingerprint and the PEM - with the result (OK, name mismatch, untrusted, expired or unreachable) and when it ran, and a check that reaches nothing keeps the certificate on file; New/Edit form split into tabs (Certificate, Paste or by hand, Notes) with a Check button that shows what the host serves before saving, the host tidied from a pasted web address, the name defaulting to the host, the domain picked from the host and limited to the client's own, and a PEM paste or issuer and expiry by hand for hosts ITFlow can't reach; new certificate quick look with the check result and what to do about it, names covered, fingerprint copy, PEM copy and .crt download, domain, services, notes and history; certificates list rebuilt with All/Starred/Expiring soon/Expired/Problems/Not checked pills, host and names covered, domain link, issuer filter, last check column, whitelisted sort, ?open= and bulk check/star/archive/restore/delete; short-lived (ACME) certificates only count as expiring soon inside 20 days and skip the 45-day alert; domain and service quick looks link certificates to their quick look (with New certificate from a domain), global search finds certificates by name, host, names covered or fingerprint, client overview gets a Certificate problems box and renewals open the certificate, dashboard links to Expiring soon, client portal shows expiry badges, export adds last check, names covered, fingerprint and more, documentation PDF adds host and last check; certificate refresher now checks hosts daily in a time-boxed batch, writes history and notifies when an OK certificate turns bad; nightly alerts skip archived certificates and open the certificate; API create uses the same form rules and checks the host; demo data adds firewall, remote access and RADIUS certificates with real check results. Fixes the delete audit log using an undefined name, the archive flash type, certificates linking to another client's domain, services linking to another client's certificates, PEM parsing assuming an issuer organisation, and the API create using an undefined variable. DB 2.8.4
This commit is contained in:
50
admin/database_updates/2.8.4.php
Normal file
50
admin/database_updates/2.8.4.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - Database update to version 2.8.4 (from 2.8.3)
|
||||
* Included by admin/database_updates.php - do not access directly
|
||||
*/
|
||||
|
||||
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
|
||||
|
||||
// What a certificate says about itself - when it was issued, the names it
|
||||
// covers and its SHA-256 fingerprint - and what the last check of the
|
||||
// site found (ok, mismatch, untrusted, expired, unreachable) and when
|
||||
mysqli_query($mysqli, "ALTER TABLE `certificates`
|
||||
ADD COLUMN `certificate_issued_at` date DEFAULT NULL AFTER `certificate_issued_by`,
|
||||
ADD COLUMN `certificate_names` text DEFAULT NULL AFTER `certificate_domain`,
|
||||
ADD COLUMN `certificate_fingerprint` varchar(100) DEFAULT NULL AFTER `certificate_public_key`,
|
||||
ADD COLUMN `certificate_check_status` varchar(20) DEFAULT NULL AFTER `certificate_fingerprint`,
|
||||
ADD COLUMN `certificate_checked_at` datetime DEFAULT NULL AFTER `certificate_accessed_at`
|
||||
");
|
||||
|
||||
// Fill those in from the certificates already on file
|
||||
$sql_certificate_update = mysqli_query($mysqli, "SELECT certificate_id, certificate_public_key FROM certificates WHERE certificate_public_key LIKE '%BEGIN CERTIFICATE%'");
|
||||
while ($row_certificate_update = mysqli_fetch_assoc($sql_certificate_update)) {
|
||||
$parsed_certificate_update = @openssl_x509_parse($row_certificate_update['certificate_public_key']);
|
||||
if (!$parsed_certificate_update) {
|
||||
continue;
|
||||
}
|
||||
$names_certificate_update = [];
|
||||
foreach (explode(',', (string) ($parsed_certificate_update['extensions']['subjectAltName'] ?? '')) as $alt_name) {
|
||||
$alt_name = trim($alt_name);
|
||||
if (stripos($alt_name, 'DNS:') === 0) {
|
||||
$names_certificate_update[] = strtolower(substr($alt_name, 4));
|
||||
} elseif (stripos($alt_name, 'IP Address:') === 0) {
|
||||
$names_certificate_update[] = strtolower(trim(substr($alt_name, 11)));
|
||||
}
|
||||
}
|
||||
if (!$names_certificate_update && !empty($parsed_certificate_update['subject']['CN'])) {
|
||||
$names_certificate_update[] = strtolower(is_array($parsed_certificate_update['subject']['CN']) ? end($parsed_certificate_update['subject']['CN']) : $parsed_certificate_update['subject']['CN']);
|
||||
}
|
||||
$fingerprint_certificate_update = @openssl_x509_fingerprint($row_certificate_update['certificate_public_key'], 'sha256');
|
||||
mysqli_query($mysqli, "UPDATE certificates SET
|
||||
certificate_issued_at = '" . date('Y-m-d', $parsed_certificate_update['validFrom_time_t']) . "',
|
||||
certificate_names = '" . mysqli_real_escape_string($mysqli, implode("\n", array_unique($names_certificate_update))) . "',
|
||||
certificate_fingerprint = '" . mysqli_real_escape_string($mysqli, $fingerprint_certificate_update ? strtoupper(implode(':', str_split($fingerprint_certificate_update, 2))) : '') . "'
|
||||
WHERE certificate_id = " . intval($row_certificate_update['certificate_id']));
|
||||
}
|
||||
|
||||
// A certificate linked to another client's domain, or to one that is gone, is linked to none
|
||||
mysqli_query($mysqli, "UPDATE `certificates` LEFT JOIN `domains` ON `domain_id` = `certificate_domain_id` AND `domain_client_id` = `certificate_client_id`
|
||||
SET `certificate_domain_id` = 0 WHERE `certificate_domain_id` > 0 AND `domain_id` IS NULL");
|
||||
@@ -1340,17 +1340,8 @@ function demoBuildClient($mysqli, $profile, $index, $context, &$counts) {
|
||||
$counts['documentation']++;
|
||||
}
|
||||
|
||||
$certificate_id = starterInsert($mysqli, 'certificates', [
|
||||
'certificate_name' => 'www.' . $profile['domain'],
|
||||
'certificate_description' => $profile['cert_issuer'] === "Let's Encrypt" ? 'Public website certificate, renewed automatically by the reverse proxy' : 'Public website certificate, renewed manually at expiry',
|
||||
'certificate_domain' => 'www.' . $profile['domain'],
|
||||
'certificate_issued_by' => $profile['cert_issuer'],
|
||||
'certificate_expire' => demoDate(-1 * (20 + ($index * 9))),
|
||||
'certificate_domain_id' => $domain_id,
|
||||
'certificate_client_id' => $client_id,
|
||||
'certificate_created_at' => demoMonthDateTime($months, 7, 9, 50),
|
||||
]);
|
||||
$counts['documentation'] += 2;
|
||||
$certificate_id = demoBuildCertificates($mysqli, $profile, $index, $client_id, $domain_id, $months, $counts);
|
||||
$counts['documentation']++;
|
||||
|
||||
// The renewals behind them. Both tables cascade off their parent, so the
|
||||
// client purge takes these with the domain and the certificate.
|
||||
@@ -1368,13 +1359,6 @@ function demoBuildClient($mysqli, $profile, $index, $context, &$counts) {
|
||||
'domain_history_domain_id' => $domain_id,
|
||||
'domain_history_modified_at' => demoMonthDateTime(max(1, min(9, $months)), 6, 15, 40),
|
||||
]);
|
||||
starterInsert($mysqli, 'certificate_history', [
|
||||
'certificate_history_column' => 'certificate_expire',
|
||||
'certificate_history_old_value' => demoMonthDate(3, 20),
|
||||
'certificate_history_new_value' => demoDate(-1 * (20 + ($index * 9))),
|
||||
'certificate_history_certificate_id' => $certificate_id,
|
||||
'certificate_history_modified_at' => demoMonthDateTime(3, 20, 4, 15),
|
||||
]);
|
||||
|
||||
// Credentials - only when the vault actually opened for this session
|
||||
$credential_ids = [];
|
||||
@@ -1624,6 +1608,110 @@ function demoBuildClient($mysqli, $profile, $index, $context, &$counts) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The client's certificates: the one on their website (checked, OK - the
|
||||
* Let's Encrypt ones short-lived, one of them overdue to renew), and for some
|
||||
* clients the firewall's factory self-signed admin certificate, a remote
|
||||
* access portal still serving the certificate for its old name, and a RADIUS
|
||||
* certificate from their own CA that has no host to check. Returns the
|
||||
* website certificate's id, for the services that use it.
|
||||
*/
|
||||
function demoBuildCertificates($mysqli, $profile, $index, $client_id, $domain_id, $months, &$counts) {
|
||||
$domain = $profile['domain'];
|
||||
$fingerprint = function ($seed) {
|
||||
return implode(':', str_split(strtoupper(hash('sha256', 'itflow-demo-' . $seed)), 2));
|
||||
};
|
||||
$short_lived = $profile['cert_issuer'] === "Let's Encrypt";
|
||||
// Let's Encrypt certificates last 90 days and renew with 30 left; one is stuck
|
||||
$expire_days = $short_lived ? ($index % 7 === 4 ? 12 : 31 + ($index * 13) % 58) : 20 + ($index * 9);
|
||||
$expire = demoDate(-1 * $expire_days);
|
||||
$issued = date('Y-m-d', strtotime($expire . ($short_lived ? ' -90 days' : ' -397 days')));
|
||||
|
||||
$website_id = starterInsert($mysqli, 'certificates', [
|
||||
'certificate_name' => 'www.' . $domain,
|
||||
'certificate_description' => $short_lived ? 'Public website certificate, renewed automatically by the reverse proxy' : 'Public website certificate, renewed manually at expiry',
|
||||
'certificate_domain' => 'www.' . $domain,
|
||||
'certificate_names' => 'www.' . $domain . "\n" . $domain,
|
||||
'certificate_issued_by' => $profile['cert_issuer'],
|
||||
'certificate_issued_at' => $issued,
|
||||
'certificate_expire' => $expire,
|
||||
'certificate_fingerprint' => $fingerprint('www.' . $domain . $issued),
|
||||
'certificate_check_status' => 'ok',
|
||||
'certificate_checked_at' => demoDateTime(1 + $index % 3, 3, 30),
|
||||
'certificate_notes' => $short_lived ? 'Issued and renewed by the reverse proxy over HTTP-01 - port 80 has to stay open to it.' : 'Renewed by us at expiry - the CSR is generated on the web server and the key never leaves it.',
|
||||
'certificate_domain_id' => $domain_id,
|
||||
'certificate_client_id' => $client_id,
|
||||
'certificate_created_at' => demoMonthDateTime($months, 7, 9, 50),
|
||||
]);
|
||||
starterInsert($mysqli, 'certificate_history', [
|
||||
'certificate_history_column' => 'certificate_expire',
|
||||
'certificate_history_old_value' => date('Y-m-d', strtotime($expire . ($short_lived ? ' -60 days' : ' -365 days'))),
|
||||
'certificate_history_new_value' => $expire,
|
||||
'certificate_history_certificate_id' => $website_id,
|
||||
'certificate_history_modified_at' => $issued . ' 04:15:00',
|
||||
]);
|
||||
$counts['documentation']++;
|
||||
|
||||
// The firewall's admin page - the factory certificate, which browsers don't trust
|
||||
$gateway = $profile['networks'][0][4] ?? '';
|
||||
if ($index % 3 === 1 && $gateway !== '') {
|
||||
starterInsert($mysqli, 'certificates', [
|
||||
'certificate_name' => 'Firewall admin',
|
||||
'certificate_description' => 'Management page on the LAN - still the factory self-signed certificate',
|
||||
'certificate_domain' => $gateway . ':8443',
|
||||
'certificate_names' => $gateway,
|
||||
'certificate_issued_by' => 'Self-signed (factory)',
|
||||
'certificate_issued_at' => demoDate(365 * 3 + $index * 17),
|
||||
'certificate_expire' => demoDate(-1 * (365 * 7 - $index * 17)),
|
||||
'certificate_fingerprint' => $fingerprint('fw-' . $domain),
|
||||
'certificate_check_status' => 'untrusted',
|
||||
'certificate_checked_at' => demoDateTime(1 + $index % 3, 3, 35),
|
||||
'certificate_notes' => 'Replace with one from the internal CA at the next firmware upgrade, so the browser warning stops training people to click through.',
|
||||
'certificate_client_id' => $client_id,
|
||||
'certificate_created_at' => demoMonthDateTime($months, 7, 10, 10),
|
||||
]);
|
||||
$counts['documentation']++;
|
||||
}
|
||||
|
||||
// A remote access portal renamed in the spring, still serving the old name's certificate
|
||||
if ($index % 4 === 2) {
|
||||
starterInsert($mysqli, 'certificates', [
|
||||
'certificate_name' => 'Remote access portal',
|
||||
'certificate_description' => 'SSL VPN portal for staff working from home',
|
||||
'certificate_domain' => 'remote.' . $domain,
|
||||
'certificate_names' => 'vpn.' . $domain,
|
||||
'certificate_issued_by' => 'Sectigo',
|
||||
'certificate_issued_at' => demoDate(200 + $index),
|
||||
'certificate_expire' => demoDate(-1 * (165 - $index)),
|
||||
'certificate_fingerprint' => $fingerprint('vpn-' . $domain),
|
||||
'certificate_check_status' => 'mismatch',
|
||||
'certificate_checked_at' => demoDateTime(1 + $index % 3, 3, 40),
|
||||
'certificate_notes' => 'The portal moved from vpn. to remote. - the new certificate is bought but not installed yet.',
|
||||
'certificate_domain_id' => $domain_id,
|
||||
'certificate_client_id' => $client_id,
|
||||
'certificate_created_at' => demoMonthDateTime($months, 7, 10, 20),
|
||||
]);
|
||||
$counts['documentation']++;
|
||||
}
|
||||
|
||||
// From the client's own CA, for Wi-Fi - nothing to connect to, so nobody checks it
|
||||
if ($index % 5 === 3) {
|
||||
starterInsert($mysqli, 'certificates', [
|
||||
'certificate_name' => 'Wi-Fi RADIUS (NPS)',
|
||||
'certificate_description' => 'Server certificate the laptops check before joining the staff Wi-Fi',
|
||||
'certificate_issued_by' => strtoupper($profile['abbreviation'] ?: substr($domain, 0, 4)) . '-DC01-CA',
|
||||
'certificate_expire' => demoDate(-1 * (40 + $index * 3)),
|
||||
'certificate_notes' => 'Renew from the internal CA before it expires - when it lapses, every laptop drops off the staff Wi-Fi at once.',
|
||||
'certificate_client_id' => $client_id,
|
||||
'certificate_created_at' => demoMonthDateTime($months, 7, 10, 30),
|
||||
]);
|
||||
$counts['documentation']++;
|
||||
}
|
||||
|
||||
return $website_id;
|
||||
}
|
||||
|
||||
|
||||
// ------------------------------
|
||||
// demoBuildAssets
|
||||
// Builds the fleet from the profile's counts, named the way an MSP names kit.
|
||||
|
||||
@@ -12,32 +12,73 @@ require_once "../includes/check_login.php";
|
||||
require_once "../libs/totp/totp.php";
|
||||
|
||||
/*
|
||||
* Fetches SSL certificates from remote hosts & returns the relevant info (issuer, expiry, public key)
|
||||
* The host in a New / Edit Certificate form, checked when asked: connect,
|
||||
* take the certificate it serves and say what it is - OK, for another name,
|
||||
* untrusted, expired, or nothing answering - with what will be saved, the
|
||||
* client's domain it belongs to, and whether the client has it already.
|
||||
*/
|
||||
if (isset($_GET['certificate_fetch_parse_json_details'])) {
|
||||
enforceUserPermission('module_support');
|
||||
if (isset($_GET['certificate_check'])) {
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
// PHP doesn't appreciate attempting SSL sockets to non-existent domains
|
||||
if (empty($_GET['domain'])) {
|
||||
exit();
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$input = trim((string) ($_GET['host'] ?? ''));
|
||||
$check_client_id = intval($_GET['client_id'] ?? 0);
|
||||
$check_certificate_id = intval($_GET['certificate_id'] ?? 0);
|
||||
|
||||
if ($input === '') {
|
||||
echo json_encode(['state' => '', 'message' => '', 'html' => '']);
|
||||
exit;
|
||||
}
|
||||
$host = certificateHost($input);
|
||||
if (!$host) {
|
||||
echo json_encode(['state' => 'bad', 'message' => "That isn't a host - something like www.example.com, or portal.example.com:8443.", 'html' => '']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$name = $_GET['domain'];
|
||||
|
||||
// Get SSL cert for domain (if exists)
|
||||
$certificate = getSslCertificate($name);
|
||||
|
||||
if ($certificate['success'] == "TRUE") {
|
||||
$response['success'] = "TRUE";
|
||||
$response['expire'] = $certificate['expire'];
|
||||
$response['issued_by'] = $certificate['issued_by'];
|
||||
$response['public_key'] = $certificate['public_key'];
|
||||
} else {
|
||||
$response['success'] = "FALSE";
|
||||
$response = ['host' => $host['display'], 'domain_id' => 0, 'html' => ''];
|
||||
$notes = [];
|
||||
if (strcasecmp($input, $host['display']) !== 0) {
|
||||
$notes[] = "Saved as {$host['display']}.";
|
||||
}
|
||||
|
||||
// Already on this client? Which of its domains is it under?
|
||||
if ($check_client_id) {
|
||||
$client_id = $check_client_id;
|
||||
enforceClientAccess();
|
||||
$host_sql = escapeSql($host['display']);
|
||||
$existing = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT certificate_name FROM certificates WHERE certificate_domain = '$host_sql' AND certificate_client_id = $check_client_id AND certificate_id <> $check_certificate_id AND certificate_archived_at IS NULL LIMIT 1"));
|
||||
if ($existing) {
|
||||
$notes[] = 'This client already has it, as ' . $existing['certificate_name'] . '.';
|
||||
}
|
||||
$response['domain_id'] = certificateDomainFor($host['host'], $check_client_id);
|
||||
}
|
||||
|
||||
$check = certificateCheck($host);
|
||||
if (empty($check['reachable'])) {
|
||||
$response['state'] = 'bad';
|
||||
$response['message'] = trim(implode(' ', $notes) . " Nothing answered on {$host['display']} - check the host and port. If ITFlow can't reach it, paste the certificate instead.");
|
||||
echo json_encode($response);
|
||||
exit;
|
||||
}
|
||||
|
||||
$state = CERTIFICATE_CHECK_STATES[$check['status']];
|
||||
$response['state'] = $check['status'] === 'ok' ? 'ok' : 'warn';
|
||||
$response['message'] = trim(implode(' ', $notes) . ' ' . $state['text'] . '.');
|
||||
|
||||
$expiry = certificateExpiry(['certificate_expire' => $check['expire'], 'certificate_issued_at' => $check['issued_at']]);
|
||||
$names = $check['names'];
|
||||
$response['html'] = '<div class="d-flex flex-wrap gap-2 mb-2">'
|
||||
. certificateStatusPill(['certificate_check_status' => $check['status'], 'certificate_domain' => $host['display']])
|
||||
. certificateExpiryPill($expiry, true) . '</div>'
|
||||
. '<dl class="itflow-asset-dl mb-0">'
|
||||
. '<dt>Issuer</dt><dd class="text-break">' . escapeHtml($check['issuer'] ?: 'Unknown') . ($check['self_signed'] ? ' <span class="text-body-secondary">(self-signed)</span>' : '') . '</dd>'
|
||||
. '<dt>Valid</dt><dd>' . escapeHtml($check['issued_at']) . ' to ' . escapeHtml($check['expire']) . ' <span class="text-body-secondary">(' . $check['days'] . ' days)</span></dd>'
|
||||
. '<dt>Covers</dt><dd class="text-break">' . escapeHtml(implode(', ', array_slice($names, 0, 6))) . (count($names) > 6 ? ' <span class="text-body-secondary">and ' . (count($names) - 6) . ' more</span>' : '') . '</dd>'
|
||||
. '</dl>';
|
||||
|
||||
echo json_encode($response);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Certificates - one client's, or every certificate the agent can see from
|
||||
* All Client Docs. Starred first. Each row has the host it is served on and
|
||||
* the domain it belongs to, who issued it, when it expires (and whether it
|
||||
* renews itself), and what the last check of the host found. The pills along
|
||||
* the top count and filter the ones to act on: expiring soon, expired,
|
||||
* problems the check found, and the ones nobody is checking.
|
||||
*/
|
||||
|
||||
// Default Column Sortby Filter
|
||||
$sort = "certificate_name";
|
||||
$order = "ASC";
|
||||
@@ -9,341 +18,457 @@ if (isset($_GET['client_id'])) {
|
||||
require_once "includes/inc_all_client.php";
|
||||
$client_query = "AND certificate_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 = "certificate_archived_at IS NOT NULL";
|
||||
} else {
|
||||
$archived = 0;
|
||||
$archive_query = "certificate_archived_at IS NULL";
|
||||
}
|
||||
$archived = isset($_GET['archived']) && $_GET['archived'] == 1 ? 1 : 0;
|
||||
$archive_query = $archived ? "certificate_archived_at IS NOT NULL" : "certificate_archived_at IS NULL";
|
||||
} else {
|
||||
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 certificate_archived_at IS NOT NULL)";
|
||||
} else {
|
||||
$archived = 0;
|
||||
$archive_query = "(client_archived_at IS NULL AND certificate_archived_at IS NULL)";
|
||||
}
|
||||
$archived = isset($_GET['archived']) && $_GET['archived'] == 1 ? 1 : 0;
|
||||
$archive_query = $archived ? "(client_archived_at IS NOT NULL OR certificate_archived_at IS NOT NULL)" : "(client_archived_at IS NULL AND certificate_archived_at IS NULL)";
|
||||
}
|
||||
|
||||
// Perms
|
||||
enforceUserPermission('module_support');
|
||||
|
||||
// Expiring In Filter
|
||||
if (isset($_GET['expire_days']) && !empty($_GET['expire_days'])) {
|
||||
if ($_GET['expire_days'] == "expired") {
|
||||
$expire_days = "expired";
|
||||
$expire_query = "AND (certificate_expire IS NOT NULL AND certificate_expire != '0000-00-00' AND certificate_expire < CURDATE())";
|
||||
} else {
|
||||
$expire_days = intval($_GET['expire_days']);
|
||||
$expire_query = "AND (certificate_expire IS NOT NULL AND certificate_expire != '0000-00-00' AND certificate_expire BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL $expire_days DAY))";
|
||||
}
|
||||
} else {
|
||||
// Default - any
|
||||
$expire_days = '';
|
||||
$expire_query = '';
|
||||
$can_edit = certificateCan(2);
|
||||
$can_delete = certificateCan(3) && !empty($config_destructive_deletes_enable);
|
||||
|
||||
// Client Filter (all clients)
|
||||
$client = '';
|
||||
if (!$client_url && !empty($_GET['client'])) {
|
||||
$client = intval($_GET['client']);
|
||||
$client_query = "AND certificate_client_id = $client";
|
||||
}
|
||||
|
||||
if (!$client_url) {
|
||||
// Client Filter
|
||||
if (isset($_GET['client']) & !empty($_GET['client'])) {
|
||||
$client_query = 'AND (certificate_client_id = ' . intval($_GET['client']) . ')';
|
||||
$client = intval($_GET['client']);
|
||||
} else {
|
||||
// Default - any
|
||||
$client_query = '';
|
||||
$client = '';
|
||||
}
|
||||
// Issuer Filter
|
||||
$issuer_filter = trim((string) ($_GET['issuer'] ?? ''));
|
||||
$issuer_query = $issuer_filter !== '' ? "AND certificates.certificate_issued_by = '" . escapeSql($issuer_filter) . "'" : '';
|
||||
|
||||
// Which ones - the pills along the top. The old "Expiring in" filter
|
||||
// (?expire_days=30 from links and bookmarks) still works.
|
||||
$shows = [
|
||||
'' => ['label' => 'All', 'where' => ''],
|
||||
'starred' => ['label' => 'Starred', 'icon' => 'fa-star', 'where' => 'certificates.certificate_favorite = 1'],
|
||||
'soon' => ['label' => 'Expiring soon', 'icon' => 'fa-hourglass-half', 'where' => certificateSoonSql(),
|
||||
'title' => 'In the next ' . CERTIFICATE_SOON_DAYS . " days - or 20 for a short-lived one, which should have renewed itself by then"],
|
||||
'expired' => ['label' => 'Expired', 'icon' => 'fa-calendar-times', 'where' => 'certificates.certificate_expire < CURDATE()'],
|
||||
'problems' => ['label' => 'Problems', 'icon' => 'fa-exclamation-triangle', 'where' => certificateProblemSql(),
|
||||
'title' => "The last check found it serving one for another name, an untrusted or expired one - or nothing answered"],
|
||||
'unchecked' => ['label' => 'Not checked', 'icon' => 'fa-eye-slash', 'where' => 'certificates.certificate_check_status IS NULL',
|
||||
'title' => 'No host to check, or not checked yet'],
|
||||
];
|
||||
$show = isset($shows[$_GET['show'] ?? '']) ? ($_GET['show'] ?? '') : '';
|
||||
$show_query = $shows[$show]['where'] ? 'AND ' . $shows[$show]['where'] : '';
|
||||
|
||||
$expire_days = $_GET['expire_days'] ?? '';
|
||||
$expire_query = '';
|
||||
if ($expire_days === 'expired') {
|
||||
$expire_query = 'AND certificates.certificate_expire < CURDATE()';
|
||||
} elseif (intval($expire_days) > 0) {
|
||||
$expire_query = 'AND certificates.certificate_expire BETWEEN CURDATE() AND CURDATE() + INTERVAL ' . intval($expire_days) . ' DAY';
|
||||
}
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS certificate_archived_at, certificate_created_at, certificate_description,
|
||||
certificate_domain, certificate_expire, certificate_id, certificate_issued_by,
|
||||
certificate_name, client_id, client_name FROM certificates
|
||||
LEFT JOIN clients ON client_id = certificate_client_id
|
||||
WHERE $archive_query
|
||||
AND (certificate_name LIKE '%$q%' OR certificate_domain LIKE '%$q%' OR certificate_description LIKE '%$q%' OR certificate_issued_by LIKE '%$q%' OR client_name LIKE '%$q%')
|
||||
" . clientScopeSql('certificate_client_id') . "
|
||||
$client_query
|
||||
$expire_query
|
||||
ORDER BY $sort $order LIMIT $record_from, $record_to"
|
||||
);
|
||||
// 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 = ['certificate_name' => 'certificates.certificate_name', 'certificate_domain' => 'certificates.certificate_domain',
|
||||
'certificate_issued_by' => 'certificates.certificate_issued_by', 'certificate_expire' => 'certificates.certificate_expire',
|
||||
'certificate_checked_at' => 'certificates.certificate_checked_at', 'client_name' => 'client_name', 'certificate_created_at' => 'certificates.certificate_created_at'];
|
||||
if (!isset($sortable_columns[$sort])) {
|
||||
$sort = 'certificate_name';
|
||||
}
|
||||
// Certificates without an expiry (or never checked) go last whichever way it is sorted
|
||||
$sort_sql = (in_array($sort, ['certificate_expire', 'certificate_checked_at'], true) ? "{$sortable_columns[$sort]} IS NULL, " : '') . $sortable_columns[$sort] . " $order";
|
||||
|
||||
[$certificate_columns, $certificate_joins] = certificateSelectSql();
|
||||
$search_query = "AND (certificates.certificate_name LIKE '%$q%' OR certificates.certificate_domain LIKE '%$q%' OR certificates.certificate_description LIKE '%$q%'
|
||||
OR certificates.certificate_issued_by LIKE '%$q%' OR certificates.certificate_names LIKE '%$q%' OR certificates.certificate_fingerprint LIKE '%$q%'
|
||||
OR certificates.certificate_notes LIKE '%$q%' OR domains.domain_name LIKE '%$q%' OR client_name LIKE '%$q%')";
|
||||
$scope_query = clientScopeSql('certificate_client_id');
|
||||
$filters = "$archive_query $issuer_query $search_query $expire_query $scope_query $client_query";
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS $certificate_columns
|
||||
FROM certificates $certificate_joins
|
||||
WHERE $filters $show_query
|
||||
ORDER BY certificates.certificate_favorite DESC, $sort_sql, certificates.certificate_name ASC LIMIT $record_from, $record_to");
|
||||
|
||||
$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
|
||||
|
||||
$certificates = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$certificates[intval($row['certificate_id'])] = $row;
|
||||
}
|
||||
|
||||
// How many of each, for the pills - everything in scope, before the pill itself
|
||||
$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 certificates $certificate_joins WHERE $filters"));
|
||||
$counts = [];
|
||||
foreach (array_keys($shows) as $i => $key) {
|
||||
$counts[$key] = intval($row[$i]);
|
||||
}
|
||||
|
||||
$filter_url = function ($changes) {
|
||||
$params = array_merge($_GET, $changes);
|
||||
unset($params['page']);
|
||||
return '?' . http_build_query(array_filter($params, function ($v) { return $v !== '' && $v !== null; }));
|
||||
};
|
||||
|
||||
// Issuers for the filter - the ones on a certificate in this scope
|
||||
$sql_issuers_filter = mysqli_query($mysqli, "SELECT certificates.certificate_issued_by, COUNT(*) AS issued FROM certificates $certificate_joins
|
||||
WHERE $archive_query $scope_query $client_query AND certificates.certificate_issued_by <> ''
|
||||
GROUP BY certificates.certificate_issued_by ORDER BY certificates.certificate_issued_by ASC");
|
||||
|
||||
// What the export starts from - the pill, as the export's own filters
|
||||
$export_extra = [
|
||||
'expire_days' => $show === 'expired' ? 'expired' : ($show === 'soon' ? CERTIFICATE_SOON_DAYS : ''),
|
||||
'problems' => $show === 'problems' ? 1 : '',
|
||||
];
|
||||
|
||||
?>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header bg-dark py-2">
|
||||
<h3 class="card-title mt-2"><i class="fas fa-fw fa-lock me-2"></i>Certificates</h3>
|
||||
<h3 class="card-title mt-2"><i class="fa fa-fw fa-lock me-2"></i>Certificates</h3>
|
||||
<div class="card-tools">
|
||||
<?php if ($can_edit || $num_rows[0]) { ?>
|
||||
<div class="btn-group">
|
||||
<button type="button" class="btn btn-primary ajax-modal" data-modal-url="modals/certificate/certificate_add.php?<?= $client_url ?>"><i class="fas fa-plus me-2"></i>New Certificate</button>
|
||||
<?php if ($can_edit) { ?>
|
||||
<button type="button" class="btn btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/certificate/certificate_add.php?<?= $client_url ?>">
|
||||
<i class="fas fa-plus me-2"></i>New Certificate
|
||||
</button>
|
||||
<?php } ?>
|
||||
<?php if ($num_rows[0] > 0) { ?>
|
||||
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown"></button>
|
||||
<div class="dropdown-menu">
|
||||
<a class="dropdown-item text-dark ajax-modal" href="#"\
|
||||
data-modal-url="<?= buildExportModalUrl('modals/certificate/certificate_export.php', ['client_id', 'client', 'expire_days', 'archived', 'q']) ?>">
|
||||
<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">
|
||||
<a class="dropdown-item text-dark ajax-modal" href="#"
|
||||
data-modal-url="<?= buildExportModalUrl('modals/certificate/certificate_export.php', ['client_id', 'client', 'expire_days', 'archived', 'q'], $export_extra) ?>">
|
||||
<i class="fa fa-fw fa-download me-2"></i>Export
|
||||
</a>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-header py-3">
|
||||
<form autocomplete="off">
|
||||
<?php if ($client_url) { ?>
|
||||
<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="<?= $client_url ? 'col-lg-5' : '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 Certificates">
|
||||
<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, host, names covered, issuer...">
|
||||
<button class="btn btn-dark" title="Search"><i class="fa fa-search"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="<?= $client_url ? 'col-lg-4' : 'col-lg-3' ?> col-md-6">
|
||||
<select class="form-select select2" name="issuer" onchange="this.form.submit()">
|
||||
<option value="">- Any issuer -</option>
|
||||
<?php while ($row = mysqli_fetch_assoc($sql_issuers_filter)) { ?>
|
||||
<option <?= $issuer_filter === $row['certificate_issued_by'] ? 'selected' : '' ?> value="<?= escapeHtml($row['certificate_issued_by']) ?>" data-icon="fas fa-building" data-description="<?= intval($row['issued']) ?> certificate<?= intval($row['issued']) === 1 ? '' : 's' ?>"><?= escapeHtml($row['certificate_issued_by']) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
<?php if (!$client_url) { ?>
|
||||
<div class="col-md-2">
|
||||
<div class="input-group">
|
||||
<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
|
||||
FROM clients
|
||||
JOIN certificates ON certificate_client_id = client_id
|
||||
WHERE $archive_query
|
||||
" . clientScopeSql('clients.client_id') . "
|
||||
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
|
||||
}
|
||||
?>
|
||||
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-3 col-md-6">
|
||||
<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
|
||||
FROM clients
|
||||
JOIN certificates ON certificate_client_id = client_id
|
||||
WHERE $archive_query
|
||||
" . clientScopeSql('clients.client_id') . "
|
||||
ORDER BY client_name ASC
|
||||
");
|
||||
while ($row = mysqli_fetch_assoc($sql_clients_filter)) {
|
||||
$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 class="col-md-2">
|
||||
<div class="input-group">
|
||||
<select class="form-select select2" name="expire_days" onchange="this.form.submit()">
|
||||
<option value="" <?php if ($expire_days == "") { echo "selected"; } ?>>- Expiring In -</option>
|
||||
<option value="expired" <?php if ($expire_days === "expired") { echo "selected"; } ?>>Expired</option>
|
||||
<option value="7" <?php if ($expire_days === 7) { echo "selected"; } ?>>7 Days</option>
|
||||
<option value="30" <?php if ($expire_days === 30) { echo "selected"; } ?>>30 Days</option>
|
||||
<option value="45" <?php if ($expire_days === 45) { echo "selected"; } ?>>45 Days</option>
|
||||
<option value="60" <?php if ($expire_days === 60) { echo "selected"; } ?>>60 Days</option>
|
||||
<option value="90" <?php if ($expire_days === 90) { echo "selected"; } ?>>90 Days</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($client_url) { // filler ?>
|
||||
<div class="col-md-2"></div>
|
||||
<?php } ?>
|
||||
|
||||
<div class="col-md-4">
|
||||
<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="<?= $client_url ? 'col-lg-3' : '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 certificates' : 'Show archived certificates' ?>">
|
||||
<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_refresh_certificates">
|
||||
<i class="fas fa-fw fa-sync-alt me-2"></i>Refresh Certificates
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<?php if (!$archived) { ?>
|
||||
<button class="dropdown-item" type="submit" form="bulkActions" name="bulk_check_certificates">
|
||||
<i class="fas fa-fw fa-sync-alt me-2"></i>Check now
|
||||
</button>
|
||||
<?php } ?>
|
||||
<button class="dropdown-item" type="submit" form="bulkActions" name="bulk_favorite_certificates">
|
||||
<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_certificates">
|
||||
<i class="far fa-fw fa-star me-2"></i>Unstar
|
||||
</button>
|
||||
<div class="dropdown-divider"></div>
|
||||
<button class="dropdown-item text-danger text-bold"
|
||||
type="submit" form="bulkActions" name="bulk_delete_certificates">
|
||||
<i class="fas fa-fw fa-trash me-2"></i>Delete
|
||||
</button>
|
||||
<?php if ($archived) { ?>
|
||||
<button class="dropdown-item text-info" type="submit" form="bulkActions" name="bulk_restore_certificates">
|
||||
<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_certificates"
|
||||
data-confirm-text="The certificates go for good, with their history. Services stop pointing at them.">
|
||||
<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_certificates">
|
||||
<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) {
|
||||
$alarm = $counts[$key] && in_array($key, ['soon', 'expired', 'problems'], true); ?>
|
||||
<a class="nav-link text-nowrap <?= $show === $key ? 'active' : '' ?>" href="<?= escapeHtml($filter_url(['show' => $key, 'expire_days' => ''])) ?>"<?= !empty($s['title']) ? ' title="' . escapeHtml($s['title']) . '"' : '' ?>>
|
||||
<?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 <?= $alarm ? ($key === 'expired' ? 'text-bg-danger' : 'text-bg-warning') : '' ?>"><?= $counts[$key] ?></span>
|
||||
</a>
|
||||
<?php } ?>
|
||||
</nav>
|
||||
<?php if ($expire_query) { ?>
|
||||
<div class="small text-body-secondary mt-2">
|
||||
<i class="fas fa-filter me-1"></i><?= $expire_days === 'expired' ? 'Expired' : 'Expiring in ' . intval($expire_days) . ' days' ?>
|
||||
<a class="ms-2" href="<?= escapeHtml($filter_url(['expire_days' => ''])) ?>">Clear</a>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
|
||||
<form id="bulkActions" action="post.php" method="post">
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<form id="bulkActions" action="post.php" method="post">
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
|
||||
<table class="table table-striped table-borderless table-hover mb-0">
|
||||
<thead class="text-dark <?php if ($num_rows[0] == 0) { echo "d-none"; } ?>">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle mb-0 itflow-asset-table itflow-certificate-table">
|
||||
<thead class="<?php if (!$num_rows[0]) { echo "d-none"; } ?> text-nowrap table-light">
|
||||
<tr>
|
||||
<td class="checkbox-column border-end">
|
||||
<?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)">
|
||||
<input class="form-check-input" id="selectAllCheckbox" type="checkbox" onclick="checkAll(this)" title="Select all on this page">
|
||||
</div>
|
||||
</td>
|
||||
</th>
|
||||
<?php } ?>
|
||||
<th>
|
||||
<a class="text-secondary" href="?<?= $url_query_strings_sort ?>&sort=certificate_name&order=<?= $disp ?>">
|
||||
Name <?php if ($sort == 'certificate_name') { echo $order_icon; } ?>
|
||||
<a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=certificate_name&order=<?= $disp ?>">
|
||||
Certificate <?php if ($sort == 'certificate_name') { echo $order_icon; } ?>
|
||||
</a>
|
||||
</th>
|
||||
<th>
|
||||
<a class="text-secondary" href="?<?= $url_query_strings_sort ?>&sort=certificate_domain&order=<?= $disp ?>">
|
||||
Domain <?php if ($sort == 'certificate_domain') { echo $order_icon; } ?>
|
||||
<a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=certificate_domain&order=<?= $disp ?>">
|
||||
Host <?php if ($sort == 'certificate_domain') { echo $order_icon; } ?>
|
||||
</a>
|
||||
</th>
|
||||
<th>
|
||||
<a class="text-secondary" href="?<?= $url_query_strings_sort ?>&sort=certificate_issued_by&order=<?= $disp ?>">
|
||||
Issued By <?php if ($sort == 'certificate_issued_by') { echo $order_icon; } ?>
|
||||
<a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=certificate_issued_by&order=<?= $disp ?>">
|
||||
Issuer <?php if ($sort == 'certificate_issued_by') { echo $order_icon; } ?>
|
||||
</a>
|
||||
</th>
|
||||
<th>
|
||||
<a class="text-secondary" href="?<?= $url_query_strings_sort ?>&sort=certificate_expire&order=<?= $disp ?>">
|
||||
Expire <?php if ($sort == 'certificate_expire') { echo $order_icon; } ?>
|
||||
<a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=certificate_expire&order=<?= $disp ?>">
|
||||
Expires <?php if ($sort == 'certificate_expire') { echo $order_icon; } ?>
|
||||
</a>
|
||||
</th>
|
||||
<th>
|
||||
<a class="text-reset text-decoration-none" href="?<?= $url_query_strings_sort ?>&sort=certificate_checked_at&order=<?= $disp ?>">
|
||||
Last check <?php if ($sort == 'certificate_checked_at') { echo $order_icon; } ?>
|
||||
</a>
|
||||
</th>
|
||||
<?php if (!$client_url) { ?>
|
||||
<th>
|
||||
<a class="text-secondary" href="?<?= $url_query_strings_sort ?>&sort=client_name&order=<?= $disp ?>">
|
||||
<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 class="text-center">Action</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php
|
||||
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$client_id = intval($row['client_id']);
|
||||
$client_name = escapeHtml($row['client_name']);
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
foreach ($certificates as $certificate_id => $row) {
|
||||
$row_client_id = intval($row['certificate_client_id']);
|
||||
$certificate_name = escapeHtml($row['certificate_name']);
|
||||
$certificate_description = escapeHtml($row['certificate_description']);
|
||||
$certificate_domain = escapeHtml($row['certificate_domain']);
|
||||
$certificate_issued_by = escapeHtml($row['certificate_issued_by']);
|
||||
$certificate_expire = escapeHtml($row['certificate_expire']);
|
||||
$certificate_created_at = escapeHtml($row['certificate_created_at']);
|
||||
$certificate_favorite = intval($row['certificate_favorite']);
|
||||
$certificate_archived_at = escapeHtml($row['certificate_archived_at']);
|
||||
|
||||
$certificate_expire_ago = timeAgo($certificate_expire);
|
||||
// Convert the expiry date to a timestamp
|
||||
$certificate_expire_timestamp = strtotime($row['certificate_expire']);
|
||||
$current_timestamp = time(); // Get current timestamp
|
||||
|
||||
// Calculate the difference in days
|
||||
$days_until_expiry = ($certificate_expire_timestamp - $current_timestamp) / (60 * 60 * 24);
|
||||
|
||||
// Determine the class based on the number of days until expiry
|
||||
if ($days_until_expiry <= 0) {
|
||||
$tr_class = "table-secondary";
|
||||
} elseif ($days_until_expiry <= 1) {
|
||||
$tr_class = "table-danger";
|
||||
} elseif ($days_until_expiry <= 7) {
|
||||
$tr_class = "table-warning";
|
||||
} else {
|
||||
$tr_class = '';
|
||||
}
|
||||
$host = certificateHost($row['certificate_domain']);
|
||||
$names = certificateNames($row);
|
||||
$other_names = $host ? array_values(array_filter($names, function ($covered) use ($host) { return strtolower($covered) !== $host['host']; })) : $names;
|
||||
$expiry = certificateExpiry($row);
|
||||
$quick_url = "modals/certificate/certificate.php?id=$certificate_id";
|
||||
|
||||
?>
|
||||
<tr class="<?= $tr_class ?>">
|
||||
<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="certificate_ids[]" value="<?= $certificate_id ?>">
|
||||
<input type="hidden" name="client_id" value="<?= $client_id ?>">
|
||||
<input class="form-check-input bulk-select" type="checkbox" name="certificate_ids[]" value="<?= $certificate_id ?>" aria-label="Select <?= $certificate_name ?>">
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<a class="text-dark ajax-modal" href="#"
|
||||
data-modal-url="modals/certificate/certificate_edit.php?<?= $client_url ?>&id=<?= $certificate_id ?>">
|
||||
<div class="d-flex">
|
||||
<i class="fa fa-fw fa-2x fa-lock me-3"></i>
|
||||
<div class="flex-grow-1">
|
||||
<div><?= $certificate_name ?></div>
|
||||
<div><small class="text-secondary"><?= $certificate_description ?></small></div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<td class="itflow-asset-name-cell">
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
<?= certificateTile() ?>
|
||||
<div class="min-w-0">
|
||||
<a class="fw-semibold text-body ajax-modal" href="#" data-modal-size="lg" data-modal-url="<?= $quick_url ?>"><?= $certificate_name ?></a>
|
||||
<?php if ($certificate_favorite) { ?><i class="fas fa-star text-warning small ms-1" title="Starred"></i><?php } ?>
|
||||
<?php if ($certificate_archived_at) { ?><span class="badge rounded-pill text-bg-secondary fw-normal ms-1">Archived</span><?php } ?>
|
||||
<?php if ($certificate_description) { ?>
|
||||
<div class="small text-body-secondary text-truncate itflow-asset-desc" title="<?= $certificate_description ?>"><?= $certificate_description ?></div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
<td><?= $certificate_domain ?></td>
|
||||
|
||||
<td><?= $certificate_issued_by ?></td>
|
||||
|
||||
<td>
|
||||
<div><?= $certificate_expire ?: '-' ?></div>
|
||||
<?php if (!empty($certificate_expire)) { ?>
|
||||
<div><small><?= $certificate_expire_ago ?></small></div>
|
||||
<td class="itflow-certificate-host">
|
||||
<?php if ($host) { ?>
|
||||
<div class="d-flex align-items-center min-w-0">
|
||||
<span class="font-monospace small text-truncate"><?= escapeHtml($host['display']) ?></span>
|
||||
<button type="button" class="itflow-copy clipboardjs" title="Copy" data-clipboard-text="<?= escapeHtml($host['display']) ?>"><i class="far fa-copy"></i></button>
|
||||
</div>
|
||||
<?php } else { ?>
|
||||
<span class="small text-body-secondary">No host</span>
|
||||
<?php } ?>
|
||||
<?php if ($host && $names && !certificateCovers($host['host'], $names)) { ?>
|
||||
<div class="small text-warning-emphasis text-truncate" title="<?= escapeHtml(implode(', ', $names)) ?>">
|
||||
<i class="fas fa-not-equal me-1"></i><?= count($names) === 1 ? 'Covers ' . escapeHtml($names[0]) : 'Covers ' . count($names) . ' other names' ?>
|
||||
</div>
|
||||
<?php } elseif ($other_names) { ?>
|
||||
<div class="small text-body-secondary text-truncate" title="<?= escapeHtml(implode(', ', $names)) ?>">
|
||||
<?= count($other_names) === 1 ? 'Also ' . escapeHtml($other_names[0]) : 'Also covers ' . count($other_names) . ' names' ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<?php if (intval($row['certificate_domain_id']) && $row['domain_name'] !== null) { ?>
|
||||
<div class="small mt-1"><?= domainLink($row['certificate_domain_id'], $row['domain_name'], ['archived' => !empty($row['domain_archived_at'])]) ?></div>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td class="small">
|
||||
<?php if ($row['certificate_issued_by'] !== '') { ?>
|
||||
<div class="text-truncate itflow-certificate-issuer" title="<?= escapeHtml($row['certificate_issued_by']) ?>"><?= escapeHtml($row['certificate_issued_by']) ?></div>
|
||||
<?php } else { ?>
|
||||
<span class="text-body-secondary">-</span>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td class="text-nowrap">
|
||||
<?= certificateExpiryPill($expiry) ?>
|
||||
<?php if ($expiry) { ?>
|
||||
<div class="small text-body-secondary mt-1"><?= escapeHtml($expiry['date']) ?></div>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td class="text-nowrap">
|
||||
<?= certificateStatusPill($row) ?>
|
||||
<?php if (!empty($row['certificate_checked_at'])) { ?>
|
||||
<div class="small text-body-secondary mt-1" title="<?= escapeHtml($row['certificate_checked_at']) ?>"><?= timeAgo($row['certificate_checked_at']) ?></div>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<?php if (!$client_url) { ?>
|
||||
<td><a href="certificates.php?client_id=<?= $client_id ?>"><?= $client_name ?></a></td>
|
||||
<td><a href="certificates.php?client_id=<?= $row_client_id ?>"><?= escapeHtml($row['client_name']) ?></a></td>
|
||||
<?php } ?>
|
||||
<td>
|
||||
<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>
|
||||
<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/certificate/certificate_edit.php?<?= $client_url ?>&id=<?= $certificate_id ?>">
|
||||
<i class="fas fa-fw fa-edit me-2"></i>Edit
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="<?= $quick_url ?>">
|
||||
<i class="fas fa-fw fa-eye text-secondary me-2"></i>Quick look
|
||||
</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<a class="dropdown-item" href="post.php?refresh_certificate=<?= $certificate_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
|
||||
<i class="fas fa-fw fa-sync-alt me-2"></i>Refresh Certificate
|
||||
</a>
|
||||
<?php if ($session_user_role == 3) { ?>
|
||||
<?php if ($certificate_archived_at) { ?>
|
||||
<div class="dropdown-divider"></div>
|
||||
<a class="dropdown-item text-info confirm-link" href="post.php?restore_certificate=<?= $certificate_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
|
||||
<i class="fas fa-fw fa-redo me-2"></i>Restore
|
||||
<?php if ($host) { ?>
|
||||
<a class="dropdown-item" href="https://<?= escapeHtml($host['display']) ?>" target="_blank" rel="noopener noreferrer">
|
||||
<i class="fas fa-fw fa-external-link-alt text-secondary me-2"></i>Open the site
|
||||
</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<a class="dropdown-item text-danger text-bold confirm-link" href="post.php?delete_certificate=<?= $certificate_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
|
||||
<i class="fas fa-fw fa-trash me-2"></i>Delete
|
||||
</a>
|
||||
<?php } else { ?>
|
||||
<div class="dropdown-divider"></div>
|
||||
<a class="dropdown-item text-danger confirm-link" href="post.php?archive_certificate=<?= $certificate_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
|
||||
<i class="fas fa-fw fa-archive me-2"></i>Archive
|
||||
<?php } ?>
|
||||
<?php if ($can_edit && !$certificate_archived_at) { ?>
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/certificate/certificate_edit.php?id=<?= $certificate_id ?>">
|
||||
<i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit
|
||||
</a>
|
||||
<?php if ($host) { ?>
|
||||
<a class="dropdown-item" href="post.php?check_certificate=<?= $certificate_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
|
||||
<i class="fas fa-fw fa-sync-alt text-secondary me-2"></i>Check now
|
||||
</a>
|
||||
<?php } ?>
|
||||
<a class="dropdown-item" href="post.php?<?= $certificate_favorite ? 'unfavorite_certificate' : 'favorite_certificate' ?>=<?= $certificate_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>">
|
||||
<i class="<?= $certificate_favorite ? 'far' : 'fas' ?> fa-fw fa-star text-secondary me-2"></i><?= $certificate_favorite ? 'Unstar' : 'Star' ?>
|
||||
</a>
|
||||
<?php } ?>
|
||||
<?php if ($can_edit) { ?>
|
||||
<div class="dropdown-divider"></div>
|
||||
<?php if ($certificate_archived_at) { ?>
|
||||
<a class="dropdown-item" href="post.php?restore_certificate=<?= $certificate_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_certificate=<?= $certificate_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"
|
||||
data-confirm-text="<?= $certificate_name ?> goes for good, with its history. Services stop pointing at it.">
|
||||
<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_certificate=<?= $certificate_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>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<?php if (!$num_rows[0]) { ?>
|
||||
<div class="itflow-asset-empty">
|
||||
<i class="fas fa-lock fa-2x mb-2 opacity-50"></i>
|
||||
<div><?= $q || $issuer_query || $show || $expire_query ? 'No certificates match.' : 'No certificates yet.' ?></div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<?php require_once "../includes/filter_footer.php"; ?>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($_GET['open'])) { ?>
|
||||
<script>
|
||||
// Opened from search, a notification or the overview - straight to that certificate's quick look
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var open = document.createElement('a');
|
||||
open.className = 'ajax-modal';
|
||||
open.href = '#';
|
||||
open.dataset.modalSize = 'lg';
|
||||
open.dataset.modalUrl = 'modals/certificate/certificate.php?id=<?= intval($_GET['open']) ?>';
|
||||
document.body.appendChild(open);
|
||||
open.click();
|
||||
open.remove();
|
||||
});
|
||||
</script>
|
||||
<?php } ?>
|
||||
|
||||
<script src="../js/bulk_actions.js"></script>
|
||||
|
||||
<?php require_once "../includes/footer.php";
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
function fetchSSL(type)
|
||||
{
|
||||
// Get the domain name input & issued/expire/key fields, based on whether this is a new cert or updating an existing
|
||||
if (type == 'new') {
|
||||
var domain = document.getElementById("domain").value;
|
||||
var issuedBy = document.getElementById("issuedBy");
|
||||
var expire = document.getElementById("expire");
|
||||
var publicKey = document.getElementById("publicKey");
|
||||
|
||||
}
|
||||
if (type == 'edit') {
|
||||
var domain = document.getElementById("editCertificateDomain").value;
|
||||
var issuedBy = document.getElementById("editCertificateIssuedBy");
|
||||
var expire = document.getElementById("editCertificateExpire");
|
||||
var publicKey = document.getElementById("editCertificatePublicKey");
|
||||
}
|
||||
|
||||
//Send a GET request to post.php as post.php?certificate_fetch_parse_json_details=TRUE&domain=DOMAIN
|
||||
itflowGet(
|
||||
"ajax.php",
|
||||
{certificate_fetch_parse_json_details: 'TRUE', domain: domain},
|
||||
function(data) {
|
||||
//If we get a response from post.php, parse it as JSON
|
||||
const ssl_data = JSON.parse(data);
|
||||
|
||||
if (ssl_data.success == "TRUE") {
|
||||
// Fill the form fields with the cert data
|
||||
issuedBy.value = ssl_data.issued_by;
|
||||
expire.value = ssl_data.expire;
|
||||
publicKey.value = ssl_data.public_key;
|
||||
}
|
||||
else{
|
||||
alert("Error whilst parsing/retrieving details for domain")
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
243
agent/modals/certificate/certificate.php
Normal file
243
agent/modals/certificate/certificate.php
Normal file
@@ -0,0 +1,243 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Certificate quick look - opened from the certificates list, domains,
|
||||
* services, the client overview and search. What the last check of the host
|
||||
* found and when, when it expires and whether it renews itself, who issued
|
||||
* it, the names it covers, its fingerprint and the certificate itself (to
|
||||
* copy or download), the domain it belongs to, the services that use it,
|
||||
* notes and its history. Changing it takes edit rights.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_support');
|
||||
|
||||
$certificate_id = intval($_GET['id'] ?? 0);
|
||||
$certificate = certificateRow($certificate_id);
|
||||
if (!$certificate) {
|
||||
echo json_encode(['error' => 'That certificate no longer exists.']);
|
||||
exit;
|
||||
}
|
||||
$client_id = intval($certificate['certificate_client_id']);
|
||||
enforceClientAccess();
|
||||
|
||||
// When it was last looked at - kept off the updated date
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_accessed_at = NOW(), certificate_updated_at = certificate_updated_at WHERE certificate_id = $certificate_id");
|
||||
|
||||
$certificate_name = escapeHtml($certificate['certificate_name']);
|
||||
$certificate_archived = !empty($certificate['certificate_archived_at']);
|
||||
$can_edit = certificateCan(2) && !$certificate_archived;
|
||||
$host = certificateHost($certificate['certificate_domain']);
|
||||
$expiry = certificateExpiry($certificate);
|
||||
$parsed = certificateParse($certificate['certificate_public_key']);
|
||||
$names = certificateNames($certificate);
|
||||
$services = certificateServices($certificate_id);
|
||||
$history = certificateHistory($certificate_id, 15);
|
||||
$pem = $parsed ? $parsed['pem'] : '';
|
||||
$fingerprint = trim((string) $certificate['certificate_fingerprint']);
|
||||
|
||||
// What the last check found, said in full when it is a problem - with what to do about it
|
||||
$status_problem = null;
|
||||
$status = (string) $certificate['certificate_check_status'];
|
||||
if ($status !== 'ok' && isset(CERTIFICATE_CHECK_STATES[$status])) {
|
||||
$status_problem = CERTIFICATE_CHECK_STATES[$status];
|
||||
$status_problem['hint'] = [
|
||||
'mismatch' => 'install the certificate for this name, or check the host is right',
|
||||
'untrusted' => !$parsed ? 'replace a self-signed certificate with one from a CA (or your own CA, for internal hosts), or install the intermediate certificates with it'
|
||||
: ($parsed['self_signed'] ? 'replace the self-signed certificate with one from a CA (or your own CA, for internal hosts)' : 'install the intermediate certificates with it'),
|
||||
'expired' => 'renew it, and install the new one',
|
||||
'unreachable' => 'check the host and port, or that ITFlow can reach it',
|
||||
][$status] ?? '';
|
||||
}
|
||||
|
||||
// Covered names - the host's own first, then the rest as the certificate lists them
|
||||
if ($host && $names) {
|
||||
usort($names, function ($a, $b) use ($host) {
|
||||
return intval(certificateCovers($host['host'], [$b])) - intval(certificateCovers($host['host'], [$a]));
|
||||
});
|
||||
}
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
|
||||
<div class="modal-header bg-dark" data-bs-theme="dark">
|
||||
<div class="d-flex align-items-center gap-3 min-w-0">
|
||||
<?= certificateTile() ?>
|
||||
<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"><?= $certificate_name ?></span>
|
||||
<?php if (intval($certificate['certificate_favorite'])) { ?><i class="fas fa-star text-warning small" title="Starred"></i><?php } ?>
|
||||
<?php if ($certificate_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($certificate['client_name']) ?></span>
|
||||
<?php if ($certificate['certificate_description']) { ?><span><?= escapeHtml($certificate['certificate_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">
|
||||
|
||||
<div class="d-flex flex-wrap align-items-center gap-2 mb-3 small text-body-secondary">
|
||||
<?= certificateStatusPill($certificate) ?>
|
||||
<?= certificateExpiryPill($expiry, true) ?>
|
||||
<?php if ($host) { ?>
|
||||
<a href="https://<?= escapeHtml($host['display']) ?>" target="_blank" rel="noopener noreferrer"><i class="fas fa-external-link-alt me-1"></i>Open the site</a>
|
||||
<?php } ?>
|
||||
<?php if ($host) { ?>
|
||||
<span title="<?= escapeHtml($certificate['certificate_checked_at'] ?? '') ?>"><i class="fas fa-search me-1"></i><?= $certificate['certificate_checked_at'] ? 'Checked ' . timeAgo($certificate['certificate_checked_at']) : 'Not checked yet' ?></span>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
<?php if ($status_problem) { ?>
|
||||
<div class="alert alert-<?= $status_problem['tone'] ?> d-flex align-items-start gap-2 py-2 small" role="status">
|
||||
<i class="fas <?= $status_problem['icon'] ?> mt-1"></i>
|
||||
<div><?= escapeHtml($status_problem['text']) ?><?= $status_problem['hint'] !== '' ? ' - ' . escapeHtml($status_problem['hint']) : '' ?>.</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-md-6">
|
||||
<div class="small text-body-secondary fw-semibold text-uppercase mb-2">Certificate</div>
|
||||
<dl class="itflow-asset-dl itflow-domain-dl mb-3">
|
||||
<dt>Issuer</dt>
|
||||
<dd class="text-break"><?= $certificate['certificate_issued_by'] !== '' ? escapeHtml($certificate['certificate_issued_by']) : '<span class="text-body-secondary">Unknown</span>' ?><?= $parsed && $parsed['self_signed'] ? ' <span class="small text-body-secondary">(self-signed)</span>' : '' ?></dd>
|
||||
<?php if (!empty($certificate['certificate_issued_at'])) { ?>
|
||||
<dt>Issued</dt>
|
||||
<dd><?= escapeHtml($certificate['certificate_issued_at']) ?> <span class="small text-body-secondary">(<?= timeAgo($certificate['certificate_issued_at']) ?>)</span></dd>
|
||||
<?php } ?>
|
||||
<dt>Expires</dt>
|
||||
<dd><?= $expiry ? escapeHtml($expiry['date']) . ' <span class="small text-body-secondary">(' . timeAgo($expiry['date']) . ')</span>' : '<span class="text-body-secondary">Unknown</span>' ?></dd>
|
||||
<?php if ($parsed) { ?>
|
||||
<dt>Valid for</dt>
|
||||
<dd><?= $parsed['days'] ?> days<?= certificateShortLived($certificate) ? ' <span class="small text-body-secondary">- short-lived, renews itself</span>' : '' ?></dd>
|
||||
<?php } ?>
|
||||
<?php if ($fingerprint !== '') { ?>
|
||||
<dt>SHA-256</dt>
|
||||
<dd class="min-w-0">
|
||||
<div class="d-flex align-items-center min-w-0">
|
||||
<span class="font-monospace small itflow-certificate-fingerprint"><?= str_replace(':', ':<wbr>', escapeHtml($fingerprint)) ?></span>
|
||||
<button type="button" class="itflow-copy clipboardjs" title="Copy" data-clipboard-text="<?= escapeHtml($fingerprint) ?>"><i class="far fa-copy"></i></button>
|
||||
</div>
|
||||
</dd>
|
||||
<?php } ?>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<div class="small text-body-secondary fw-semibold text-uppercase mb-2">Where</div>
|
||||
<dl class="itflow-asset-dl itflow-domain-dl mb-3">
|
||||
<dt>Host</dt>
|
||||
<dd class="min-w-0">
|
||||
<?php if ($host) { ?>
|
||||
<div class="d-flex align-items-center min-w-0">
|
||||
<span class="font-monospace small text-truncate"><?= escapeHtml($host['display']) ?></span>
|
||||
<button type="button" class="itflow-copy clipboardjs" title="Copy" data-clipboard-text="<?= escapeHtml($host['display']) ?>"><i class="far fa-copy"></i></button>
|
||||
</div>
|
||||
<?php } else { ?>
|
||||
<span class="text-body-secondary">None<?= $can_edit ? ' - Edit to add the host, so it can be checked' : '' ?></span>
|
||||
<?php } ?>
|
||||
</dd>
|
||||
<dt>Domain</dt>
|
||||
<dd class="min-w-0"><?= intval($certificate['certificate_domain_id']) && $certificate['domain_name'] !== null
|
||||
? domainLink($certificate['certificate_domain_id'], $certificate['domain_name'], ['archived' => !empty($certificate['domain_archived_at'])])
|
||||
: '<span class="text-body-secondary">None</span>' ?></dd>
|
||||
<dt>Covers</dt>
|
||||
<dd class="min-w-0">
|
||||
<?php if ($names) { ?>
|
||||
<ul class="list-unstyled mb-0 small">
|
||||
<?php foreach (array_slice($names, 0, 8) as $covered) { ?>
|
||||
<li class="font-monospace text-break"><?= escapeHtml($covered) ?><?= $host && certificateCovers($host['host'], [$covered]) ? ' <i class="fas fa-check text-success ms-1" title="Covers the host"></i>' : '' ?></li>
|
||||
<?php } ?>
|
||||
</ul>
|
||||
<?php if (count($names) > 8) { ?>
|
||||
<details class="small">
|
||||
<summary class="text-body-secondary"><?= count($names) - 8 ?> more</summary>
|
||||
<ul class="list-unstyled mb-0">
|
||||
<?php foreach (array_slice($names, 8) as $covered) { ?>
|
||||
<li class="font-monospace text-break"><?= escapeHtml($covered) ?></li>
|
||||
<?php } ?>
|
||||
</ul>
|
||||
</details>
|
||||
<?php } ?>
|
||||
<?php } else { ?>
|
||||
<span class="text-body-secondary">Unknown</span>
|
||||
<?php } ?>
|
||||
</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($services) { ?>
|
||||
<div class="small text-body-secondary fw-semibold text-uppercase mt-1 mb-1">Services that use it</div>
|
||||
<ul class="list-unstyled mb-0 itflow-links">
|
||||
<?php foreach ($services as $service) { ?>
|
||||
<li class="itflow-link-row">
|
||||
<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=<?= intval($service['service_id']) ?>"><?= escapeHtml($service['service_name']) ?></a></div>
|
||||
<div class="small text-body-secondary"><?= escapeHtml($service['service_importance']) ?> importance</div>
|
||||
</div>
|
||||
</li>
|
||||
<?php } ?>
|
||||
</ul>
|
||||
<?php } ?>
|
||||
|
||||
<?php if (trim((string) $certificate['certificate_notes']) !== '') { ?>
|
||||
<div class="small text-body-secondary fw-semibold text-uppercase mt-3 mb-1">Notes</div>
|
||||
<div class="itflow-credential-note small"><?= nl2br(escapeHtml($certificate['certificate_notes'])) ?></div>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($pem !== '') {
|
||||
$file_name = preg_replace('/[^a-z0-9.\-]+/i', '-', $host ? $host['host'] : $certificate['certificate_name']) . '.crt'; ?>
|
||||
<details class="mt-3">
|
||||
<summary class="small text-body-secondary fw-semibold text-uppercase">Certificate (PEM)</summary>
|
||||
<div class="d-flex flex-wrap gap-2 mt-2 mb-2">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary clipboardjs" data-clipboard-text="<?= escapeHtml($pem) ?>"><i class="far fa-copy me-1"></i>Copy</button>
|
||||
<a class="btn btn-sm btn-outline-secondary" href="<?= certificateDownloadHref($pem) ?>" download="<?= escapeHtml($file_name) ?>"><i class="fas fa-download me-1"></i>Download .crt</a>
|
||||
</div>
|
||||
<pre class="itflow-credential-note small mb-0"><?= escapeHtml($pem) ?></pre>
|
||||
</details>
|
||||
<?php } ?>
|
||||
|
||||
<?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) {
|
||||
$old = trim((string) $entry['certificate_history_old_value']);
|
||||
$new = trim((string) $entry['certificate_history_new_value']); ?>
|
||||
<li class="d-flex gap-2 py-1 border-bottom">
|
||||
<span class="flex-grow-1 min-w-0 text-break">
|
||||
<strong><?= escapeHtml($entry['label']) ?></strong>
|
||||
<?php if (mb_strlen($old) <= 60 && mb_strlen($new) <= 60 && strpos($old . $new, "\n") === false) { ?>
|
||||
<?= $old === '' ? 'set to' : '<span class="text-body-secondary">' . escapeHtml($old) . '</span> →' ?> <?= $new === '' ? '<span class="text-body-secondary">cleared</span>' : escapeHtml($new) ?>
|
||||
<?php } else { ?>
|
||||
changed
|
||||
<?php } ?>
|
||||
</span>
|
||||
<span class="text-body-secondary text-nowrap" title="<?= escapeHtml($entry['certificate_history_modified_at']) ?>"><?= timeAgo($entry['certificate_history_modified_at']) ?></span>
|
||||
</li>
|
||||
<?php } ?>
|
||||
</ul>
|
||||
</details>
|
||||
<?php } ?>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<?php if ($can_edit) { ?>
|
||||
<?php if ($host) { ?>
|
||||
<a class="btn btn-outline-secondary me-auto" href="post.php?check_certificate=<?= $certificate_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"><i class="fas fa-sync-alt me-2"></i>Check now</a>
|
||||
<?php } ?>
|
||||
<button type="button" class="btn btn-primary text-bold ajax-modal" data-modal-size="lg" data-modal-url="modals/certificate/certificate_edit.php?id=<?= $certificate_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';
|
||||
@@ -1,8 +1,36 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* New certificate - for the client it was opened from, or pick the client
|
||||
* here. Give the host it is served on and it is checked as it is saved: the
|
||||
* certificate it serves, its issuer, dates and names, and whether it is OK.
|
||||
* For a host ITFlow can't reach, paste the certificate or type the issuer
|
||||
* and expiry. Opened from a domain (?domain_id=) it starts on that domain.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
$client_id = intval($_GET['client_id'] ?? 0);
|
||||
$certificate_domain_id = 0;
|
||||
$certificate_domain = '';
|
||||
|
||||
// From a domain - its client, the domain, and the domain as the host
|
||||
$from_domain = domainRow($_GET['domain_id'] ?? 0);
|
||||
if ($from_domain) {
|
||||
$client_id = intval($from_domain['domain_client_id']);
|
||||
$certificate_domain_id = intval($from_domain['domain_id']);
|
||||
$certificate_domain = escapeHtml($from_domain['domain_name']);
|
||||
}
|
||||
if ($client_id) {
|
||||
enforceClientAccess();
|
||||
}
|
||||
|
||||
$certificate_form_mode = 'add';
|
||||
$certificate_id = 0;
|
||||
$certificate_name = $certificate_description = $certificate_issued_by = $certificate_expire = $certificate_public_key = $certificate_notes = '';
|
||||
$certificate_favorite = 0;
|
||||
|
||||
ob_start();
|
||||
|
||||
@@ -13,145 +41,18 @@ ob_start();
|
||||
</div>
|
||||
<form action="post.php" method="post" autocomplete="off">
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<?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-details">Details</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" data-bs-toggle="pill" href="#pills-certificate">Certificate</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" data-bs-toggle="pill" href="#pills-notes">Notes</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<hr>
|
||||
|
||||
<div class="tab-content">
|
||||
|
||||
<div class="tab-pane fade show active" id="pills-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>Certificate Name <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" name="name" placeholder="Certificate name" maxlength="200" required autofocus>
|
||||
</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="Short Description">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($client_id) { ?>
|
||||
<div class="mb-3">
|
||||
<label>Domain</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-globe"></i></span>
|
||||
<select class="form-select select2" name="domain_id">
|
||||
<option value="">- Domain -</option>
|
||||
<?php
|
||||
$domains_sql = mysqli_query($mysqli, "SELECT domain_id, domain_name FROM domains WHERE domain_archived_at IS NULL AND domain_client_id = $client_id ORDER BY domain_name ASC");
|
||||
while ($domain_row = mysqli_fetch_assoc($domains_sql)) {
|
||||
$domain_id = intval($domain_row['domain_id']);
|
||||
$domain_name = escapeHtml($domain_row['domain_name']);
|
||||
echo "<option value=\"$domain_id\">$domain_name</option>";
|
||||
}
|
||||
?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="tab-pane fade" id="pills-certificate">
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Domain <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-globe"></i> https://</span>
|
||||
<input type="text" class="form-control" name="domain" id="domain" placeholder="FQDN" maxlength="200" required>
|
||||
<button type="button" class="btn btn-secondary" title="Fetch certificate" onclick="fetchSSL('new')"><i class="fas fa-fw fa-sync-alt"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Issued By </label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
|
||||
<input type="text" class="form-control" name="issued_by" id="issuedBy" placeholder="Issued By" maxlength="200">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Expire Date</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-calendar-times"></i></span>
|
||||
<input type="date" class="form-control" name="expire" id="expire" max="2999-12-31">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Public Key </label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
|
||||
<textarea class="form-control" rows="8" name="public_key" id="publicKey" placeholder="-----BEGIN CERTIFICATE-----"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="tab-pane fade" id="pills-notes">
|
||||
<div class="mb-3">
|
||||
<textarea class="form-control" rows="12" placeholder="Enter some notes" name="notes"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<?php require 'certificate_form.php'; ?>
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<button type="submit" name="add_certificate" class="btn btn-primary text-bold"><i class="fa fa-check"></i> Create</button>
|
||||
<button type="submit" name="add_certificate" class="btn btn-primary text-bold"><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/certificate_fetch_ssl.js"></script>
|
||||
|
||||
<?php
|
||||
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
|
||||
@@ -1,189 +1,57 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Edit a certificate - the host it is served on, its name, what it is for,
|
||||
* the star, the domain it belongs to, the certificate itself (or its issuer
|
||||
* and expiry by hand) and notes. Saving doesn't check the host again unless
|
||||
* it changed; Check now does that. Its history is in the quick look.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
$certificate_id = intval($_GET['id']);
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT certificate_client_id, certificate_created_at, certificate_description, certificate_domain,
|
||||
certificate_domain_id, certificate_expire, certificate_issued_by, certificate_name,
|
||||
certificate_notes, certificate_public_key FROM certificates WHERE certificate_id = $certificate_id LIMIT 1");
|
||||
|
||||
$row = mysqli_fetch_assoc($sql);
|
||||
$certificate_name = escapeHtml($row['certificate_name']);
|
||||
$certificate_description = escapeHtml($row['certificate_description']);
|
||||
$certificate_domain = escapeHtml($row['certificate_domain']);
|
||||
$certificate_domain_id = intval($row['certificate_domain_id']);
|
||||
$certificate_issued_by = escapeHtml($row['certificate_issued_by']);
|
||||
$certificate_public_key = escapeHtml($row['certificate_public_key']);
|
||||
$certificate_notes = escapeHtml($row['certificate_notes']);
|
||||
$certificate_expire = escapeHtml($row['certificate_expire']);
|
||||
$certificate_created_at = escapeHtml($row['certificate_created_at']);
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
|
||||
$history_sql = mysqli_query($mysqli, "SELECT certificate_history_column, certificate_history_modified_at, certificate_history_new_value,
|
||||
certificate_history_old_value FROM certificate_history WHERE certificate_history_certificate_id = $certificate_id");
|
||||
|
||||
$certificate_id = intval($_GET['id'] ?? 0);
|
||||
$certificate = certificateRow($certificate_id);
|
||||
if (!$certificate) {
|
||||
echo json_encode(['error' => 'That certificate no longer exists.']);
|
||||
exit;
|
||||
}
|
||||
$client_id = intval($certificate['certificate_client_id']);
|
||||
enforceClientAccess();
|
||||
|
||||
$certificate_form_mode = 'edit';
|
||||
$certificate_name = escapeHtml($certificate['certificate_name']);
|
||||
$certificate_description = escapeHtml($certificate['certificate_description']);
|
||||
$certificate_domain = escapeHtml($certificate['certificate_domain']);
|
||||
$certificate_domain_id = intval($certificate['certificate_domain_id']);
|
||||
$certificate_issued_by = escapeHtml($certificate['certificate_issued_by']);
|
||||
$certificate_expire = escapeHtml($certificate['certificate_expire']);
|
||||
$certificate_notes = escapeHtml($certificate['certificate_notes']);
|
||||
$certificate_favorite = intval($certificate['certificate_favorite']);
|
||||
// Only a real certificate is shown to keep - anything else on file is cleared on save
|
||||
$certificate_public_key = certificateParse($certificate['certificate_public_key']) ? escapeHtml(trim($certificate['certificate_public_key'])) : '';
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title"><i class="fa fa-fw fa-lock me-2"></i>Editing certificate: <span class="text-bold"><?= $certificate_name ?></span></h5>
|
||||
<h5 class="modal-title text-truncate"><i class="fa fa-fw fa-lock me-2"></i>Editing certificate: <strong><?= $certificate_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="certificate_id" value="<?= $certificate_id ?>">
|
||||
<input type="hidden" name="client_id" value="<?= $client_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="#pillsEditDetails<?= $certificate_id ?>">Details</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" data-bs-toggle="pill" href="#pillsEditCertificate<?= $certificate_id ?>">Certificate</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" data-bs-toggle="pill" href="#pillsEditNotes<?= $certificate_id ?>">Notes</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" data-bs-toggle="pill" href="#pillsEditHistory<?= $certificate_id ?>">History</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<hr>
|
||||
|
||||
<div class="tab-content" <?php if (lookupUserPermission('module_support') <= 1) { echo 'inert'; } ?>>
|
||||
|
||||
<div class="tab-pane fade show active" id="pillsEditDetails<?= $certificate_id ?>">
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Certificate Name <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" name="name" placeholder="Certificate name" maxlength="200" value="<?= $certificate_name ?>" required>
|
||||
</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="Short Description" value="<?= $certificate_description ?>">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Domain</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-globe"></i></span>
|
||||
<select class="form-select select2" name="domain_id">
|
||||
<option value="">- Select Domain -</option>
|
||||
<?php
|
||||
$domains_sql = mysqli_query($mysqli, "SELECT domain_id, domain_name FROM domains WHERE domain_client_id = $client_id");
|
||||
while ($row = mysqli_fetch_assoc($domains_sql)) {
|
||||
$domain_id = intval($row['domain_id']);
|
||||
$domain_name = escapeHtml($row['domain_name']);
|
||||
?>
|
||||
<option value="<?= $domain_id ?>" <?php if ($certificate_domain_id == $domain_id) { echo "selected"; } ?>><?= $domain_name ?></option>
|
||||
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="tab-pane fade" id="pillsEditCertificate<?= $certificate_id ?>">
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Domain <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-globe"></i> https://</span>
|
||||
<input type="text" class="form-control" name="domain" id="editCertificateDomain" placeholder="Domain" maxlength="200" value="<?= $certificate_domain ?>" required>
|
||||
<button type="button" class="btn btn-secondary" title="Fetch certificate" onclick="fetchSSL('edit')"><i class="fas fa-fw fa-sync-alt"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Issued By</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
|
||||
<input type="text" class="form-control" name="issued_by" id="editCertificateIssuedBy" maxlength="200" placeholder="Issued By" value="<?= $certificate_issued_by ?>">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Expire Date</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-calendar-times"></i></span>
|
||||
<input type="date" class="form-control" name="expire" id="editCertificateExpire" max="2999-12-31" value="<?= $certificate_expire ?>">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Public Key </label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-key"></i></span>
|
||||
<textarea class="form-control" rows="8" name="public_key" id="editCertificatePublicKey"><?= $certificate_public_key ?></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="tab-pane fade" id="pillsEditNotes<?= $certificate_id ?>">
|
||||
<div class="mb-3">
|
||||
<textarea class="form-control" name="notes" rows="12" placeholder="Enter some notes"><?= $certificate_notes ?></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tab-pane fade" id="pillsEditHistory<?= $certificate_id ?>">
|
||||
<div class="table-responsive">
|
||||
<table class='table table-sm table-striped border table-hover'>
|
||||
<thead class='table-dark'>
|
||||
<tr>
|
||||
<th>Date</th>
|
||||
<th>Field</th>
|
||||
<th>Before</th>
|
||||
<th>After</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php
|
||||
while ($row = mysqli_fetch_assoc($history_sql)) {
|
||||
$certificate_modified_at = escapeHtml($row['certificate_history_modified_at']);
|
||||
$certificate_field = escapeHtml($row['certificate_history_column']);
|
||||
$certificate_before_value = escapeHtml($row['certificate_history_old_value']);
|
||||
$certificate_after_value = escapeHtml($row['certificate_history_new_value']);
|
||||
?>
|
||||
<tr>
|
||||
<td><?= $certificate_modified_at ?></td>
|
||||
<td><?= $certificate_field ?></td>
|
||||
<td><?= $certificate_before_value ?></td>
|
||||
<td><?= $certificate_after_value ?></td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<?php require 'certificate_form.php'; ?>
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<button type="submit" name="edit_certificate" class="btn btn-primary text-bold"><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>
|
||||
|
||||
<script src="/agent/js/certificate_fetch_ssl.js"></script>
|
||||
|
||||
<?php
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
|
||||
@@ -20,6 +20,9 @@ $client_filter = intval($_GET['client'] ?? 0);
|
||||
// Expiring In Filter
|
||||
$expire_filter = $_GET['expire_days'] ?? '';
|
||||
|
||||
// Problems Filter
|
||||
$problems_filter = !empty($_GET['problems']) ? 1 : 0;
|
||||
|
||||
// Archived Filter
|
||||
$archived_filter = (isset($_GET['archived']) && $_GET['archived'] == 1) ? 1 : 0;
|
||||
|
||||
@@ -46,7 +49,7 @@ ob_start();
|
||||
<label>Search</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-search"></i></span>
|
||||
<input type="text" class="form-control" name="q" value="<?= stripslashes(escapeHtml($q_filter)) ?>" placeholder="Name, domain, issuer">
|
||||
<input type="text" class="form-control" name="q" value="<?= stripslashes(escapeHtml($q_filter)) ?>" placeholder="Name, host, names covered, issuer, fingerprint">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -86,6 +89,17 @@ ob_start();
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Last Check</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-shield-alt"></i></span>
|
||||
<select class="form-select select2" name="problems">
|
||||
<option <?php if (!$problems_filter) { echo "selected"; } ?> value="0">- Any -</option>
|
||||
<option <?php if ($problems_filter) { echo "selected"; } ?> value="1">Problems found - mismatch, untrusted, expired or unreachable</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label>Archived</label>
|
||||
<div class="input-group">
|
||||
|
||||
270
agent/modals/certificate/certificate_form.php
Normal file
270
agent/modals/certificate/certificate_form.php
Normal file
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
/*
|
||||
* Certificate form fields - shared by certificate_add.php and
|
||||
* certificate_edit.php, which set $certificate_form_mode ('add' | 'edit'),
|
||||
* $client_id (0 = pick the client here), $certificate_id and the
|
||||
* $certificate_* values (escaped; empty for a new one) before including
|
||||
* this. Posts what certificateFormSet() (functions/certificate.php) reads.
|
||||
*
|
||||
* Tabs: Certificate (the host it is served on, with Check to see what it
|
||||
* serves now; the name, the star, what it is for and the client's domain it
|
||||
* belongs to), Details (paste the certificate, or type the issuer and expiry
|
||||
* when there is nothing to paste) and Notes. What a check finds - the
|
||||
* issuer, dates, names and fingerprint - is saved, never typed.
|
||||
*
|
||||
* Should not be accessed directly.
|
||||
*/
|
||||
|
||||
isset($mysqli) || die("Direct file access is not allowed");
|
||||
|
||||
$client_options = $domain_options = [];
|
||||
if ($client_id) {
|
||||
$sql = mysqli_query($mysqli, "SELECT domain_id, domain_name FROM domains
|
||||
WHERE domain_client_id = $client_id AND (domain_archived_at IS NULL OR domain_id = " . intval($certificate_domain_id) . ")
|
||||
ORDER BY domain_name ASC");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$domain_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;
|
||||
}
|
||||
}
|
||||
|
||||
$form_id = 'certificateForm' . ($certificate_form_mode === 'edit' ? $certificate_id : 'New');
|
||||
$has_pem = trim(html_entity_decode($certificate_public_key, ENT_QUOTES, 'UTF-8')) !== '';
|
||||
|
||||
?>
|
||||
|
||||
<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 ?>Certificate"><i class="fas fa-fw fa-lock me-2 d-none d-lg-inline"></i>Certificate</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" data-bs-toggle="pill" href="#<?= $form_id ?>Details"><i class="fas fa-fw fa-file-code me-2 d-none d-lg-inline"></i>Paste or by hand</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 ?>">
|
||||
|
||||
<!-- Where it is served, and what it is -->
|
||||
<div class="tab-pane fade show active" id="<?= $form_id ?>Certificate">
|
||||
<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 data-certificate-client>
|
||||
<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>
|
||||
<?php } ?>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Host</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-server"></i></span>
|
||||
<input type="text" class="form-control" name="domain" placeholder="www.example.com, portal.example.com:8443, fw01.example.local" maxlength="200" value="<?= $certificate_domain ?>"
|
||||
autocomplete="off" spellcheck="false" data-certificate-host <?= $certificate_form_mode === 'edit' ? '' : 'autofocus' ?>>
|
||||
<button type="button" class="btn btn-outline-secondary" data-certificate-check-button><i class="fas fa-fw fa-search me-1"></i>Check</button>
|
||||
</div>
|
||||
<div class="form-text" data-certificate-check>Where it is served - a web address is fine, and a port when it isn't 443. Check shows what it serves now; saving a new one checks it.</div>
|
||||
<div class="itflow-certificate-check-result mt-2 d-none" data-certificate-result></div>
|
||||
</div>
|
||||
<div class="col-md-8">
|
||||
<label class="form-label">Name</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" name="name" placeholder="<?= $certificate_domain !== '' ? $certificate_domain : 'The host, if left empty' ?>" maxlength="200" value="<?= $certificate_name ?>" data-certificate-name>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4 d-flex align-items-end">
|
||||
<div class="form-check form-switch mb-2">
|
||||
<input type="checkbox" class="form-check-input" name="favorite" value="1" id="<?= $form_id ?>Favorite" <?= $certificate_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">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="Client portal, VPN, firewall admin, Exchange" maxlength="500" value="<?= $certificate_description ?>">
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Domain</label>
|
||||
<?php if ($client_id) { ?>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-globe"></i></span>
|
||||
<select class="form-select select2" name="domain_id" data-certificate-domain>
|
||||
<option value="0">- Matched from the host -</option>
|
||||
<?php foreach ($domain_options as $domain_option) {
|
||||
$domain_option_id = intval($domain_option['domain_id']); ?>
|
||||
<option value="<?= $domain_option_id ?>" <?= intval($certificate_domain_id) === $domain_option_id ? 'selected' : '' ?> data-icon="fas fa-globe"><?= escapeHtml($domain_option['domain_name']) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-text">The client's domain it is for - left to itself, the one the host is under.</div>
|
||||
<?php } else { ?>
|
||||
<div class="form-text mt-0">Matched to the client's domain the host is under when it's saved.</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- The certificate itself, or the issuer and expiry by hand -->
|
||||
<div class="tab-pane fade" id="<?= $form_id ?>Details">
|
||||
<label class="form-label">Certificate (PEM)</label>
|
||||
<textarea class="form-control font-monospace small" rows="9" name="public_key" spellcheck="false" placeholder="-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----" data-certificate-pem><?= $certificate_public_key ?></textarea>
|
||||
<div class="form-text mb-3">For a host ITFlow can't reach. The issuer, dates, names it covers and fingerprint are read from it - a whole chain is fine, only the first certificate is kept. Never paste the private key.</div>
|
||||
|
||||
<fieldset data-certificate-by-hand>
|
||||
<div class="small text-body-secondary fw-semibold text-uppercase mb-2">Nothing to paste? By hand</div>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-7">
|
||||
<label class="form-label">Issuer</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
|
||||
<input type="text" class="form-control" name="issued_by" maxlength="200" placeholder="Let's Encrypt, DigiCert, Sectigo" value="<?= $certificate_issued_by ?>">
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Expires</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fa fa-fw fa-calendar-times"></i></span>
|
||||
<input type="date" class="form-control" name="expire" max="2999-12-31" value="<?= $certificate_expire ?>">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-text" data-certificate-by-hand-note<?= $has_pem ? '' : ' hidden' ?>>Read from the certificate above - clear it to type these.</div>
|
||||
</fieldset>
|
||||
<?php if ($certificate_form_mode === 'edit') { ?>
|
||||
<p class="text-body-secondary small text-end mt-3 mb-0">Certificate ID <span class="font-monospace"><?= intval($certificate_id) ?></span></p>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
<!-- Notes -->
|
||||
<div class="tab-pane fade" id="<?= $form_id ?>Notes">
|
||||
<label class="form-label">Notes</label>
|
||||
<textarea class="form-control" rows="10" name="notes" placeholder="Where it is installed, who renews it and how, the CSR and where the private key lives, anything to know before replacing it"><?= $certificate_notes ?></textarea>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
itflowReady(function () {
|
||||
var form = document.getElementById(<?= json_encode($form_id) ?>).closest('form');
|
||||
if (form.dataset.certificateFormWired) {
|
||||
return;
|
||||
}
|
||||
form.dataset.certificateFormWired = '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);
|
||||
|
||||
// A pasted certificate says the issuer and expiry - typing them is for when there is none
|
||||
var pem = form.querySelector('[data-certificate-pem]');
|
||||
var byHand = form.querySelector('[data-certificate-by-hand]');
|
||||
var byHandNote = form.querySelector('[data-certificate-by-hand-note]');
|
||||
function syncByHand() {
|
||||
var pasted = pem.value.trim() !== '';
|
||||
byHand.disabled = pasted;
|
||||
byHandNote.hidden = !pasted;
|
||||
}
|
||||
pem.addEventListener('input', syncByHand);
|
||||
syncByHand();
|
||||
|
||||
// The host: the name it is saved under, and Check - what it serves now
|
||||
var host = form.querySelector('[data-certificate-host]');
|
||||
var name = form.querySelector('[data-certificate-name]');
|
||||
var button = form.querySelector('[data-certificate-check-button]');
|
||||
var message = form.querySelector('[data-certificate-check]');
|
||||
var result = form.querySelector('[data-certificate-result]');
|
||||
var domainSelect = form.querySelector('[data-certificate-domain]');
|
||||
var clientSelect = form.querySelector('[data-certificate-client]');
|
||||
var clientInput = form.querySelector('input[name="client_id"]');
|
||||
var messageDefault = message.textContent;
|
||||
var buttonDefault = button.innerHTML;
|
||||
var last = '';
|
||||
|
||||
host.addEventListener('input', function () {
|
||||
name.placeholder = host.value.trim().replace(/^[a-z][a-z0-9+.\-]*:\/\//i, '').split(/[\/?#\s]/)[0].toLowerCase() || 'The host, if left empty';
|
||||
});
|
||||
|
||||
function runCheck(force) {
|
||||
var value = host.value.trim();
|
||||
var client = clientSelect ? clientSelect.value : (clientInput ? clientInput.value : '');
|
||||
var key = value + '|' + client;
|
||||
if (!force && key === last) {
|
||||
return;
|
||||
}
|
||||
last = key;
|
||||
message.classList.remove('text-danger', 'text-warning', 'text-success');
|
||||
result.classList.add('d-none');
|
||||
result.innerHTML = '';
|
||||
if (!value) {
|
||||
message.textContent = messageDefault;
|
||||
return;
|
||||
}
|
||||
button.disabled = true;
|
||||
button.innerHTML = '<span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span>Checking';
|
||||
message.textContent = 'Connecting to ' + value + '...';
|
||||
itflowGet('ajax.php', { certificate_check: 'true', host: value, client_id: client, certificate_id: <?= intval($certificate_id) ?> }, function (data) {
|
||||
button.disabled = false;
|
||||
button.innerHTML = buttonDefault;
|
||||
var response = {};
|
||||
try { response = JSON.parse(data); } catch (e) {}
|
||||
if (!response.message) {
|
||||
message.textContent = messageDefault;
|
||||
return;
|
||||
}
|
||||
message.classList.add({ ok: 'text-success', warn: 'text-warning', bad: 'text-danger' }[response.state] || '');
|
||||
message.textContent = response.message;
|
||||
if (response.html) {
|
||||
result.innerHTML = response.html;
|
||||
result.classList.remove('d-none');
|
||||
}
|
||||
// The client's domain it is under, unless one is picked already
|
||||
if (domainSelect && response.domain_id && (domainSelect.value === '0' || domainSelect.value === '')) {
|
||||
if (domainSelect.itflowSelect) {
|
||||
domainSelect.itflowSelect.setValue(String(response.domain_id));
|
||||
} else {
|
||||
domainSelect.value = String(response.domain_id);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
button.addEventListener('click', function () { runCheck(true); });
|
||||
// Enter in the host checks it, rather than saving half a form
|
||||
host.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
runCheck(true);
|
||||
}
|
||||
});
|
||||
if (clientSelect) {
|
||||
clientSelect.addEventListener('change', function () { if (last) { runCheck(true); } });
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -134,20 +134,31 @@ ob_start();
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($certificates) { ?>
|
||||
<div class="small text-body-secondary fw-semibold text-uppercase mt-3 mb-1">Certificates</div>
|
||||
<ul class="list-unstyled mb-0 itflow-links">
|
||||
<?php foreach ($certificates as $certificate) { ?>
|
||||
<li class="itflow-link-row">
|
||||
<span class="itflow-link-icon" aria-hidden="true"><i class="fas fa-fw fa-lock"></i></span>
|
||||
<div class="min-w-0 flex-grow-1">
|
||||
<div class="d-flex"><a class="ajax-modal text-truncate" href="#" data-modal-url="modals/certificate/certificate_edit.php?id=<?= intval($certificate['certificate_id']) ?>"><?= escapeHtml($certificate['certificate_domain'] ?: $certificate['certificate_name']) ?></a></div>
|
||||
<div class="small text-body-secondary text-truncate"><?= escapeHtml($certificate['certificate_issued_by'] ?: 'Issuer unknown') ?></div>
|
||||
</div>
|
||||
<?= softwareRenewalPill(softwareRenewal($certificate['certificate_expire']), true) ?>
|
||||
</li>
|
||||
<?php if ($certificates || $can_edit) { ?>
|
||||
<div class="d-flex align-items-center mt-3 mb-1">
|
||||
<div class="small text-body-secondary fw-semibold text-uppercase me-auto">Certificates</div>
|
||||
<?php if ($can_edit) { ?>
|
||||
<a class="small ajax-modal" href="#" data-modal-size="lg" data-modal-url="modals/certificate/certificate_add.php?domain_id=<?= $domain_id ?>"><i class="fas fa-plus me-1"></i>New certificate</a>
|
||||
<?php } ?>
|
||||
</ul>
|
||||
</div>
|
||||
<?php if ($certificates) { ?>
|
||||
<ul class="list-unstyled mb-0 itflow-links">
|
||||
<?php foreach ($certificates as $certificate) { ?>
|
||||
<li class="itflow-link-row">
|
||||
<div class="min-w-0 flex-grow-1">
|
||||
<div class="d-flex min-w-0"><?= certificateLink($certificate['certificate_id'], $certificate['certificate_name']) ?></div>
|
||||
<div class="small text-body-secondary text-truncate"><?= escapeHtml(implode(' · ', array_filter([$certificate['certificate_domain'] !== $certificate['certificate_name'] ? $certificate['certificate_domain'] : '', $certificate['certificate_issued_by'] ?: 'Issuer unknown']))) ?></div>
|
||||
</div>
|
||||
<div class="d-flex flex-wrap justify-content-end gap-1">
|
||||
<?php if (!in_array($certificate['certificate_check_status'], [null, '', 'ok'], true)) { ?><?= certificateStatusPill($certificate) ?><?php } ?>
|
||||
<?= certificateExpiryPill(certificateExpiry($certificate)) ?>
|
||||
</div>
|
||||
</li>
|
||||
<?php } ?>
|
||||
</ul>
|
||||
<?php } else { ?>
|
||||
<p class="small text-body-secondary mb-0">None on this domain yet.</p>
|
||||
<?php } ?>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($services) { ?>
|
||||
|
||||
@@ -63,9 +63,11 @@ $sql_domains = mysqli_query(
|
||||
// Associated Certificates
|
||||
$sql_certificates = mysqli_query(
|
||||
$mysqli,
|
||||
"SELECT certificate_domain, certificate_name FROM service_certificates
|
||||
LEFT JOIN certificates ON service_certificates.certificate_id = certificates.certificate_id
|
||||
WHERE service_id = $service_id"
|
||||
"SELECT certificates.certificate_id, certificate_domain, certificate_name, certificate_issued_at, certificate_expire, certificate_check_status,
|
||||
certificate_checked_at, certificate_archived_at FROM service_certificates
|
||||
JOIN certificates ON service_certificates.certificate_id = certificates.certificate_id
|
||||
WHERE service_id = $service_id
|
||||
ORDER BY certificate_name"
|
||||
);
|
||||
|
||||
// Associated Vendors
|
||||
@@ -194,14 +196,13 @@ ob_start();
|
||||
<!-- Certificates -->
|
||||
<?php
|
||||
if (mysqli_num_rows($sql_certificates) > 0) {
|
||||
echo "<h5><i class='fas fa-fw fa-lock me-2'></i>Certificates</h5><ul>";
|
||||
echo "<h5><i class='fas fa-fw fa-lock me-2'></i>Certificates</h5><ul class='list-unstyled ms-1'>";
|
||||
mysqli_data_seek($sql_certificates, 0);
|
||||
while ($row = mysqli_fetch_assoc($sql_certificates)) {
|
||||
if (!empty($row['certificate_name'])) {
|
||||
$certificate_name = escapeHtml($row['certificate_name']);
|
||||
$certificate_domain = escapeHtml($row['certificate_domain']);
|
||||
echo "<li><a href='certificates.php?client_id=$client_id&q=$certificate_name'>$certificate_name ($certificate_domain)</a></li>";
|
||||
}
|
||||
// Each opens its quick look, with when it expires and anything the last check found wrong
|
||||
$certificate_problem = !in_array($row['certificate_check_status'], [null, '', 'ok'], true);
|
||||
echo '<li class="mb-1 d-flex flex-wrap align-items-center gap-2">' . certificateLink($row['certificate_id'], $row['certificate_name'], ['archived' => !empty($row['certificate_archived_at'])])
|
||||
. ($certificate_problem ? certificateStatusPill($row) : '') . certificateExpiryPill(certificateExpiry($row)) . '</li>';
|
||||
}
|
||||
echo "</ul>";
|
||||
}
|
||||
|
||||
@@ -214,12 +214,12 @@ ob_start();
|
||||
<label for="certificates">Select related certificates</label>
|
||||
<select class="form-select select2" id="certificates" name="certificates[]" multiple>
|
||||
<?php
|
||||
$sql = mysqli_query($mysqli, "SELECT certificate_domain, certificate_id, certificate_name FROM certificates WHERE certificate_archived_at IS NULL AND certificate_client_id = $client_id");
|
||||
$sql = mysqli_query($mysqli, "SELECT certificate_domain, certificate_id, certificate_name, certificate_issued_at, certificate_expire FROM certificates
|
||||
WHERE certificate_archived_at IS NULL AND certificate_client_id = $client_id ORDER BY certificate_name ASC");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$cert_id = intval($row['certificate_id']);
|
||||
$cert_name = escapeHtml($row['certificate_name']);
|
||||
$cert_domain = escapeHtml($row['certificate_domain']);
|
||||
echo "<option value=\"$cert_id\">$cert_name ($cert_domain)</option>";
|
||||
echo "<option value=\"$cert_id\"" . selectOptionCertificate($row) . ">$cert_name</option>";
|
||||
}
|
||||
?>
|
||||
</select>
|
||||
|
||||
@@ -310,17 +310,12 @@ ob_start();
|
||||
<?php
|
||||
$selected_ids = array_column(mysqli_fetch_all($sql_certificates, MYSQLI_ASSOC), "certificate_id");
|
||||
|
||||
$sql_all = mysqli_query($mysqli, "SELECT certificate_id, certificate_name FROM certificates WHERE (certificate_archived_at > '$service_created_at' OR certificate_archived_at IS NULL) AND certificate_client_id = $client_id");
|
||||
$sql_all = mysqli_query($mysqli, "SELECT certificate_id, certificate_name, certificate_domain, certificate_issued_at, certificate_expire FROM certificates
|
||||
WHERE (certificate_archived_at > '$service_created_at' OR certificate_archived_at IS NULL) AND certificate_client_id = $client_id ORDER BY certificate_name ASC");
|
||||
while ($row_all = mysqli_fetch_assoc($sql_all)) {
|
||||
$cert_id = intval($row_all['certificate_id']);
|
||||
$cert_name = escapeHtml($row_all['certificate_name']);
|
||||
|
||||
if (in_array($cert_id, $selected_ids)) {
|
||||
echo "<option value=\"$cert_id\" selected>$cert_name</option>";
|
||||
}
|
||||
else{
|
||||
echo "<option value=\"$cert_id\">$cert_name</option>";
|
||||
}
|
||||
echo "<option value=\"$cert_id\"" . (in_array($cert_id, $selected_ids) ? ' selected' : '') . selectOptionCertificate($row_all) . ">$cert_name</option>";
|
||||
}
|
||||
?>
|
||||
</select>
|
||||
|
||||
@@ -2,45 +2,103 @@
|
||||
|
||||
/*
|
||||
* ITFlow - GET/POST request handler for client SSL certificates
|
||||
*
|
||||
* Every handler checks the support module and the certificate's own client;
|
||||
* the domain a certificate links to must be one of that client's. Checks of
|
||||
* the host go through certificateCheck() in functions/certificate.php, and a
|
||||
* check that reaches nothing records only that - the certificate on file,
|
||||
* its dates and its issuer stay as they were.
|
||||
*/
|
||||
|
||||
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
|
||||
|
||||
/** The certificate a request names, after the module and client checks - or back with an error if it is gone. */
|
||||
function certificateForRequest($certificate_id, $level) {
|
||||
global $client_id;
|
||||
enforceUserPermission('module_support', $level);
|
||||
$row = certificateRow($certificate_id);
|
||||
if (!$row) {
|
||||
flashAlert('That certificate no longer exists.', 'error');
|
||||
redirect();
|
||||
}
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
enforceClientAccess();
|
||||
return $row;
|
||||
}
|
||||
|
||||
/** The certificates a bulk action names that this agent may act on - [id => row]. */
|
||||
function certificatesForBulk($level) {
|
||||
global $client_id;
|
||||
enforceUserPermission('module_support', $level);
|
||||
$rows = [];
|
||||
foreach (array_unique(array_map('intval', (array) ($_POST['certificate_ids'] ?? []))) as $certificate_id) {
|
||||
$row = certificateRow($certificate_id);
|
||||
if (!$row) {
|
||||
continue;
|
||||
}
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
enforceClientAccess();
|
||||
$rows[$certificate_id] = $row;
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** What a check found, for a flash message - [message, type]. $name is shown as given. */
|
||||
function certificateCheckMessage($check, $name, $host_display) {
|
||||
$name = escapeHtml($name);
|
||||
if ($check === null) {
|
||||
return ["<strong>$name</strong> has no host to check - Edit it to add the host it is served on, or paste the certificate.", 'error'];
|
||||
}
|
||||
if (empty($check['reachable'])) {
|
||||
return ["Nothing answered on <strong>" . escapeHtml($host_display) . "</strong> - the certificate on file was left as it was. Check the host and port, or paste the certificate if ITFlow can't reach it.", 'error'];
|
||||
}
|
||||
$state = CERTIFICATE_CHECK_STATES[$check['status']];
|
||||
if ($check['status'] === 'ok') {
|
||||
$expiry = certificateExpiry(['certificate_expire' => $check['expire'], 'certificate_issued_at' => $check['issued_at']]);
|
||||
return ["Checked <strong>$name</strong> - OK" . ($expiry ? ', ' . lcfirst($expiry['text']) : ''), $expiry && $expiry['state'] === 'soon' ? 'warning' : 'success'];
|
||||
}
|
||||
return ["Checked <strong>$name</strong> - " . escapeHtml($state['label']) . ': ' . escapeHtml(lcfirst($state['text'])), $check['status'] === 'expired' ? 'error' : 'warning'];
|
||||
}
|
||||
|
||||
if (isset($_POST['add_certificate'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
require_once 'certificate_model.php';
|
||||
|
||||
$client_id = intval($_POST['client_id']);
|
||||
$client_id = intval($_POST['client_id'] ?? 0);
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
// Parse public key data for a manually provided public key
|
||||
if (!empty($public_key) && (empty($expire) && empty($issued_by))) {
|
||||
// Parse the public certificate key. If successful, set attributes from the certificate
|
||||
$public_key_obj = openssl_x509_parse($_POST['public_key']);
|
||||
if ($public_key_obj) {
|
||||
$expire = date('Y-m-d', $public_key_obj['validTo_time_t']);
|
||||
$issued_by = escapeSql($public_key_obj['issuer']['O']);
|
||||
}
|
||||
if (!$client_id || !getFieldById('clients', $client_id, 'client_name')) {
|
||||
flashAlert('Pick the client this certificate is for.', 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
if (empty($expire)) {
|
||||
$expire = "NULL";
|
||||
} else {
|
||||
$expire = "'" . $expire . "'";
|
||||
$form = certificateFormSet($_POST, $client_id, $error);
|
||||
if ($form === null) {
|
||||
flashAlert($error, 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
mysqli_query($mysqli,"INSERT INTO certificates SET certificate_name = '$name', certificate_description = '$description', certificate_domain = '$domain', certificate_issued_by = '$issued_by', certificate_expire = $expire, certificate_public_key = '$public_key', certificate_notes = '$notes', certificate_domain_id = $domain_id, certificate_client_id = $client_id");
|
||||
|
||||
mysqli_query($mysqli, "INSERT INTO certificates SET {$form['set']}, certificate_client_id = $client_id");
|
||||
$certificate_id = mysqli_insert_id($mysqli);
|
||||
|
||||
logAudit("Certificate", "Create", "$session_name created certificate $name", $client_id, $certificate_id);
|
||||
// What the host serves - unless a different certificate was pasted, which is kept
|
||||
$check = $form['host'] ? certificateCheckAndSave($certificate_id, $form['parsed']['pem'] ?? '', false) : null;
|
||||
|
||||
flashAlert("Certificate <strong>$name</strong> created");
|
||||
$name = $form['name'];
|
||||
$name_html = escapeHtml($name);
|
||||
logAudit("Certificate", "Create", "$session_name created certificate " . escapeSql($name), $client_id, $certificate_id);
|
||||
|
||||
if ($check !== null && empty($check['reachable'])) {
|
||||
flashAlert("Certificate <strong>$name_html</strong> created - nothing answered on <strong>" . escapeHtml($form['host']['display']) . "</strong>, so " . ($form['parsed'] ? 'what you pasted is what is on file' : 'paste the certificate, or set the expiry by hand'), 'warning');
|
||||
} elseif ($check !== null) {
|
||||
[$message, $type] = certificateCheckMessage($check, $name, $form['host']['display']);
|
||||
flashAlert("Certificate <strong>$name_html</strong> created and " . lcfirst(str_replace("<strong>$name_html</strong> ", '', $message)), $type);
|
||||
} else {
|
||||
flashAlert("Certificate <strong>$name_html</strong> created");
|
||||
}
|
||||
|
||||
redirect();
|
||||
|
||||
@@ -50,111 +108,74 @@ if (isset($_POST['edit_certificate'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
$row = certificateForRequest($_POST['certificate_id'] ?? 0, 2);
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
|
||||
require_once 'certificate_model.php';
|
||||
|
||||
$certificate_id = intval($_POST['certificate_id']);
|
||||
|
||||
$client_id = intval(getFieldById('certificates', $certificate_id, 'certificate_client_id'));
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
// Parse public key data for a manually provided public key
|
||||
if (!empty($public_key) && (empty($expire) && empty($issued_by))) {
|
||||
// Parse the public certificate key. If successful, set attributes from the certificate
|
||||
$public_key_obj = openssl_x509_parse($_POST['public_key']);
|
||||
if ($public_key_obj) {
|
||||
$expire = date('Y-m-d', $public_key_obj['validTo_time_t']);
|
||||
$issued_by = escapeSql($public_key_obj['issuer']['O']);
|
||||
}
|
||||
$form = certificateFormSet($_POST, $client_id, $error);
|
||||
if ($form === null) {
|
||||
flashAlert($error, 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
if (empty($expire)) {
|
||||
$expire = "NULL";
|
||||
} else {
|
||||
$expire = "'" . $expire . "'";
|
||||
$before = certificateHistorySnapshot($certificate_id);
|
||||
|
||||
mysqli_query($mysqli, "UPDATE certificates SET {$form['set']} WHERE certificate_id = $certificate_id");
|
||||
|
||||
certificateWriteHistory($certificate_id, $before, certificateHistorySnapshot($certificate_id));
|
||||
|
||||
// A new host is a new place to check; otherwise saving stays quick. A
|
||||
// certificate newly pasted here is kept over what the host serves.
|
||||
$host_changed = $form['host'] && $form['host']['display'] !== (string) $row['certificate_domain'];
|
||||
$pasted_new = $form['parsed'] && $form['parsed']['fingerprint'] !== (string) $row['certificate_fingerprint'];
|
||||
if (!$form['host']) {
|
||||
// No host - nothing to check, so no result from one
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_check_status = NULL, certificate_checked_at = NULL WHERE certificate_id = $certificate_id");
|
||||
} elseif ($host_changed) {
|
||||
certificateCheckAndSave($certificate_id, $pasted_new ? $form['parsed']['pem'] : '');
|
||||
}
|
||||
|
||||
// Get current certificate info
|
||||
$original_certificate_info = mysqli_fetch_assoc(mysqli_query($mysqli,"
|
||||
SELECT
|
||||
certificates.*,
|
||||
domains.domain_name
|
||||
FROM certificates
|
||||
LEFT JOIN domains ON certificate_domain_id = domain_id
|
||||
WHERE certificate_id = $certificate_id
|
||||
"));
|
||||
$name = $form['name'];
|
||||
logAudit("Certificate", "Edit", "$session_name edited certificate " . escapeSql($name), $client_id, $certificate_id);
|
||||
|
||||
// Update certificate
|
||||
mysqli_query($mysqli,"UPDATE certificates SET certificate_name = '$name', certificate_description = '$description', certificate_domain = '$domain', certificate_issued_by = '$issued_by', certificate_expire = $expire, certificate_public_key = '$public_key', certificate_notes = '$notes', certificate_domain_id = '$domain_id' WHERE certificate_id = $certificate_id");
|
||||
|
||||
// Fetch the updated info
|
||||
$new_certificate_info = mysqli_fetch_assoc(mysqli_query($mysqli,"
|
||||
SELECT
|
||||
certificates.*,
|
||||
domains.domain_name
|
||||
FROM certificates
|
||||
LEFT JOIN domains ON certificate_domain_id = domain_id
|
||||
WHERE certificate_id = $certificate_id
|
||||
"));
|
||||
|
||||
// Compare/log changes between old/new info
|
||||
$ignored_columns = ["certificate_public_key", "certificate_updated_at", "certificate_accessed_at", "certificate_domain_id"];
|
||||
foreach ($original_certificate_info as $column => $old_value) {
|
||||
$new_value = $new_certificate_info[$column];
|
||||
if ($old_value != $new_value && !in_array($column, $ignored_columns)) {
|
||||
$column = escapeSql($column);
|
||||
$old_value = escapeSql($old_value);
|
||||
$new_value = escapeSql($new_value);
|
||||
mysqli_query($mysqli,"INSERT INTO certificate_history SET certificate_history_column = '$column', certificate_history_old_value = '$old_value', certificate_history_new_value = '$new_value', certificate_history_certificate_id = $certificate_id");
|
||||
}
|
||||
}
|
||||
|
||||
logAudit("Certificate", "Edit", "$session_name edited certificate $name", $client_id, $certificate_id);
|
||||
|
||||
flashAlert("Certificate <strong>$name</strong> updated");
|
||||
flashAlert("Certificate <strong>" . escapeHtml($name) . "</strong> updated");
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_GET['refresh_certificate'])) {
|
||||
// Check now - connect to the host and save what it serves
|
||||
if (isset($_GET['check_certificate']) || isset($_GET['refresh_certificate'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
$row = certificateForRequest($_GET['check_certificate'] ?? $_GET['refresh_certificate'], 2);
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
|
||||
$certificate_id = intval($_GET['refresh_certificate']);
|
||||
$check = certificateCheckAndSave($certificate_id);
|
||||
[$message, $type] = certificateCheckMessage($check, $row['certificate_name'], $row['certificate_domain']);
|
||||
|
||||
// Get Name, Domain and Client ID for lookup, logging and alert message
|
||||
$sql = mysqli_query($mysqli,"SELECT certificate_name, certificate_domain, certificate_client_id FROM certificates WHERE certificate_id = $certificate_id");
|
||||
$row = mysqli_fetch_assoc($sql);
|
||||
$certificate_name = escapeSql($row['certificate_name']);
|
||||
$certificate_domain = escapeSql($row['certificate_domain']);
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
// Get fresh certificate from the live host
|
||||
$certificate = getSslCertificate($certificate_domain);
|
||||
|
||||
if ($certificate_domain && $certificate['success']) {
|
||||
|
||||
$expire = escapeSql($certificate['expire']);
|
||||
$issued_by = escapeSql($certificate['issued_by']);
|
||||
$public_key = escapeSql($certificate['public_key']);
|
||||
|
||||
mysqli_query($mysqli,"UPDATE certificates SET certificate_issued_by = '$issued_by', certificate_expire = '$expire', certificate_public_key = '$public_key' WHERE certificate_id = $certificate_id");
|
||||
|
||||
logAudit("Certificate", "Refresh", "$session_name refreshed certificate $certificate_name", $client_id, $certificate_id);
|
||||
|
||||
flashAlert("Refreshed certificate <strong>$certificate_name</strong>");
|
||||
|
||||
} else {
|
||||
flashAlert("Could not retrieve a certificate for <strong>$certificate_name</strong>", 'error');
|
||||
if ($check !== null) {
|
||||
logAudit("Certificate", "Check", "$session_name checked certificate " . escapeSql($row['certificate_name']) . ' - ' . (empty($check['reachable']) ? 'unreachable' : $check['status']), $client_id, $certificate_id);
|
||||
}
|
||||
|
||||
flashAlert($message, $type);
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_GET['favorite_certificate']) || isset($_GET['unfavorite_certificate'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
$favorite = isset($_GET['favorite_certificate']) ? 1 : 0;
|
||||
$row = certificateForRequest($favorite ? $_GET['favorite_certificate'] : $_GET['unfavorite_certificate'], 2);
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_favorite = $favorite WHERE certificate_id = $certificate_id");
|
||||
|
||||
logAudit("Certificate", "Edit", "$session_name " . ($favorite ? 'starred' : 'unstarred') . " certificate " . escapeSql($row['certificate_name']), $client_id, $certificate_id);
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
@@ -163,23 +184,14 @@ if (isset($_GET['archive_certificate'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
$row = certificateForRequest($_GET['archive_certificate'], 2);
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
|
||||
$certificate_id = intval($_GET['archive_certificate']);
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_archived_at = NOW() WHERE certificate_id = $certificate_id");
|
||||
|
||||
// Get Certificate Name and Client ID for logging and alert message
|
||||
$sql = mysqli_query($mysqli,"SELECT certificate_name, certificate_client_id FROM certificates WHERE certificate_id = $certificate_id");
|
||||
$row = mysqli_fetch_assoc($sql);
|
||||
$certificate_name = escapeSql($row['certificate_name']);
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
logAudit("Certificate", "Archive", "$session_name archived certificate " . escapeSql($row['certificate_name']), $client_id, $certificate_id);
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
mysqli_query($mysqli,"UPDATE certificates SET certificate_archived_at = NOW() WHERE certificate_id = $certificate_id");
|
||||
|
||||
logAudit("Certificate", "Archive", "$session_name archived certificate $certificate_name", $client_id, $certificate_id);
|
||||
|
||||
flashAlert("Certificate <strong>$certificate_name</strong> archived", 'alert');
|
||||
flashAlert("Certificate <strong>" . escapeHtml($row['certificate_name']) . "</strong> archived", 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
@@ -189,23 +201,14 @@ if (isset($_GET['restore_certificate'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
$row = certificateForRequest($_GET['restore_certificate'], 2);
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
|
||||
$certificate_id = intval($_GET['restore_certificate']);
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_archived_at = NULL WHERE certificate_id = $certificate_id");
|
||||
|
||||
// Get Certificate Name and Client ID for logging and alert message
|
||||
$sql = mysqli_query($mysqli,"SELECT certificate_name, certificate_client_id FROM certificates WHERE certificate_id = $certificate_id");
|
||||
$row = mysqli_fetch_assoc($sql);
|
||||
$certificate_name = escapeSql($row['certificate_name']);
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
logAudit("Certificate", "Restore", "$session_name restored certificate " . escapeSql($row['certificate_name']), $client_id, $certificate_id);
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
mysqli_query($mysqli,"UPDATE certificates SET certificate_archived_at = NULL WHERE certificate_id = $certificate_id");
|
||||
|
||||
logAudit("Certificate", "Restore", "$session_name restored certificate $certificate_name", $client_id, $certificate_id);
|
||||
|
||||
flashAlert("Certificate <strong>$certificate_name</strong> restored");
|
||||
flashAlert("Certificate <strong>" . escapeHtml($row['certificate_name']) . "</strong> restored");
|
||||
|
||||
redirect();
|
||||
|
||||
@@ -215,85 +218,102 @@ if (isset($_GET['delete_certificate'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_support', 3);
|
||||
$row = certificateForRequest($_GET['delete_certificate'], 3);
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
|
||||
$certificate_id = intval($_GET['delete_certificate']);
|
||||
// Its history and its links to services go with it (ON DELETE CASCADE)
|
||||
mysqli_query($mysqli, "DELETE FROM certificates WHERE certificate_id = $certificate_id");
|
||||
|
||||
// Get Certificate Name and Client ID for logging and alert message
|
||||
$sql = mysqli_query($mysqli,"SELECT certificate_name, certificate_client_id FROM certificates WHERE certificate_id = $certificate_id");
|
||||
$row = mysqli_fetch_assoc($sql);
|
||||
$certificate_name = escapeSql($row['certificate_name']);
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
logAudit("Certificate", "Delete", "$session_name deleted certificate " . escapeSql($row['certificate_name']), $client_id);
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
mysqli_query($mysqli,"DELETE FROM certificates WHERE certificate_id = $certificate_id");
|
||||
|
||||
logAudit("Certificate", "Delete", "$session_name deleted certificate $name", $client_id);
|
||||
|
||||
flashAlert("Certificate <strong>$certificate_name</strong> deleted");
|
||||
flashAlert("Certificate <strong>" . escapeHtml($row['certificate_name']) . "</strong> deleted", 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_POST['bulk_refresh_certificates'])) {
|
||||
if (isset($_POST['bulk_favorite_certificates']) || isset($_POST['bulk_unfavorite_certificates'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
if (isset($_POST['certificate_ids'])) {
|
||||
|
||||
// TLS lookups on dead hosts wait out a 5 sec timeout each - don't time out mid-batch
|
||||
set_time_limit(0);
|
||||
|
||||
// Get Selected Count
|
||||
$count = count($_POST['certificate_ids']);
|
||||
$refreshed_count = 0;
|
||||
|
||||
// Cycle through array and refresh each record
|
||||
foreach ($_POST['certificate_ids'] as $certificate_id) {
|
||||
|
||||
$certificate_id = intval($certificate_id);
|
||||
|
||||
// Get Name, Domain and Client ID for lookup, logging and alert message
|
||||
$sql = mysqli_query($mysqli,"SELECT certificate_name, certificate_domain, certificate_client_id FROM certificates WHERE certificate_id = $certificate_id");
|
||||
$row = mysqli_fetch_assoc($sql);
|
||||
$certificate_name = escapeSql($row['certificate_name']);
|
||||
$certificate_domain = escapeSql($row['certificate_domain']);
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
// Skip certificates without a domain to query (eg manually pasted keys)
|
||||
if (!$certificate_domain) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get fresh certificate from the live host
|
||||
$certificate = getSslCertificate($certificate_domain);
|
||||
|
||||
if ($certificate['success']) {
|
||||
|
||||
$expire = escapeSql($certificate['expire']);
|
||||
$issued_by = escapeSql($certificate['issued_by']);
|
||||
$public_key = escapeSql($certificate['public_key']);
|
||||
|
||||
mysqli_query($mysqli,"UPDATE certificates SET certificate_issued_by = '$issued_by', certificate_expire = '$expire', certificate_public_key = '$public_key' WHERE certificate_id = $certificate_id");
|
||||
|
||||
logAudit("Certificate", "Refresh", "$session_name refreshed certificate $certificate_name", $client_id, $certificate_id);
|
||||
|
||||
$refreshed_count++;
|
||||
}
|
||||
}
|
||||
|
||||
logAudit("Certificate", "Bulk Refresh", "$session_name refreshed $refreshed_count certificate(s)", $client_id);
|
||||
|
||||
flashAlert("Refreshed <strong>$refreshed_count</strong> of <strong>$count</strong> certificate(s)");
|
||||
|
||||
$favorite = isset($_POST['bulk_favorite_certificates']) ? 1 : 0;
|
||||
$count = 0;
|
||||
foreach (certificatesForBulk(2) as $certificate_id => $row) {
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_favorite = $favorite WHERE certificate_id = $certificate_id");
|
||||
logAudit("Certificate", "Edit", "$session_name " . ($favorite ? 'starred' : 'unstarred') . " certificate " . escapeSql($row['certificate_name']), intval($row['certificate_client_id']), $certificate_id);
|
||||
$count++;
|
||||
}
|
||||
|
||||
flashAlert(($favorite ? 'Starred' : 'Unstarred') . " <strong>$count</strong> certificate" . ($count === 1 ? '' : 's'));
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_POST['bulk_check_certificates']) || isset($_POST['bulk_refresh_certificates'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
// A host that doesn't answer waits out a timeout - don't time out mid-batch
|
||||
set_time_limit(0);
|
||||
|
||||
$tally = array_fill_keys(array_keys(CERTIFICATE_CHECK_STATES), 0);
|
||||
$no_host = 0;
|
||||
foreach (certificatesForBulk(2) as $certificate_id => $row) {
|
||||
$check = certificateCheckAndSave($certificate_id);
|
||||
if ($check === null) {
|
||||
$no_host++;
|
||||
continue;
|
||||
}
|
||||
$status = empty($check['reachable']) ? 'unreachable' : $check['status'];
|
||||
$tally[$status]++;
|
||||
logAudit("Certificate", "Check", "$session_name checked certificate " . escapeSql($row['certificate_name']) . " - $status", intval($row['certificate_client_id']), $certificate_id);
|
||||
}
|
||||
|
||||
$checked = array_sum($tally);
|
||||
$parts = [];
|
||||
foreach ($tally as $status => $count) {
|
||||
if ($count) {
|
||||
$parts[] = "<strong>$count</strong> " . (in_array($status, ['ok', 'mismatch'], true) ? CERTIFICATE_CHECK_STATES[$status]['label'] : strtolower(CERTIFICATE_CHECK_STATES[$status]['label']));
|
||||
}
|
||||
}
|
||||
$problems = $checked - $tally['ok'];
|
||||
flashAlert("Checked <strong>$checked</strong> certificate" . ($checked === 1 ? '' : 's') . ($parts ? ' - ' . implode(', ', $parts) : '') . ($no_host ? "; <strong>$no_host</strong> with no host to check" : ''), $problems || $no_host ? 'warning' : 'success');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_POST['bulk_archive_certificates'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
$count = 0;
|
||||
foreach (certificatesForBulk(2) as $certificate_id => $row) {
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_archived_at = NOW() WHERE certificate_id = $certificate_id");
|
||||
logAudit("Certificate", "Archive", "$session_name archived certificate " . escapeSql($row['certificate_name']), intval($row['certificate_client_id']), $certificate_id);
|
||||
$count++;
|
||||
}
|
||||
|
||||
flashAlert("Archived <strong>$count</strong> certificate" . ($count === 1 ? '' : 's'), 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_POST['bulk_restore_certificates'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
$count = 0;
|
||||
foreach (certificatesForBulk(2) as $certificate_id => $row) {
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_archived_at = NULL WHERE certificate_id = $certificate_id");
|
||||
logAudit("Certificate", "Restore", "$session_name restored certificate " . escapeSql($row['certificate_name']), intval($row['certificate_client_id']), $certificate_id);
|
||||
$count++;
|
||||
}
|
||||
|
||||
flashAlert("Restored <strong>$count</strong> certificate" . ($count === 1 ? '' : 's'));
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
@@ -302,38 +322,15 @@ if (isset($_POST['bulk_delete_certificates'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
enforceUserPermission('module_support', 3);
|
||||
|
||||
if (isset($_POST['certificate_ids'])) {
|
||||
|
||||
// Get selected count
|
||||
$count = count($_POST['certificate_ids']);
|
||||
|
||||
// Cycle through array and delete each certificate
|
||||
foreach ($_POST['certificate_ids'] as $certificate_id) {
|
||||
|
||||
$certificate_id = intval($certificate_id);
|
||||
|
||||
// Get Certificate Name and Client ID for logging and alert message
|
||||
$sql = mysqli_query($mysqli,"SELECT certificate_name, certificate_client_id FROM certificates WHERE certificate_id = $certificate_id");
|
||||
$row = mysqli_fetch_assoc($sql);
|
||||
$certificate_name = escapeSql($row['certificate_name']);
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
|
||||
enforceClientAccess();
|
||||
|
||||
mysqli_query($mysqli, "DELETE FROM certificates WHERE certificate_id = $certificate_id AND certificate_client_id = $client_id");
|
||||
|
||||
logAudit("Certificate", "Delete", "$session_name deleted certificate $certificate_name", $client_id);
|
||||
|
||||
}
|
||||
|
||||
logAudit("Certificate", "Bulk Delete", "$session_name deleted $count certificates", $client_id);
|
||||
|
||||
flashAlert("Deleted <strong>$count</strong> certificate(s)", 'error');
|
||||
|
||||
$count = 0;
|
||||
foreach (certificatesForBulk(3) as $certificate_id => $row) {
|
||||
mysqli_query($mysqli, "DELETE FROM certificates WHERE certificate_id = $certificate_id");
|
||||
logAudit("Certificate", "Delete", "$session_name deleted certificate " . escapeSql($row['certificate_name']), intval($row['certificate_client_id']));
|
||||
$count++;
|
||||
}
|
||||
|
||||
flashAlert("Deleted <strong>$count</strong> certificate" . ($count === 1 ? '' : 's'), 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
@@ -382,18 +379,23 @@ if (isExportRequest('export_certificates')) {
|
||||
}
|
||||
|
||||
// Expiring In Filter
|
||||
$expire_query = '';
|
||||
if (!empty($_POST['expire_days'])) {
|
||||
if ($_POST['expire_days'] == "expired") {
|
||||
$expire_query = "AND (certificate_expire IS NOT NULL AND certificate_expire != '0000-00-00' AND certificate_expire < CURDATE())";
|
||||
$expire_query = "AND (certificate_expire IS NOT NULL AND certificate_expire < CURDATE())";
|
||||
$filter_summary['Expiry'] = 'Expired';
|
||||
} else {
|
||||
$expire_days = intval($_POST['expire_days']);
|
||||
$expire_query = "AND (certificate_expire IS NOT NULL AND certificate_expire != '0000-00-00' AND certificate_expire BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL $expire_days DAY))";
|
||||
$expire_query = "AND (certificate_expire IS NOT NULL AND certificate_expire BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL $expire_days DAY))";
|
||||
$filter_summary['Expiry'] = "Expiring within $expire_days days";
|
||||
}
|
||||
} else {
|
||||
// Default - any
|
||||
$expire_query = '';
|
||||
}
|
||||
|
||||
// Problems Filter - the last check of the host found something wrong
|
||||
$problem_query = '';
|
||||
if (!empty($_POST['problems'])) {
|
||||
$problem_query = 'AND ' . certificateProblemSql();
|
||||
$filter_summary['Check'] = 'Problems found';
|
||||
}
|
||||
|
||||
// Search Filter
|
||||
@@ -402,16 +404,25 @@ if (isExportRequest('export_certificates')) {
|
||||
$filter_summary['Search'] = $_POST['q'];
|
||||
}
|
||||
|
||||
[$certificate_columns, $certificate_joins] = certificateSelectSql();
|
||||
$status_labels = [];
|
||||
foreach (CERTIFICATE_CHECK_STATES as $status => $state) {
|
||||
$status_labels[] = "WHEN '$status' THEN '" . escapeSql($state['label']) . "'";
|
||||
}
|
||||
$sql = mysqli_query(
|
||||
$mysqli,
|
||||
"SELECT * FROM certificates
|
||||
LEFT JOIN clients ON client_id = certificate_client_id
|
||||
"SELECT $certificate_columns,
|
||||
CASE certificate_check_status " . implode(' ', $status_labels) . " ELSE '' END AS certificate_check_label,
|
||||
REPLACE(certificate_names, '\\n', ', ') AS certificate_names_list
|
||||
FROM certificates $certificate_joins
|
||||
WHERE $archive_query
|
||||
AND (certificate_name LIKE '%$q%' OR certificate_domain LIKE '%$q%' OR certificate_description LIKE '%$q%' OR certificate_issued_by LIKE '%$q%' OR client_name LIKE '%$q%')
|
||||
AND (certificate_name LIKE '%$q%' OR certificate_domain LIKE '%$q%' OR certificate_description LIKE '%$q%' OR certificate_issued_by LIKE '%$q%'
|
||||
OR certificate_names LIKE '%$q%' OR certificate_fingerprint LIKE '%$q%' OR client_name LIKE '%$q%')
|
||||
" . clientScopeSql('certificate_client_id') . "
|
||||
$client_query
|
||||
$expire_query
|
||||
ORDER BY certificate_name ASC"
|
||||
$problem_query
|
||||
ORDER BY client_name ASC, certificate_name ASC"
|
||||
);
|
||||
|
||||
$num_rows = mysqli_num_rows($sql);
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
|
||||
|
||||
$name = escapeSql($_POST['name']);
|
||||
$description = escapeSql($_POST['description']);
|
||||
$domain = escapeSql($_POST['domain']);
|
||||
$issued_by = escapeSql($_POST['issued_by']);
|
||||
$expire = escapeSql($_POST['expire']);
|
||||
$public_key = escapeSql($_POST['public_key']);
|
||||
$notes = escapeSql($_POST['notes']);
|
||||
$domain_id = intval($_POST['domain_id'] ?? 0);
|
||||
@@ -1960,9 +1960,10 @@ if (isset($_POST["export_client_pdf"])) {
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Certificate Name</th>
|
||||
<th>Domain Name</th>
|
||||
<th>Host</th>
|
||||
<th>Issuer</th>
|
||||
<th>Expiration Date</th>
|
||||
<th>Last Check</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>";
|
||||
@@ -1971,12 +1972,14 @@ if (isset($_POST["export_client_pdf"])) {
|
||||
$certificate_domain = escapeHtml($row["certificate_domain"]);
|
||||
$certificate_issued_by = escapeHtml($row["certificate_issued_by"]);
|
||||
$certificate_expire = escapeHtml($row["certificate_expire"]);
|
||||
$certificate_check = escapeHtml(CERTIFICATE_CHECK_STATES[$row["certificate_check_status"] ?? '']['label'] ?? '');
|
||||
$html .= "
|
||||
<tr style='page-break-inside: avoid;'>
|
||||
<td>$certificate_name</td>
|
||||
<td>$certificate_domain</td>
|
||||
<td>$certificate_issued_by</td>
|
||||
<td>$certificate_expire</td>
|
||||
<td>$certificate_check</td>
|
||||
</tr>";
|
||||
}
|
||||
$html .= "
|
||||
|
||||
@@ -76,7 +76,8 @@ if (isset($_POST['add_service'])) {
|
||||
if (isset($_POST['certificates'])) {
|
||||
foreach($_POST['certificates'] as $cert_id) {
|
||||
$cert_id = intval($cert_id);
|
||||
mysqli_query($mysqli, "INSERT INTO service_certificates SET service_id = $service_id, certificate_id = $cert_id");
|
||||
// Only the client's own certificates
|
||||
mysqli_query($mysqli, "INSERT INTO service_certificates (service_id, certificate_id) SELECT $service_id, certificate_id FROM certificates WHERE certificate_id = $cert_id AND certificate_client_id = $client_id");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,8 +166,9 @@ if (isset($_POST['edit_service'])) {
|
||||
|
||||
if (isset($_POST['certificates'])) {
|
||||
foreach($_POST['certificates'] as $cert_id) {
|
||||
$cert_id = intval($cert_id);
|
||||
mysqli_query($mysqli, "INSERT INTO service_certificates SET service_id = $service_id, certificate_id = $cert_id");
|
||||
$cert_id = intval($cert_id);
|
||||
// Only the client's own certificates
|
||||
mysqli_query($mysqli, "INSERT INTO service_certificates (service_id, certificate_id) SELECT $service_id, certificate_id FROM certificates WHERE certificate_id = $cert_id AND certificate_client_id = $client_id");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
<?php
|
||||
|
||||
// Variable assignment from POST (or: blank/from DB is updating)
|
||||
|
||||
if (isset($_POST['certificate_name'])) {
|
||||
$name = escapeSql($_POST['certificate_name']);
|
||||
} elseif ($certificate_row) {
|
||||
$name = $certificate_row['certificate_name'];
|
||||
} else {
|
||||
$name = '';
|
||||
}
|
||||
|
||||
if (isset($_POST['certificate_description'])) {
|
||||
$description = escapeSql($_POST['certificate_description']);
|
||||
} elseif ($certificate_row) {
|
||||
$description = $certificate_row['certificate_description'];
|
||||
} else {
|
||||
$description = '';
|
||||
}
|
||||
|
||||
if (isset($_POST['certificate_domain'])) {
|
||||
$domain = escapeSql($_POST['certificate_domain']);
|
||||
} elseif ($certificate_row) {
|
||||
$domain = $certificate_row['certificate_domain'];
|
||||
} else {
|
||||
$domain = '';
|
||||
}
|
||||
|
||||
if (isset($_POST['certificate_issued_by'])) {
|
||||
$issued_by = escapeSql($_POST['certificate_issued_by']);
|
||||
} elseif ($certificate_row) {
|
||||
$issued_by = $certificate_row['certificate_issued_by'];
|
||||
} else {
|
||||
$issued_by = '';
|
||||
}
|
||||
|
||||
if (isset($_POST['certificate_expire'])) {
|
||||
$expire = escapeSql($_POST['certificate_expire']);
|
||||
} elseif ($certificate_row) {
|
||||
$expire = $certificate_row['certificate_expire'];
|
||||
} else {
|
||||
$expire = '';
|
||||
}
|
||||
|
||||
if (isset($_POST['certificate_public_key'])) {
|
||||
$public_key = escapeSql($_POST['certificate_public_key']);
|
||||
} elseif ($certificate_row) {
|
||||
$public_key = $certificate_row['certificate_public_key'];
|
||||
} else {
|
||||
$public_key = '';
|
||||
}
|
||||
|
||||
if (isset($_POST['certificate_notes'])) {
|
||||
$notes = escapeSql($_POST['certificate_notes']);
|
||||
} elseif ($certificate_row) {
|
||||
$notes = $certificate_row['certificate_notes'];
|
||||
} else {
|
||||
$notes = '';
|
||||
}
|
||||
|
||||
if (isset($_POST['certificate_domain_id'])) {
|
||||
$domain_id = intval($_POST['certificate_domain_id']);
|
||||
} elseif ($certificate_row) {
|
||||
$domain_id = intval($certificate_row['certificate_domain_id']);
|
||||
} else {
|
||||
$domain_id = 0;
|
||||
}
|
||||
@@ -3,56 +3,41 @@
|
||||
require_once '../validate_api_key.php';
|
||||
require_once '../require_post_method.php';
|
||||
|
||||
// Parse Info
|
||||
require_once 'certificate_model.php';
|
||||
/*
|
||||
* Create a certificate - a name and/or the host it is served on
|
||||
* (certificate_domain, as host or host:port). The same rules as the New
|
||||
* Certificate form (certificateFormSet()): the host is tidied, a PEM in
|
||||
* certificate_public_key is the last word on the issuer, dates, names and
|
||||
* fingerprint, the domain must be one of the client's (matched from the host
|
||||
* when none is given), and a host is checked as it is saved.
|
||||
*/
|
||||
|
||||
// Default
|
||||
$insert_id = false;
|
||||
|
||||
// Require name and domain_name
|
||||
if (!empty($name) && !empty($domain) && !empty($client_id)) {
|
||||
if (!empty($client_id) && is_array($_POST)) {
|
||||
$post = [];
|
||||
foreach (['name', 'description', 'domain', 'issued_by', 'expire', 'public_key', 'notes', 'domain_id', 'favorite'] as $field) {
|
||||
$post[$field] = $_POST["certificate_$field"] ?? '';
|
||||
}
|
||||
|
||||
// TODO: Doesn't work. Making this work seems tricky. Think we need to be json-encoding the pubkey on POST and then decoding & parsing it here?
|
||||
// For now, just let the certificate refresher catch this
|
||||
// Parse public key data if provided and expire/issued_by are missing
|
||||
if (!empty($public_key) && (empty($expire) && empty($issued_by))) {
|
||||
$public_key_obj = openssl_x509_parse($_POST['certificate_public_key']);
|
||||
if ($public_key_obj) {
|
||||
$expire = date('Y-m-d', $public_key_obj['validTo_time_t']);
|
||||
$issued_by = escapeSql($public_key_obj['issuer']['O']);
|
||||
$form = certificateFormSet($post, $client_id, $error);
|
||||
if ($form !== null) {
|
||||
$insert_sql = mysqli_query($mysqli, "INSERT INTO certificates SET {$form['set']}, certificate_client_id = " . intval($client_id));
|
||||
|
||||
if ($insert_sql) {
|
||||
$insert_id = mysqli_insert_id($mysqli);
|
||||
|
||||
// What the host serves - unless a different certificate was posted, which is kept
|
||||
if ($form['host']) {
|
||||
certificateCheckAndSave($insert_id, $form['parsed']['pem'] ?? '', false);
|
||||
}
|
||||
|
||||
$name = escapeSql($form['name']);
|
||||
logAudit("Certificate", "Create", "$name via API ($api_key_name)", $client_id, $insert_id);
|
||||
logAudit("API", "Success", "Created certificate $name via API ($api_key_name)", $client_id, $insert_id);
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize expire value
|
||||
if (empty($expire)) {
|
||||
$expire = "NULL";
|
||||
} else {
|
||||
$expire = "'" . $expire . "'";
|
||||
}
|
||||
|
||||
// Insert certificate
|
||||
$insert_sql = mysqli_query($mysqli, "
|
||||
INSERT INTO certificates SET
|
||||
certificate_name = '$name',
|
||||
certificate_description = '$description',
|
||||
certificate_domain = '$domain',
|
||||
certificate_issued_by = '$issued_by',
|
||||
certificate_expire = $expire,
|
||||
certificate_public_key = '$public_key',
|
||||
certificate_notes = '$notes',
|
||||
certificate_domain_id = $domain_id,
|
||||
certificate_client_id = $client_id
|
||||
");
|
||||
|
||||
// Check insert & get insert ID
|
||||
if ($insert_sql) {
|
||||
$insert_id = mysqli_insert_id($mysqli);
|
||||
|
||||
// Logging
|
||||
logAudit("Certificate", "Create", "$name via API ($api_key_name)", $client_id, $insert_id);
|
||||
logAudit("API", "Success", "Created certificate $name via API ($api_key_name)", $client_id, $insert_id);
|
||||
}
|
||||
}
|
||||
|
||||
// Output
|
||||
require_once '../create_output.php';
|
||||
require_once '../create_output.php';
|
||||
|
||||
@@ -10,7 +10,7 @@ require_once "includes/inc_all.php";
|
||||
|
||||
enforceContactCan('itdoc');
|
||||
|
||||
$certificates_sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_name, certificate_domain, certificate_issued_by, certificate_expire FROM certificates WHERE certificate_client_id = $session_client_id AND certificate_archived_at IS NULL ORDER BY certificate_expire ASC");
|
||||
$certificates_sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_name, certificate_domain, certificate_issued_by, certificate_issued_at, certificate_expire FROM certificates WHERE certificate_client_id = $session_client_id AND certificate_archived_at IS NULL ORDER BY certificate_expire IS NULL, certificate_expire ASC");
|
||||
?>
|
||||
|
||||
<h3>Web Certificates</h3>
|
||||
@@ -38,6 +38,7 @@ $certificates_sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_na
|
||||
$certificate_domain = escapeHtml($row['certificate_domain']);
|
||||
$certificate_issued_by = escapeHtml($row['certificate_issued_by']);
|
||||
$certificate_expire = escapeHtml($row['certificate_expire']);
|
||||
$expiry = certificateExpiry($row);
|
||||
|
||||
?>
|
||||
|
||||
@@ -45,7 +46,14 @@ $certificates_sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_na
|
||||
<td><?= $certificate_name ?></td>
|
||||
<td><?= $certificate_domain ?></td>
|
||||
<td><?= $certificate_issued_by ?></td>
|
||||
<td><?= $certificate_expire ?></td>
|
||||
<td>
|
||||
<?= $certificate_expire ?: '-' ?>
|
||||
<?php if ($expiry && $expiry['state'] !== 'active') { ?>
|
||||
<span class="badge text-bg-<?= $expiry['state'] === 'expired' ? 'danger' : 'warning' ?> ms-1"><?= $expiry['state'] === 'expired' ? 'Expired' : 'Expiring soon' ?></span>
|
||||
<?php } elseif ($expiry && $expiry['short_lived']) { ?>
|
||||
<span class="badge text-bg-info ms-1">Renews automatically</span>
|
||||
<?php } ?>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<?php } ?>
|
||||
|
||||
@@ -34,75 +34,58 @@ if ($config_enable_cron == 0) {
|
||||
|
||||
/*
|
||||
* ###############################################################################################################
|
||||
* UPDATE CERTIFICATE EXPIRY DATE
|
||||
* CHECK CERTIFICATES
|
||||
* ###############################################################################################################
|
||||
*/
|
||||
|
||||
$sql_certificates = mysqli_query(
|
||||
$mysqli,
|
||||
"SELECT certificate_domain, certificate_id FROM certificates
|
||||
LEFT JOIN clients ON certificates.certificate_client_id = clients.client_id
|
||||
WHERE certificate_archived_at IS NULL
|
||||
AND client_archived_at IS NULL"
|
||||
);
|
||||
// Every certificate with a host, once a day - connect, take what it serves,
|
||||
// and save it with what the check found (certificateCheckAndSave()). Never
|
||||
// checked first, then least recently checked; as many as fit in ten minutes,
|
||||
// the rest first in line tomorrow. A host that doesn't answer is recorded as
|
||||
// unreachable and keeps the certificate on file. Certificates with no host
|
||||
// (pasted, or typed by hand) have nothing to check and are left alone.
|
||||
$started = time();
|
||||
$tally = array_fill_keys(array_keys(CERTIFICATE_CHECK_STATES), 0);
|
||||
$sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_name, certificate_domain, certificate_check_status, certificate_client_id, client_name FROM certificates
|
||||
LEFT JOIN clients ON client_id = certificate_client_id
|
||||
WHERE certificate_archived_at IS NULL AND client_archived_at IS NULL
|
||||
AND certificate_domain IS NOT NULL AND certificate_domain <> ''
|
||||
AND (certificate_checked_at IS NULL OR certificate_checked_at < NOW() - INTERVAL 20 HOUR)
|
||||
ORDER BY certificate_checked_at IS NOT NULL, certificate_checked_at ASC
|
||||
LIMIT 1000");
|
||||
|
||||
while ($row = mysqli_fetch_assoc($sql_certificates)) {
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
$domain = escapeSql($row['certificate_domain']);
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
|
||||
$certificate = getSslCertificate($domain);
|
||||
|
||||
$expire = escapeSql($certificate['expire']);
|
||||
$issued_by = escapeSql($certificate['issued_by']);
|
||||
$public_key = escapeSql($certificate['public_key']);
|
||||
|
||||
if (!empty($expire)) {
|
||||
|
||||
echo "\n$domain\n";
|
||||
echo "$issued_by\n";
|
||||
echo "$expire\n";
|
||||
echo "$public_key\n\n";
|
||||
|
||||
$expire = "'" . $expire . "'";
|
||||
|
||||
// Get current certificate info
|
||||
$original_certificate_info = mysqli_fetch_assoc(mysqli_query($mysqli,"
|
||||
SELECT
|
||||
certificates.*,
|
||||
domains.domain_name
|
||||
FROM certificates
|
||||
LEFT JOIN domains ON certificate_domain_id = domain_id
|
||||
WHERE certificate_id = $certificate_id
|
||||
"));
|
||||
|
||||
// Update
|
||||
mysqli_query($mysqli,"UPDATE certificates SET certificate_issued_by = '$issued_by', certificate_expire = $expire, certificate_public_key = '$public_key' WHERE certificate_id = $certificate_id");
|
||||
|
||||
// Fetch the updated info
|
||||
$new_certificate_info = mysqli_fetch_assoc(mysqli_query($mysqli,"
|
||||
SELECT
|
||||
certificates.*,
|
||||
domains.domain_name
|
||||
FROM certificates
|
||||
LEFT JOIN domains ON certificate_domain_id = domain_id
|
||||
WHERE certificate_id = $certificate_id
|
||||
"));
|
||||
|
||||
// Compare/log changes between old/new info
|
||||
$ignored_columns = ["certificate_public_key", "certificate_updated_at", "certificate_accessed_at", "certificate_domain_id"];
|
||||
foreach ($original_certificate_info as $column => $old_value) {
|
||||
$new_value = $new_certificate_info[$column];
|
||||
if ($old_value != $new_value && !in_array($column, $ignored_columns)) {
|
||||
$column = escapeSql($column);
|
||||
$old_value = escapeSql($old_value);
|
||||
$new_value = escapeSql($new_value);
|
||||
mysqli_query($mysqli,"INSERT INTO certificate_history SET certificate_history_column = '$column', certificate_history_old_value = '$old_value', certificate_history_new_value = '$new_value', certificate_history_certificate_id = $certificate_id");
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
logApp("Cron-Certificate-Refresher", "error", "Cron Certificate Refresh - error updating Error updating $domain.");
|
||||
error_log("Certificate Cron Error - Error updating $domain");
|
||||
if (time() - $started > 600) {
|
||||
break;
|
||||
}
|
||||
|
||||
$check = certificateCheckAndSave($row['certificate_id']);
|
||||
if ($check === null) {
|
||||
// Not a host it can connect to - leave it be, but out of the queue until tomorrow
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_checked_at = NOW(), certificate_check_status = NULL WHERE certificate_id = " . intval($row['certificate_id']));
|
||||
continue;
|
||||
}
|
||||
$status = empty($check['reachable']) ? 'unreachable' : $check['status'];
|
||||
$tally[$status]++;
|
||||
echo "{$row['certificate_domain']}: $status\n";
|
||||
|
||||
// Was fine yesterday, isn't today - someone installed the wrong one, or it lapsed.
|
||||
// (A host not answering is left to the list - that is as often a blip as a fault.)
|
||||
if ($row['certificate_check_status'] === 'ok' && in_array($status, ['mismatch', 'untrusted', 'expired'], true)) {
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
$client_id = intval($row['certificate_client_id']);
|
||||
appNotify("Certificate Problem", escapeSql("Certificate {$row['certificate_name']} for {$row['client_name']}: " . CERTIFICATE_CHECK_STATES[$status]['text']), "/agent/certificates.php?client_id=$client_id&open=$certificate_id", $client_id);
|
||||
}
|
||||
}
|
||||
|
||||
$checked = array_sum($tally);
|
||||
if ($checked) {
|
||||
$parts = [];
|
||||
foreach ($tally as $status => $count) {
|
||||
if ($count) {
|
||||
$parts[] = "$count $status";
|
||||
}
|
||||
}
|
||||
logApp("Cron-Certificate-Refresher", "info", "Checked $checked certificate(s): " . implode(', ', $parts) . '.');
|
||||
}
|
||||
|
||||
@@ -257,6 +257,10 @@ if ($config_enable_alert_domain_expire == 1) {
|
||||
|
||||
// CERTIFICATES EXPIRING
|
||||
|
||||
// A month and a half out, then a week, then the day before. A short-lived
|
||||
// certificate (Let's Encrypt and friends) renews itself with about 30 days
|
||||
// left, so its 45-day mark is routine - only the week and the day are said,
|
||||
// and by then it should already have renewed.
|
||||
$certificateAlertArray = [1,7,45];
|
||||
|
||||
foreach ($certificateAlertArray as $day) {
|
||||
@@ -264,42 +268,29 @@ foreach ($certificateAlertArray as $day) {
|
||||
//Get Certs Expiring
|
||||
$sql = mysqli_query(
|
||||
$mysqli,
|
||||
"SELECT certificate_domain, certificate_expire, certificate_id, certificate_name,
|
||||
certificate_public_key, client_id, client_name FROM certificates
|
||||
"SELECT certificate_domain, certificate_expire, certificate_issued_at, certificate_id, certificate_name,
|
||||
client_id, client_name FROM certificates
|
||||
LEFT JOIN clients ON certificate_client_id = client_id
|
||||
WHERE certificate_expire = CURDATE() + INTERVAL $day DAY"
|
||||
WHERE certificate_expire = CURDATE() + INTERVAL $day DAY
|
||||
AND certificate_archived_at IS NULL AND client_archived_at IS NULL"
|
||||
);
|
||||
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
$certificate_name = escapeSql($row['certificate_name']);
|
||||
$certificate_domain = escapeSql($row['certificate_domain']);
|
||||
$certificate_expire = escapeSql($row['certificate_expire']);
|
||||
$certificate_public_key = $row['certificate_public_key']; // Sanitize input breaks parsing
|
||||
$client_id = intval($row['client_id']);
|
||||
$client_name = escapeSql($row['client_name']);
|
||||
$short_lived = certificateShortLived($row);
|
||||
|
||||
// Calculate the validity period
|
||||
if (!empty($certificate_public_key)) {
|
||||
$cert_public_key_obj = openssl_x509_parse($certificate_public_key);
|
||||
$validity_days = intval(round(($cert_public_key_obj['validTo_time_t'] - $cert_public_key_obj['validFrom_time_t']) / (60 * 60 * 24)));
|
||||
|
||||
// Only raise a notification at 45 days if the certificate is valid for more than 90 days (i.e. not a LE)
|
||||
|
||||
if ($day == 45 && $validity_days < 91) {
|
||||
// LE certificate - Do nothing here
|
||||
echo "Not raising notification for LE certificate $certificate_name expiring in 45 days";
|
||||
|
||||
} else {
|
||||
// This certificate is either expiring in 1 or 7 days or is a non-LE certificate expiring in 45 days
|
||||
appNotify("Certificate Expiring", "Certificate $certificate_name for $client_name will expire in $day day(s) on $certificate_expire", "/agent/certificates.php?client_id=$client_id", $client_id);
|
||||
}
|
||||
|
||||
} else {
|
||||
// No public key - notify anyway as we can't check the validity period
|
||||
appNotify("Certificate Expiring", "Certificate $certificate_name for $client_name will expire in $day day(s) on $certificate_expire", "/agent/certificates.php?client_id=$client_id", $client_id);
|
||||
if ($day == 45 && $short_lived) {
|
||||
echo "Not raising a notification for short-lived certificate $certificate_name expiring in 45 days\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
$renewal = $short_lived ? ' - it renews itself, so check why it has not' : '';
|
||||
appNotify("Certificate Expiring", "Certificate $certificate_name for $client_name will expire in $day day(s) on $certificate_expire$renewal", "/agent/certificates.php?client_id=$client_id&open=$certificate_id", $client_id);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4706,3 +4706,26 @@ img.itflow-contact-avatar {
|
||||
.itflow-domain-mail > .d-inline-flex {
|
||||
flex-wrap: nowrap !important;
|
||||
}
|
||||
|
||||
/* Certificates - agent/certificates.php and agent/modals/certificate/
|
||||
(functions/certificate.php). The host column and the issuer keep to one
|
||||
width; the fingerprint breaks anywhere rather than widen the quick look. */
|
||||
.itflow-certificate-host {
|
||||
max-width: 15rem;
|
||||
}
|
||||
.itflow-certificate-table .itflow-asset-desc {
|
||||
max-width: 14rem;
|
||||
}
|
||||
.itflow-certificate-issuer {
|
||||
max-width: 10rem;
|
||||
}
|
||||
.itflow-certificate-fingerprint {
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.itflow-certificate-check-result {
|
||||
padding: .75rem;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: var(--bs-border-radius);
|
||||
background: var(--bs-tertiary-bg);
|
||||
}
|
||||
|
||||
5
db.sql
5
db.sql
@@ -565,15 +565,20 @@ CREATE TABLE `certificates` (
|
||||
`certificate_name` varchar(200) NOT NULL,
|
||||
`certificate_description` mediumtext DEFAULT NULL,
|
||||
`certificate_domain` varchar(200) DEFAULT NULL,
|
||||
`certificate_names` text DEFAULT NULL,
|
||||
`certificate_issued_by` varchar(200) NOT NULL,
|
||||
`certificate_issued_at` date DEFAULT NULL,
|
||||
`certificate_expire` date DEFAULT NULL,
|
||||
`certificate_public_key` mediumtext DEFAULT NULL,
|
||||
`certificate_fingerprint` varchar(100) DEFAULT NULL,
|
||||
`certificate_check_status` varchar(20) DEFAULT NULL,
|
||||
`certificate_notes` mediumtext DEFAULT NULL,
|
||||
`certificate_favorite` tinyint(1) NOT NULL DEFAULT 0,
|
||||
`certificate_created_at` datetime NOT NULL DEFAULT current_timestamp(),
|
||||
`certificate_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
|
||||
`certificate_archived_at` datetime DEFAULT NULL,
|
||||
`certificate_accessed_at` datetime DEFAULT NULL,
|
||||
`certificate_checked_at` datetime DEFAULT NULL,
|
||||
`certificate_domain_id` int(11) NOT NULL DEFAULT 0,
|
||||
`certificate_client_id` int(11) NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`certificate_id`),
|
||||
|
||||
@@ -17,6 +17,7 @@ require_once __DIR__ . '/functions/format.php';
|
||||
require_once __DIR__ . '/functions/request.php';
|
||||
require_once __DIR__ . '/functions/files.php';
|
||||
require_once __DIR__ . '/functions/domain.php';
|
||||
require_once __DIR__ . '/functions/certificate.php';
|
||||
require_once __DIR__ . '/functions/network.php';
|
||||
require_once __DIR__ . '/functions/rack.php';
|
||||
require_once __DIR__ . '/functions/asset.php';
|
||||
|
||||
552
functions/certificate.php
Normal file
552
functions/certificate.php
Normal file
@@ -0,0 +1,552 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Certificates - the TLS certificates on a client's websites, portals,
|
||||
* firewalls and appliances.
|
||||
*
|
||||
* A certificate has a host it is served on (certificate_domain, as host or
|
||||
* host:port), and what the certificate itself says - issuer, issued and
|
||||
* expiry dates, the names it covers, its SHA-256 fingerprint and the PEM.
|
||||
* Those come from a check of the host (certificateCheck(), which also says
|
||||
* whether what the host serves is OK, for another name, untrusted, expired
|
||||
* or not answering) or from a pasted PEM (certificateParse()). A check that
|
||||
* reaches nothing records that it couldn't, and changes nothing else.
|
||||
*/
|
||||
|
||||
/** Expiring within this many days is "soon" - 20 for a short-lived certificate that should renew itself by then. */
|
||||
const CERTIFICATE_SOON_DAYS = 30;
|
||||
|
||||
/** A certificate valid for no more than this many days is short-lived - issued by ACME (Let's Encrypt and friends) and renewed automatically. */
|
||||
const CERTIFICATE_SHORT_LIVED_DAYS = 100;
|
||||
|
||||
/** What a check of the host can find. */
|
||||
const CERTIFICATE_CHECK_STATES = [
|
||||
'ok' => ['label' => 'OK', 'tone' => 'success', 'icon' => 'fa-check', 'text' => 'The host serves it, valid and trusted'],
|
||||
'mismatch' => ['label' => 'Name mismatch', 'tone' => 'warning', 'icon' => 'fa-not-equal', 'text' => "What the host serves doesn't cover the host name - browsers will warn"],
|
||||
'untrusted' => ['label' => 'Untrusted', 'tone' => 'warning', 'icon' => 'fa-exclamation-triangle', 'text' => 'Self-signed, or its chain is incomplete - browsers will warn'],
|
||||
'expired' => ['label' => 'Expired', 'tone' => 'danger', 'icon' => 'fa-calendar-times', 'text' => 'The host serves an expired certificate'],
|
||||
'unreachable' => ['label' => 'Unreachable', 'tone' => 'secondary', 'icon' => 'fa-plug', 'text' => 'Nothing answered on that host and port'],
|
||||
];
|
||||
|
||||
/** What each tracked column is called in a certificate's history. */
|
||||
const CERTIFICATE_HISTORY_LABELS = [
|
||||
'certificate_name' => 'Name', 'certificate_description' => 'Description', 'certificate_domain' => 'Host', 'domain_name' => 'Domain',
|
||||
'certificate_issued_by' => 'Issuer', 'certificate_issued_at' => 'Issued', 'certificate_expire' => 'Expiry', 'certificate_names' => 'Names covered',
|
||||
'certificate_fingerprint' => 'Fingerprint', 'certificate_notes' => 'Notes',
|
||||
];
|
||||
|
||||
/** May this agent do this with certificates? 1 is to see them, 2 to change them, 3 to delete them. */
|
||||
function certificateCan($level) {
|
||||
return lookupUserPermission('module_support') >= $level;
|
||||
}
|
||||
|
||||
/** The columns and joins for a certificate with its client and the domain it is linked to (the client's own). */
|
||||
function certificateSelectSql() {
|
||||
return ['certificates.*, client_name, domains.domain_name AS domain_name, domains.domain_archived_at AS domain_archived_at',
|
||||
'LEFT JOIN clients ON client_id = certificate_client_id
|
||||
LEFT JOIN domains ON domains.domain_id = certificate_domain_id AND domains.domain_client_id = certificate_client_id'];
|
||||
}
|
||||
|
||||
/** One certificate by id, with its client and domain - raw, or null. */
|
||||
function certificateRow($certificate_id) {
|
||||
global $mysqli;
|
||||
$certificate_id = intval($certificate_id);
|
||||
if (!$certificate_id) {
|
||||
return null;
|
||||
}
|
||||
[$columns, $joins] = certificateSelectSql();
|
||||
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT $columns FROM certificates $joins WHERE certificate_id = $certificate_id LIMIT 1"));
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a certificate is served, as it is kept - a host name or IP address,
|
||||
* with the port when it isn't 443 - from whatever was pasted
|
||||
* ("https://Portal.Example.com:8443/login"). ['host', 'port', 'display'], or
|
||||
* null when it is not a host. Internal names (fw01, nas.local) are fine.
|
||||
*/
|
||||
function certificateHost($input) {
|
||||
$value = strtolower(trim(html_entity_decode((string) $input, ENT_QUOTES, 'UTF-8')));
|
||||
$value = preg_replace('#^[a-z][a-z0-9+.\-]*://#', '', $value);
|
||||
$value = preg_replace('#^[^@/]*@#', '', $value);
|
||||
$value = preg_split('#[/?\#]#', $value)[0];
|
||||
if ($value === '' || preg_match('/\s/', $value)) {
|
||||
return null;
|
||||
}
|
||||
$port = 443;
|
||||
if (preg_match('/^\[([0-9a-f:.]+)\](?::(\d+))?$/', $value, $match)) {
|
||||
// [IPv6]:port
|
||||
$host = $match[1];
|
||||
$port = isset($match[2]) ? intval($match[2]) : 443;
|
||||
} elseif (substr_count($value, ':') === 1) {
|
||||
[$host, $port_part] = explode(':', $value);
|
||||
if (!ctype_digit($port_part)) {
|
||||
return null;
|
||||
}
|
||||
$port = intval($port_part);
|
||||
} else {
|
||||
$host = $value;
|
||||
}
|
||||
$host = trim($host, '.');
|
||||
if ($port < 1 || $port > 65535) {
|
||||
return null;
|
||||
}
|
||||
$is_ip = filter_var($host, FILTER_VALIDATE_IP) !== false;
|
||||
if (!$is_ip && ($host === '' || strlen($host) > 200 || !filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME))) {
|
||||
return null;
|
||||
}
|
||||
$shown = strpos($host, ':') !== false ? "[$host]" : $host;
|
||||
return ['host' => $host, 'port' => $port, 'display' => $port === 443 ? $shown : "$shown:$port", 'ip' => $is_ip];
|
||||
}
|
||||
|
||||
/**
|
||||
* What a certificate says about itself, from its PEM - the issuer, the dates,
|
||||
* the names it covers, its SHA-256 fingerprint, whether it signed itself.
|
||||
* The PEM given may be a whole chain or carry a key; only the first
|
||||
* certificate is kept. Null when there is no certificate in it.
|
||||
*/
|
||||
function certificateParse($pem) {
|
||||
if (!preg_match('/-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----/s', (string) $pem, $match)) {
|
||||
return null;
|
||||
}
|
||||
$pem = $match[0];
|
||||
$parsed = @openssl_x509_parse($pem);
|
||||
if (!$parsed || empty($parsed['validTo_time_t'])) {
|
||||
return null;
|
||||
}
|
||||
$field = function ($value) {
|
||||
return is_array($value) ? (string) end($value) : (string) $value;
|
||||
};
|
||||
$names = [];
|
||||
foreach (explode(',', (string) ($parsed['extensions']['subjectAltName'] ?? '')) as $alt_name) {
|
||||
$alt_name = trim($alt_name);
|
||||
if (stripos($alt_name, 'DNS:') === 0) {
|
||||
$names[] = strtolower(substr($alt_name, 4));
|
||||
} elseif (stripos($alt_name, 'IP Address:') === 0) {
|
||||
$names[] = strtolower(trim(substr($alt_name, 11)));
|
||||
}
|
||||
}
|
||||
$subject_cn = $field($parsed['subject']['CN'] ?? '');
|
||||
if (!$names && $subject_cn !== '') {
|
||||
$names[] = strtolower($subject_cn);
|
||||
}
|
||||
$issuer = $field($parsed['issuer']['O'] ?? '') ?: $field($parsed['issuer']['CN'] ?? '');
|
||||
$fingerprint = @openssl_x509_fingerprint($pem, 'sha256');
|
||||
$valid_from = intval($parsed['validFrom_time_t']);
|
||||
$valid_to = intval($parsed['validTo_time_t']);
|
||||
return [
|
||||
'pem' => $pem,
|
||||
'issuer' => mb_substr(strip_tags($issuer), 0, 200),
|
||||
'subject' => $subject_cn,
|
||||
'issued_at' => date('Y-m-d', $valid_from),
|
||||
'expire' => date('Y-m-d', $valid_to),
|
||||
'expired' => $valid_to < time(),
|
||||
'names' => array_values(array_unique($names)),
|
||||
'fingerprint' => $fingerprint ? strtoupper(implode(':', str_split($fingerprint, 2))) : '',
|
||||
'self_signed' => ($parsed['issuer'] ?? null) == ($parsed['subject'] ?? null),
|
||||
'days' => intval(round(($valid_to - $valid_from) / 86400)),
|
||||
];
|
||||
}
|
||||
|
||||
/** Does a certificate covering these names cover this host? Exact, or one label under a wildcard. */
|
||||
function certificateCovers($host, array $names) {
|
||||
$host = strtolower(trim((string) $host, '.'));
|
||||
foreach ($names as $name) {
|
||||
$name = strtolower(trim((string) $name, '.'));
|
||||
if ($name === $host) {
|
||||
return true;
|
||||
}
|
||||
if (strpos($name, '*.') === 0) {
|
||||
$suffix = substr($name, 1);
|
||||
$label = substr($host, 0, -strlen($suffix));
|
||||
if (substr($host, -strlen($suffix)) === $suffix && $label !== '' && strpos($label, '.') === false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a check finds, from the certificate a host served: expired first, then
|
||||
* one for another name, then one nothing trusts (self-signed or a broken
|
||||
* chain), otherwise OK.
|
||||
*/
|
||||
function certificateStatus(array $parsed, $host, $trusted) {
|
||||
if ($parsed['expired']) {
|
||||
return 'expired';
|
||||
}
|
||||
if (!certificateCovers($host, $parsed['names'])) {
|
||||
return 'mismatch';
|
||||
}
|
||||
return $trusted ? 'ok' : 'untrusted';
|
||||
}
|
||||
|
||||
/** Open a TLS connection to a host - [stream or false]. Verification is the caller's choice; SNI is always sent. */
|
||||
function certificateConnect($host, $port, $verify) {
|
||||
$options = ['ssl' => [
|
||||
'capture_peer_cert' => true,
|
||||
'verify_peer' => $verify,
|
||||
'verify_peer_name' => false,
|
||||
'allow_self_signed' => false,
|
||||
'SNI_enabled' => true,
|
||||
'peer_name' => $host,
|
||||
]];
|
||||
$target = strpos($host, ':') !== false ? "[$host]" : $host;
|
||||
return @stream_socket_client("ssl://$target:$port", $errno, $errstr, 5, STREAM_CLIENT_CONNECT, stream_context_create($options));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a host - connect, take the certificate it serves, and say what it is.
|
||||
* ['reachable' => false] when nothing answered; otherwise what
|
||||
* certificateParse() gives plus 'status' (see CERTIFICATE_CHECK_STATES).
|
||||
*/
|
||||
function certificateCheck($host_input) {
|
||||
$host = is_array($host_input) ? $host_input : certificateHost($host_input);
|
||||
if (!$host) {
|
||||
return ['reachable' => false];
|
||||
}
|
||||
$stream = certificateConnect($host['host'], $host['port'], false);
|
||||
if (!$stream) {
|
||||
return ['reachable' => false];
|
||||
}
|
||||
$params = stream_context_get_params($stream);
|
||||
fclose($stream);
|
||||
$pem = '';
|
||||
if (!empty($params['options']['ssl']['peer_certificate'])) {
|
||||
@openssl_x509_export($params['options']['ssl']['peer_certificate'], $pem);
|
||||
}
|
||||
$parsed = certificateParse($pem);
|
||||
if (!$parsed) {
|
||||
return ['reachable' => false];
|
||||
}
|
||||
// Trusted - a second handshake that checks the chain against the system's CAs
|
||||
$trusted = false;
|
||||
if (!$parsed['expired'] && !$parsed['self_signed']) {
|
||||
$verified = certificateConnect($host['host'], $host['port'], true);
|
||||
if ($verified) {
|
||||
$trusted = true;
|
||||
fclose($verified);
|
||||
}
|
||||
}
|
||||
$parsed['reachable'] = true;
|
||||
$parsed['status'] = certificateStatus($parsed, $host['host'], $trusted);
|
||||
return $parsed;
|
||||
}
|
||||
|
||||
/** Save what a pasted PEM or a check says the certificate is. */
|
||||
function certificateApplyParsed($certificate_id, array $parsed) {
|
||||
global $mysqli;
|
||||
$certificate_id = intval($certificate_id);
|
||||
mysqli_query($mysqli, "UPDATE certificates SET
|
||||
certificate_public_key = '" . escapeSql($parsed['pem']) . "',
|
||||
certificate_issued_by = '" . escapeSql($parsed['issuer']) . "',
|
||||
certificate_issued_at = '" . escapeSql($parsed['issued_at']) . "',
|
||||
certificate_expire = '" . escapeSql($parsed['expire']) . "',
|
||||
certificate_names = '" . escapeSql(implode("\n", $parsed['names'])) . "',
|
||||
certificate_fingerprint = '" . escapeSql($parsed['fingerprint']) . "'
|
||||
WHERE certificate_id = $certificate_id");
|
||||
}
|
||||
|
||||
/**
|
||||
* Save what a check found - the certificate and the result when the host
|
||||
* answered, only the result (unreachable) when it didn't. True when it answered.
|
||||
*/
|
||||
function certificateApplyCheck($certificate_id, array $check) {
|
||||
global $mysqli;
|
||||
$certificate_id = intval($certificate_id);
|
||||
if (empty($check['reachable'])) {
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_check_status = 'unreachable', certificate_checked_at = NOW() WHERE certificate_id = $certificate_id");
|
||||
return false;
|
||||
}
|
||||
certificateApplyParsed($certificate_id, $check);
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_check_status = '" . escapeSql($check['status']) . "', certificate_checked_at = NOW() WHERE certificate_id = $certificate_id");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the host a certificate is served on and save what it serves, with
|
||||
* its history (not for one just added - there is nothing before it). With
|
||||
* $keep_pem, a certificate pasted in the form that differs from what the
|
||||
* host serves is kept - only the result of the check is saved. The check,
|
||||
* or null without a host.
|
||||
*/
|
||||
function certificateCheckAndSave($certificate_id, $keep_pem = '', $with_history = true) {
|
||||
global $mysqli;
|
||||
$certificate_id = intval($certificate_id);
|
||||
$row = certificateRow($certificate_id);
|
||||
$host = $row ? certificateHost($row['certificate_domain']) : null;
|
||||
if (!$host) {
|
||||
return null;
|
||||
}
|
||||
$check = certificateCheck($host);
|
||||
$before = certificateHistorySnapshot($certificate_id);
|
||||
$kept_parsed = $keep_pem !== '' && !empty($check['reachable']) ? certificateParse($keep_pem) : null;
|
||||
if ($kept_parsed && $kept_parsed['fingerprint'] !== $check['fingerprint']) {
|
||||
mysqli_query($mysqli, "UPDATE certificates SET certificate_check_status = '" . escapeSql($check['status']) . "', certificate_checked_at = NOW() WHERE certificate_id = $certificate_id");
|
||||
} else {
|
||||
certificateApplyCheck($certificate_id, $check);
|
||||
}
|
||||
if ($with_history) {
|
||||
certificateWriteHistory($certificate_id, $before, certificateHistorySnapshot($certificate_id));
|
||||
}
|
||||
return $check;
|
||||
}
|
||||
|
||||
/** The client's domain a host belongs to - the domain itself, or the longest one it is under - or 0. */
|
||||
function certificateDomainFor($host, $client_id) {
|
||||
global $mysqli;
|
||||
$host = strtolower((string) $host);
|
||||
$client_id = intval($client_id);
|
||||
if ($host === '' || filter_var($host, FILTER_VALIDATE_IP)) {
|
||||
return 0;
|
||||
}
|
||||
$host_sql = escapeSql($host);
|
||||
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT domain_id FROM domains
|
||||
WHERE domain_client_id = $client_id AND domain_archived_at IS NULL
|
||||
AND ('$host_sql' = domain_name OR '$host_sql' LIKE CONCAT('%.', domain_name))
|
||||
ORDER BY LENGTH(domain_name) DESC LIMIT 1"));
|
||||
return $row ? intval($row[0]) : 0;
|
||||
}
|
||||
|
||||
/** A domain id a certificate may link to - one of its client's - else 0. */
|
||||
function certificateDomainId($domain_id, $client_id) {
|
||||
global $mysqli;
|
||||
$domain_id = intval($domain_id);
|
||||
$client_id = intval($client_id);
|
||||
if (!$domain_id) {
|
||||
return 0;
|
||||
}
|
||||
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT domain_id FROM domains WHERE domain_id = $domain_id AND domain_client_id = $client_id LIMIT 1"));
|
||||
return $row ? intval($row[0]) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields a New / Edit form posts, as a SQL SET list. A pasted PEM is the
|
||||
* last word on the issuer, dates, names and fingerprint; with none, the
|
||||
* issuer and expiry typed by hand are all there is. With no name the
|
||||
* host is the name; with no domain picked, the client's domain the host is
|
||||
* under. Null with $error set when it cannot be saved. Also returns the
|
||||
* host and what the PEM said, if there was one.
|
||||
*/
|
||||
function certificateFormSet($post, $client_id, &$error = '') {
|
||||
$error = '';
|
||||
$client_id = intval($client_id);
|
||||
$host_input = trim((string) ($post['domain'] ?? ''));
|
||||
$host = $host_input === '' ? null : certificateHost($host_input);
|
||||
if ($host_input !== '' && !$host) {
|
||||
$error = "That isn't a host - something like www.example.com, or portal.example.com:8443.";
|
||||
return null;
|
||||
}
|
||||
$pem_input = trim((string) ($post['public_key'] ?? ''));
|
||||
$parsed = $pem_input === '' ? null : certificateParse($pem_input);
|
||||
if ($pem_input !== '' && !$parsed) {
|
||||
$error = "That isn't a certificate - paste the PEM, from -----BEGIN CERTIFICATE----- to -----END CERTIFICATE-----.";
|
||||
return null;
|
||||
}
|
||||
$name = trim((string) ($post['name'] ?? '')) ?: ($host ? $host['display'] : ($parsed['subject'] ?? ''));
|
||||
if ($name === '') {
|
||||
$error = 'A certificate needs a name, or the host it is served on.';
|
||||
return null;
|
||||
}
|
||||
$expire = trim((string) ($post['expire'] ?? ''));
|
||||
if ($expire !== '' && (!($date = DateTime::createFromFormat('!Y-m-d', $expire)) || $date->format('Y-m-d') !== $expire)) {
|
||||
$error = 'The expiry date is not a date.';
|
||||
return null;
|
||||
}
|
||||
$domain_id = certificateDomainId($post['domain_id'] ?? 0, $client_id) ?: ($host ? certificateDomainFor($host['host'], $client_id) : 0);
|
||||
|
||||
$text = function ($value, $length) {
|
||||
return "'" . escapeSql(mb_substr(trim((string) $value), 0, $length)) . "'";
|
||||
};
|
||||
$fields = [
|
||||
'certificate_name' => $text($name, 200),
|
||||
'certificate_description' => $text($post['description'] ?? '', 500),
|
||||
'certificate_domain' => $text($host ? $host['display'] : '', 200),
|
||||
'certificate_notes' => "'" . escapeSql(trim((string) ($post['notes'] ?? ''))) . "'",
|
||||
'certificate_favorite' => intval($post['favorite'] ?? 0) ? 1 : 0,
|
||||
'certificate_domain_id' => $domain_id,
|
||||
];
|
||||
if ($parsed) {
|
||||
$fields['certificate_public_key'] = "'" . escapeSql($parsed['pem']) . "'";
|
||||
$fields['certificate_issued_by'] = $text($parsed['issuer'], 200);
|
||||
$fields['certificate_issued_at'] = "'" . $parsed['issued_at'] . "'";
|
||||
$fields['certificate_expire'] = "'" . $parsed['expire'] . "'";
|
||||
$fields['certificate_names'] = "'" . escapeSql(implode("\n", $parsed['names'])) . "'";
|
||||
$fields['certificate_fingerprint'] = "'" . escapeSql($parsed['fingerprint']) . "'";
|
||||
} else {
|
||||
// No certificate - what was typed by hand, and nothing a certificate would have said
|
||||
$fields['certificate_public_key'] = "''";
|
||||
$fields['certificate_issued_by'] = $text($post['issued_by'] ?? '', 200);
|
||||
$fields['certificate_issued_at'] = 'NULL';
|
||||
$fields['certificate_expire'] = $expire === '' ? 'NULL' : "'$expire'";
|
||||
$fields['certificate_names'] = "''";
|
||||
$fields['certificate_fingerprint'] = "''";
|
||||
}
|
||||
$set = [];
|
||||
foreach ($fields as $column => $value) {
|
||||
$set[] = "$column = $value";
|
||||
}
|
||||
return ['set' => implode(', ', $set), 'name' => $name, 'host' => $host, 'parsed' => $parsed];
|
||||
}
|
||||
|
||||
/** The names a certificate covers, as a list. */
|
||||
function certificateNames($row) {
|
||||
return array_values(array_filter(array_map('trim', preg_split('/[\r\n,]+/', (string) ($row['certificate_names'] ?? ''))), 'strlen'));
|
||||
}
|
||||
|
||||
/** Is it short-lived - an ACME certificate that renews itself? From its own dates, when they are known. */
|
||||
function certificateShortLived($row) {
|
||||
$issued = strtotime((string) ($row['certificate_issued_at'] ?? ''));
|
||||
$expire = strtotime((string) ($row['certificate_expire'] ?? ''));
|
||||
return $issued && $expire && ($expire - $issued) / 86400 <= CERTIFICATE_SHORT_LIVED_DAYS;
|
||||
}
|
||||
|
||||
/**
|
||||
* When it expires: 'expired', 'soon' or 'active', with a tone and a line to
|
||||
* show. A short-lived certificate is only "soon" inside 20 days - by then it
|
||||
* should already have renewed itself, so it is a warning rather than routine.
|
||||
*/
|
||||
function certificateExpiry($row) {
|
||||
$short_lived = certificateShortLived($row);
|
||||
$renewal = softwareRenewal($row['certificate_expire'] ?? '', $short_lived ? 20 : CERTIFICATE_SOON_DAYS);
|
||||
if (!$renewal) {
|
||||
return null;
|
||||
}
|
||||
$days = $renewal['days'];
|
||||
if ($renewal['state'] === 'expired') {
|
||||
$renewal['short'] = 'Expired';
|
||||
} elseif ($renewal['state'] === 'soon') {
|
||||
$when = $days === 0 ? 'today' : ($days === 1 ? 'tomorrow' : "in $days days");
|
||||
$renewal['text'] = 'Expires ' . $when . ($short_lived ? ' - it should have renewed by now' : '');
|
||||
$renewal['short'] = $days === 0 ? 'Today' : ($days === 1 ? 'Tomorrow' : "$days days");
|
||||
} else {
|
||||
$renewal['text'] = ($short_lived ? 'Renews itself, expires ' : 'Expires ') . timeAgo($renewal['date']);
|
||||
$renewal['short'] = timeAgo($renewal['date']);
|
||||
}
|
||||
$renewal['short_lived'] = $short_lived;
|
||||
return $renewal;
|
||||
}
|
||||
|
||||
/** The expiry as a soft pill - red expired, amber soon, green otherwise (with a renew icon when it renews itself). */
|
||||
function certificateExpiryPill($expiry, $use_text = false) {
|
||||
if (!$expiry) {
|
||||
return '<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis border border-secondary-subtle fw-normal" title="No expiry date - check the host or paste the certificate">'
|
||||
. '<i class="fas fa-question me-1"></i>Unknown</span>';
|
||||
}
|
||||
$tone = $expiry['tone'];
|
||||
$icon = $expiry['state'] === 'expired' ? 'fa-calendar-times' : ($expiry['state'] === 'soon' ? 'fa-hourglass-half' : ($expiry['short_lived'] ? 'fa-sync-alt' : 'fa-calendar-check'));
|
||||
return '<span class="badge rounded-pill bg-' . $tone . '-subtle text-' . $tone . '-emphasis border border-' . $tone . '-subtle fw-normal" title="' . escapeHtml($expiry['date'] . ($expiry['short_lived'] ? ' - short-lived, renews itself' : '')) . '">'
|
||||
. '<i class="fas ' . $icon . ' me-1"></i>' . escapeHtml($use_text ? $expiry['text'] : $expiry['short']) . '</span>';
|
||||
}
|
||||
|
||||
/** What the last check of the host found, as a pill - or "Not checked" without a host or a check. */
|
||||
function certificateStatusPill($row, $use_text = false) {
|
||||
$status = (string) ($row['certificate_check_status'] ?? '');
|
||||
if (!isset(CERTIFICATE_CHECK_STATES[$status])) {
|
||||
$label = trim((string) ($row['certificate_domain'] ?? '')) === '' ? 'No host to check' : 'Not checked';
|
||||
return '<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis border border-secondary-subtle fw-normal"><i class="fas fa-minus me-1"></i>' . $label . '</span>';
|
||||
}
|
||||
$state = CERTIFICATE_CHECK_STATES[$status];
|
||||
$when = !empty($row['certificate_checked_at']) ? ' - checked ' . timeAgo($row['certificate_checked_at']) : '';
|
||||
return '<span class="badge rounded-pill bg-' . $state['tone'] . '-subtle text-' . $state['tone'] . '-emphasis border border-' . $state['tone'] . '-subtle fw-normal" title="' . escapeHtml($state['text'] . $when) . '">'
|
||||
. '<i class="fas ' . $state['icon'] . ' me-1"></i>' . escapeHtml($use_text ? $state['text'] : $state['label']) . '</span>';
|
||||
}
|
||||
|
||||
/** A certificate's tile - a padlock, in the same rounded square as the other tiles. $size 'xs' | 'sm' | '' | 'lg'. */
|
||||
function certificateTile($size = '') {
|
||||
$size_class = in_array($size, ['xs', 'sm', 'lg'], true) ? " itflow-asset-icon-$size" . ($size === 'xs' ? ' itflow-vendor-tile-xs' : '') : '';
|
||||
return '<span class="itflow-asset-icon' . $size_class . ' itflow-asset-tone-phone" aria-hidden="true"><i class="fas fa-fw fa-lock"></i></span>';
|
||||
}
|
||||
|
||||
/** A certificate wherever a page mentions one: its tile and its name, opening its quick look. 'archived' strikes it through. */
|
||||
function certificateLink($certificate_id, $name, $options = []) {
|
||||
$certificate_id = intval($certificate_id);
|
||||
$label = escapeHtml(html_entity_decode((string) $name, ENT_QUOTES, 'UTF-8'));
|
||||
$archived = !empty($options['archived']);
|
||||
$class = trim('text-truncate ' . ($options['class'] ?? '') . ($archived ? ' text-decoration-line-through text-body-secondary' : ''));
|
||||
return '<span class="itflow-contact-ref">' . certificateTile('xs')
|
||||
. "<a class=\"ajax-modal $class\" href=\"#\" data-modal-size=\"lg\" data-modal-url=\"modals/certificate/certificate.php?id=$certificate_id\">$label</a></span>";
|
||||
}
|
||||
|
||||
/** A certificate as an option in a picker (itflow_select.js) - the padlock, and the host and when it expires underneath. */
|
||||
function selectOptionCertificate($row) {
|
||||
$expiry = certificateExpiry($row);
|
||||
$host = trim((string) ($row['certificate_domain'] ?? ''));
|
||||
$description = implode(' - ', array_filter([$host !== '' && $host !== $row['certificate_name'] ? $host : '', $expiry ? $expiry['text'] : '']));
|
||||
return selectOptionData(['icon' => 'fas fa-lock', 'description' => $description, 'keywords' => $host]);
|
||||
}
|
||||
|
||||
/** The certificate as a .crt file to download - a data: link, '' without a PEM. */
|
||||
function certificateDownloadHref($pem) {
|
||||
$pem = trim((string) $pem);
|
||||
return $pem === '' ? '' : 'data:application/x-x509-ca-cert;base64,' . base64_encode($pem . "\n");
|
||||
}
|
||||
|
||||
/** What a certificate's history tracks, as it stands now. */
|
||||
function certificateHistorySnapshot($certificate_id) {
|
||||
$row = certificateRow($certificate_id);
|
||||
if (!$row) {
|
||||
return [];
|
||||
}
|
||||
$snapshot = [];
|
||||
foreach (array_keys(CERTIFICATE_HISTORY_LABELS) as $column) {
|
||||
$snapshot[$column] = (string) ($row[$column] ?? '');
|
||||
}
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
/** Record what changed between two snapshots in the certificate's history. */
|
||||
function certificateWriteHistory($certificate_id, array $before, array $after) {
|
||||
global $mysqli;
|
||||
$certificate_id = intval($certificate_id);
|
||||
foreach ($after as $column => $new_value) {
|
||||
$old_value = $before[$column] ?? '';
|
||||
if ((string) $old_value === (string) $new_value) {
|
||||
continue;
|
||||
}
|
||||
mysqli_query($mysqli, "INSERT INTO certificate_history SET certificate_history_column = '" . escapeSql($column) . "',
|
||||
certificate_history_old_value = '" . escapeSql($old_value) . "', certificate_history_new_value = '" . escapeSql($new_value) . "',
|
||||
certificate_history_certificate_id = $certificate_id");
|
||||
}
|
||||
}
|
||||
|
||||
/** A certificate's history, newest first - each change with its label. */
|
||||
function certificateHistory($certificate_id, $limit = 25) {
|
||||
global $mysqli;
|
||||
$certificate_id = intval($certificate_id);
|
||||
$limit = max(1, intval($limit));
|
||||
$sql = mysqli_query($mysqli, "SELECT certificate_history_column, certificate_history_old_value, certificate_history_new_value, certificate_history_modified_at
|
||||
FROM certificate_history WHERE certificate_history_certificate_id = $certificate_id
|
||||
ORDER BY certificate_history_modified_at DESC, certificate_history_id DESC LIMIT $limit");
|
||||
$rows = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$row['label'] = CERTIFICATE_HISTORY_LABELS[$row['certificate_history_column']] ?? ucfirst(str_replace('_', ' ', preg_replace('/^certificate_/', '', $row['certificate_history_column'])));
|
||||
$rows[] = $row;
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** The services that use a certificate. */
|
||||
function certificateServices($certificate_id) {
|
||||
global $mysqli;
|
||||
$certificate_id = intval($certificate_id);
|
||||
$sql = mysqli_query($mysqli, "SELECT services.service_id, service_name, service_importance FROM service_certificates
|
||||
JOIN services ON services.service_id = service_certificates.service_id WHERE service_certificates.certificate_id = $certificate_id ORDER BY service_name");
|
||||
$rows = [];
|
||||
while ($service = mysqli_fetch_assoc($sql)) {
|
||||
$rows[] = $service;
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** The SQL for "expiring soon" - inside CERTIFICATE_SOON_DAYS, or 20 days for a short-lived one (see certificateExpiry()). */
|
||||
function certificateSoonSql($alias = 'certificates') {
|
||||
return "$alias.certificate_expire BETWEEN CURDATE() AND CURDATE() + INTERVAL IF($alias.certificate_issued_at IS NOT NULL
|
||||
AND DATEDIFF($alias.certificate_expire, $alias.certificate_issued_at) <= " . CERTIFICATE_SHORT_LIVED_DAYS . ", 20, " . CERTIFICATE_SOON_DAYS . ") DAY";
|
||||
}
|
||||
|
||||
/** The SQL for "the last check found a problem" - the Problems filter. */
|
||||
function certificateProblemSql($alias = 'certificates') {
|
||||
return "$alias.certificate_check_status IN ('mismatch', 'untrusted', 'expired', 'unreachable')";
|
||||
}
|
||||
@@ -89,6 +89,14 @@ function clientOverviewAttention($client_id, $access, $renewals) {
|
||||
'label' => 'Licenses over seats', 'icon' => 'cube', 'tone' => 'danger',
|
||||
'url' => "/agent/software.php?client_id=$client_id&status=over",
|
||||
];
|
||||
// What the last check of a host found wrong - the same rule as certificates.php?show=problems
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(certificate_id) FROM certificates WHERE certificate_client_id = $client_id AND certificate_archived_at IS NULL
|
||||
AND " . certificateProblemSql()),
|
||||
'label' => 'Certificate problems', 'icon' => 'lock', 'tone' => 'warning',
|
||||
'detail' => 'Name mismatch, untrusted, expired or unreachable',
|
||||
'url' => "/agent/certificates.php?client_id=$client_id&show=problems",
|
||||
];
|
||||
}
|
||||
|
||||
if ($access['credentials']) {
|
||||
@@ -286,7 +294,7 @@ function clientOverviewRenewals($client_id, $days = 45) {
|
||||
'Domain', "/agent/domains.php?client_id=$client_id&open="],
|
||||
['certificate', 'lock', "SELECT certificate_id AS id, certificate_name AS name, certificate_expire AS d FROM certificates
|
||||
WHERE certificate_client_id = $client_id AND certificate_archived_at IS NULL AND certificate_expire IS NOT NULL AND certificate_expire <= $window",
|
||||
'Certificate', "/agent/certificates.php?client_id=$client_id&q="],
|
||||
'Certificate', "/agent/certificates.php?client_id=$client_id&open="],
|
||||
['software', 'cube', "SELECT software_id AS id, software_name AS name, software_expire AS d FROM software
|
||||
WHERE software_client_id = $client_id AND software_archived_at IS NULL AND software_expire IS NOT NULL AND software_expire <= $window",
|
||||
'License', "/agent/license.php?client_id=$client_id&software_id="],
|
||||
@@ -308,7 +316,7 @@ function clientOverviewRenewals($client_id, $days = 45) {
|
||||
'kind' => $kind, 'icon' => $icon, 'label' => $label,
|
||||
'name' => $row['name'], 'date' => $row['d'],
|
||||
'days' => (int) $today->diff($date)->format('%r%a'),
|
||||
'url' => in_array($kind, ['domain', 'warranty', 'retire', 'software'], true) ? $url . intval($row['id']) : $url . rawurlencode($row['name']),
|
||||
'url' => in_array($kind, ['domain', 'certificate', 'warranty', 'retire', 'software'], true) ? $url . intval($row['id']) : $url . rawurlencode($row['name']),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,9 +275,9 @@ function dashboardAttention($access) {
|
||||
'url' => '/agent/domains.php?expire_days=30&sort=domain_expire&order=ASC',
|
||||
];
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(certificate_id) FROM certificates WHERE certificate_archived_at IS NULL AND certificate_expire $soon " . clientScopeSql('certificate_client_id')),
|
||||
'count' => dashboardCount("SELECT COUNT(certificate_id) FROM certificates WHERE certificate_archived_at IS NULL AND " . certificateSoonSql() . ' ' . clientScopeSql('certificate_client_id')),
|
||||
'label' => 'Certificates expiring', 'icon' => 'lock', 'tone' => 'warning', 'detail' => 'Next 30 days',
|
||||
'url' => '/agent/certificates.php?expire_days=30&sort=certificate_expire&order=ASC',
|
||||
'url' => '/agent/certificates.php?show=soon&sort=certificate_expire&order=ASC',
|
||||
];
|
||||
$items[] = [
|
||||
'count' => dashboardCount("SELECT COUNT(software_id) FROM software WHERE software_archived_at IS NULL AND software_expire $soon " . clientScopeSql('software_client_id')),
|
||||
|
||||
@@ -1,51 +1,16 @@
|
||||
<?php
|
||||
|
||||
|
||||
// Used to automatically attempt to get SSL certificates as part of adding domains
|
||||
// The logic for the fetch (sync) button on the client_certificates page is in ajax.php, and allows ports other than 443
|
||||
// The certificate a host serves - kept for the callers that only want its
|
||||
// expiry, issuer and PEM. certificateCheck() (functions/certificate.php) does
|
||||
// the work, and also says whether it is trusted and covers the name.
|
||||
function getSslCertificate($full_name)
|
||||
{
|
||||
|
||||
// Parse host and port
|
||||
$name = parse_url("//$full_name", PHP_URL_HOST);
|
||||
$port = parse_url("//$full_name", PHP_URL_PORT);
|
||||
|
||||
// Default port
|
||||
if (!$port) {
|
||||
$port = "443";
|
||||
$check = certificateCheck($full_name);
|
||||
if (empty($check['reachable'])) {
|
||||
return ['success' => false, 'expire' => '', 'issued_by' => '', 'public_key' => ''];
|
||||
}
|
||||
|
||||
$certificate = array();
|
||||
$certificate['success'] = false;
|
||||
|
||||
// Only run if we think the domain is valid
|
||||
if (!filter_var($name, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
|
||||
$certificate['expire'] = '';
|
||||
$certificate['issued_by'] = '';
|
||||
$certificate['public_key'] = '';
|
||||
return $certificate;
|
||||
}
|
||||
|
||||
// Get SSL/TSL certificate (using verify peer false to allow for self-signed certs) for domain on default port
|
||||
$socket = "ssl://$name:$port";
|
||||
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "verify_peer" => false,)));
|
||||
$read = stream_socket_client($socket, $errno, $errstr, 5, STREAM_CLIENT_CONNECT, $get);
|
||||
|
||||
// If the socket connected
|
||||
if ($read) {
|
||||
$cert = stream_context_get_params($read);
|
||||
$cert_public_key_obj = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
|
||||
openssl_x509_export($cert['options']['ssl']['peer_certificate'], $export);
|
||||
|
||||
if ($cert_public_key_obj) {
|
||||
$certificate['success'] = true;
|
||||
$certificate['expire'] = date('Y-m-d', $cert_public_key_obj['validTo_time_t']);
|
||||
$certificate['issued_by'] = strip_tags($cert_public_key_obj['issuer']['O']);
|
||||
$certificate['public_key'] = $export;
|
||||
}
|
||||
}
|
||||
|
||||
return $certificate;
|
||||
return ['success' => true, 'expire' => $check['expire'], 'issued_by' => $check['issuer'], 'public_key' => $check['pem']];
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
@@ -933,7 +898,8 @@ function domainCertificates($row) {
|
||||
$client_id = intval($row['domain_client_id']);
|
||||
$name = escapeSql($row['domain_name']);
|
||||
$name_like = escapeSql(str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $row['domain_name']));
|
||||
$sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_name, certificate_domain, certificate_issued_by, certificate_expire FROM certificates
|
||||
$sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_name, certificate_domain, certificate_issued_by, certificate_issued_at, certificate_expire,
|
||||
certificate_check_status, certificate_checked_at FROM certificates
|
||||
WHERE certificate_archived_at IS NULL AND certificate_client_id = $client_id
|
||||
AND (certificate_domain_id = $domain_id OR certificate_domain = '$name' OR certificate_domain LIKE '%.$name_like')
|
||||
ORDER BY certificate_expire IS NULL, certificate_expire ASC");
|
||||
@@ -988,12 +954,12 @@ function domainAddCertificate($domain_id, $name, $client_id) {
|
||||
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM certificates WHERE certificate_client_id = $client_id AND certificate_domain IN ('$name_sql', 'www.$name_sql') LIMIT 1"))) {
|
||||
return false;
|
||||
}
|
||||
$certificate = getSslCertificate($name);
|
||||
if (empty($certificate['success'])) {
|
||||
$check = certificateCheck($name);
|
||||
if (empty($check['reachable'])) {
|
||||
return false;
|
||||
}
|
||||
mysqli_query($mysqli, "INSERT INTO certificates SET certificate_name = '$name_sql', certificate_domain = '$name_sql',
|
||||
certificate_issued_by = '" . escapeSql($certificate['issued_by']) . "', certificate_expire = '" . escapeSql($certificate['expire']) . "',
|
||||
certificate_public_key = '" . escapeSql($certificate['public_key']) . "', certificate_domain_id = $domain_id, certificate_client_id = $client_id");
|
||||
mysqli_query($mysqli, "INSERT INTO certificates SET certificate_name = '$name_sql', certificate_domain = '$name_sql', certificate_issued_by = '',
|
||||
certificate_domain_id = $domain_id, certificate_client_id = $client_id");
|
||||
certificateApplyCheck(mysqli_insert_id($mysqli), $check);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -175,9 +175,18 @@ function getExportColumns($export_type) {
|
||||
'certificates' => [
|
||||
'certificate_name' => ['label' => 'Name', 'weight' => 2],
|
||||
'certificate_description' => ['label' => 'Description', 'weight' => 3],
|
||||
'certificate_domain' => ['label' => 'Domain', 'weight' => 2],
|
||||
'certificate_domain' => ['label' => 'Host', 'weight' => 2],
|
||||
'certificate_issued_by' => ['label' => 'Issuer', 'weight' => 2],
|
||||
'certificate_expire' => ['label' => 'Expiration Date'],
|
||||
// The status column holds a key; the handler aliases its label
|
||||
'certificate_check_status' => ['label' => 'Last Check', 'field' => 'certificate_check_label'],
|
||||
'certificate_issued_at' => ['label' => 'Issued', 'default' => false],
|
||||
'certificate_names' => ['label' => 'Names Covered', 'field' => 'certificate_names_list', 'weight' => 3, 'default' => false],
|
||||
'certificate_fingerprint' => ['label' => 'SHA-256 Fingerprint', 'weight' => 3, 'default' => false],
|
||||
'certificate_checked_at' => ['label' => 'Checked At', 'default' => false],
|
||||
'domain_name' => ['label' => 'Domain', 'default' => false],
|
||||
'certificate_notes' => ['label' => 'Notes', 'weight' => 3, 'default' => false],
|
||||
'client_name' => ['label' => 'Client', 'weight' => 2, 'default' => false],
|
||||
],
|
||||
|
||||
'domains' => [
|
||||
|
||||
@@ -304,6 +304,33 @@ function globalSearchGroups($terms, $deep) {
|
||||
},
|
||||
];
|
||||
|
||||
$groups[] = [
|
||||
'key' => 'certificates', 'label' => 'Certificates', 'icon' => 'lock', 'module' => 'module_support',
|
||||
'select' => 'certificate_id, certificate_name, certificate_description, certificate_domain, certificate_expire, certificate_issued_at, certificate_check_status, certificate_client_id, client_name',
|
||||
'from' => 'certificates LEFT JOIN clients ON certificate_client_id = client_id',
|
||||
'where' => "certificate_archived_at IS NULL AND (certificate_name LIKE '%$like%' OR certificate_domain LIKE '%$like%' OR certificate_names LIKE '%$like%'
|
||||
OR certificate_description LIKE '%$like%' OR certificate_fingerprint LIKE '%$like%')",
|
||||
'scope' => 'certificate_client_id',
|
||||
'order' => "(certificate_name = '$eq' OR certificate_domain = '$eq') DESC, (certificate_name LIKE '$like%') DESC, certificate_name",
|
||||
'list_url' => '/agent/certificates.php?' . http_build_query(['q' => $q]),
|
||||
'item' => function ($row) {
|
||||
$expiry = certificateExpiry($row);
|
||||
$status = CERTIFICATE_CHECK_STATES[$row['certificate_check_status'] ?? ''] ?? null;
|
||||
return [
|
||||
'title' => $row['certificate_name'],
|
||||
'subtitle' => implode(' · ', array_filter([
|
||||
$row['certificate_domain'] !== $row['certificate_name'] ? $row['certificate_domain'] : '',
|
||||
$status && $row['certificate_check_status'] !== 'ok' ? $status['label'] : '',
|
||||
$expiry ? $expiry['text'] : '',
|
||||
$row['certificate_description'],
|
||||
])),
|
||||
'context' => $row['client_name'],
|
||||
// Straight to its quick look on the client's certificates page
|
||||
'url' => globalSearchClientUrl('certificates.php', $row['certificate_client_id'], ['open' => intval($row['certificate_id'])]),
|
||||
];
|
||||
},
|
||||
];
|
||||
|
||||
$document_deep_match = $deep ? "OR MATCH(document_content_raw) AGAINST ('$eq')" : '';
|
||||
$groups[] = [
|
||||
'key' => 'documents', 'label' => 'Documents', 'icon' => 'file-alt', 'module' => 'module_support',
|
||||
|
||||
@@ -98,7 +98,7 @@ function cronJobRegistry(): array
|
||||
'name' => 'certificate_refresher',
|
||||
'label' => 'Certificate Refresher',
|
||||
'script' => 'certificate_refresher.php',
|
||||
'description' => 'Re-reads the expiry date and issuer of every SSL certificate on file.',
|
||||
'description' => 'Checks the host of every certificate once a day - what it serves now, its expiry and issuer, and whether it is OK, for another name, untrusted, expired or unreachable.',
|
||||
'schedule' => 'Daily',
|
||||
'daily_at' => '03:30',
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user