mta-sts-check.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. <?php
  2. declare(strict_types=1);
  3. const POLICY_TIMEOUT = 12; // seconds for the HTTPS policy fetch
  4. const POLICY_MAX_BYTES = 65536; // RFC 8461: policies are small; cap the download
  5. /**
  6. * Checks whether a domain publishes an MTA-STS policy (RFC 8461) and evaluates
  7. * its consistency: the `_mta-sts` DNS TXT record, the HTTPS-hosted policy file
  8. * at `mta-sts.<domain>/.well-known/mta-sts.txt`, and the accompanying TLS-RPT
  9. * (`_smtp._tls`) reporting record.
  10. */
  11. class MtaStsChecker
  12. {
  13. /** @return array MTA-STS / TLS-RPT report for the given domain. */
  14. public function check(string $domain): array
  15. {
  16. $report = [
  17. 'domain' => $domain,
  18. 'supported' => false, // TXT + fetchable, parseable policy
  19. 'enforced' => false, // policy mode is "enforce"
  20. 'errors' => [],
  21. 'warnings' => [],
  22. 'txt' => null, // the _mta-sts TXT record contents
  23. 'txt_id' => null,
  24. 'policy_url'=> 'https://mta-sts.' . $domain . '/.well-known/mta-sts.txt',
  25. 'policy_raw'=> null, // raw fetched policy body
  26. 'policy' => null, // parsed: version, mode, mx[], max_age
  27. 'http' => null, // http status / content-type of the fetch
  28. 'tlsrpt' => null, // the _smtp._tls TXT record contents
  29. ];
  30. // 1) The MTA-STS DNS record lives at _mta-sts.<domain> and signals a policy.
  31. $this->checkTxtRecord($domain, $report);
  32. // 2) The policy itself is served over HTTPS from the mta-sts. subdomain.
  33. $this->fetchPolicy($report);
  34. // 3) TLS-RPT is optional but strongly recommended alongside MTA-STS.
  35. $this->checkTlsRpt($domain, $report);
  36. $mode = $report['policy']['mode'] ?? null;
  37. $report['supported'] = ($report['txt'] !== null && $report['policy'] !== null);
  38. $report['enforced'] = ($report['supported'] && $mode === 'enforce');
  39. return $report;
  40. }
  41. /** Looks up and validates the _mta-sts.<domain> TXT record. */
  42. private function checkTxtRecord(string $domain, array &$report): void
  43. {
  44. $host = '_mta-sts.' . $domain;
  45. $records = @dns_get_record($host, DNS_TXT) ?: [];
  46. $sts = [];
  47. foreach ($records as $rec) {
  48. $txt = $rec['txt'] ?? implode('', $rec['entries'] ?? []);
  49. if (stripos($txt, 'v=STSv1') !== false) {
  50. $sts[] = $txt;
  51. }
  52. }
  53. if (!$sts) {
  54. $report['errors'][] = 'No "v=STSv1" TXT record found at ' . $host . '.';
  55. return;
  56. }
  57. if (count($sts) > 1) {
  58. $report['warnings'][] = 'Multiple STS TXT records found at ' . $host
  59. . ' — RFC 8461 requires exactly one.';
  60. }
  61. $txt = $sts[0];
  62. $report['txt'] = $txt;
  63. // Parse the semicolon-separated key=value fields; "id" is mandatory.
  64. $fields = [];
  65. foreach (explode(';', $txt) as $pair) {
  66. if (str_contains($pair, '=')) {
  67. [$k, $v] = explode('=', $pair, 2);
  68. $fields[strtolower(trim($k))] = trim($v);
  69. }
  70. }
  71. if (($fields['v'] ?? '') !== 'STSv1') {
  72. $report['warnings'][] = 'TXT record does not start with "v=STSv1".';
  73. }
  74. if (empty($fields['id'])) {
  75. $report['errors'][] = 'TXT record is missing the required "id" field.';
  76. } elseif (!preg_match('/^[A-Za-z0-9]{1,32}$/', $fields['id'])) {
  77. $report['warnings'][] = 'The "id" value should be 1–32 alphanumeric characters.';
  78. }
  79. $report['txt_id'] = $fields['id'] ?? null;
  80. }
  81. /** Fetches the HTTPS policy file and parses its key/value directives. */
  82. private function fetchPolicy(array &$report): void
  83. {
  84. $url = $report['policy_url'];
  85. // RFC 8461: the policy MUST be served over HTTPS with a valid certificate,
  86. // and redirects MUST NOT be followed. We verify the chain explicitly.
  87. $ctx = stream_context_create([
  88. 'http' => [
  89. 'method' => 'GET',
  90. 'timeout' => POLICY_TIMEOUT,
  91. 'follow_location'=> 0,
  92. 'ignore_errors' => true, // so we still see 4xx/5xx bodies + headers
  93. 'header' => "User-Agent: mta-sts-check (tool.medowar.de)\r\n",
  94. ],
  95. 'ssl' => [
  96. 'verify_peer' => true,
  97. 'verify_peer_name' => true,
  98. 'SNI_enabled' => true,
  99. ],
  100. ]);
  101. $body = @file_get_contents($url, false, $ctx, 0, POLICY_MAX_BYTES);
  102. // $http_response_header is populated by the HTTP wrapper on any response.
  103. $status = null; $ctype = null;
  104. foreach ($http_response_header ?? [] as $h) {
  105. if (preg_match('#^HTTP/\S+\s+(\d{3})#', $h, $m)) {
  106. $status = (int) $m[1]; // last one wins (in case of intermediates)
  107. } elseif (stripos($h, 'Content-Type:') === 0) {
  108. $ctype = trim(substr($h, strlen('Content-Type:')));
  109. }
  110. }
  111. $report['http'] = ['status' => $status, 'content_type' => $ctype];
  112. if ($body === false) {
  113. $err = error_get_last()['message'] ?? '';
  114. $err = trim(preg_replace('/\s+/', ' ', preg_replace('#^file_get_contents\([^)]*\):\s*#', '', $err)));
  115. $report['errors'][] = 'Could not fetch the policy over HTTPS'
  116. . ($err !== '' ? ': ' . $err : '. The mta-sts host or its certificate may be misconfigured.');
  117. return;
  118. }
  119. if ($status !== null && $status !== 200) {
  120. $report['errors'][] = 'Policy fetch returned HTTP ' . $status . ' (expected 200).';
  121. return;
  122. }
  123. if ($ctype !== null && stripos($ctype, 'text/plain') === false) {
  124. $report['warnings'][] = 'Policy Content-Type is "' . $ctype . '"; RFC 8461 requires "text/plain".';
  125. }
  126. $report['policy_raw'] = $body;
  127. $this->parsePolicy($body, $report);
  128. }
  129. /** Parses the mta-sts.txt body into version/mode/mx[]/max_age and validates it. */
  130. private function parsePolicy(string $body, array &$report): void
  131. {
  132. $policy = ['version' => null, 'mode' => null, 'mx' => [], 'max_age' => null];
  133. foreach (preg_split('/\r\n|\r|\n/', $body) as $line) {
  134. $line = trim($line);
  135. if ($line === '' || !str_contains($line, ':')) {
  136. continue;
  137. }
  138. [$key, $val] = explode(':', $line, 2);
  139. $key = strtolower(trim($key));
  140. $val = trim($val);
  141. switch ($key) {
  142. case 'version': $policy['version'] = $val; break;
  143. case 'mode': $policy['mode'] = strtolower($val); break;
  144. case 'mx': if ($val !== '') { $policy['mx'][] = $val; } break;
  145. case 'max_age': $policy['max_age'] = (int) $val; break;
  146. }
  147. }
  148. if ($policy['version'] !== 'STSv1') {
  149. $report['errors'][] = 'Policy "version" is not "STSv1".';
  150. }
  151. if (!in_array($policy['mode'], ['enforce', 'testing', 'none'], true)) {
  152. $report['errors'][] = 'Policy "mode" is missing or invalid (expected enforce, testing or none).';
  153. }
  154. if ($policy['mode'] !== 'none' && empty($policy['mx'])) {
  155. $report['errors'][] = 'Policy declares no "mx" host patterns.';
  156. }
  157. if ($policy['max_age'] === null) {
  158. $report['errors'][] = 'Policy is missing the required "max_age" field.';
  159. } elseif ($policy['max_age'] < 86400) {
  160. $report['warnings'][] = 'A "max_age" below 86400 (1 day) is unusually short; long-lived caching is the point of MTA-STS.';
  161. } elseif ($policy['max_age'] > 31557600) {
  162. $report['warnings'][] = 'A "max_age" above 31557600 (1 year) exceeds the RFC 8461 recommended maximum.';
  163. }
  164. // Cross-check: the TXT id should change whenever the policy changes, but
  165. // a mode of "testing" means failures are reported, not enforced.
  166. if ($policy['mode'] === 'testing') {
  167. $report['warnings'][] = 'Policy mode is "testing" — TLS failures are reported but mail is still delivered.';
  168. }
  169. if ($policy['mode'] === 'none') {
  170. $report['warnings'][] = 'Policy mode is "none" — this actively signals that any previous MTA-STS policy is withdrawn.';
  171. }
  172. $report['policy'] = $policy;
  173. }
  174. /** Looks up the optional TLS-RPT (_smtp._tls.<domain>) reporting record. */
  175. private function checkTlsRpt(string $domain, array &$report): void
  176. {
  177. $host = '_smtp._tls.' . $domain;
  178. $records = @dns_get_record($host, DNS_TXT) ?: [];
  179. foreach ($records as $rec) {
  180. $txt = $rec['txt'] ?? implode('', $rec['entries'] ?? []);
  181. if (stripos($txt, 'v=TLSRPTv1') !== false) {
  182. $report['tlsrpt'] = $txt;
  183. return;
  184. }
  185. }
  186. $report['warnings'][] = 'No TLS-RPT (v=TLSRPTv1) record at ' . $host
  187. . ' — you would not receive reports about TLS delivery failures.';
  188. }
  189. }
  190. $domain = trim((string) ($_GET['domain'] ?? ''));
  191. $report = null;
  192. $inputError = null;
  193. if ($domain !== '') {
  194. // Accept a bare domain, an email address, or a pasted URL — reduce to the domain.
  195. $domain = preg_replace('#^\w+://#', '', $domain);
  196. $domain = explode('/', $domain)[0];
  197. if (str_contains($domain, '@')) {
  198. $domain = substr($domain, strrpos($domain, '@') + 1);
  199. }
  200. $domain = strtolower(trim($domain, ". \t"));
  201. if (str_contains($domain, ':')) {
  202. $domain = explode(':', $domain)[0];
  203. }
  204. if (!preg_match('/^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/', $domain)) {
  205. $inputError = 'Please enter a valid domain (e.g. example.com).';
  206. } else {
  207. $report = (new MtaStsChecker())->check($domain);
  208. }
  209. }
  210. function fmtMaxAge(?int $secs): string
  211. {
  212. if ($secs === null) { return '—'; }
  213. $days = $secs / 86400;
  214. if ($days >= 1) {
  215. return $secs . ' s (' . rtrim(rtrim(number_format($days, 1), '0'), '.') . ' days)';
  216. }
  217. return $secs . ' s';
  218. }
  219. ?>
  220. <!DOCTYPE html>
  221. <html lang="en">
  222. <head>
  223. <meta charset="UTF-8">
  224. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  225. <title>MTA-STS Checker</title>
  226. <style>
  227. body {
  228. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  229. max-width: 1000px;
  230. margin: 40px auto;
  231. padding: 0 20px;
  232. background: #f5f5f5;
  233. color: #333;
  234. }
  235. h1 { color: #333; }
  236. .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
  237. form.lookup { margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; align-items: stretch; }
  238. input[type=text] {
  239. padding: 10px; font-size: 15px; border: 1px solid #ccc; border-radius: 5px; background: white; flex: 1; min-width: 220px;
  240. }
  241. .btn {
  242. display: inline-block; padding: 10px 20px; background: #2196F3; color: white;
  243. text-decoration: none; border-radius: 5px; border: none; cursor: pointer; font-size: 15px;
  244. }
  245. .btn:hover { background: #1976D2; }
  246. .error { background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin: 6px 0; }
  247. .warn { background: #fff3e0; color: #e65100; padding: 10px; border-radius: 5px; margin: 6px 0; }
  248. .verdict {
  249. display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-radius: 6px;
  250. font-size: 18px; font-weight: 600; margin: 16px 0;
  251. }
  252. .verdict.ok { background: #e8f5e9; color: #2e7d32; border-left: 6px solid #43a047; }
  253. .verdict.part { background: #fff3e0; color: #e65100; border-left: 6px solid #fb8c00; }
  254. .verdict.fail { background: #ffebee; color: #c62828; border-left: 6px solid #e53935; }
  255. .checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; margin: 16px 0; }
  256. .check {
  257. display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-radius: 5px;
  258. background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); font-size: 14px;
  259. }
  260. .check .ic { font-size: 18px; }
  261. .check.pass { border-left: 4px solid #43a047; }
  262. .check.warn { border-left: 4px solid #fb8c00; }
  263. .check.crit { border-left: 4px solid #e53935; }
  264. h2 { color: #333; margin-top: 30px; }
  265. table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 10px; }
  266. th, td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; vertical-align: top; }
  267. th { width: 180px; color: #555; background: #fafafa; font-weight: 600; }
  268. td.mono, .mono { font-family: monospace; word-break: break-all; }
  269. ul.mx { margin: 0; padding-left: 18px; }
  270. ul.mx li { font-family: monospace; font-size: 13px; }
  271. .pill { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 12px; font-weight: 600; }
  272. .pill.g { background: #e8f5e9; color: #2e7d32; }
  273. .pill.r { background: #ffebee; color: #c62828; }
  274. .pill.o { background: #fff3e0; color: #e65100; }
  275. details { margin-top: 16px; }
  276. details pre {
  277. background: #263238; color: #cfd8dc; padding: 12px 14px; border-radius: 5px;
  278. font-size: 12px; overflow-x: auto; line-height: 1.5; white-space: pre-wrap; word-break: break-all;
  279. }
  280. summary { cursor: pointer; font-weight: 600; color: #1976D2; }
  281. a.url { color: #1976D2; word-break: break-all; }
  282. </style>
  283. </head>
  284. <body>
  285. <h1>📮 MTA-STS Checker</h1>
  286. <div class="info">
  287. Checks whether a domain supports <strong>MTA-STS</strong> (SMTP MTA Strict Transport Security,
  288. <a href="https://www.rfc-editor.org/rfc/rfc8461" target="_blank" rel="noopener">RFC&nbsp;8461</a>).
  289. It reads the <code>_mta-sts</code> DNS record, fetches the HTTPS policy at
  290. <code>mta-sts.&lt;domain&gt;/.well-known/mta-sts.txt</code>, and looks for a
  291. <strong>TLS-RPT</strong> reporting record. Nothing is sent — only public DNS and the policy file are read.
  292. </div>
  293. <form class="lookup" method="GET">
  294. <input type="text" name="domain" placeholder="example.com"
  295. value="<?= htmlspecialchars($domain) ?>" autofocus>
  296. <button type="submit" class="btn">🔍 Check MTA-STS</button>
  297. </form>
  298. <?php if ($inputError): ?>
  299. <div class="error"><?= htmlspecialchars($inputError) ?></div>
  300. <?php endif; ?>
  301. <?php if ($report !== null): ?>
  302. <?php if ($report['enforced']): ?>
  303. <div class="verdict ok">✅ MTA-STS is supported and set to <strong>enforce</strong> for <?= htmlspecialchars($report['domain']) ?>.</div>
  304. <?php elseif ($report['supported']): ?>
  305. <div class="verdict part">⚠️ MTA-STS is published (mode: <?= htmlspecialchars($report['policy']['mode'] ?? '?') ?>) but not enforcing.</div>
  306. <?php else: ?>
  307. <div class="verdict fail">❌ <?= htmlspecialchars($report['domain']) ?> does not have a working MTA-STS policy.</div>
  308. <?php endif; ?>
  309. <div class="checks">
  310. <?php
  311. $renderCheck = function (bool $pass, string $label, string $detail, bool $criticalIfFail = true) {
  312. $cls = $pass ? 'pass' : ($criticalIfFail ? 'crit' : 'warn');
  313. $ic = $pass ? '✔️' : ($criticalIfFail ? '❌' : '⚠️');
  314. printf(
  315. '<div class="check %s"><span class="ic">%s</span><div><strong>%s</strong><br>%s</div></div>',
  316. $cls, $ic, htmlspecialchars($label), htmlspecialchars($detail)
  317. );
  318. };
  319. $renderCheck($report['txt'] !== null, 'DNS TXT record',
  320. $report['txt'] !== null ? '_mta-sts record found (id=' . ($report['txt_id'] ?? '?') . ')' : 'No _mta-sts TXT record');
  321. $renderCheck($report['policy'] !== null, 'HTTPS policy',
  322. $report['policy'] !== null ? 'Fetched and parsed over HTTPS' : 'Policy missing or invalid');
  323. $mode = $report['policy']['mode'] ?? null;
  324. $renderCheck($mode === 'enforce', 'Enforcing',
  325. $mode === 'enforce' ? 'mode: enforce' : ('mode: ' . ($mode ?? '—')), false);
  326. $renderCheck($report['tlsrpt'] !== null, 'TLS-RPT reporting',
  327. $report['tlsrpt'] !== null ? 'Reporting record present' : 'No _smtp._tls record', false);
  328. ?>
  329. </div>
  330. <?php foreach ($report['errors'] as $e): ?>
  331. <div class="error">❌ <?= htmlspecialchars($e) ?></div>
  332. <?php endforeach; ?>
  333. <?php foreach ($report['warnings'] as $w): ?>
  334. <div class="warn">⚠️ <?= htmlspecialchars($w) ?></div>
  335. <?php endforeach; ?>
  336. <h2>DNS record</h2>
  337. <table>
  338. <tr><th>Host</th><td class="mono">_mta-sts.<?= htmlspecialchars($report['domain']) ?></td></tr>
  339. <tr><th>TXT</th><td class="mono"><?= $report['txt'] !== null ? htmlspecialchars($report['txt']) : '—' ?></td></tr>
  340. <tr><th>Policy id</th><td class="mono"><?= htmlspecialchars($report['txt_id'] ?? '—') ?></td></tr>
  341. </table>
  342. <h2>HTTPS policy</h2>
  343. <table>
  344. <tr><th>URL</th><td><a class="url" href="<?= htmlspecialchars($report['policy_url']) ?>" target="_blank" rel="noopener"><?= htmlspecialchars($report['policy_url']) ?></a></td></tr>
  345. <tr><th>HTTP status</th><td class="mono"><?= $report['http']['status'] !== null ? (int) $report['http']['status'] : '—' ?></td></tr>
  346. <tr><th>Content-Type</th><td class="mono"><?= htmlspecialchars($report['http']['content_type'] ?? '—') ?></td></tr>
  347. <?php if ($report['policy'] !== null): $p = $report['policy']; ?>
  348. <tr><th>Version</th><td class="mono"><?= htmlspecialchars($p['version'] ?? '—') ?></td></tr>
  349. <tr>
  350. <th>Mode</th>
  351. <td><?php
  352. $mp = ['enforce' => 'g', 'testing' => 'o', 'none' => 'r'][$p['mode']] ?? 'r';
  353. echo '<span class="pill ' . $mp . '">' . htmlspecialchars($p['mode'] ?? '—') . '</span>';
  354. ?></td>
  355. </tr>
  356. <tr>
  357. <th>MX patterns</th>
  358. <td>
  359. <?php if (!empty($p['mx'])): ?>
  360. <ul class="mx">
  361. <?php foreach ($p['mx'] as $mx): ?>
  362. <li><?= htmlspecialchars($mx) ?></li>
  363. <?php endforeach; ?>
  364. </ul>
  365. <?php else: ?>—<?php endif; ?>
  366. </td>
  367. </tr>
  368. <tr><th>max_age</th><td class="mono"><?= htmlspecialchars(fmtMaxAge($p['max_age'])) ?></td></tr>
  369. <?php endif; ?>
  370. </table>
  371. <h2>TLS-RPT</h2>
  372. <table>
  373. <tr><th>Host</th><td class="mono">_smtp._tls.<?= htmlspecialchars($report['domain']) ?></td></tr>
  374. <tr><th>TXT</th><td class="mono"><?= $report['tlsrpt'] !== null ? htmlspecialchars($report['tlsrpt']) : '—' ?></td></tr>
  375. </table>
  376. <?php if ($report['policy_raw'] !== null): ?>
  377. <details>
  378. <summary>Raw policy file</summary>
  379. <pre><?= htmlspecialchars($report['policy_raw']) ?></pre>
  380. </details>
  381. <?php endif; ?>
  382. <?php endif; ?>
  383. </body>
  384. </html>