| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775 |
- <?php
- declare(strict_types=1);
- const CONNECT_TIMEOUT = 12; // seconds
- const EHLO_NAME = 'tool.medowar.de';
- const CIPHER_PROBE_TIMEOUT = 6; // per-cipher probe, kept short so enumeration stays snappy
- const MAX_CIPHERS_PER_VERSION = 64; // safety cap on the exclusion loop
- /**
- * Connects to a mail server, negotiates STARTTLS (or implicit TLS), and reports
- * on the TLS handshake and the server certificate: trust chain, hostname match,
- * validity window, issuer/subject and SANs.
- */
- class MailTlsChecker
- {
- /**
- * @return array TLS/certificate report for the given host:port and protocol.
- */
- public function check(string $host, int $port, string $protocol): array
- {
- $report = [
- 'host' => $host,
- 'port' => $port,
- 'protocol' => $protocol,
- 'mode' => in_array($protocol, ['smtps', 'imaps', 'pop3s'], true) ? 'implicit' : 'starttls',
- 'connected' => false,
- 'starttls' => null, // negotiation transcript lines (starttls only)
- 'tls_ok' => false, // handshake succeeded *and* peer verified
- 'trusted' => false, // chain verified against CA bundle
- 'hostname_ok' => false, // certificate valid for the requested host
- 'errors' => [],
- 'cert' => null,
- 'tls_version' => null,
- 'cipher' => null,
- 'ciphers' => [], // version => list of accepted cipher suites
- ];
- // 1) Handshake with full verification to learn whether the chain is trusted.
- $verified = $this->handshake($host, $port, $protocol, true, $vErr, $transcript);
- $report['starttls'] = $transcript;
- if ($verified === null) {
- // Could not even reach the TLS stage — connection/protocol error.
- $report['errors'][] = $vErr;
- return $report;
- }
- $report['connected'] = true;
- $report['trusted'] = ($vErr === null);
- if ($vErr !== null) {
- $report['errors'][] = 'Certificate chain not trusted: ' . $vErr;
- }
- // 2) Handshake again without verification so we can always inspect the cert,
- // even when it is self-signed, expired, or for the wrong hostname.
- $stream = $this->handshake($host, $port, $protocol, false, $rErr, $t2);
- if (!is_resource($stream)) {
- if ($rErr !== null) {
- $report['errors'][] = $rErr;
- }
- return $report;
- }
- $params = stream_context_get_params($stream);
- $meta = stream_get_meta_data($stream);
- $certRes = $params['options']['ssl']['peer_certificate'] ?? null;
- // Negotiated protocol version / cipher (from the crypto meta, when exposed).
- foreach (($meta['crypto'] ?? []) as $k => $v) {
- if ($k === 'protocol') { $report['tls_version'] = $v; }
- if ($k === 'cipher_name') { $report['cipher'] = $v; }
- }
- if ($certRes) {
- $report['cert'] = $this->describeCert($certRes, $host, $report);
- $report['hostname_ok'] = $report['cert']['hostname_ok'];
- } else {
- $report['errors'][] = 'TLS handshake completed but no peer certificate was presented.';
- }
- fclose($stream);
- $report['tls_ok'] = $report['trusted']
- && $report['hostname_ok']
- && ($report['cert']['time_ok'] ?? false);
- // 3) Enumerate every cipher suite the server is willing to negotiate on
- // this port. Best-effort — never let it break the main report.
- try {
- $report['ciphers'] = $this->enumerateCiphers($host, $port, $protocol);
- } catch (\Throwable $e) {
- // ignore — the core TLS/cert report above is what matters.
- }
- return $report;
- }
- /**
- * Discovers which cipher suites the server accepts, per TLS version.
- *
- * For TLS 1.2 and below we offer the full set, note the suite the server
- * picks, exclude it, and repeat until no common cipher remains — this yields
- * the complete list of server-supported suites in one connection each. PHP
- * cannot restrict the TLS 1.3 ciphersuite list, so for 1.3 we can only report
- * the single suite that gets negotiated.
- *
- * @return array<string,string[]> e.g. ['TLS 1.2' => ['ECDHE-RSA-AES256-GCM-SHA384', ...]]
- */
- public function enumerateCiphers(string $host, int $port, string $protocol): array
- {
- $versions = [];
- if (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT')) { $versions['TLS 1.3'] = STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT; }
- if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { $versions['TLS 1.2'] = STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; }
- if (defined('STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT')) { $versions['TLS 1.1'] = STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; }
- if (defined('STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT')) { $versions['TLS 1.0'] = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT; }
- $tls13Method = defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') ? STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT : -1;
- $out = [];
- foreach ($versions as $label => $method) {
- $isTls13 = ($method === $tls13Method);
- $found = [];
- for ($i = 0; $i < MAX_CIPHERS_PER_VERSION; $i++) {
- // null exclude => don't touch the cipher list (TLS 1.3 case).
- $name = $this->probeCipher($host, $port, $protocol, $method, $isTls13 ? null : $found);
- if ($name === null || in_array($name, $found, true)) {
- break; // no (further) suite negotiated for this version.
- }
- $found[] = $name;
- if ($isTls13) {
- break; // cannot iterate the 1.3 suite list from PHP.
- }
- }
- if ($found) {
- $out[$label] = $found;
- }
- }
- return $out;
- }
- /**
- * Attempts a single handshake at a fixed TLS version, optionally offering
- * every cipher except those in $exclude, and returns the negotiated cipher
- * suite name (or null if the handshake did not complete).
- *
- * @param string[]|null $exclude Suites to withhold, or null to leave the
- * cipher list untouched (used for TLS 1.3).
- */
- private function probeCipher(string $host, int $port, string $protocol, int $method, ?array $exclude): ?string
- {
- $ssl = [
- 'verify_peer' => false,
- 'verify_peer_name' => false,
- 'allow_self_signed' => true,
- 'SNI_enabled' => true,
- 'peer_name' => $host,
- ];
- if ($exclude !== null) {
- // @SECLEVEL=0 lets us also see weak/legacy suites the server still offers.
- $parts = ['ALL', 'COMPLEMENTOFALL'];
- foreach ($exclude as $c) {
- $parts[] = '!' . $c;
- }
- $parts[] = '@SECLEVEL=0';
- $ssl['ciphers'] = implode(':', $parts);
- }
- $ctx = stream_context_create(['ssl' => $ssl]);
- $errno = 0; $errstr = '';
- $stream = @stream_socket_client(
- sprintf('tcp://%s:%d', $host, $port),
- $errno, $errstr, CIPHER_PROBE_TIMEOUT, STREAM_CLIENT_CONNECT, $ctx
- );
- if (!is_resource($stream)) {
- return null;
- }
- stream_set_timeout($stream, CIPHER_PROBE_TIMEOUT);
- if (!in_array($protocol, ['smtps', 'imaps', 'pop3s'], true)) {
- try {
- $t = [];
- $this->negotiateStartTls($stream, $protocol, $t);
- } catch (\Throwable $e) {
- fclose($stream);
- return null;
- }
- }
- openssl_error_string(); // clear stale queue
- $ok = @stream_socket_enable_crypto($stream, true, $method);
- if ($ok !== true) {
- fclose($stream);
- return null;
- }
- $name = null;
- foreach ((stream_get_meta_data($stream)['crypto'] ?? []) as $k => $v) {
- if ($k === 'cipher_name') { $name = $v; }
- }
- fclose($stream);
- return ($name !== null && $name !== '') ? $name : null;
- }
- /**
- * Opens a TCP connection, runs the STARTTLS dance if required, then enables
- * crypto. Returns the stream resource on success. On verification failure
- * with $verify=true, returns false-y stream but populates $err. On connection
- * failure returns null. $transcript receives the plaintext protocol lines.
- *
- * @return resource|false|null
- */
- private function handshake(string $host, int $port, string $protocol, bool $verify, ?string &$err, ?array &$transcript)
- {
- $err = null;
- $transcript = [];
- $ctx = stream_context_create(['ssl' => [
- 'verify_peer' => $verify,
- 'verify_peer_name' => $verify,
- 'allow_self_signed' => !$verify,
- 'capture_peer_cert' => true,
- 'SNI_enabled' => true,
- 'peer_name' => $host,
- ]]);
- // Always connect over plain TCP and drive the crypto switch ourselves.
- // For implicit-TLS ports that simply means enabling crypto immediately,
- // with no plaintext exchange — this keeps a single code path and gives us
- // reliable error reporting via the OpenSSL error queue.
- $errno = 0; $errstr = '';
- $stream = @stream_socket_client(
- sprintf('tcp://%s:%d', $host, $port),
- $errno,
- $errstr,
- CONNECT_TIMEOUT,
- STREAM_CLIENT_CONNECT,
- $ctx
- );
- if (!is_resource($stream)) {
- $err = $errstr !== '' ? "Connection failed: $errstr (errno $errno)" : 'Connection failed.';
- return null;
- }
- stream_set_timeout($stream, CONNECT_TIMEOUT);
- // STARTTLS protocols exchange a few plaintext commands before the switch.
- if (!in_array($protocol, ['smtps', 'imaps', 'pop3s'], true)) {
- try {
- $this->negotiateStartTls($stream, $protocol, $transcript);
- } catch (\RuntimeException $e) {
- fclose($stream);
- $err = $e->getMessage();
- return null;
- }
- }
- openssl_error_string(); // clear any stale queue entries
- error_clear_last();
- $ok = @stream_socket_enable_crypto(
- $stream,
- true,
- STREAM_CRYPTO_METHOD_TLS_CLIENT
- );
- if ($ok !== true) {
- $sslErr = $this->drainSslErrors();
- $last = error_get_last()['message'] ?? '';
- fclose($stream);
- // Trim PHP's noisy function prefix and collapse multi-line OpenSSL blurb.
- $detail = trim(preg_replace('/\s+/', ' ', str_replace('stream_socket_enable_crypto():', '', $sslErr ?: $last)));
- if ($verify) {
- // The handshake was reached; the certificate simply did not verify.
- $err = $detail ?: 'Certificate verification failed.';
- return false;
- }
- $err = $detail ?: 'TLS handshake failed.';
- return null;
- }
- return $stream;
- }
- /**
- * Speaks the protocol-specific STARTTLS handshake up to (not including) the
- * crypto switch. Throws RuntimeException if the server refuses.
- * @param resource $stream
- */
- private function negotiateStartTls($stream, string $protocol, array &$transcript): void
- {
- switch ($protocol) {
- case 'smtp': // submission, port 587
- case 'smtp25': // MX / server-to-server, port 25
- $this->expect($stream, '220', $transcript);
- $this->send($stream, 'EHLO ' . EHLO_NAME, $transcript);
- $ehlo = $this->readSmtp($stream, $transcript);
- if (stripos($ehlo, 'STARTTLS') === false) {
- throw new \RuntimeException('Server did not advertise STARTTLS in its EHLO response.');
- }
- $this->send($stream, 'STARTTLS', $transcript);
- $this->expect($stream, '220', $transcript);
- break;
- case 'imap':
- $this->expect($stream, '* OK', $transcript, true);
- $this->send($stream, 'a1 STARTTLS', $transcript);
- $resp = $this->readLine($stream, $transcript);
- if (stripos($resp, 'a1 OK') === false) {
- throw new \RuntimeException('IMAP server refused STARTTLS: ' . trim($resp));
- }
- break;
- case 'pop3':
- $this->expect($stream, '+OK', $transcript, true);
- $this->send($stream, 'STLS', $transcript);
- $resp = $this->readLine($stream, $transcript);
- if (stripos($resp, '+OK') !== 0) {
- throw new \RuntimeException('POP3 server refused STLS: ' . trim($resp));
- }
- break;
- default:
- throw new \RuntimeException('Unsupported protocol: ' . $protocol);
- }
- }
- /** @param resource $stream */
- private function send($stream, string $line, array &$transcript): void
- {
- $transcript[] = 'C: ' . $line;
- fwrite($stream, $line . "\r\n");
- }
- /**
- * Reads one line and asserts it starts with $code (or contains it, when $contains).
- * @param resource $stream
- */
- private function expect($stream, string $code, array &$transcript, bool $contains = false): void
- {
- $line = $this->readLine($stream, $transcript);
- $hit = $contains ? (stripos($line, $code) !== false) : (strpos(ltrim($line), $code) === 0);
- if (!$hit) {
- throw new \RuntimeException(sprintf('Expected "%s" but got: %s', $code, trim($line)));
- }
- }
- /**
- * Reads a full multiline SMTP reply (lines like "250-..." until "250 ...").
- * @param resource $stream
- */
- private function readSmtp($stream, array &$transcript): string
- {
- $all = '';
- while (($line = $this->readLine($stream, $transcript)) !== '') {
- $all .= $line;
- // Continuation lines have a hyphen as the 4th character.
- if (strlen($line) < 4 || $line[3] !== '-') {
- break;
- }
- }
- return $all;
- }
- /** @param resource $stream */
- private function readLine($stream, array &$transcript): string
- {
- $line = fgets($stream, 4096);
- if ($line === false) {
- $meta = stream_get_meta_data($stream);
- if (!empty($meta['timed_out'])) {
- throw new \RuntimeException('Timed out waiting for the server to respond.');
- }
- throw new \RuntimeException('Connection closed by server before a reply was received.');
- }
- $transcript[] = 'S: ' . rtrim($line, "\r\n");
- return $line;
- }
- /** Collects any pending messages from the OpenSSL error queue. */
- private function drainSslErrors(): string
- {
- $msgs = [];
- while ($e = openssl_error_string()) {
- $msgs[] = $e;
- }
- return implode('; ', $msgs);
- }
- /**
- * Parses the peer certificate and evaluates validity window + hostname match.
- * @param \OpenSSLCertificate|resource $certRes
- */
- private function describeCert($certRes, string $host, array $report): array
- {
- $info = openssl_x509_parse($certRes) ?: [];
- $now = time();
- $from = $info['validFrom_time_t'] ?? 0;
- $to = $info['validTo_time_t'] ?? 0;
- $sans = [];
- $altName = $info['extensions']['subjectAltName'] ?? '';
- foreach (array_filter(array_map('trim', explode(',', $altName))) as $entry) {
- if (stripos($entry, 'DNS:') === 0) {
- $sans[] = substr($entry, 4);
- } elseif (stripos($entry, 'IP Address:') === 0) {
- $sans[] = substr($entry, 11);
- } else {
- $sans[] = $entry;
- }
- }
- // Fall back to CN if there are no SANs (legacy certs).
- $cn = $info['subject']['CN'] ?? null;
- $names = $sans ?: ($cn !== null ? [$cn] : []);
- $pem = '';
- openssl_x509_export($certRes, $pem);
- return [
- 'subject' => $this->dn($info['subject'] ?? []),
- 'issuer' => $this->dn($info['issuer'] ?? []),
- 'cn' => $cn,
- 'sans' => $sans,
- 'valid_from' => $from,
- 'valid_to' => $to,
- 'time_ok' => $from && $to && $now >= $from && $now <= $to,
- 'expired' => $to && $now > $to,
- 'not_yet' => $from && $now < $from,
- 'days_left' => $to ? (int) floor(($to - $now) / 86400) : null,
- 'hostname_ok' => $this->matchesHost($host, $names),
- 'self_signed' => ($this->dn($info['subject'] ?? []) === $this->dn($info['issuer'] ?? [])),
- 'serial' => $info['serialNumberHex'] ?? ($info['serialNumber'] ?? ''),
- 'sig_type' => $info['signatureTypeSN'] ?? '',
- 'fingerprint' => openssl_x509_fingerprint($certRes, 'sha256') ?: '',
- ];
- }
- /** @param array<string,mixed> $dn */
- private function dn(array $dn): string
- {
- $parts = [];
- foreach ($dn as $k => $v) {
- $v = is_array($v) ? implode(' + ', $v) : $v;
- $parts[] = "$k=$v";
- }
- return implode(', ', $parts);
- }
- /**
- * RFC 6125 style match: exact or single leftmost wildcard.
- * @param string[] $names
- */
- private function matchesHost(string $host, array $names): bool
- {
- $host = strtolower(rtrim($host, '.'));
- foreach ($names as $name) {
- $name = strtolower(rtrim($name, '.'));
- if ($name === $host) {
- return true;
- }
- if (str_starts_with($name, '*.')) {
- $suffix = substr($name, 1); // ".example.com"
- // Wildcard matches exactly one leftmost label.
- if (str_ends_with($host, $suffix)
- && substr_count($host, '.') === substr_count($name, '.')) {
- return true;
- }
- }
- }
- return false;
- }
- }
- /** Default port for each protocol, used when the user leaves the port blank. */
- const DEFAULT_PORTS = [
- 'smtp25' => 25,
- 'smtp' => 587,
- 'smtps' => 465,
- 'imap' => 143,
- 'imaps' => 993,
- 'pop3' => 110,
- 'pop3s' => 995,
- ];
- const PROTOCOL_LABELS = [
- 'smtp25' => 'SMTP + STARTTLS — MX / server-to-server (25)',
- 'smtp' => 'SMTP + STARTTLS — submission (587)',
- 'smtps' => 'SMTPS — implicit TLS (465)',
- 'imap' => 'IMAP + STARTTLS (143)',
- 'imaps' => 'IMAPS — implicit TLS (993)',
- 'pop3' => 'POP3 + STLS (110)',
- 'pop3s' => 'POP3S — implicit TLS (995)',
- ];
- $host = trim((string) ($_GET['host'] ?? ''));
- $protocol = (string) ($_GET['protocol'] ?? 'smtp25');
- $portRaw = trim((string) ($_GET['port'] ?? ''));
- $report = null;
- $inputError = null;
- if (!isset(DEFAULT_PORTS[$protocol])) {
- $protocol = 'smtp25';
- }
- $port = $portRaw !== '' ? (int) $portRaw : DEFAULT_PORTS[$protocol];
- if ($host !== '') {
- // Accept a bare hostname; strip scheme/path/port if a URL was pasted.
- $host = preg_replace('#^\w+://#', '', $host);
- $host = explode('/', $host)[0];
- $host = strtolower(trim($host));
- if (str_contains($host, ':')) {
- $host = explode(':', $host)[0];
- }
- if (!preg_match('/^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/', $host)) {
- $inputError = 'Please enter a valid mail server hostname (e.g. mail.example.com).';
- } elseif ($port < 1 || $port > 65535) {
- $inputError = 'Please enter a valid port between 1 and 65535.';
- } else {
- $report = (new MailTlsChecker())->check($host, $port, $protocol);
- }
- }
- function fmtDate(?int $ts): string
- {
- return $ts ? gmdate('Y-m-d H:i:s', $ts) . ' UTC' : '—';
- }
- /** Rough strength bucket for a cipher suite, used only for colour-coding. */
- function cipherStrength(string $name): string
- {
- $n = strtoupper($name);
- if (preg_match('/NULL|EXP|RC4|DES|MD5|ADH|AECDH|ANON|SEED|IDEA/', $n)) {
- return 'weak';
- }
- if (str_starts_with($n, 'TLS_')
- || str_contains($n, 'GCM') || str_contains($n, 'CHACHA')
- || str_contains($n, 'POLY1305') || str_contains($n, 'CCM')) {
- return 'strong';
- }
- return 'medium'; // typically CBC-mode AEAD-less suites
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Mail TLS Checker</title>
- <style>
- body {
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- max-width: 1000px;
- margin: 40px auto;
- padding: 0 20px;
- background: #f5f5f5;
- color: #333;
- }
- h1 { color: #333; }
- .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
- form.lookup { margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; align-items: stretch; }
- input[type=text], select {
- padding: 10px; font-size: 15px; border: 1px solid #ccc; border-radius: 5px; background: white;
- }
- input[name=host] { flex: 1; min-width: 220px; }
- input[name=port] { width: 90px; }
- .btn {
- display: inline-block; padding: 10px 20px; background: #2196F3; color: white;
- text-decoration: none; border-radius: 5px; border: none; cursor: pointer; font-size: 15px;
- }
- .btn:hover { background: #1976D2; }
- .error { background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin: 10px 0; }
- .verdict {
- display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-radius: 6px;
- font-size: 18px; font-weight: 600; margin: 16px 0;
- }
- .verdict.ok { background: #e8f5e9; color: #2e7d32; border-left: 6px solid #43a047; }
- .verdict.fail { background: #ffebee; color: #c62828; border-left: 6px solid #e53935; }
- .checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; margin: 16px 0; }
- .check {
- display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-radius: 5px;
- background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); font-size: 14px;
- }
- .check .ic { font-size: 18px; }
- .check.pass { border-left: 4px solid #43a047; }
- .check.warn { border-left: 4px solid #fb8c00; }
- .check.crit { border-left: 4px solid #e53935; }
- .errlist { margin: 10px 0; }
- .errlist .error { margin: 6px 0; }
- h2 { color: #333; margin-top: 30px; }
- table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 10px; }
- th, td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; vertical-align: top; }
- th { width: 180px; color: #555; background: #fafafa; font-weight: 600; }
- td.mono, .mono { font-family: monospace; word-break: break-all; }
- ul.sans { margin: 0; padding-left: 18px; }
- ul.sans li { font-family: monospace; font-size: 13px; }
- .pill { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 12px; font-weight: 600; }
- .pill.g { background: #e8f5e9; color: #2e7d32; }
- .pill.r { background: #ffebee; color: #c62828; }
- .pill.o { background: #fff3e0; color: #e65100; }
- details.transcript { margin-top: 20px; }
- details.transcript pre {
- background: #263238; color: #cfd8dc; padding: 12px 14px; border-radius: 5px;
- font-size: 12px; overflow-x: auto; line-height: 1.5;
- }
- summary { cursor: pointer; font-weight: 600; color: #1976D2; }
- </style>
- </head>
- <body>
- <h1>🔐 Mail TLS Checker</h1>
- <div class="info">
- Connects to a mail server, negotiates <strong>STARTTLS</strong> (or implicit TLS) and reports on the
- <strong>TLS handshake</strong> and <strong>server certificate</strong>: trust chain, hostname match,
- validity window, issuer and SANs. Nothing is sent beyond the TLS negotiation — no login, no mail.
- </div>
- <form class="lookup" method="GET">
- <input type="text" name="host" placeholder="mail.example.com"
- value="<?= htmlspecialchars($host) ?>" autofocus>
- <select name="protocol">
- <?php foreach (PROTOCOL_LABELS as $key => $label): ?>
- <option value="<?= $key ?>" <?= $protocol === $key ? 'selected' : '' ?>>
- <?= htmlspecialchars($label) ?>
- </option>
- <?php endforeach; ?>
- </select>
- <input type="text" name="port" placeholder="port"
- value="<?= htmlspecialchars($portRaw) ?>">
- <button type="submit" class="btn">🔍 Test TLS</button>
- </form>
- <p style="color:#888;font-size:12px;margin-top:-10px;">
- Leave the port blank to use the protocol default
- (<?= implode(', ', array_map(fn($p, $n) => "$p=$n", array_keys(DEFAULT_PORTS), DEFAULT_PORTS)) ?>).
- </p>
- <?php if ($inputError): ?>
- <div class="error"><?= htmlspecialchars($inputError) ?></div>
- <?php endif; ?>
- <?php if ($report !== null): ?>
- <?php $cert = $report['cert']; ?>
- <?php if ($report['tls_ok']): ?>
- <div class="verdict ok">✅ TLS is valid — trusted chain, correct hostname and within its validity period.</div>
- <?php else: ?>
- <div class="verdict fail">❌ TLS check failed — see the details below.</div>
- <?php endif; ?>
- <?php if (!empty($report['errors'])): ?>
- <div class="errlist">
- <?php foreach ($report['errors'] as $e): ?>
- <div class="error">⚠️ <?= htmlspecialchars($e) ?></div>
- <?php endforeach; ?>
- </div>
- <?php endif; ?>
- <?php if ($report['connected']): ?>
- <div class="checks">
- <?php
- $timeOk = $cert['time_ok'] ?? false;
- $renderCheck = function (bool $pass, string $label, string $detail, bool $criticalIfFail = true) {
- $cls = $pass ? 'pass' : ($criticalIfFail ? 'crit' : 'warn');
- $ic = $pass ? '✔️' : ($criticalIfFail ? '❌' : '⚠️');
- printf(
- '<div class="check %s"><span class="ic">%s</span><div><strong>%s</strong><br>%s</div></div>',
- $cls, $ic, htmlspecialchars($label), htmlspecialchars($detail)
- );
- };
- $renderCheck($report['trusted'], 'Trusted chain',
- $report['trusted'] ? 'Verified against system CA bundle' : 'Not verifiable / self-signed');
- $renderCheck($report['hostname_ok'], 'Hostname match',
- $report['hostname_ok'] ? $report['host'] . ' is covered' : 'Certificate not valid for ' . $report['host']);
- $renderCheck((bool) $timeOk, 'Validity period',
- $timeOk
- ? ($cert['days_left'] !== null ? $cert['days_left'] . ' day(s) until expiry' : 'Currently valid')
- : (($cert['expired'] ?? false) ? 'Certificate has expired' : 'Certificate not yet valid'));
- if ($cert && ($cert['days_left'] ?? null) !== null && $cert['days_left'] >= 0 && $cert['days_left'] <= 21) {
- $renderCheck(false, 'Expiry warning', 'Expires in ' . $cert['days_left'] . ' day(s)', false);
- }
- ?>
- </div>
- <?php endif; ?>
- <h2>Connection</h2>
- <table>
- <tr><th>Server</th><td class="mono"><?= htmlspecialchars($report['host'] . ':' . $report['port']) ?></td></tr>
- <tr><th>Protocol</th><td><?= htmlspecialchars(PROTOCOL_LABELS[$report['protocol']] ?? $report['protocol']) ?> — <?= htmlspecialchars($report['mode']) ?></td></tr>
- <tr><th>TLS version</th><td class="mono"><?= htmlspecialchars($report['tls_version'] ?: '—') ?></td></tr>
- <tr><th>Cipher</th><td class="mono"><?= htmlspecialchars($report['cipher'] ?: '—') ?></td></tr>
- </table>
- <?php if (!empty($report['ciphers'])): ?>
- <h2>Supported ciphers</h2>
- <table>
- <?php foreach ($report['ciphers'] as $ver => $list): ?>
- <tr>
- <th><?= htmlspecialchars($ver) ?> <span style="font-weight:400;color:#999;">(<?= count($list) ?>)</span></th>
- <td>
- <?php foreach ($list as $c):
- $cls = ['strong' => 'g', 'weak' => 'r', 'medium' => 'o'][cipherStrength($c)]; ?>
- <span class="pill <?= $cls ?>" style="font-family:monospace;margin:2px 4px 2px 0;"><?= htmlspecialchars($c) ?></span>
- <?php endforeach; ?>
- <?php if ($ver === 'TLS 1.3'): ?>
- <div style="color:#888;font-size:11px;margin-top:6px;">
- PHP cannot iterate individual TLS 1.3 suites — only the negotiated suite is shown.
- </div>
- <?php endif; ?>
- </td>
- </tr>
- <?php endforeach; ?>
- </table>
- <p style="color:#888;font-size:12px;margin-top:8px;">
- Enumerated by repeatedly handshaking and excluding the negotiated suite.
- <span class="pill g">strong</span> AEAD / TLS 1.3
- <span class="pill o">legacy</span> CBC-mode
- <span class="pill r">weak</span> RC4/DES/NULL/export/anon.
- </p>
- <?php endif; ?>
- <?php if ($cert): ?>
- <h2>Certificate</h2>
- <table>
- <tr><th>Subject</th><td class="mono"><?= htmlspecialchars($cert['subject']) ?></td></tr>
- <tr><th>Common name</th><td class="mono"><?= htmlspecialchars($cert['cn'] ?? '—') ?></td></tr>
- <tr><th>Issuer</th><td class="mono"><?= htmlspecialchars($cert['issuer']) ?></td></tr>
- <tr>
- <th>Self-signed</th>
- <td><?= $cert['self_signed']
- ? '<span class="pill o">yes</span>'
- : '<span class="pill g">no</span>' ?></td>
- </tr>
- <tr>
- <th>Valid from</th>
- <td class="mono"><?= htmlspecialchars(fmtDate($cert['valid_from'])) ?>
- <?= ($cert['not_yet'] ?? false) ? ' <span class="pill r">not yet valid</span>' : '' ?></td>
- </tr>
- <tr>
- <th>Valid to</th>
- <td class="mono"><?= htmlspecialchars(fmtDate($cert['valid_to'])) ?>
- <?php if ($cert['expired'] ?? false): ?>
- <span class="pill r">expired</span>
- <?php elseif (($cert['days_left'] ?? 99) <= 21): ?>
- <span class="pill o"><?= (int) $cert['days_left'] ?> day(s) left</span>
- <?php else: ?>
- <span class="pill g"><?= (int) $cert['days_left'] ?> day(s) left</span>
- <?php endif; ?>
- </td>
- </tr>
- <tr>
- <th>Subject Alt Names</th>
- <td>
- <?php if (!empty($cert['sans'])): ?>
- <ul class="sans">
- <?php foreach ($cert['sans'] as $s): ?>
- <li><?= htmlspecialchars($s) ?></li>
- <?php endforeach; ?>
- </ul>
- <?php else: ?>—<?php endif; ?>
- </td>
- </tr>
- <tr><th>Signature</th><td class="mono"><?= htmlspecialchars($cert['sig_type'] ?: '—') ?></td></tr>
- <tr><th>Serial</th><td class="mono"><?= htmlspecialchars((string) $cert['serial']) ?></td></tr>
- <tr><th>SHA-256 fingerprint</th><td class="mono"><?= htmlspecialchars(trim(chunk_split($cert['fingerprint'], 2, ':'), ':')) ?></td></tr>
- </table>
- <?php endif; ?>
- <?php if (!empty($report['starttls'])): ?>
- <details class="transcript">
- <summary>STARTTLS negotiation transcript</summary>
- <pre><?= htmlspecialchars(implode("\n", $report['starttls'])) ?></pre>
- </details>
- <?php endif; ?>
- <?php endif; ?>
- </body>
- </html>
|