send-test-mail.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. <?php
  2. declare(strict_types=1);
  3. // ─────────────────────────────────────────────────────────────────────────────
  4. // CONFIGURATION — set the access password here.
  5. // Every visitor must enter this before they can send a test mail.
  6. // Set it to '' (empty string) to disable the password gate entirely.
  7. // ─────────────────────────────────────────────────────────────────────────────
  8. const ACCESS_PASSWORD = 'asdf123!';
  9. const SENDER_ADDRESS = 'test@med0.de';
  10. const SENDER_NAME = 'med0.de Mail Test';
  11. const MIN_FORM_SECONDS = 3; // reject sends submitted faster than a human could type
  12. const HONEYPOT_FIELD = 'website'; // hidden decoy field; if filled, the sender is a bot
  13. const SMTP_TIMEOUT = 15; // seconds per SMTP step
  14. const EHLO_NAME = 'tool.medowar.de'; // name announced in EHLO
  15. /**
  16. * Builds the fixed test message. Returns the subject, body and an ordered map of
  17. * header name => value. The subject and body are predefined — only the recipient
  18. * and (optionally) the target server vary.
  19. *
  20. * Mail hygiene is kept deliberately lightweight but complete: a real From with
  21. * display name, matching Reply-To, a unique Message-ID, Date, correct MIME
  22. * headers, and Auto-Submitted so downstream systems know it is machine-generated
  23. * and should not auto-reply. The envelope sender is always SENDER_ADDRESS, which
  24. * is what SPF evaluates.
  25. *
  26. * @return array{subject:string, body:string, headers:array<string,string>}
  27. */
  28. function buildMessage(string $selfUrl): array
  29. {
  30. $now = new DateTimeImmutable('now', new DateTimeZone('UTC'));
  31. // Subject stays ASCII so it needs no MIME encoded-word wrapping.
  32. $subject = 'Test message from the med0.de mail tools';
  33. $body =
  34. "Hello,\r\n" .
  35. "\r\n" .
  36. "This is an automated TEST message sent by the med0.de mail-testing tools.\r\n" .
  37. "If you received it, delivery from " . SENDER_ADDRESS . " to your address is working.\r\n" .
  38. "You can safely ignore or delete this message — no action is required.\r\n" .
  39. "\r\n" .
  40. "Test page: " . $selfUrl . "\r\n" .
  41. "Sent (UTC): " . $now->format('Y-m-d H:i:s') . "\r\n" .
  42. "\r\n" .
  43. "— med0.de mail tools\r\n";
  44. // A unique, domain-scoped Message-ID aids threading and spam scoring.
  45. $messageId = sprintf('<%s.%s@med0.de>', $now->format('YmdHis'), bin2hex(random_bytes(8)));
  46. $headers = [
  47. 'From' => sprintf('%s <%s>', SENDER_NAME, SENDER_ADDRESS),
  48. 'Reply-To' => SENDER_ADDRESS,
  49. 'Message-ID' => $messageId,
  50. 'Date' => $now->format(DateTimeInterface::RFC2822),
  51. 'MIME-Version' => '1.0',
  52. 'Content-Type' => 'text/plain; charset=UTF-8',
  53. 'Content-Transfer-Encoding' => '8bit',
  54. 'Auto-Submitted' => 'auto-generated', // RFC 3834: do not auto-reply
  55. 'X-Mailer' => 'med0.de-test-tool',
  56. ];
  57. return ['subject' => $subject, 'body' => $body, 'headers' => $headers];
  58. }
  59. /**
  60. * Dispatches the test message. With $mailserver empty the message goes through
  61. * PHP's mail() (the local MTA does the usual MX routing). With $mailserver set it
  62. * is delivered by talking SMTP directly to that host — no local MTA involved.
  63. *
  64. * @param string[] $transcript filled with the SMTP conversation (direct mode only)
  65. */
  66. function sendTestMail(string $recipient, string $selfUrl, ?string $mailserver, ?string &$error, ?array &$transcript): bool
  67. {
  68. $error = null;
  69. $transcript = [];
  70. $msg = buildMessage($selfUrl);
  71. if ($mailserver === null || $mailserver === '') {
  72. // Normal path: hand off to the local MTA. The 5th parameter sets the
  73. // envelope sender (Return-Path) so SPF checks the med0.de domain.
  74. $headerLines = [];
  75. foreach ($msg['headers'] as $k => $v) {
  76. $headerLines[] = $k . ': ' . $v;
  77. }
  78. $ok = @mail($recipient, $msg['subject'], $msg['body'], implode("\r\n", $headerLines), '-f' . SENDER_ADDRESS);
  79. if (!$ok) {
  80. $error = 'The local mail server rejected or failed to accept the message. '
  81. . 'Check that this host is configured to send mail for med0.de.';
  82. return false;
  83. }
  84. return true;
  85. }
  86. // Direct path: parse host[:port] (default 25) and speak SMTP to that server.
  87. $host = $mailserver;
  88. $port = 25;
  89. if (preg_match('/^(.+):(\d+)$/', $mailserver, $m)) {
  90. $host = $m[1];
  91. $port = (int) $m[2];
  92. }
  93. // Assemble the full RFC 5322 message (To/Subject go inside DATA here).
  94. $lines = ['To: ' . $recipient, 'Subject: ' . $msg['subject']];
  95. foreach ($msg['headers'] as $k => $v) {
  96. $lines[] = $k . ': ' . $v;
  97. }
  98. $raw = implode("\r\n", $lines) . "\r\n\r\n" . $msg['body'];
  99. return smtpDeliver($host, $port, SENDER_ADDRESS, $recipient, $raw, $error, $transcript);
  100. }
  101. /**
  102. * Minimal SMTP client: connects, EHLOs, opportunistically upgrades with STARTTLS
  103. * when offered, then MAIL FROM / RCPT TO / DATA. No AUTH — this mirrors how an MTA
  104. * delivers straight to a recipient's mail exchanger on port 25.
  105. *
  106. * @param string[] $transcript
  107. */
  108. function smtpDeliver(string $host, int $port, string $from, string $to, string $rawMessage, ?string &$error, array &$transcript): bool
  109. {
  110. $errno = 0; $errstr = '';
  111. $stream = @stream_socket_client(
  112. sprintf('tcp://%s:%d', $host, $port), $errno, $errstr,
  113. SMTP_TIMEOUT, STREAM_CLIENT_CONNECT
  114. );
  115. if (!is_resource($stream)) {
  116. $error = $errstr !== '' ? "Connection to $host:$port failed: $errstr (errno $errno)" : 'Connection failed.';
  117. return false;
  118. }
  119. stream_set_timeout($stream, SMTP_TIMEOUT);
  120. // Reads a full (possibly multiline) reply and asserts the leading status code.
  121. $expect = function (string $code) use ($stream, &$transcript, &$error): bool {
  122. $status = '';
  123. while (($line = fgets($stream, 4096)) !== false) {
  124. $transcript[] = 'S: ' . rtrim($line, "\r\n");
  125. $status = substr($line, 0, 3);
  126. if (strlen($line) < 4 || $line[3] !== '-') { // last line has a space, not '-'
  127. break;
  128. }
  129. }
  130. if (strpos($status, $code) !== 0) {
  131. $error = sprintf('Expected %s but server said: %s', $code, trim($status . ' ...'));
  132. return false;
  133. }
  134. return true;
  135. };
  136. $send = function (string $cmd) use ($stream, &$transcript): void {
  137. $transcript[] = 'C: ' . $cmd;
  138. fwrite($stream, $cmd . "\r\n");
  139. };
  140. try {
  141. if (!$expect('220')) { throw new RuntimeException($error); }
  142. $send('EHLO ' . EHLO_NAME);
  143. // Capture EHLO capabilities to decide whether STARTTLS is offered.
  144. $caps = '';
  145. while (($line = fgets($stream, 4096)) !== false) {
  146. $transcript[] = 'S: ' . rtrim($line, "\r\n");
  147. $caps .= $line;
  148. if (strlen($line) < 4 || $line[3] !== '-') { break; }
  149. }
  150. if (strpos($caps, '250') !== 0) {
  151. throw new RuntimeException('EHLO was rejected by ' . $host . '.');
  152. }
  153. // Opportunistic STARTTLS — encrypt when offered, but do not require a
  154. // trusted certificate (recipient MXs routinely use self-signed certs).
  155. if (stripos($caps, 'STARTTLS') !== false) {
  156. $send('STARTTLS');
  157. if (!$expect('220')) { throw new RuntimeException($error); }
  158. stream_context_set_option($stream, 'ssl', 'verify_peer', false);
  159. stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
  160. stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
  161. if (@stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) !== true) {
  162. throw new RuntimeException('STARTTLS negotiation failed with ' . $host . '.');
  163. }
  164. $transcript[] = '* TLS established';
  165. $send('EHLO ' . EHLO_NAME); // RFC 3207: re-issue EHLO after the upgrade
  166. if (!$expect('250')) { throw new RuntimeException($error); }
  167. }
  168. $send('MAIL FROM:<' . $from . '>');
  169. if (!$expect('250')) { throw new RuntimeException($error); }
  170. $send('RCPT TO:<' . $to . '>');
  171. if (!$expect('25')) { throw new RuntimeException($error); } // 250 or 251
  172. $send('DATA');
  173. if (!$expect('354')) { throw new RuntimeException($error); }
  174. // Dot-stuff any line that begins with '.' then terminate with <CRLF>.<CRLF>.
  175. $data = preg_replace('/^\./m', '..', $rawMessage);
  176. $transcript[] = 'C: [message data, ' . strlen($data) . ' bytes]';
  177. fwrite($stream, $data . "\r\n.\r\n");
  178. if (!$expect('250')) { throw new RuntimeException($error); }
  179. $send('QUIT');
  180. $expect('221'); // best-effort; delivery already accepted above
  181. fclose($stream);
  182. return true;
  183. } catch (\Throwable $e) {
  184. @fclose($stream);
  185. if ($error === null || $error === '') {
  186. $error = $e->getMessage();
  187. }
  188. return false;
  189. }
  190. }
  191. session_start();
  192. // ── Access gate ──────────────────────────────────────────────────────────────
  193. // A correct password unlocks the tool for the rest of the session.
  194. $gateEnabled = (ACCESS_PASSWORD !== '');
  195. $authed = !$gateEnabled || !empty($_SESSION['stm_authed']);
  196. $loginError = null;
  197. $isPost = $_SERVER['REQUEST_METHOD'] === 'POST';
  198. // The login form carries only "password"; the send form carries "recipient".
  199. $isLoginAttempt = $isPost && isset($_POST['password']) && !isset($_POST['recipient']);
  200. if (!$authed && $isLoginAttempt) {
  201. if (hash_equals(ACCESS_PASSWORD, (string) $_POST['password'])) {
  202. session_regenerate_id(true); // fresh id on privilege change (fixation defence)
  203. $_SESSION['stm_authed'] = true;
  204. $authed = true;
  205. } else {
  206. $loginError = 'Incorrect password.';
  207. }
  208. }
  209. // Build an absolute URL to this page, used in the mail body and the form action.
  210. $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  211. $host = $_SERVER['HTTP_HOST'] ?? 'tool.medowar.de';
  212. $path = strtok($_SERVER['REQUEST_URI'] ?? '/send-test-mail.php', '?');
  213. $selfUrl = $scheme . '://' . $host . $path;
  214. $recipient = trim((string) ($_POST['recipient'] ?? ''));
  215. $mailserver = trim((string) ($_POST['mailserver'] ?? ''));
  216. $sent = false;
  217. $sendError = null;
  218. $inputError = null;
  219. $transcript = [];
  220. $isSendAttempt = $authed && $isPost && isset($_POST['recipient']);
  221. if ($isSendAttempt) {
  222. $honeypot = trim((string) ($_POST[HONEYPOT_FIELD] ?? ''));
  223. $formTs = (int) ($_SESSION['stm_form_ts'] ?? 0);
  224. $elapsed = time() - $formTs;
  225. if ($honeypot !== '') {
  226. // (1) Honeypot: a hidden field only a bot would fill. Feign success, send nothing.
  227. $sent = true;
  228. } elseif ($formTs === 0 || $elapsed < MIN_FORM_SECONDS) {
  229. // (2) Time-trap: nobody fills and submits the form this fast — likely a bot.
  230. $inputError = 'That was submitted a little too quickly — please try again.';
  231. } else {
  232. // FILTER_VALIDATE_EMAIL also rejects CR/LF, closing the header-injection door.
  233. $clean = filter_var($recipient, FILTER_VALIDATE_EMAIL);
  234. if ($clean === false) {
  235. $inputError = 'Please enter a valid recipient email address.';
  236. } elseif ($mailserver !== '' && !preg_match('/^(?:[a-z0-9](?:-?[a-z0-9])*\.)+[a-z]{2,}(?::\d{1,5})?$|^\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?$/i', $mailserver)) {
  237. $inputError = 'Please enter a valid mailserver as host or host:port (or leave it blank for normal MX delivery).';
  238. } else {
  239. $recipient = $clean;
  240. $sent = sendTestMail($recipient, $selfUrl, $mailserver !== '' ? $mailserver : null, $sendError, $transcript);
  241. }
  242. }
  243. }
  244. // Stamp a fresh render time so the next send has a timing baseline to check against.
  245. if ($authed) {
  246. $_SESSION['stm_form_ts'] = time();
  247. }
  248. ?>
  249. <!DOCTYPE html>
  250. <html lang="en">
  251. <head>
  252. <meta charset="UTF-8">
  253. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  254. <title>Send Test Mail</title>
  255. <style>
  256. body {
  257. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  258. max-width: 1000px;
  259. margin: 40px auto;
  260. padding: 0 20px;
  261. background: #f5f5f5;
  262. color: #333;
  263. }
  264. h1 { color: #333; }
  265. .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
  266. form.lookup { margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; align-items: stretch; }
  267. input[type=email], input[type=password], input[type=text] {
  268. padding: 10px; font-size: 15px; border: 1px solid #ccc; border-radius: 5px; background: white; flex: 1; min-width: 220px;
  269. }
  270. details.transcript { margin: 16px 0; }
  271. details.transcript pre {
  272. background: #263238; color: #cfd8dc; padding: 12px 14px; border-radius: 5px;
  273. font-size: 12px; overflow-x: auto; line-height: 1.5;
  274. }
  275. details.transcript summary { cursor: pointer; font-weight: 600; color: #1976D2; }
  276. /* Honeypot: kept in the layout for bots but invisible and unfocusable for humans. */
  277. .hp { position: absolute; left: -9999px; top: -9999px; width: 1px; height: 1px; overflow: hidden; }
  278. .btn {
  279. display: inline-block; padding: 10px 20px; background: #2196F3; color: white;
  280. text-decoration: none; border-radius: 5px; border: none; cursor: pointer; font-size: 15px;
  281. }
  282. .btn:hover { background: #1976D2; }
  283. .error { background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin: 6px 0; }
  284. .verdict {
  285. display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-radius: 6px;
  286. font-size: 18px; font-weight: 600; margin: 16px 0;
  287. }
  288. .verdict.ok { background: #e8f5e9; color: #2e7d32; border-left: 6px solid #43a047; }
  289. .verdict.fail { background: #ffebee; color: #c62828; border-left: 6px solid #e53935; }
  290. h2 { color: #333; margin-top: 30px; }
  291. table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 10px; }
  292. th, td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #eee; font-size: 13px; vertical-align: top; }
  293. th { width: 180px; color: #555; background: #fafafa; font-weight: 600; }
  294. td.mono, .mono { font-family: monospace; word-break: break-all; }
  295. pre.preview {
  296. background: #263238; color: #cfd8dc; padding: 12px 14px; border-radius: 5px;
  297. font-size: 12px; overflow-x: auto; line-height: 1.5; white-space: pre-wrap; word-break: break-word;
  298. }
  299. </style>
  300. </head>
  301. <body>
  302. <h1>✉️ Send Test Mail</h1>
  303. <?php if (!$authed): ?>
  304. <div class="info">🔒 This tool is password-protected. Enter the password to continue.</div>
  305. <?php if ($loginError): ?>
  306. <div class="error"><?= htmlspecialchars($loginError) ?></div>
  307. <?php endif; ?>
  308. <form class="lookup" method="POST" action="<?= htmlspecialchars($selfUrl) ?>">
  309. <input type="password" name="password" placeholder="Password" required autofocus>
  310. <button type="submit" class="btn">🔓 Unlock</button>
  311. </form>
  312. <?php else: ?>
  313. <div class="info">
  314. Sends a fixed, clearly-labelled <strong>test message</strong> from
  315. <code><?= htmlspecialchars(SENDER_ADDRESS) ?></code> to the address you enter.
  316. The subject and body are predefined — the only input is the recipient. Use it to
  317. confirm that outbound delivery for <code>med0.de</code> reaches a given mailbox.
  318. </div>
  319. <form class="lookup" method="POST" action="<?= htmlspecialchars($selfUrl) ?>">
  320. <input type="email" name="recipient" placeholder="recipient@example.com"
  321. value="<?= htmlspecialchars($recipient) ?>" required autofocus>
  322. <input type="text" name="mailserver" placeholder="mailserver (optional, e.g. mx.example.com:25)"
  323. value="<?= htmlspecialchars($mailserver) ?>">
  324. <!-- Honeypot: humans never see or fill this; bots that auto-fill forms do. -->
  325. <div class="hp" aria-hidden="true">
  326. <label>Leave this field empty
  327. <input type="text" name="<?= htmlspecialchars(HONEYPOT_FIELD) ?>" tabindex="-1" autocomplete="off">
  328. </label>
  329. </div>
  330. <button type="submit" class="btn">✉️ Send test mail</button>
  331. </form>
  332. <p style="color:#888;font-size:12px;margin-top:-10px;">
  333. Leave <strong>mailserver</strong> empty to deliver via the local mail system (normal MX routing).
  334. Fill it to deliver <strong>directly</strong> to that host over SMTP (default port 25, opportunistic STARTTLS).
  335. </p>
  336. <?php if ($inputError): ?>
  337. <div class="error"><?= htmlspecialchars($inputError) ?></div>
  338. <?php endif; ?>
  339. <?php if ($isSendAttempt && !$inputError): ?>
  340. <?php $direct = ($mailserver !== ''); ?>
  341. <?php if ($sent): ?>
  342. <div class="verdict ok">✅ Test message
  343. <?= $direct
  344. ? 'accepted by ' . htmlspecialchars($mailserver)
  345. : 'handed off to the local mail server' ?>
  346. for <?= htmlspecialchars($recipient) ?>.</div>
  347. <p style="color:#888;font-size:13px;">
  348. <?= $direct
  349. ? 'The target server accepted the message for delivery.'
  350. : 'A successful hand-off means the local mail system accepted the message — it does not guarantee final delivery.' ?>
  351. Check the recipient's inbox (and spam folder).
  352. </p>
  353. <?php else: ?>
  354. <div class="verdict fail">❌ Could not send the test message.</div>
  355. <?php if ($sendError): ?>
  356. <div class="error"><?= htmlspecialchars($sendError) ?></div>
  357. <?php endif; ?>
  358. <?php endif; ?>
  359. <?php if (!empty($transcript)): ?>
  360. <details class="transcript" open>
  361. <summary>SMTP conversation with <?= htmlspecialchars($mailserver) ?></summary>
  362. <pre><?= htmlspecialchars(implode("\n", $transcript)) ?></pre>
  363. </details>
  364. <?php endif; ?>
  365. <?php endif; ?>
  366. <h2>What gets sent</h2>
  367. <table>
  368. <tr><th>From</th><td class="mono"><?= htmlspecialchars(SENDER_NAME . ' <' . SENDER_ADDRESS . '>') ?></td></tr>
  369. <tr><th>Reply-To</th><td class="mono"><?= htmlspecialchars(SENDER_ADDRESS) ?></td></tr>
  370. <tr><th>Subject</th><td class="mono">Test message from the med0.de mail tools</td></tr>
  371. <tr>
  372. <th>Body</th>
  373. <td>
  374. <pre class="preview">Hello,
  375. This is an automated TEST message sent by the med0.de mail-testing tools.
  376. If you received it, delivery from <?= htmlspecialchars(SENDER_ADDRESS) ?> to your address is working.
  377. You can safely ignore or delete this message — no action is required.
  378. Test page: <?= htmlspecialchars($selfUrl) ?>
  379. Sent (UTC): …
  380. — med0.de mail tools</pre>
  381. </td>
  382. </tr>
  383. </table>
  384. <?php endif; ?>
  385. </body>
  386. </html>