dkim-check.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. declare(strict_types=1);
  3. /** Selectors tried when the user leaves the selector field blank. */
  4. const COMMON_SELECTORS = [
  5. 'default', 'selector1', 'selector2', 'google', 'k1', 'k2', 's1', 's2',
  6. 'dkim', 'mail', 'smtp', 'mx', 'pm', 'zoho', 'mandrill', 'sendgrid',
  7. 'amazonses', 'mailjet', 'mailgun',
  8. ];
  9. /**
  10. * Looks up a DKIM selector TXT record, parses its tags and validates the
  11. * public key (RSA or Ed25519).
  12. */
  13. class DkimChecker
  14. {
  15. public function check(string $domain, string $selector): array
  16. {
  17. $fqdn = $selector . '._domainkey.' . $domain;
  18. $report = [
  19. 'fqdn' => $fqdn,
  20. 'selector' => $selector,
  21. 'record' => null,
  22. 'tags' => [],
  23. 'key' => null,
  24. 'errors' => [],
  25. 'warnings' => [],
  26. 'valid' => false,
  27. ];
  28. $record = self::getTxtRecord($fqdn);
  29. if ($record === null) {
  30. $report['errors'][] = 'No TXT record found at ' . $fqdn;
  31. return $report;
  32. }
  33. $report['record'] = $record;
  34. $tags = self::parseTags($record);
  35. $report['tags'] = $tags;
  36. $version = $tags['v'] ?? null;
  37. if ($version !== null && strtoupper($version) !== 'DKIM1') {
  38. $report['errors'][] = 'Unexpected v= tag: "' . $version . '" (expected "DKIM1").';
  39. }
  40. $keyType = strtolower($tags['k'] ?? 'rsa');
  41. if (!in_array($keyType, ['rsa', 'ed25519'], true)) {
  42. $report['warnings'][] = 'Unknown key type k=' . $keyType . ' — treating as opaque.';
  43. }
  44. if (!isset($tags['p'])) {
  45. $report['errors'][] = 'Missing p= tag — record is not a valid DKIM key record.';
  46. } elseif ($tags['p'] === '') {
  47. $report['errors'][] = 'Empty p= tag — this key has been revoked.';
  48. } else {
  49. $report['key'] = self::analyzeKey($tags['p'], $keyType);
  50. if (!$report['key']['valid']) {
  51. $report['errors'][] = 'Public key could not be parsed: ' . $report['key']['error'];
  52. } elseif ($keyType === 'rsa' && $report['key']['bits'] !== null && $report['key']['bits'] < 1024) {
  53. $report['warnings'][] = 'RSA key is only ' . $report['key']['bits'] . ' bits — below the recommended 1024-bit minimum.';
  54. } elseif ($keyType === 'rsa' && $report['key']['bits'] !== null && $report['key']['bits'] < 2048) {
  55. $report['warnings'][] = 'RSA key is ' . $report['key']['bits'] . ' bits — 2048 bits is recommended for new keys.';
  56. }
  57. }
  58. if (($tags['t'] ?? '') !== '' && str_contains($tags['t'], 'y')) {
  59. $report['warnings'][] = 'Testing mode is on (t=y) — receivers may not enforce this key\'s signatures.';
  60. }
  61. if (isset($tags['h'])) {
  62. $algos = array_map('trim', explode(':', $tags['h']));
  63. if (!array_intersect($algos, ['sha256'])) {
  64. $report['warnings'][] = 'h= tag does not list sha256 — allowed hash algorithms: ' . $tags['h'];
  65. }
  66. }
  67. $report['valid'] = empty($report['errors']);
  68. return $report;
  69. }
  70. /** @return array<string,string> */
  71. private static function parseTags(string $record): array
  72. {
  73. $tags = [];
  74. foreach (explode(';', $record) as $part) {
  75. $part = trim($part);
  76. if ($part === '' || !str_contains($part, '=')) {
  77. continue;
  78. }
  79. [$key, $value] = explode('=', $part, 2);
  80. $tags[strtolower(trim($key))] = trim($value);
  81. }
  82. return $tags;
  83. }
  84. private static function analyzeKey(string $p, string $keyType): array
  85. {
  86. $clean = preg_replace('/\s+/', '', $p) ?? '';
  87. $der = base64_decode($clean, true);
  88. if ($der === false) {
  89. return ['valid' => false, 'error' => 'p= is not valid base64.', 'bits' => null, 'type' => $keyType];
  90. }
  91. if ($keyType === 'ed25519') {
  92. if (strlen($der) !== 32) {
  93. return [
  94. 'valid' => false,
  95. 'error' => sprintf('Ed25519 keys must be 32 raw bytes, got %d.', strlen($der)),
  96. 'bits' => null,
  97. 'type' => $keyType,
  98. ];
  99. }
  100. return ['valid' => true, 'error' => null, 'bits' => 256, 'type' => $keyType];
  101. }
  102. // RSA (or unknown, treated as RSA-encoded SubjectPublicKeyInfo).
  103. $pem = "-----BEGIN PUBLIC KEY-----\n" . chunk_split(base64_encode($der), 64, "\n") . "-----END PUBLIC KEY-----\n";
  104. $pubKey = @openssl_pkey_get_public($pem);
  105. if ($pubKey === false) {
  106. return ['valid' => false, 'error' => 'OpenSSL could not parse the public key.', 'bits' => null, 'type' => $keyType];
  107. }
  108. $details = openssl_pkey_get_details($pubKey);
  109. return [
  110. 'valid' => true,
  111. 'error' => null,
  112. 'bits' => $details['bits'] ?? null,
  113. 'type' => $keyType,
  114. ];
  115. }
  116. private static function getTxtRecord(string $fqdn): ?string
  117. {
  118. foreach ((@dns_get_record($fqdn, DNS_TXT) ?: []) as $r) {
  119. $txt = $r['txt'] ?? (isset($r['entries']) ? implode('', $r['entries']) : '');
  120. if ($txt !== '') {
  121. return $txt;
  122. }
  123. }
  124. return null;
  125. }
  126. }
  127. $domain = trim((string) ($_GET['domain'] ?? ''));
  128. $selector = trim((string) ($_GET['selector'] ?? ''));
  129. $report = null;
  130. $scanResults = [];
  131. $inputError = null;
  132. if ($domain !== '') {
  133. // Accept a bare hostname; strip scheme/path if a URL was pasted.
  134. $domain = preg_replace('#^\w+://#', '', $domain);
  135. $domain = explode('/', $domain)[0];
  136. $domain = strtolower(trim($domain));
  137. if (!preg_match('/^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/', $domain)) {
  138. $inputError = 'Please enter a valid domain name (e.g. example.com).';
  139. } elseif ($selector !== '' && !preg_match('/^[a-zA-Z0-9]([a-zA-Z0-9._-]{0,127})?$/', $selector)) {
  140. $inputError = 'Please enter a valid selector (letters, digits, dot, dash, underscore).';
  141. } else {
  142. $checker = new DkimChecker();
  143. if ($selector !== '') {
  144. $report = $checker->check($domain, $selector);
  145. } else {
  146. foreach (COMMON_SELECTORS as $candidate) {
  147. $result = $checker->check($domain, $candidate);
  148. if ($result['record'] !== null) {
  149. $scanResults[] = $result;
  150. }
  151. }
  152. }
  153. }
  154. }
  155. /** Renders a single DKIM report (verdict, checks, tag table). */
  156. function renderReport(array $report): void
  157. {
  158. $h = 'htmlspecialchars';
  159. $key = $report['key'];
  160. ?>
  161. <?php if ($report['valid']): ?>
  162. <div class="verdict ok">✅ <?= $h($report['fqdn']) ?> — valid DKIM key record.</div>
  163. <?php else: ?>
  164. <div class="verdict fail">❌ <?= $h($report['fqdn']) ?> — invalid or unusable DKIM record.</div>
  165. <?php endif; ?>
  166. <?php foreach ($report['errors'] as $e): ?>
  167. <div class="error">⚠️ <?= $h($e) ?></div>
  168. <?php endforeach; ?>
  169. <?php foreach ($report['warnings'] as $w): ?>
  170. <div class="warning">⚠️ <?= $h($w) ?></div>
  171. <?php endforeach; ?>
  172. <?php if ($report['record'] !== null): ?>
  173. <div class="record"><?= $h($report['record']) ?></div>
  174. <div class="checks">
  175. <?php
  176. $renderCheck = function (bool $pass, string $label, string $detail, bool $criticalIfFail = true) use ($h) {
  177. $cls = $pass ? 'pass' : ($criticalIfFail ? 'crit' : 'warn');
  178. $ic = $pass ? '✔️' : ($criticalIfFail ? '❌' : '⚠️');
  179. printf(
  180. '<div class="check %s"><span class="ic">%s</span><div><strong>%s</strong><br>%s</div></div>',
  181. $cls, $ic, $h($label), $h($detail)
  182. );
  183. };
  184. $renderCheck(($report['tags']['p'] ?? '') !== '', 'Public key present', ($report['tags']['p'] ?? '') !== '' ? 'p= tag is populated' : 'Key missing or revoked');
  185. if ($key) {
  186. $renderCheck($key['valid'], 'Key parses', $key['valid'] ? strtoupper($key['type']) . ($key['bits'] ? ', ' . $key['bits'] . ' bits' : '') : ($key['error'] ?? 'Parse error'));
  187. }
  188. $renderCheck(!str_contains($report['tags']['t'] ?? '', 'y'), 'Not in testing mode', str_contains($report['tags']['t'] ?? '', 'y') ? 't=y is set' : 'No testing flag', false);
  189. ?>
  190. </div>
  191. <table>
  192. <thead><tr><th>Tag</th><th>Meaning</th><th>Value</th></tr></thead>
  193. <tbody>
  194. <?php
  195. $meanings = [
  196. 'v' => 'Version', 'k' => 'Key type', 'p' => 'Public key (base64)',
  197. 'h' => 'Hash algorithms', 't' => 'Flags', 's' => 'Service type',
  198. 'n' => 'Notes', 'g' => 'Granularity',
  199. ];
  200. foreach ($report['tags'] as $tag => $value):
  201. ?>
  202. <tr>
  203. <td class="mono"><?= $h($tag) ?></td>
  204. <td><?= $h($meanings[$tag] ?? '—') ?></td>
  205. <td class="mono" style="word-break: break-all;">
  206. <?= $tag === 'p' ? $h(substr($value, 0, 60) . (strlen($value) > 60 ? '…' : '')) : $h($value) ?>
  207. </td>
  208. </tr>
  209. <?php endforeach; ?>
  210. </tbody>
  211. </table>
  212. <?php endif; ?>
  213. <?php
  214. }
  215. ?>
  216. <!DOCTYPE html>
  217. <html lang="en">
  218. <head>
  219. <meta charset="UTF-8">
  220. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  221. <title>DKIM Record Checker</title>
  222. <style>
  223. body {
  224. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  225. max-width: 1000px;
  226. margin: 40px auto;
  227. padding: 0 20px;
  228. background: #f5f5f5;
  229. color: #333;
  230. }
  231. h1 { color: #333; }
  232. .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
  233. form.lookup { margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; }
  234. input[type=text] {
  235. flex: 1; min-width: 180px; padding: 10px; font-size: 15px;
  236. border: 1px solid #ccc; border-radius: 5px;
  237. }
  238. input[name=selector] { flex: 0 0 200px; min-width: 140px; }
  239. .btn {
  240. display: inline-block; padding: 10px 20px; background: #2196F3; color: white;
  241. text-decoration: none; border-radius: 5px; border: none; cursor: pointer; font-size: 15px;
  242. }
  243. .btn:hover { background: #1976D2; }
  244. .error { background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin: 10px 0; }
  245. .warning {
  246. background: #fff8e1; color: #e65100; padding: 10px; border-radius: 5px;
  247. margin: 10px 0; border-left: 5px solid #ff9800;
  248. }
  249. .verdict {
  250. display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-radius: 6px;
  251. font-size: 17px; font-weight: 600; margin: 20px 0 10px;
  252. }
  253. .verdict.ok { background: #e8f5e9; color: #2e7d32; border-left: 6px solid #43a047; }
  254. .verdict.fail { background: #ffebee; color: #c62828; border-left: 6px solid #e53935; }
  255. .record {
  256. background: #263238; color: #aed581; padding: 8px 12px; border-radius: 4px;
  257. font-family: monospace; font-size: 13px; word-break: break-all; margin: 10px 0;
  258. }
  259. .checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; margin: 12px 0; }
  260. .check {
  261. display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-radius: 5px;
  262. background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); font-size: 14px;
  263. }
  264. .check .ic { font-size: 18px; }
  265. .check.pass { border-left: 4px solid #43a047; }
  266. .check.warn { border-left: 4px solid #fb8c00; }
  267. .check.crit { border-left: 4px solid #e53935; }
  268. table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 10px; }
  269. th, td { padding: 8px 12px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; }
  270. th { background: #fafafa; color: #555; font-weight: 600; }
  271. td.mono, .mono { font-family: monospace; }
  272. h2 { color: #333; margin-top: 30px; }
  273. details.scan { margin: 14px 0; }
  274. summary { cursor: pointer; font-weight: 600; color: #1976D2; }
  275. .empty { text-align: center; color: #999; padding: 40px; }
  276. </style>
  277. </head>
  278. <body>
  279. <h1>✉️ DKIM Record Checker</h1>
  280. <div class="info">
  281. Looks up the <strong>DKIM</strong> TXT record for a domain + selector
  282. (<code>selector._domainkey.domain</code>), parses its tags and validates the
  283. public key. Leave the selector blank to scan a list of common selectors.
  284. </div>
  285. <form class="lookup" method="GET">
  286. <input type="text" name="domain" placeholder="example.com" value="<?= htmlspecialchars($domain) ?>" autofocus>
  287. <input type="text" name="selector" placeholder="selector (optional)" value="<?= htmlspecialchars($selector) ?>">
  288. <button type="submit" class="btn">🔍 Check DKIM</button>
  289. </form>
  290. <?php if ($inputError): ?>
  291. <div class="error"><?= htmlspecialchars($inputError) ?></div>
  292. <?php endif; ?>
  293. <?php if ($report !== null): ?>
  294. <?php renderReport($report); ?>
  295. <?php elseif ($domain !== '' && $selector === '' && !$inputError): ?>
  296. <h2>Common selector scan</h2>
  297. <?php if (empty($scanResults)): ?>
  298. <div class="empty">No DKIM record found at any of the <?= count(COMMON_SELECTORS) ?> common selectors tried.<br>
  299. If you know the selector, enter it above for a direct lookup.</div>
  300. <?php else: ?>
  301. <?php foreach ($scanResults as $result): ?>
  302. <details class="scan" open>
  303. <summary><?= htmlspecialchars($result['selector']) ?></summary>
  304. <?php renderReport($result); ?>
  305. </details>
  306. <?php endforeach; ?>
  307. <?php endif; ?>
  308. <?php endif; ?>
  309. </body>
  310. </html>