bimi-check.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Looks up a BIMI record (default._bimi.domain), parses its tags, fetches and
  5. * validates the referenced SVG logo, and checks that DMARC is at enforcement —
  6. * the precondition mailbox providers require before they will show a BIMI logo.
  7. */
  8. class BimiChecker
  9. {
  10. /** Hard cap on how much of the logo/certificate we download. */
  11. private const MAX_FETCH_BYTES = 256 * 1024;
  12. /** BIMI logos must be SVG Tiny Portable/Secure and stay under this size. */
  13. private const MAX_SVG_BYTES = 32 * 1024;
  14. public function check(string $domain, string $selector): array
  15. {
  16. $fqdn = $selector . '._bimi.' . $domain;
  17. $report = [
  18. 'domain' => $domain,
  19. 'selector' => $selector,
  20. 'fqdn' => $fqdn,
  21. 'record' => null,
  22. 'tags' => [],
  23. 'logo' => null,
  24. 'dmarc' => self::checkDmarc($domain),
  25. 'errors' => [],
  26. 'warnings' => [],
  27. 'valid' => false,
  28. ];
  29. $record = self::getTxtRecord($fqdn);
  30. if ($record === null) {
  31. $report['errors'][] = 'No BIMI TXT record found at ' . $fqdn . '.';
  32. return $report;
  33. }
  34. $report['record'] = $record;
  35. $tags = self::parseTags($record);
  36. $report['tags'] = $tags;
  37. $version = strtoupper($tags['v'] ?? '');
  38. if ($version === '') {
  39. $report['errors'][] = 'Missing v= tag — a BIMI record must start with v=BIMI1.';
  40. } elseif ($version !== 'BIMI1') {
  41. $report['errors'][] = 'Unexpected v= tag: "' . ($tags['v'] ?? '') . '" (expected "BIMI1").';
  42. }
  43. $logoUrl = trim($tags['l'] ?? '');
  44. if ($logoUrl === '') {
  45. // An empty l= is a valid "opt out / decline" signal, but usually a mistake.
  46. $report['warnings'][] = 'l= tag is empty — this domain declines to publish a logo.';
  47. } elseif (!self::isHttpsUrl($logoUrl)) {
  48. $report['errors'][] = 'l= must be an https:// URL. Got: ' . $logoUrl;
  49. } else {
  50. $report['logo'] = self::inspectLogo($logoUrl);
  51. foreach ($report['logo']['errors'] as $e) {
  52. $report['errors'][] = $e;
  53. }
  54. foreach ($report['logo']['warnings'] as $w) {
  55. $report['warnings'][] = $w;
  56. }
  57. }
  58. $authUrl = trim($tags['a'] ?? '');
  59. if ($authUrl === '') {
  60. $report['warnings'][] = 'No a= tag — Gmail and Apple Mail require a Verified Mark Certificate (VMC/CMC) to show the logo.';
  61. } elseif (!self::isHttpsUrl($authUrl)) {
  62. $report['errors'][] = 'a= must be an https:// URL pointing to a PEM certificate. Got: ' . $authUrl;
  63. }
  64. // BIMI only renders when DMARC is enforced. Fold that into the verdict.
  65. $dmarc = $report['dmarc'];
  66. if (!$dmarc['found']) {
  67. $report['errors'][] = 'No DMARC record found — BIMI requires an enforced DMARC policy.';
  68. } elseif (!$dmarc['enforced']) {
  69. $report['errors'][] = 'DMARC policy is p=' . ($dmarc['policy'] ?? 'none')
  70. . ' — BIMI requires p=quarantine or p=reject.';
  71. } elseif ($dmarc['pct'] !== null && $dmarc['pct'] < 100) {
  72. $report['warnings'][] = 'DMARC pct=' . $dmarc['pct'] . ' — BIMI needs pct=100 (or no pct tag) to apply to all mail.';
  73. }
  74. $report['valid'] = empty($report['errors']);
  75. return $report;
  76. }
  77. /** @return array<string,string> */
  78. private static function parseTags(string $record): array
  79. {
  80. $tags = [];
  81. foreach (explode(';', $record) as $part) {
  82. $part = trim($part);
  83. if ($part === '' || !str_contains($part, '=')) {
  84. continue;
  85. }
  86. [$key, $value] = explode('=', $part, 2);
  87. $tags[strtolower(trim($key))] = trim($value);
  88. }
  89. return $tags;
  90. }
  91. /** Downloads the SVG logo and checks the SVG Tiny PS constraints BIMI imposes. */
  92. private static function inspectLogo(string $url): array
  93. {
  94. $logo = [
  95. 'url' => $url,
  96. 'bytes' => null,
  97. 'mime' => null,
  98. 'title' => null,
  99. 'errors' => [],
  100. 'warnings' => [],
  101. ];
  102. $fetch = self::fetch($url);
  103. if ($fetch['error'] !== null) {
  104. $logo['errors'][] = 'Could not fetch logo (' . $url . '): ' . $fetch['error'];
  105. return $logo;
  106. }
  107. $body = $fetch['body'];
  108. $logo['bytes'] = strlen($body);
  109. $logo['mime'] = $fetch['mime'];
  110. if ($logo['bytes'] > self::MAX_SVG_BYTES) {
  111. $logo['errors'][] = sprintf(
  112. 'Logo is %.1f KB — BIMI requires the SVG to be under 32 KB.',
  113. $logo['bytes'] / 1024
  114. );
  115. }
  116. if (!str_contains($body, '<svg')) {
  117. $logo['errors'][] = 'Logo does not look like an SVG file (no <svg> element found).';
  118. return $logo;
  119. }
  120. // Pull the root <svg> attributes to check the required Tiny PS profile.
  121. if (preg_match('/<svg\b[^>]*>/is', $body, $m)) {
  122. $svgTag = $m[0];
  123. if (!preg_match('/baseProfile\s*=\s*["\']tiny-ps["\']/i', $svgTag)) {
  124. $logo['errors'][] = 'SVG is missing baseProfile="tiny-ps" — BIMI requires the SVG Tiny Portable/Secure profile.';
  125. }
  126. if (!preg_match('/version\s*=\s*["\']1\.2["\']/i', $svgTag)) {
  127. $logo['warnings'][] = 'SVG root should declare version="1.2" for the Tiny profile.';
  128. }
  129. if (preg_match('/\b(x|y|width|height)\s*=/i', $svgTag)) {
  130. $logo['warnings'][] = 'SVG root should not have x/y/width/height — use a square viewBox instead.';
  131. }
  132. if (!preg_match('/viewBox\s*=\s*["\']\s*0\s+0\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)\s*["\']/i', $svgTag, $vb)) {
  133. $logo['warnings'][] = 'SVG should have a square viewBox starting at "0 0".';
  134. } elseif (abs((float) $vb[1] - (float) $vb[2]) > 0.01) {
  135. $logo['warnings'][] = 'viewBox is not square (' . $vb[1] . '×' . $vb[2] . ') — BIMI logos must be square.';
  136. }
  137. }
  138. // Forbidden constructs in the Tiny PS profile.
  139. if (preg_match('/<script\b/i', $body)) {
  140. $logo['errors'][] = 'SVG contains a <script> element — scripts are forbidden in BIMI logos.';
  141. }
  142. if (preg_match('/<(a|image|use|foreignObject)\b/i', $body, $m)) {
  143. $logo['errors'][] = 'SVG contains a <' . strtolower($m[1]) . '> element, which is not allowed in the Tiny PS profile.';
  144. }
  145. if (preg_match('/xlink:href|(?<![a-z])href\s*=/i', $body)) {
  146. $logo['warnings'][] = 'SVG references external content (href) — external references are not permitted.';
  147. }
  148. if (preg_match('/<(animate|animateTransform|animateMotion|set)\b/i', $body)) {
  149. $logo['warnings'][] = 'SVG contains animation elements — animation is not allowed.';
  150. }
  151. if (preg_match('/<title>(.*?)<\/title>/is', $body, $m)) {
  152. $logo['title'] = trim(html_entity_decode(strip_tags($m[1])));
  153. } else {
  154. $logo['warnings'][] = 'SVG has no <title> element — recommended so the logo has an accessible name.';
  155. }
  156. return $logo;
  157. }
  158. /** Reads the domain's DMARC record and decides whether it is at enforcement. */
  159. private static function checkDmarc(string $domain): array
  160. {
  161. $record = self::getTxtRecord('_dmarc.' . $domain);
  162. $out = ['found' => false, 'record' => null, 'policy' => null, 'pct' => null, 'enforced' => false];
  163. if ($record === null || stripos($record, 'v=DMARC1') === false) {
  164. return $out;
  165. }
  166. $out['found'] = true;
  167. $out['record'] = $record;
  168. $tags = self::parseTags($record);
  169. $out['policy'] = strtolower($tags['p'] ?? 'none');
  170. if (isset($tags['pct']) && is_numeric($tags['pct'])) {
  171. $out['pct'] = (int) $tags['pct'];
  172. }
  173. $out['enforced'] = in_array($out['policy'], ['quarantine', 'reject'], true);
  174. return $out;
  175. }
  176. private static function isHttpsUrl(string $url): bool
  177. {
  178. return (bool) preg_match('#^https://[^\s/]+#i', $url);
  179. }
  180. private static function fetch(string $url): array
  181. {
  182. $ctx = stream_context_create([
  183. 'http' => [
  184. 'method' => 'GET',
  185. 'timeout' => 8,
  186. 'user_agent' => 'medowar-bimi-check/1.0',
  187. 'max_redirects' => 3,
  188. 'ignore_errors' => true,
  189. ],
  190. 'ssl' => [
  191. 'verify_peer' => true,
  192. 'verify_peer_name' => true,
  193. ],
  194. ]);
  195. $stream = @fopen($url, 'rb', false, $ctx);
  196. if ($stream === false) {
  197. return ['body' => '', 'mime' => null, 'error' => 'connection failed or TLS error'];
  198. }
  199. $meta = stream_get_meta_data($stream);
  200. $status = self::statusFromHeaders($meta['wrapper_data'] ?? []);
  201. $mime = self::headerValue($meta['wrapper_data'] ?? [], 'content-type');
  202. $body = @stream_get_contents($stream, self::MAX_FETCH_BYTES);
  203. fclose($stream);
  204. if ($status !== null && $status >= 400) {
  205. return ['body' => '', 'mime' => $mime, 'error' => 'HTTP ' . $status];
  206. }
  207. if ($body === false || $body === '') {
  208. return ['body' => '', 'mime' => $mime, 'error' => 'empty response'];
  209. }
  210. return ['body' => $body, 'mime' => $mime, 'error' => null];
  211. }
  212. /** @param array<int,string> $headers */
  213. private static function statusFromHeaders(array $headers): ?int
  214. {
  215. foreach ($headers as $h) {
  216. if (preg_match('#^HTTP/\S+\s+(\d{3})#', $h, $m)) {
  217. $status = (int) $m[1];
  218. }
  219. }
  220. return $status ?? null;
  221. }
  222. /** @param array<int,string> $headers */
  223. private static function headerValue(array $headers, string $name): ?string
  224. {
  225. foreach ($headers as $h) {
  226. if (stripos($h, $name . ':') === 0) {
  227. return trim(substr($h, strlen($name) + 1));
  228. }
  229. }
  230. return null;
  231. }
  232. private static function getTxtRecord(string $fqdn): ?string
  233. {
  234. foreach ((@dns_get_record($fqdn, DNS_TXT) ?: []) as $r) {
  235. $txt = $r['txt'] ?? (isset($r['entries']) ? implode('', $r['entries']) : '');
  236. if ($txt !== '') {
  237. return $txt;
  238. }
  239. }
  240. return null;
  241. }
  242. }
  243. $domain = trim((string) ($_GET['domain'] ?? ''));
  244. $selector = trim((string) ($_GET['selector'] ?? ''));
  245. $report = null;
  246. $inputError = null;
  247. if ($selector === '') {
  248. $selector = 'default';
  249. }
  250. if ($domain !== '') {
  251. // Accept a bare hostname; strip scheme/path if a URL was pasted.
  252. $domain = preg_replace('#^\w+://#', '', $domain);
  253. $domain = explode('/', $domain)[0];
  254. $domain = strtolower(trim($domain));
  255. if (!preg_match('/^(?=.{1,253}$)([a-z0-9](-?[a-z0-9])*\.)+[a-z]{2,}$/', $domain)) {
  256. $inputError = 'Please enter a valid domain name (e.g. example.com).';
  257. } elseif (!preg_match('/^[a-zA-Z0-9]([a-zA-Z0-9._-]{0,127})?$/', $selector)) {
  258. $inputError = 'Please enter a valid selector (letters, digits, dot, dash, underscore).';
  259. } else {
  260. $report = (new BimiChecker())->check($domain, $selector);
  261. }
  262. }
  263. $h = 'htmlspecialchars';
  264. ?>
  265. <!DOCTYPE html>
  266. <html lang="en">
  267. <head>
  268. <meta charset="UTF-8">
  269. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  270. <title>BIMI Record Checker</title>
  271. <style>
  272. body {
  273. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  274. max-width: 1000px;
  275. margin: 40px auto;
  276. padding: 0 20px;
  277. background: #f5f5f5;
  278. color: #333;
  279. }
  280. h1 { color: #333; }
  281. .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
  282. form.lookup { margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; }
  283. input[type=text] {
  284. flex: 1; min-width: 180px; padding: 10px; font-size: 15px;
  285. border: 1px solid #ccc; border-radius: 5px;
  286. }
  287. input[name=selector] { flex: 0 0 200px; min-width: 140px; }
  288. .btn {
  289. display: inline-block; padding: 10px 20px; background: #2196F3; color: white;
  290. text-decoration: none; border-radius: 5px; border: none; cursor: pointer; font-size: 15px;
  291. }
  292. .btn:hover { background: #1976D2; }
  293. .error { background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin: 10px 0; }
  294. .warning {
  295. background: #fff8e1; color: #e65100; padding: 10px; border-radius: 5px;
  296. margin: 10px 0; border-left: 5px solid #ff9800;
  297. }
  298. .verdict {
  299. display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-radius: 6px;
  300. font-size: 17px; font-weight: 600; margin: 20px 0 10px;
  301. }
  302. .verdict.ok { background: #e8f5e9; color: #2e7d32; border-left: 6px solid #43a047; }
  303. .verdict.fail { background: #ffebee; color: #c62828; border-left: 6px solid #e53935; }
  304. .record {
  305. background: #263238; color: #aed581; padding: 8px 12px; border-radius: 4px;
  306. font-family: monospace; font-size: 13px; word-break: break-all; margin: 10px 0;
  307. }
  308. .logo-preview {
  309. display: flex; align-items: center; gap: 16px; background: white; padding: 14px;
  310. border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin: 12px 0;
  311. }
  312. .logo-preview img {
  313. width: 64px; height: 64px; border-radius: 50%; border: 1px solid #eee;
  314. background: #fafafa; object-fit: contain;
  315. }
  316. .logo-preview .meta { font-size: 13px; color: #555; }
  317. table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 10px; }
  318. th, td { padding: 8px 12px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; }
  319. th { background: #fafafa; color: #555; font-weight: 600; }
  320. td.mono, .mono { font-family: monospace; word-break: break-all; }
  321. h2 { color: #333; margin-top: 30px; }
  322. .empty { text-align: center; color: #999; padding: 40px; }
  323. </style>
  324. </head>
  325. <body>
  326. <h1>🎨 BIMI Record Checker</h1>
  327. <div class="info">
  328. Looks up the <strong>BIMI</strong> TXT record for a domain
  329. (<code>selector._bimi.domain</code>, default selector <code>default</code>),
  330. parses its tags, fetches the SVG logo to validate the SVG&nbsp;Tiny&nbsp;PS profile,
  331. and confirms <strong>DMARC</strong> is enforced — the precondition for a logo to display.
  332. </div>
  333. <form class="lookup" method="GET">
  334. <input type="text" name="domain" placeholder="example.com" value="<?= $h($domain) ?>" autofocus>
  335. <input type="text" name="selector" placeholder="selector (default)" value="<?= $h($report ? $report['selector'] : ($_GET['selector'] ?? '')) ?>">
  336. <button type="submit" class="btn">🔍 Check BIMI</button>
  337. </form>
  338. <?php if ($inputError): ?>
  339. <div class="error"><?= $h($inputError) ?></div>
  340. <?php endif; ?>
  341. <?php if ($report !== null): ?>
  342. <?php if ($report['valid']): ?>
  343. <div class="verdict ok">✅ <?= $h($report['fqdn']) ?> — valid, displayable BIMI record.</div>
  344. <?php else: ?>
  345. <div class="verdict fail">❌ <?= $h($report['fqdn']) ?> — BIMI record is missing or will not display.</div>
  346. <?php endif; ?>
  347. <?php foreach ($report['errors'] as $e): ?>
  348. <div class="error">❌ <?= $h($e) ?></div>
  349. <?php endforeach; ?>
  350. <?php foreach ($report['warnings'] as $w): ?>
  351. <div class="warning">⚠️ <?= $h($w) ?></div>
  352. <?php endforeach; ?>
  353. <?php if ($report['record'] !== null): ?>
  354. <h2>BIMI record</h2>
  355. <div class="record"><?= $h($report['record']) ?></div>
  356. <?php if ($report['logo'] !== null && $report['logo']['bytes'] !== null): ?>
  357. <div class="logo-preview">
  358. <img src="<?= $h($report['logo']['url']) ?>" alt="BIMI logo" loading="lazy">
  359. <div class="meta">
  360. <strong><?= $h($report['logo']['title'] ?? 'Logo') ?></strong><br>
  361. <?= number_format($report['logo']['bytes'] / 1024, 1) ?> KB
  362. <?= $report['logo']['mime'] ? '· ' . $h($report['logo']['mime']) : '' ?><br>
  363. <span class="mono"><?= $h($report['logo']['url']) ?></span>
  364. </div>
  365. </div>
  366. <?php endif; ?>
  367. <table>
  368. <thead><tr><th>Tag</th><th>Meaning</th><th>Value</th></tr></thead>
  369. <tbody>
  370. <?php
  371. $meanings = ['v' => 'Version', 'l' => 'Logo URL (SVG)', 'a' => 'Authority (VMC/CMC)'];
  372. foreach ($report['tags'] as $tag => $value):
  373. ?>
  374. <tr>
  375. <td class="mono"><?= $h($tag) ?></td>
  376. <td><?= $h($meanings[$tag] ?? '—') ?></td>
  377. <td class="mono"><?= $value === '' ? '<em>(empty)</em>' : $h($value) ?></td>
  378. </tr>
  379. <?php endforeach; ?>
  380. </tbody>
  381. </table>
  382. <?php endif; ?>
  383. <h2>DMARC prerequisite</h2>
  384. <?php if ($report['dmarc']['found']): ?>
  385. <div class="record"><?= $h($report['dmarc']['record']) ?></div>
  386. <p style="font-size:14px;color:#555;">
  387. Policy <strong>p=<?= $h($report['dmarc']['policy'] ?? 'none') ?></strong><?php
  388. if ($report['dmarc']['pct'] !== null) echo ', pct=' . (int) $report['dmarc']['pct'];
  389. ?> —
  390. <?= $report['dmarc']['enforced'] ? 'meets the BIMI enforcement requirement.' : 'not enforced; BIMI will not display.' ?>
  391. </p>
  392. <?php else: ?>
  393. <div class="empty">No DMARC record found at _dmarc.<?= $h($report['domain']) ?>.</div>
  394. <?php endif; ?>
  395. <?php endif; ?>
  396. </body>
  397. </html>