| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423 |
- <?php
- declare(strict_types=1);
- const POLICY_TIMEOUT = 12; // seconds for the HTTPS policy fetch
- const POLICY_MAX_BYTES = 65536; // RFC 8461: policies are small; cap the download
- /**
- * Checks whether a domain publishes an MTA-STS policy (RFC 8461) and evaluates
- * its consistency: the `_mta-sts` DNS TXT record, the HTTPS-hosted policy file
- * at `mta-sts.<domain>/.well-known/mta-sts.txt`, and the accompanying TLS-RPT
- * (`_smtp._tls`) reporting record.
- */
- class MtaStsChecker
- {
- /** @return array MTA-STS / TLS-RPT report for the given domain. */
- public function check(string $domain): array
- {
- $report = [
- 'domain' => $domain,
- 'supported' => false, // TXT + fetchable, parseable policy
- 'enforced' => false, // policy mode is "enforce"
- 'errors' => [],
- 'warnings' => [],
- 'txt' => null, // the _mta-sts TXT record contents
- 'txt_id' => null,
- 'policy_url'=> 'https://mta-sts.' . $domain . '/.well-known/mta-sts.txt',
- 'policy_raw'=> null, // raw fetched policy body
- 'policy' => null, // parsed: version, mode, mx[], max_age
- 'http' => null, // http status / content-type of the fetch
- 'tlsrpt' => null, // the _smtp._tls TXT record contents
- ];
- // 1) The MTA-STS DNS record lives at _mta-sts.<domain> and signals a policy.
- $this->checkTxtRecord($domain, $report);
- // 2) The policy itself is served over HTTPS from the mta-sts. subdomain.
- $this->fetchPolicy($report);
- // 3) TLS-RPT is optional but strongly recommended alongside MTA-STS.
- $this->checkTlsRpt($domain, $report);
- $mode = $report['policy']['mode'] ?? null;
- $report['supported'] = ($report['txt'] !== null && $report['policy'] !== null);
- $report['enforced'] = ($report['supported'] && $mode === 'enforce');
- return $report;
- }
- /** Looks up and validates the _mta-sts.<domain> TXT record. */
- private function checkTxtRecord(string $domain, array &$report): void
- {
- $host = '_mta-sts.' . $domain;
- $records = @dns_get_record($host, DNS_TXT) ?: [];
- $sts = [];
- foreach ($records as $rec) {
- $txt = $rec['txt'] ?? implode('', $rec['entries'] ?? []);
- if (stripos($txt, 'v=STSv1') !== false) {
- $sts[] = $txt;
- }
- }
- if (!$sts) {
- $report['errors'][] = 'No "v=STSv1" TXT record found at ' . $host . '.';
- return;
- }
- if (count($sts) > 1) {
- $report['warnings'][] = 'Multiple STS TXT records found at ' . $host
- . ' — RFC 8461 requires exactly one.';
- }
- $txt = $sts[0];
- $report['txt'] = $txt;
- // Parse the semicolon-separated key=value fields; "id" is mandatory.
- $fields = [];
- foreach (explode(';', $txt) as $pair) {
- if (str_contains($pair, '=')) {
- [$k, $v] = explode('=', $pair, 2);
- $fields[strtolower(trim($k))] = trim($v);
- }
- }
- if (($fields['v'] ?? '') !== 'STSv1') {
- $report['warnings'][] = 'TXT record does not start with "v=STSv1".';
- }
- if (empty($fields['id'])) {
- $report['errors'][] = 'TXT record is missing the required "id" field.';
- } elseif (!preg_match('/^[A-Za-z0-9]{1,32}$/', $fields['id'])) {
- $report['warnings'][] = 'The "id" value should be 1–32 alphanumeric characters.';
- }
- $report['txt_id'] = $fields['id'] ?? null;
- }
- /** Fetches the HTTPS policy file and parses its key/value directives. */
- private function fetchPolicy(array &$report): void
- {
- $url = $report['policy_url'];
- // RFC 8461: the policy MUST be served over HTTPS with a valid certificate,
- // and redirects MUST NOT be followed. We verify the chain explicitly.
- $ctx = stream_context_create([
- 'http' => [
- 'method' => 'GET',
- 'timeout' => POLICY_TIMEOUT,
- 'follow_location'=> 0,
- 'ignore_errors' => true, // so we still see 4xx/5xx bodies + headers
- 'header' => "User-Agent: mta-sts-check (tool.medowar.de)\r\n",
- ],
- 'ssl' => [
- 'verify_peer' => true,
- 'verify_peer_name' => true,
- 'SNI_enabled' => true,
- ],
- ]);
- $body = @file_get_contents($url, false, $ctx, 0, POLICY_MAX_BYTES);
- // $http_response_header is populated by the HTTP wrapper on any response.
- $status = null; $ctype = null;
- foreach ($http_response_header ?? [] as $h) {
- if (preg_match('#^HTTP/\S+\s+(\d{3})#', $h, $m)) {
- $status = (int) $m[1]; // last one wins (in case of intermediates)
- } elseif (stripos($h, 'Content-Type:') === 0) {
- $ctype = trim(substr($h, strlen('Content-Type:')));
- }
- }
- $report['http'] = ['status' => $status, 'content_type' => $ctype];
- if ($body === false) {
- $err = error_get_last()['message'] ?? '';
- $err = trim(preg_replace('/\s+/', ' ', preg_replace('#^file_get_contents\([^)]*\):\s*#', '', $err)));
- $report['errors'][] = 'Could not fetch the policy over HTTPS'
- . ($err !== '' ? ': ' . $err : '. The mta-sts host or its certificate may be misconfigured.');
- return;
- }
- if ($status !== null && $status !== 200) {
- $report['errors'][] = 'Policy fetch returned HTTP ' . $status . ' (expected 200).';
- return;
- }
- if ($ctype !== null && stripos($ctype, 'text/plain') === false) {
- $report['warnings'][] = 'Policy Content-Type is "' . $ctype . '"; RFC 8461 requires "text/plain".';
- }
- $report['policy_raw'] = $body;
- $this->parsePolicy($body, $report);
- }
- /** Parses the mta-sts.txt body into version/mode/mx[]/max_age and validates it. */
- private function parsePolicy(string $body, array &$report): void
- {
- $policy = ['version' => null, 'mode' => null, 'mx' => [], 'max_age' => null];
- foreach (preg_split('/\r\n|\r|\n/', $body) as $line) {
- $line = trim($line);
- if ($line === '' || !str_contains($line, ':')) {
- continue;
- }
- [$key, $val] = explode(':', $line, 2);
- $key = strtolower(trim($key));
- $val = trim($val);
- switch ($key) {
- case 'version': $policy['version'] = $val; break;
- case 'mode': $policy['mode'] = strtolower($val); break;
- case 'mx': if ($val !== '') { $policy['mx'][] = $val; } break;
- case 'max_age': $policy['max_age'] = (int) $val; break;
- }
- }
- if ($policy['version'] !== 'STSv1') {
- $report['errors'][] = 'Policy "version" is not "STSv1".';
- }
- if (!in_array($policy['mode'], ['enforce', 'testing', 'none'], true)) {
- $report['errors'][] = 'Policy "mode" is missing or invalid (expected enforce, testing or none).';
- }
- if ($policy['mode'] !== 'none' && empty($policy['mx'])) {
- $report['errors'][] = 'Policy declares no "mx" host patterns.';
- }
- if ($policy['max_age'] === null) {
- $report['errors'][] = 'Policy is missing the required "max_age" field.';
- } elseif ($policy['max_age'] < 86400) {
- $report['warnings'][] = 'A "max_age" below 86400 (1 day) is unusually short; long-lived caching is the point of MTA-STS.';
- } elseif ($policy['max_age'] > 31557600) {
- $report['warnings'][] = 'A "max_age" above 31557600 (1 year) exceeds the RFC 8461 recommended maximum.';
- }
- // Cross-check: the TXT id should change whenever the policy changes, but
- // a mode of "testing" means failures are reported, not enforced.
- if ($policy['mode'] === 'testing') {
- $report['warnings'][] = 'Policy mode is "testing" — TLS failures are reported but mail is still delivered.';
- }
- if ($policy['mode'] === 'none') {
- $report['warnings'][] = 'Policy mode is "none" — this actively signals that any previous MTA-STS policy is withdrawn.';
- }
- $report['policy'] = $policy;
- }
- /** Looks up the optional TLS-RPT (_smtp._tls.<domain>) reporting record. */
- private function checkTlsRpt(string $domain, array &$report): void
- {
- $host = '_smtp._tls.' . $domain;
- $records = @dns_get_record($host, DNS_TXT) ?: [];
- foreach ($records as $rec) {
- $txt = $rec['txt'] ?? implode('', $rec['entries'] ?? []);
- if (stripos($txt, 'v=TLSRPTv1') !== false) {
- $report['tlsrpt'] = $txt;
- return;
- }
- }
- $report['warnings'][] = 'No TLS-RPT (v=TLSRPTv1) record at ' . $host
- . ' — you would not receive reports about TLS delivery failures.';
- }
- }
- $domain = trim((string) ($_GET['domain'] ?? ''));
- $report = null;
- $inputError = null;
- if ($domain !== '') {
- // Accept a bare domain, an email address, or a pasted URL — reduce to the domain.
- $domain = preg_replace('#^\w+://#', '', $domain);
- $domain = explode('/', $domain)[0];
- if (str_contains($domain, '@')) {
- $domain = substr($domain, strrpos($domain, '@') + 1);
- }
- $domain = strtolower(trim($domain, ". \t"));
- if (str_contains($domain, ':')) {
- $domain = explode(':', $domain)[0];
- }
- if (!preg_match('/^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/', $domain)) {
- $inputError = 'Please enter a valid domain (e.g. example.com).';
- } else {
- $report = (new MtaStsChecker())->check($domain);
- }
- }
- function fmtMaxAge(?int $secs): string
- {
- if ($secs === null) { return '—'; }
- $days = $secs / 86400;
- if ($days >= 1) {
- return $secs . ' s (' . rtrim(rtrim(number_format($days, 1), '0'), '.') . ' days)';
- }
- return $secs . ' s';
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>MTA-STS 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] {
- padding: 10px; font-size: 15px; border: 1px solid #ccc; border-radius: 5px; background: white; flex: 1; min-width: 220px;
- }
- .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: 6px 0; }
- .warn { background: #fff3e0; color: #e65100; padding: 10px; border-radius: 5px; margin: 6px 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.part { background: #fff3e0; color: #e65100; border-left: 6px solid #fb8c00; }
- .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; }
- 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.mx { margin: 0; padding-left: 18px; }
- ul.mx 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 { margin-top: 16px; }
- details pre {
- background: #263238; color: #cfd8dc; padding: 12px 14px; border-radius: 5px;
- font-size: 12px; overflow-x: auto; line-height: 1.5; white-space: pre-wrap; word-break: break-all;
- }
- summary { cursor: pointer; font-weight: 600; color: #1976D2; }
- a.url { color: #1976D2; word-break: break-all; }
- </style>
- </head>
- <body>
- <h1>📮 MTA-STS Checker</h1>
- <div class="info">
- Checks whether a domain supports <strong>MTA-STS</strong> (SMTP MTA Strict Transport Security,
- <a href="https://www.rfc-editor.org/rfc/rfc8461" target="_blank" rel="noopener">RFC 8461</a>).
- It reads the <code>_mta-sts</code> DNS record, fetches the HTTPS policy at
- <code>mta-sts.<domain>/.well-known/mta-sts.txt</code>, and looks for a
- <strong>TLS-RPT</strong> reporting record. Nothing is sent — only public DNS and the policy file are read.
- </div>
- <form class="lookup" method="GET">
- <input type="text" name="domain" placeholder="example.com"
- value="<?= htmlspecialchars($domain) ?>" autofocus>
- <button type="submit" class="btn">🔍 Check MTA-STS</button>
- </form>
- <?php if ($inputError): ?>
- <div class="error"><?= htmlspecialchars($inputError) ?></div>
- <?php endif; ?>
- <?php if ($report !== null): ?>
- <?php if ($report['enforced']): ?>
- <div class="verdict ok">✅ MTA-STS is supported and set to <strong>enforce</strong> for <?= htmlspecialchars($report['domain']) ?>.</div>
- <?php elseif ($report['supported']): ?>
- <div class="verdict part">⚠️ MTA-STS is published (mode: <?= htmlspecialchars($report['policy']['mode'] ?? '?') ?>) but not enforcing.</div>
- <?php else: ?>
- <div class="verdict fail">❌ <?= htmlspecialchars($report['domain']) ?> does not have a working MTA-STS policy.</div>
- <?php endif; ?>
- <div class="checks">
- <?php
- $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['txt'] !== null, 'DNS TXT record',
- $report['txt'] !== null ? '_mta-sts record found (id=' . ($report['txt_id'] ?? '?') . ')' : 'No _mta-sts TXT record');
- $renderCheck($report['policy'] !== null, 'HTTPS policy',
- $report['policy'] !== null ? 'Fetched and parsed over HTTPS' : 'Policy missing or invalid');
- $mode = $report['policy']['mode'] ?? null;
- $renderCheck($mode === 'enforce', 'Enforcing',
- $mode === 'enforce' ? 'mode: enforce' : ('mode: ' . ($mode ?? '—')), false);
- $renderCheck($report['tlsrpt'] !== null, 'TLS-RPT reporting',
- $report['tlsrpt'] !== null ? 'Reporting record present' : 'No _smtp._tls record', false);
- ?>
- </div>
- <?php foreach ($report['errors'] as $e): ?>
- <div class="error">❌ <?= htmlspecialchars($e) ?></div>
- <?php endforeach; ?>
- <?php foreach ($report['warnings'] as $w): ?>
- <div class="warn">⚠️ <?= htmlspecialchars($w) ?></div>
- <?php endforeach; ?>
- <h2>DNS record</h2>
- <table>
- <tr><th>Host</th><td class="mono">_mta-sts.<?= htmlspecialchars($report['domain']) ?></td></tr>
- <tr><th>TXT</th><td class="mono"><?= $report['txt'] !== null ? htmlspecialchars($report['txt']) : '—' ?></td></tr>
- <tr><th>Policy id</th><td class="mono"><?= htmlspecialchars($report['txt_id'] ?? '—') ?></td></tr>
- </table>
- <h2>HTTPS policy</h2>
- <table>
- <tr><th>URL</th><td><a class="url" href="<?= htmlspecialchars($report['policy_url']) ?>" target="_blank" rel="noopener"><?= htmlspecialchars($report['policy_url']) ?></a></td></tr>
- <tr><th>HTTP status</th><td class="mono"><?= $report['http']['status'] !== null ? (int) $report['http']['status'] : '—' ?></td></tr>
- <tr><th>Content-Type</th><td class="mono"><?= htmlspecialchars($report['http']['content_type'] ?? '—') ?></td></tr>
- <?php if ($report['policy'] !== null): $p = $report['policy']; ?>
- <tr><th>Version</th><td class="mono"><?= htmlspecialchars($p['version'] ?? '—') ?></td></tr>
- <tr>
- <th>Mode</th>
- <td><?php
- $mp = ['enforce' => 'g', 'testing' => 'o', 'none' => 'r'][$p['mode']] ?? 'r';
- echo '<span class="pill ' . $mp . '">' . htmlspecialchars($p['mode'] ?? '—') . '</span>';
- ?></td>
- </tr>
- <tr>
- <th>MX patterns</th>
- <td>
- <?php if (!empty($p['mx'])): ?>
- <ul class="mx">
- <?php foreach ($p['mx'] as $mx): ?>
- <li><?= htmlspecialchars($mx) ?></li>
- <?php endforeach; ?>
- </ul>
- <?php else: ?>—<?php endif; ?>
- </td>
- </tr>
- <tr><th>max_age</th><td class="mono"><?= htmlspecialchars(fmtMaxAge($p['max_age'])) ?></td></tr>
- <?php endif; ?>
- </table>
- <h2>TLS-RPT</h2>
- <table>
- <tr><th>Host</th><td class="mono">_smtp._tls.<?= htmlspecialchars($report['domain']) ?></td></tr>
- <tr><th>TXT</th><td class="mono"><?= $report['tlsrpt'] !== null ? htmlspecialchars($report['tlsrpt']) : '—' ?></td></tr>
- </table>
- <?php if ($report['policy_raw'] !== null): ?>
- <details>
- <summary>Raw policy file</summary>
- <pre><?= htmlspecialchars($report['policy_raw']) ?></pre>
- </details>
- <?php endif; ?>
- <?php endif; ?>
- </body>
- </html>
|