mail-tls-check.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. <?php
  2. declare(strict_types=1);
  3. const CONNECT_TIMEOUT = 12; // seconds
  4. const EHLO_NAME = 'tool.medowar.de';
  5. /**
  6. * Connects to a mail server, negotiates STARTTLS (or implicit TLS), and reports
  7. * on the TLS handshake and the server certificate: trust chain, hostname match,
  8. * validity window, issuer/subject and SANs.
  9. */
  10. class MailTlsChecker
  11. {
  12. /**
  13. * @return array TLS/certificate report for the given host:port and protocol.
  14. */
  15. public function check(string $host, int $port, string $protocol): array
  16. {
  17. $report = [
  18. 'host' => $host,
  19. 'port' => $port,
  20. 'protocol' => $protocol,
  21. 'mode' => in_array($protocol, ['smtps', 'imaps', 'pop3s'], true) ? 'implicit' : 'starttls',
  22. 'connected' => false,
  23. 'starttls' => null, // negotiation transcript lines (starttls only)
  24. 'tls_ok' => false, // handshake succeeded *and* peer verified
  25. 'trusted' => false, // chain verified against CA bundle
  26. 'hostname_ok' => false, // certificate valid for the requested host
  27. 'errors' => [],
  28. 'cert' => null,
  29. 'tls_version' => null,
  30. 'cipher' => null,
  31. ];
  32. // 1) Handshake with full verification to learn whether the chain is trusted.
  33. $verified = $this->handshake($host, $port, $protocol, true, $vErr, $transcript);
  34. $report['starttls'] = $transcript;
  35. if ($verified === null) {
  36. // Could not even reach the TLS stage — connection/protocol error.
  37. $report['errors'][] = $vErr;
  38. return $report;
  39. }
  40. $report['connected'] = true;
  41. $report['trusted'] = ($vErr === null);
  42. if ($vErr !== null) {
  43. $report['errors'][] = 'Certificate chain not trusted: ' . $vErr;
  44. }
  45. // 2) Handshake again without verification so we can always inspect the cert,
  46. // even when it is self-signed, expired, or for the wrong hostname.
  47. $stream = $this->handshake($host, $port, $protocol, false, $rErr, $t2);
  48. if (!is_resource($stream)) {
  49. if ($rErr !== null) {
  50. $report['errors'][] = $rErr;
  51. }
  52. return $report;
  53. }
  54. $params = stream_context_get_params($stream);
  55. $meta = stream_get_meta_data($stream);
  56. $certRes = $params['options']['ssl']['peer_certificate'] ?? null;
  57. // Negotiated protocol version / cipher (from the crypto meta, when exposed).
  58. foreach (($meta['crypto'] ?? []) as $k => $v) {
  59. if ($k === 'protocol') { $report['tls_version'] = $v; }
  60. if ($k === 'cipher_name') { $report['cipher'] = $v; }
  61. }
  62. if ($certRes) {
  63. $report['cert'] = $this->describeCert($certRes, $host, $report);
  64. $report['hostname_ok'] = $report['cert']['hostname_ok'];
  65. } else {
  66. $report['errors'][] = 'TLS handshake completed but no peer certificate was presented.';
  67. }
  68. fclose($stream);
  69. $report['tls_ok'] = $report['trusted']
  70. && $report['hostname_ok']
  71. && ($report['cert']['time_ok'] ?? false);
  72. return $report;
  73. }
  74. /**
  75. * Opens a TCP connection, runs the STARTTLS dance if required, then enables
  76. * crypto. Returns the stream resource on success. On verification failure
  77. * with $verify=true, returns false-y stream but populates $err. On connection
  78. * failure returns null. $transcript receives the plaintext protocol lines.
  79. *
  80. * @return resource|false|null
  81. */
  82. private function handshake(string $host, int $port, string $protocol, bool $verify, ?string &$err, ?array &$transcript)
  83. {
  84. $err = null;
  85. $transcript = [];
  86. $ctx = stream_context_create(['ssl' => [
  87. 'verify_peer' => $verify,
  88. 'verify_peer_name' => $verify,
  89. 'allow_self_signed' => !$verify,
  90. 'capture_peer_cert' => true,
  91. 'SNI_enabled' => true,
  92. 'peer_name' => $host,
  93. ]]);
  94. // Always connect over plain TCP and drive the crypto switch ourselves.
  95. // For implicit-TLS ports that simply means enabling crypto immediately,
  96. // with no plaintext exchange — this keeps a single code path and gives us
  97. // reliable error reporting via the OpenSSL error queue.
  98. $errno = 0; $errstr = '';
  99. $stream = @stream_socket_client(
  100. sprintf('tcp://%s:%d', $host, $port),
  101. $errno,
  102. $errstr,
  103. CONNECT_TIMEOUT,
  104. STREAM_CLIENT_CONNECT,
  105. $ctx
  106. );
  107. if (!is_resource($stream)) {
  108. $err = $errstr !== '' ? "Connection failed: $errstr (errno $errno)" : 'Connection failed.';
  109. return null;
  110. }
  111. stream_set_timeout($stream, CONNECT_TIMEOUT);
  112. // STARTTLS protocols exchange a few plaintext commands before the switch.
  113. if (!in_array($protocol, ['smtps', 'imaps', 'pop3s'], true)) {
  114. try {
  115. $this->negotiateStartTls($stream, $protocol, $transcript);
  116. } catch (\RuntimeException $e) {
  117. fclose($stream);
  118. $err = $e->getMessage();
  119. return null;
  120. }
  121. }
  122. openssl_error_string(); // clear any stale queue entries
  123. error_clear_last();
  124. $ok = @stream_socket_enable_crypto(
  125. $stream,
  126. true,
  127. STREAM_CRYPTO_METHOD_TLS_CLIENT
  128. );
  129. if ($ok !== true) {
  130. $sslErr = $this->drainSslErrors();
  131. $last = error_get_last()['message'] ?? '';
  132. fclose($stream);
  133. // Trim PHP's noisy function prefix and collapse multi-line OpenSSL blurb.
  134. $detail = trim(preg_replace('/\s+/', ' ', str_replace('stream_socket_enable_crypto():', '', $sslErr ?: $last)));
  135. if ($verify) {
  136. // The handshake was reached; the certificate simply did not verify.
  137. $err = $detail ?: 'Certificate verification failed.';
  138. return false;
  139. }
  140. $err = $detail ?: 'TLS handshake failed.';
  141. return null;
  142. }
  143. return $stream;
  144. }
  145. /**
  146. * Speaks the protocol-specific STARTTLS handshake up to (not including) the
  147. * crypto switch. Throws RuntimeException if the server refuses.
  148. * @param resource $stream
  149. */
  150. private function negotiateStartTls($stream, string $protocol, array &$transcript): void
  151. {
  152. switch ($protocol) {
  153. case 'smtp': // submission, port 587
  154. case 'smtp25': // MX / server-to-server, port 25
  155. $this->expect($stream, '220', $transcript);
  156. $this->send($stream, 'EHLO ' . EHLO_NAME, $transcript);
  157. $ehlo = $this->readSmtp($stream, $transcript);
  158. if (stripos($ehlo, 'STARTTLS') === false) {
  159. throw new \RuntimeException('Server did not advertise STARTTLS in its EHLO response.');
  160. }
  161. $this->send($stream, 'STARTTLS', $transcript);
  162. $this->expect($stream, '220', $transcript);
  163. break;
  164. case 'imap':
  165. $this->expect($stream, '* OK', $transcript, true);
  166. $this->send($stream, 'a1 STARTTLS', $transcript);
  167. $resp = $this->readLine($stream, $transcript);
  168. if (stripos($resp, 'a1 OK') === false) {
  169. throw new \RuntimeException('IMAP server refused STARTTLS: ' . trim($resp));
  170. }
  171. break;
  172. case 'pop3':
  173. $this->expect($stream, '+OK', $transcript, true);
  174. $this->send($stream, 'STLS', $transcript);
  175. $resp = $this->readLine($stream, $transcript);
  176. if (stripos($resp, '+OK') !== 0) {
  177. throw new \RuntimeException('POP3 server refused STLS: ' . trim($resp));
  178. }
  179. break;
  180. default:
  181. throw new \RuntimeException('Unsupported protocol: ' . $protocol);
  182. }
  183. }
  184. /** @param resource $stream */
  185. private function send($stream, string $line, array &$transcript): void
  186. {
  187. $transcript[] = 'C: ' . $line;
  188. fwrite($stream, $line . "\r\n");
  189. }
  190. /**
  191. * Reads one line and asserts it starts with $code (or contains it, when $contains).
  192. * @param resource $stream
  193. */
  194. private function expect($stream, string $code, array &$transcript, bool $contains = false): void
  195. {
  196. $line = $this->readLine($stream, $transcript);
  197. $hit = $contains ? (stripos($line, $code) !== false) : (strpos(ltrim($line), $code) === 0);
  198. if (!$hit) {
  199. throw new \RuntimeException(sprintf('Expected "%s" but got: %s', $code, trim($line)));
  200. }
  201. }
  202. /**
  203. * Reads a full multiline SMTP reply (lines like "250-..." until "250 ...").
  204. * @param resource $stream
  205. */
  206. private function readSmtp($stream, array &$transcript): string
  207. {
  208. $all = '';
  209. while (($line = $this->readLine($stream, $transcript)) !== '') {
  210. $all .= $line;
  211. // Continuation lines have a hyphen as the 4th character.
  212. if (strlen($line) < 4 || $line[3] !== '-') {
  213. break;
  214. }
  215. }
  216. return $all;
  217. }
  218. /** @param resource $stream */
  219. private function readLine($stream, array &$transcript): string
  220. {
  221. $line = fgets($stream, 4096);
  222. if ($line === false) {
  223. $meta = stream_get_meta_data($stream);
  224. if (!empty($meta['timed_out'])) {
  225. throw new \RuntimeException('Timed out waiting for the server to respond.');
  226. }
  227. throw new \RuntimeException('Connection closed by server before a reply was received.');
  228. }
  229. $transcript[] = 'S: ' . rtrim($line, "\r\n");
  230. return $line;
  231. }
  232. /** Collects any pending messages from the OpenSSL error queue. */
  233. private function drainSslErrors(): string
  234. {
  235. $msgs = [];
  236. while ($e = openssl_error_string()) {
  237. $msgs[] = $e;
  238. }
  239. return implode('; ', $msgs);
  240. }
  241. /**
  242. * Parses the peer certificate and evaluates validity window + hostname match.
  243. * @param \OpenSSLCertificate|resource $certRes
  244. */
  245. private function describeCert($certRes, string $host, array $report): array
  246. {
  247. $info = openssl_x509_parse($certRes) ?: [];
  248. $now = time();
  249. $from = $info['validFrom_time_t'] ?? 0;
  250. $to = $info['validTo_time_t'] ?? 0;
  251. $sans = [];
  252. $altName = $info['extensions']['subjectAltName'] ?? '';
  253. foreach (array_filter(array_map('trim', explode(',', $altName))) as $entry) {
  254. if (stripos($entry, 'DNS:') === 0) {
  255. $sans[] = substr($entry, 4);
  256. } elseif (stripos($entry, 'IP Address:') === 0) {
  257. $sans[] = substr($entry, 11);
  258. } else {
  259. $sans[] = $entry;
  260. }
  261. }
  262. // Fall back to CN if there are no SANs (legacy certs).
  263. $cn = $info['subject']['CN'] ?? null;
  264. $names = $sans ?: ($cn !== null ? [$cn] : []);
  265. $pem = '';
  266. openssl_x509_export($certRes, $pem);
  267. return [
  268. 'subject' => $this->dn($info['subject'] ?? []),
  269. 'issuer' => $this->dn($info['issuer'] ?? []),
  270. 'cn' => $cn,
  271. 'sans' => $sans,
  272. 'valid_from' => $from,
  273. 'valid_to' => $to,
  274. 'time_ok' => $from && $to && $now >= $from && $now <= $to,
  275. 'expired' => $to && $now > $to,
  276. 'not_yet' => $from && $now < $from,
  277. 'days_left' => $to ? (int) floor(($to - $now) / 86400) : null,
  278. 'hostname_ok' => $this->matchesHost($host, $names),
  279. 'self_signed' => ($this->dn($info['subject'] ?? []) === $this->dn($info['issuer'] ?? [])),
  280. 'serial' => $info['serialNumberHex'] ?? ($info['serialNumber'] ?? ''),
  281. 'sig_type' => $info['signatureTypeSN'] ?? '',
  282. 'fingerprint' => openssl_x509_fingerprint($certRes, 'sha256') ?: '',
  283. ];
  284. }
  285. /** @param array<string,mixed> $dn */
  286. private function dn(array $dn): string
  287. {
  288. $parts = [];
  289. foreach ($dn as $k => $v) {
  290. $v = is_array($v) ? implode(' + ', $v) : $v;
  291. $parts[] = "$k=$v";
  292. }
  293. return implode(', ', $parts);
  294. }
  295. /**
  296. * RFC 6125 style match: exact or single leftmost wildcard.
  297. * @param string[] $names
  298. */
  299. private function matchesHost(string $host, array $names): bool
  300. {
  301. $host = strtolower(rtrim($host, '.'));
  302. foreach ($names as $name) {
  303. $name = strtolower(rtrim($name, '.'));
  304. if ($name === $host) {
  305. return true;
  306. }
  307. if (str_starts_with($name, '*.')) {
  308. $suffix = substr($name, 1); // ".example.com"
  309. // Wildcard matches exactly one leftmost label.
  310. if (str_ends_with($host, $suffix)
  311. && substr_count($host, '.') === substr_count($name, '.')) {
  312. return true;
  313. }
  314. }
  315. }
  316. return false;
  317. }
  318. }
  319. /** Default port for each protocol, used when the user leaves the port blank. */
  320. const DEFAULT_PORTS = [
  321. 'smtp25' => 25,
  322. 'smtp' => 587,
  323. 'smtps' => 465,
  324. 'imap' => 143,
  325. 'imaps' => 993,
  326. 'pop3' => 110,
  327. 'pop3s' => 995,
  328. ];
  329. const PROTOCOL_LABELS = [
  330. 'smtp25' => 'SMTP + STARTTLS — MX / server-to-server (25)',
  331. 'smtp' => 'SMTP + STARTTLS — submission (587)',
  332. 'smtps' => 'SMTPS — implicit TLS (465)',
  333. 'imap' => 'IMAP + STARTTLS (143)',
  334. 'imaps' => 'IMAPS — implicit TLS (993)',
  335. 'pop3' => 'POP3 + STLS (110)',
  336. 'pop3s' => 'POP3S — implicit TLS (995)',
  337. ];
  338. $host = trim((string) ($_GET['host'] ?? ''));
  339. $protocol = (string) ($_GET['protocol'] ?? 'smtp');
  340. $portRaw = trim((string) ($_GET['port'] ?? ''));
  341. $report = null;
  342. $inputError = null;
  343. if (!isset(DEFAULT_PORTS[$protocol])) {
  344. $protocol = 'smtp';
  345. }
  346. $port = $portRaw !== '' ? (int) $portRaw : DEFAULT_PORTS[$protocol];
  347. if ($host !== '') {
  348. // Accept a bare hostname; strip scheme/path/port if a URL was pasted.
  349. $host = preg_replace('#^\w+://#', '', $host);
  350. $host = explode('/', $host)[0];
  351. $host = strtolower(trim($host));
  352. if (str_contains($host, ':')) {
  353. $host = explode(':', $host)[0];
  354. }
  355. if (!preg_match('/^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/', $host)) {
  356. $inputError = 'Please enter a valid mail server hostname (e.g. mail.example.com).';
  357. } elseif ($port < 1 || $port > 65535) {
  358. $inputError = 'Please enter a valid port between 1 and 65535.';
  359. } else {
  360. $report = (new MailTlsChecker())->check($host, $port, $protocol);
  361. }
  362. }
  363. function fmtDate(?int $ts): string
  364. {
  365. return $ts ? gmdate('Y-m-d H:i:s', $ts) . ' UTC' : '—';
  366. }
  367. ?>
  368. <!DOCTYPE html>
  369. <html lang="en">
  370. <head>
  371. <meta charset="UTF-8">
  372. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  373. <title>Mail TLS Checker</title>
  374. <style>
  375. body {
  376. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  377. max-width: 1000px;
  378. margin: 40px auto;
  379. padding: 0 20px;
  380. background: #f5f5f5;
  381. color: #333;
  382. }
  383. h1 { color: #333; }
  384. .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
  385. form.lookup { margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; align-items: stretch; }
  386. input[type=text], select {
  387. padding: 10px; font-size: 15px; border: 1px solid #ccc; border-radius: 5px; background: white;
  388. }
  389. input[name=host] { flex: 1; min-width: 220px; }
  390. input[name=port] { width: 90px; }
  391. .btn {
  392. display: inline-block; padding: 10px 20px; background: #2196F3; color: white;
  393. text-decoration: none; border-radius: 5px; border: none; cursor: pointer; font-size: 15px;
  394. }
  395. .btn:hover { background: #1976D2; }
  396. .error { background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin: 10px 0; }
  397. .verdict {
  398. display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-radius: 6px;
  399. font-size: 18px; font-weight: 600; margin: 16px 0;
  400. }
  401. .verdict.ok { background: #e8f5e9; color: #2e7d32; border-left: 6px solid #43a047; }
  402. .verdict.fail { background: #ffebee; color: #c62828; border-left: 6px solid #e53935; }
  403. .checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; margin: 16px 0; }
  404. .check {
  405. display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-radius: 5px;
  406. background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); font-size: 14px;
  407. }
  408. .check .ic { font-size: 18px; }
  409. .check.pass { border-left: 4px solid #43a047; }
  410. .check.warn { border-left: 4px solid #fb8c00; }
  411. .check.crit { border-left: 4px solid #e53935; }
  412. .errlist { margin: 10px 0; }
  413. .errlist .error { margin: 6px 0; }
  414. h2 { color: #333; margin-top: 30px; }
  415. table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 10px; }
  416. th, td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; vertical-align: top; }
  417. th { width: 180px; color: #555; background: #fafafa; font-weight: 600; }
  418. td.mono, .mono { font-family: monospace; word-break: break-all; }
  419. ul.sans { margin: 0; padding-left: 18px; }
  420. ul.sans li { font-family: monospace; font-size: 13px; }
  421. .pill { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 12px; font-weight: 600; }
  422. .pill.g { background: #e8f5e9; color: #2e7d32; }
  423. .pill.r { background: #ffebee; color: #c62828; }
  424. .pill.o { background: #fff3e0; color: #e65100; }
  425. details.transcript { margin-top: 20px; }
  426. details.transcript pre {
  427. background: #263238; color: #cfd8dc; padding: 12px 14px; border-radius: 5px;
  428. font-size: 12px; overflow-x: auto; line-height: 1.5;
  429. }
  430. summary { cursor: pointer; font-weight: 600; color: #1976D2; }
  431. </style>
  432. </head>
  433. <body>
  434. <h1>🔐 Mail TLS Checker</h1>
  435. <div class="info">
  436. Connects to a mail server, negotiates <strong>STARTTLS</strong> (or implicit TLS) and reports on the
  437. <strong>TLS handshake</strong> and <strong>server certificate</strong>: trust chain, hostname match,
  438. validity window, issuer and SANs. Nothing is sent beyond the TLS negotiation — no login, no mail.
  439. </div>
  440. <form class="lookup" method="GET">
  441. <input type="text" name="host" placeholder="mail.example.com"
  442. value="<?= htmlspecialchars($host) ?>" autofocus>
  443. <select name="protocol">
  444. <?php foreach (PROTOCOL_LABELS as $key => $label): ?>
  445. <option value="<?= $key ?>" <?= $protocol === $key ? 'selected' : '' ?>>
  446. <?= htmlspecialchars($label) ?>
  447. </option>
  448. <?php endforeach; ?>
  449. </select>
  450. <input type="text" name="port" placeholder="port"
  451. value="<?= htmlspecialchars($portRaw) ?>">
  452. <button type="submit" class="btn">🔍 Test TLS</button>
  453. </form>
  454. <p style="color:#888;font-size:12px;margin-top:-10px;">
  455. Leave the port blank to use the protocol default
  456. (<?= implode(', ', array_map(fn($p, $n) => "$p=$n", array_keys(DEFAULT_PORTS), DEFAULT_PORTS)) ?>).
  457. </p>
  458. <?php if ($inputError): ?>
  459. <div class="error"><?= htmlspecialchars($inputError) ?></div>
  460. <?php endif; ?>
  461. <?php if ($report !== null): ?>
  462. <?php $cert = $report['cert']; ?>
  463. <?php if ($report['tls_ok']): ?>
  464. <div class="verdict ok">✅ TLS is valid — trusted chain, correct hostname and within its validity period.</div>
  465. <?php else: ?>
  466. <div class="verdict fail">❌ TLS check failed — see the details below.</div>
  467. <?php endif; ?>
  468. <?php if (!empty($report['errors'])): ?>
  469. <div class="errlist">
  470. <?php foreach ($report['errors'] as $e): ?>
  471. <div class="error">⚠️ <?= htmlspecialchars($e) ?></div>
  472. <?php endforeach; ?>
  473. </div>
  474. <?php endif; ?>
  475. <?php if ($report['connected']): ?>
  476. <div class="checks">
  477. <?php
  478. $timeOk = $cert['time_ok'] ?? false;
  479. $renderCheck = function (bool $pass, string $label, string $detail, bool $criticalIfFail = true) {
  480. $cls = $pass ? 'pass' : ($criticalIfFail ? 'crit' : 'warn');
  481. $ic = $pass ? '✔️' : ($criticalIfFail ? '❌' : '⚠️');
  482. printf(
  483. '<div class="check %s"><span class="ic">%s</span><div><strong>%s</strong><br>%s</div></div>',
  484. $cls, $ic, htmlspecialchars($label), htmlspecialchars($detail)
  485. );
  486. };
  487. $renderCheck($report['trusted'], 'Trusted chain',
  488. $report['trusted'] ? 'Verified against system CA bundle' : 'Not verifiable / self-signed');
  489. $renderCheck($report['hostname_ok'], 'Hostname match',
  490. $report['hostname_ok'] ? $report['host'] . ' is covered' : 'Certificate not valid for ' . $report['host']);
  491. $renderCheck((bool) $timeOk, 'Validity period',
  492. $timeOk
  493. ? ($cert['days_left'] !== null ? $cert['days_left'] . ' day(s) until expiry' : 'Currently valid')
  494. : (($cert['expired'] ?? false) ? 'Certificate has expired' : 'Certificate not yet valid'));
  495. if ($cert && ($cert['days_left'] ?? null) !== null && $cert['days_left'] >= 0 && $cert['days_left'] <= 21) {
  496. $renderCheck(false, 'Expiry warning', 'Expires in ' . $cert['days_left'] . ' day(s)', false);
  497. }
  498. ?>
  499. </div>
  500. <?php endif; ?>
  501. <h2>Connection</h2>
  502. <table>
  503. <tr><th>Server</th><td class="mono"><?= htmlspecialchars($report['host'] . ':' . $report['port']) ?></td></tr>
  504. <tr><th>Protocol</th><td><?= htmlspecialchars(PROTOCOL_LABELS[$report['protocol']] ?? $report['protocol']) ?> — <?= htmlspecialchars($report['mode']) ?></td></tr>
  505. <tr><th>TLS version</th><td class="mono"><?= htmlspecialchars($report['tls_version'] ?: '—') ?></td></tr>
  506. <tr><th>Cipher</th><td class="mono"><?= htmlspecialchars($report['cipher'] ?: '—') ?></td></tr>
  507. </table>
  508. <?php if ($cert): ?>
  509. <h2>Certificate</h2>
  510. <table>
  511. <tr><th>Subject</th><td class="mono"><?= htmlspecialchars($cert['subject']) ?></td></tr>
  512. <tr><th>Common name</th><td class="mono"><?= htmlspecialchars($cert['cn'] ?? '—') ?></td></tr>
  513. <tr><th>Issuer</th><td class="mono"><?= htmlspecialchars($cert['issuer']) ?></td></tr>
  514. <tr>
  515. <th>Self-signed</th>
  516. <td><?= $cert['self_signed']
  517. ? '<span class="pill o">yes</span>'
  518. : '<span class="pill g">no</span>' ?></td>
  519. </tr>
  520. <tr>
  521. <th>Valid from</th>
  522. <td class="mono"><?= htmlspecialchars(fmtDate($cert['valid_from'])) ?>
  523. <?= ($cert['not_yet'] ?? false) ? ' <span class="pill r">not yet valid</span>' : '' ?></td>
  524. </tr>
  525. <tr>
  526. <th>Valid to</th>
  527. <td class="mono"><?= htmlspecialchars(fmtDate($cert['valid_to'])) ?>
  528. <?php if ($cert['expired'] ?? false): ?>
  529. <span class="pill r">expired</span>
  530. <?php elseif (($cert['days_left'] ?? 99) <= 21): ?>
  531. <span class="pill o"><?= (int) $cert['days_left'] ?> day(s) left</span>
  532. <?php else: ?>
  533. <span class="pill g"><?= (int) $cert['days_left'] ?> day(s) left</span>
  534. <?php endif; ?>
  535. </td>
  536. </tr>
  537. <tr>
  538. <th>Subject Alt Names</th>
  539. <td>
  540. <?php if (!empty($cert['sans'])): ?>
  541. <ul class="sans">
  542. <?php foreach ($cert['sans'] as $s): ?>
  543. <li><?= htmlspecialchars($s) ?></li>
  544. <?php endforeach; ?>
  545. </ul>
  546. <?php else: ?>—<?php endif; ?>
  547. </td>
  548. </tr>
  549. <tr><th>Signature</th><td class="mono"><?= htmlspecialchars($cert['sig_type'] ?: '—') ?></td></tr>
  550. <tr><th>Serial</th><td class="mono"><?= htmlspecialchars((string) $cert['serial']) ?></td></tr>
  551. <tr><th>SHA-256 fingerprint</th><td class="mono"><?= htmlspecialchars(trim(chunk_split($cert['fingerprint'], 2, ':'), ':')) ?></td></tr>
  552. </table>
  553. <?php endif; ?>
  554. <?php if (!empty($report['starttls'])): ?>
  555. <details class="transcript">
  556. <summary>STARTTLS negotiation transcript</summary>
  557. <pre><?= htmlspecialchars(implode("\n", $report['starttls'])) ?></pre>
  558. </details>
  559. <?php endif; ?>
  560. <?php endif; ?>
  561. </body>
  562. </html>