diff --git a/CHANGELOG.md b/CHANGELOG.md index 88d5549..e780e08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,68 @@ All notable changes to `initphp/mailer` are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Security + +- A CR, LF or NUL in an address, display name or return path is now rejected + with an `InvalidAddressException` **whether or not** the `validate` option is + on (`Address`, `setFrom()`, `setReplyTo()`, `setTo()`, `setCC()`, `setBCC()`). + Before, `validate => false` also switched off the only line-break check, so a + request-supplied address could add headers or SMTP commands. Leading and + trailing line breaks are still trimmed, and a recipient string is still split + on whitespace. +- `setHeader()` throws a `MailerException` for a header name containing a CR, LF + or NUL. A header value keeps its documented behaviour: CR and LF are stripped, + and NUL is now stripped too. The subject is stripped of NUL as well. +- Attachment names, dispositions and MIME types containing a CR, LF or NUL throw + an `AttachmentException`; the `userAgent` and `charset` options containing one + throw a `ConfigurationException`. +- `SmtpTransport` refuses a recipient containing a CR, LF, NUL, `<` or `>` + (`InvalidAddressException`) or a client hostname containing a CR, LF or NUL + (`TransportException`) before it connects, instead of writing it to the socket. + +### Fixed + +- **SMTP connection state after a failure.** A failed greeting, `EHLO`, `STARTTLS`, + TLS handshake, `AUTH`, recipient or message now closes the connection and + forgets the "authenticated" flag. Before, the socket stayed open, so the next + `send()` skipped `STARTTLS` and wrote `AUTH LOGIN` with the base64 credentials + in clear text. A greeting other than `220` is now an error. +- With `DSN` on, the `ORCPT` address is xtext-encoded (RFC 3461); before, a space + in an address (possible with `validate` off) could append SMTP parameters. +- `StreamSocketClient::enableCrypto()` refuses to start TLS while clear-text + bytes are still in the read buffer (STARTTLS response injection). +- The `Message-ID` domain is taken from the parsed sender, not from the raw + `fromEmail` option, and `Address::parse()` checks the whole input before the + display name is split off, so a CR, LF or NUL cannot hide in the part that is + discarded. +- A `<` or `>` inside an address is rejected (even with `validate` off): it could + close the SMTP path and add parameters (`RCPT TO: NOTIFY=NEVER>`). +- `setHeader()`: a header the library writes itself for the message wins over a + custom one of the same name whatever the case (a custom `from`, or `bcc` next + to a real BCC list, is dropped instead of added as a second header). A header + the library does not write is kept as before: `setHeader('Cc'|'Bcc'|'To', …)` + without `setCC()`/`setBCC()`/`setTo()` still adds that header. (3.0.0 lost a + custom `To` on sendmail and SMTP when the message had no To recipient; it is now + kept there too. `sendmail -t` reads recipients from the headers, so such a + hand-set `To` is now also a recipient on sendmail.) A name with a space, a + colon or any non-printable or non-ASCII character throws a `MailerException`. +- `setAltMessage()` strips carriage returns like `setMessage()`. The SMTP + dot-stuffing now also handles a bare `"\r"` or `"\n\r"` newline. +- A `"` or `\` in an attachment name is escaped inside the quoted `name` + parameter; the generated Content-ID keeps only `[A-Za-z0-9._-]` of the name. +- `QEncoder`: input that is not valid UTF-8 is replaced with `?` instead of + raising iconv notices and producing garbage, and the fallback encoder for a + non-UTF-8 charset writes the missing `=` before each byte, so the encoded-words + are valid again. +- `HeaderRenderer` (used by all three transports) and the `mail()` / sendmail + transports refuse a header name that is not a field name, a value with a line + break other than a fold (a line break followed by a space or tab), and + recipients with a line break or angle bracket, so a `PreparedEmail` built by + hand cannot inject headers. A MIME boundary from `setBoundaryFactory()` that is + empty or contains a quote, CR, LF or NUL throws a `MailerException`. + ## [3.0.0] - 2026-11-22 ### Changed (breaking) diff --git a/docs/API-Reference.md b/docs/API-Reference.md index 08876b7..17b26e9 100644 --- a/docs/API-Reference.md +++ b/docs/API-Reference.md @@ -23,34 +23,42 @@ $mailer = Mailer::newInstance(['protocol' => 'smtp', /* … */]); ### `setFrom(string $from, string $name = '', ?string $returnPath = null): self` Sets the sender. `$from` may be `address` or `"Name"
`; `$name` wins over an embedded name. `$returnPath` sets the envelope sender. -**Throws** `InvalidAddressException`. +**Throws** `InvalidAddressException` — also when the address, the name or +`$returnPath` contains a CR, LF or NUL, whatever the `validate` option says. ### `setReplyTo(string $replyTo, string $name = ''): self` Sets the `Reply-To`. Defaults to the sender when never called. -**Throws** `InvalidAddressException`. +**Throws** `InvalidAddressException` (also for a CR, LF or NUL, even with +`validate` off). ### `setTo(string|array $to): self` Sets the To recipients. Accepts one address, a comma/space-separated string, or -an array. **Throws** `InvalidAddressException`. +an array. **Throws** `InvalidAddressException`. An address containing a CR, LF or +NUL is rejected even with `validate` off; in a string, whitespace (including line +breaks) still separates addresses. ### `setCC(string|array $cc): self` -Sets the CC recipients. **Throws** `InvalidAddressException`. +Sets the CC recipients. **Throws** `InvalidAddressException` (same line-break +rule as `setTo()`). ### `setBCC(string|array $bcc, ?int $limit = null): self` Sets the BCC recipients. A non-null `$limit` enables [BCC batching](Sending-Mail.md#bcc-batching) -with that batch size. **Throws** `InvalidAddressException`. +with that batch size. **Throws** `InvalidAddressException` (same line-break rule as +`setTo()`). ## Content ### `setSubject(string $subject): self` Sets the subject. Encoded (RFC 2047 Q) automatically when it contains non-ASCII. +CR, LF and NUL are removed when the message is built. ### `setMessage(string $body): self` Sets the body (plain text or HTML depending on the mail type). Carriage returns are stripped and surrounding blank lines trimmed. ### `setAltMessage(string $str): self` -Sets the plain-text alternative used for HTML messages. +Sets the plain-text alternative used for HTML messages. Carriage returns are +stripped, like in `setMessage()`. ### `setMailType(string $type = 'text'): self` `'html'` for the value `html` (case-insensitive), otherwise `'text'`. @@ -60,11 +68,13 @@ Sets the plain-text alternative used for HTML messages. ### `attach(string $file, string $disposition = '', ?string $newName = null, ?string $mime = null): self` Attaches a file from disk. `$disposition` defaults to `attachment` (use `inline` for embedded images), `$newName` overrides the displayed name, `$mime` skips -auto-detection. **Throws** `AttachmentException`. +auto-detection. **Throws** `AttachmentException`, also when the name, disposition +or MIME type contains a CR, LF or NUL. ### `attachContent(string $content, string $name, string $disposition = 'attachment', ?string $mime = null): self` Attaches in-memory/generated content. `$mime` defaults to -`application/octet-stream`. +`application/octet-stream`. **Throws** `AttachmentException` when the name, +disposition or MIME type contains a CR, LF or NUL. ### `setAttachmentCID(string $fileName): string` Promotes a previously added attachment (matched by its path/name) to an inline @@ -74,8 +84,14 @@ Promotes a previously added attachment (matched by its path/name) to an inline ## Formatting & headers ### `setHeader(string $header, string $value): self` -Adds a custom header. CR/LF are stripped; library-managed headers take -precedence. +Adds a custom header. CR, LF and NUL are stripped from the value. A header the +library writes for the message itself (From, Subject, To with To recipients, +Cc with CC recipients, +Bcc with BCC recipients on sendmail and `mail()`, Date, Message-ID, …) wins over +a custom one of the same name, whatever the case; one it does not write is kept +as you set it. Use `setCC()`/`setBCC()` for recipients, not headers. +**Throws** `MailerException` when the header name is not printable ASCII +without `:` or spaces. ### `setPriority(int $n = 3): self` `X-Priority`, 1 (highest)–5 (lowest); out-of-range → 3. @@ -136,6 +152,8 @@ Overrides the protocol-derived transport (used in [Testing](Testing.md)). ### `setBoundaryFactory(callable $factory): self` Overrides the MIME boundary generator: `callable(string $prefix): string`. +`send()` throws a `MailerException` for an empty boundary or one containing a +quote, CR, LF or NUL. --- diff --git a/docs/Attachments.md b/docs/Attachments.md index 3a9046c..2e5c792 100644 --- a/docs/Attachments.md +++ b/docs/Attachments.md @@ -23,7 +23,12 @@ $mailer->attach( ``` If the file cannot be read, or its type cannot be detected and you didn't supply -one, `attach()` throws [`AttachmentException`](Error-Handling.md). +one, `attach()` throws [`AttachmentException`](Error-Handling.md). It also throws +when the name, disposition or MIME type contains a CR, LF or NUL, since they are +written into the part's MIME headers (this applies to `attachContent()` too). A +`"` or `\` in the name is escaped with a backslash inside the quoted `name` +parameter, and the generated Content-ID keeps only letters, digits, `.`, `_` and +`-` of the name (anything else becomes `_`). ## In-memory or generated content diff --git a/docs/Configuration.md b/docs/Configuration.md index f7286bd..d9b146a 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -30,11 +30,11 @@ $mailer = Mailer::newInstance([ | `fromEmail` | string | `''` | Sender used when [`setFrom()`](Sending-Mail.md) is not called. | | `fromName` | string | `''` | Display name paired with `fromEmail`. | | `mailType` | string | `'text'` | `'text'` or `'html'`. | -| `charset` | string | `'UTF-8'` | Character set; stored upper-cased. | +| `charset` | string | `'UTF-8'` | Character set; stored upper-cased. A CR, LF or NUL throws a `ConfigurationException`. | | `priority` | int | `3` | `X-Priority`, 1 (highest)–5 (lowest); out-of-range → 3. | | `altMessage` | string | `''` | Plain-text alternative for HTML messages. | -| `userAgent` | string | `'InitPHP Mailer'` | `User-Agent` / `X-Mailer` header value. | -| `validate` | bool | `true` | Validate addresses as they are added. Turning it off also removes the CR/LF check — see [Error Handling](Error-Handling.md). | +| `userAgent` | string | `'InitPHP Mailer'` | `User-Agent` / `X-Mailer` header value. A CR, LF or NUL throws a `ConfigurationException`. | +| `validate` | bool | `true` | Validate addresses as they are added. Turning it off removes the format check only; a CR, LF, NUL, `<` or `>` in an address is rejected either way — see [Error Handling](Error-Handling.md). | ## Transport selection diff --git a/docs/Encoding-and-Headers.md b/docs/Encoding-and-Headers.md index 4cda10e..9973444 100644 --- a/docs/Encoding-and-Headers.md +++ b/docs/Encoding-and-Headers.md @@ -30,6 +30,11 @@ $mailer->setSubject('Café ☕'); ``` Encoding happens when the message is built, so you always pass plain strings. +Line breaks and NUL are removed from a subject; a display name containing one is +rejected with an `InvalidAddressException`. With a `UTF-8` charset, bytes that are +not valid UTF-8 are replaced with `?` before encoding. With any other charset +the bytes are encoded as they are and must already be in that charset (the +mailer does not convert them). ## Body encoding @@ -83,9 +88,13 @@ Out-of-range values fall back to 3. ## Custom headers -Add any header with `setHeader()`. CR/LF are stripped from the value to prevent -header injection, and the headers the library manages (From, To, Subject, Date, -Message-ID, MIME-Version, X-*, …) always take precedence over custom ones. +Add any header with `setHeader()`. CR, LF and NUL are stripped from the value to +prevent header injection, a header name that is not printable ASCII without `:` +or spaces throws a `MailerException`. The headers the library writes itself +(From, To, Subject, Date, Message-ID, MIME-Version, X-Mailer, …, and Cc/Bcc when +there are such recipients) win over a custom header of the same name, whatever +the case; a header the library does not write is kept. See +[Sending Mail](Sending-Mail.md#custom-headers). ```php $mailer->setHeader('List-Unsubscribe', ''); diff --git a/docs/Error-Handling.md b/docs/Error-Handling.md index 14cd251..a4d2658 100644 --- a/docs/Error-Handling.md +++ b/docs/Error-Handling.md @@ -14,9 +14,10 @@ MailerException (extends \RuntimeException) | Exception | Thrown when | Thrown by | | --- | --- | --- | -| `InvalidAddressException` | An address fails validation (and validation is on). | `setFrom()`, `setReplyTo()`, `setTo()`, `setCC()`, `setBCC()` | -| `ConfigurationException` | A required value is missing: no sender, no recipient, empty SMTP host, auth without credentials. | `send()` | -| `AttachmentException` | A file can't be read, its type can't be detected, or `setAttachmentCID()` finds no match. | `attach()`, `setAttachmentCID()` | +| `InvalidAddressException` | An address fails validation (and validation is on), or an address or return path contains a CR, LF, NUL, `<` or `>`, or a display name a CR, LF or NUL (always). | `setFrom()`, `setReplyTo()`, `setTo()`, `setCC()`, `setBCC()`, `send()` | +| `ConfigurationException` | A required value is missing: no sender, no recipient, empty SMTP host, auth without credentials; or `userAgent`/`charset` contains a CR, LF or NUL. | `send()`, `new Mailer()` | +| `AttachmentException` | A file can't be read, its type can't be detected, the name, disposition or MIME type contains a CR, LF or NUL, or `setAttachmentCID()` finds no match. | `attach()`, `attachContent()`, `setAttachmentCID()` | +| `MailerException` (the base type) | A custom header name is not a valid field name; a MIME boundary from `setBoundaryFactory()` is empty or contains a quote, CR, LF or NUL; a header or subject handed to a transport by hand contains a line break other than a fold. | `setHeader()`, `send()` | | `TransportException` | Delivery failed: refused connection, unexpected SMTP reply, sendmail non-zero exit, or `mail()` returning false. | `send()` | ## Catch everything @@ -56,20 +57,16 @@ Need to accept addresses the PHP filter rejects? Turn validation off: $mailer = Mailer::newInstance(['validate' => false]); ``` -> **Security:** `validate => false` removes the only check on addresses. The -> mailer only trims whitespace from the ends of an address, so a CR or LF inside -> one (`user@example.com\r\nBcc: attacker@example.test`) is written into the -> `From` / `Cc` header or the SMTP command as given, which lets a request-supplied -> address add headers or recipients. If you turn validation off, reject line -> breaks yourself before the address reaches the mailer: -> -> ```php -> if (preg_match('/[\r\n]/', $address) === 1) { -> throw new \InvalidArgumentException('Invalid address.'); -> } -> ``` -> -> Never turn validation off for addresses that come from user input. +> **Security:** `validate => false` removes the format check on addresses, but +> not the character check. A CR, LF or NUL inside an address or a display name +> (`user@example.com\r\nBcc: attacker@example.test`), or a `<` or `>` inside an +> address (`user@example.com> NOTIFY=NEVER`), is rejected with an +> `InvalidAddressException` whether validation is on or off, so a request-supplied +> address cannot start another header or add parameters to an SMTP command. Only +> a leading or trailing line break is trimmed. The check does not limit how many +> recipients a string names: `"a@x.com,b@x.com"` is two. Avoid turning validation +> off for addresses that come from user input, and pass a single untrusted +> address as `setTo([$address])`. ## Handle delivery failures specifically diff --git a/docs/FAQ.md b/docs/FAQ.md index 37b5707..af29f03 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -58,20 +58,16 @@ rejects, disable validation: $mailer = Mailer::newInstance(['validate' => false]); ``` -> **Security:** `validate => false` removes the only check on addresses. The -> mailer only trims whitespace from the ends of an address, so a CR or LF inside -> one (`user@example.com\r\nBcc: attacker@example.test`) is written into the -> `From` / `Cc` header or the SMTP command as given, which lets a request-supplied -> address add headers or recipients. If you turn validation off, reject line -> breaks yourself before the address reaches the mailer: -> -> ```php -> if (preg_match('/[\r\n]/', $address) === 1) { -> throw new \InvalidArgumentException('Invalid address.'); -> } -> ``` -> -> Never turn validation off for addresses that come from user input. +> **Security:** `validate => false` removes the format check on addresses, but +> not the character check. A CR, LF or NUL inside an address or a display name +> (`user@example.com\r\nBcc: attacker@example.test`), or a `<` or `>` inside an +> address (`user@example.com> NOTIFY=NEVER`), is rejected with an +> `InvalidAddressException` whether validation is on or off, so a request-supplied +> address cannot start another header or add parameters to an SMTP command. Only +> a leading or trailing line break is trimmed. The check does not limit how many +> recipients a string names: `"a@x.com,b@x.com"` is two. Avoid turning validation +> off for addresses that come from user input, and pass a single untrusted +> address as `setTo([$address])`. ### Non-Latin subjects or names look like `=?UTF-8?Q?...?=`. diff --git a/docs/SMTP-Transport.md b/docs/SMTP-Transport.md index 15329c8..b801647 100644 --- a/docs/SMTP-Transport.md +++ b/docs/SMTP-Transport.md @@ -81,6 +81,13 @@ With `'SMTPKeepAlive' => true` the connection is reused between messages — an avoids the connect/handshake cost when sending many messages in a loop. The connection is closed when the mailer is garbage-collected. +If a send fails at any point — the greeting or `EHLO` is refused, `STARTTLS` is +refused or the TLS handshake fails, authentication or a recipient is rejected, +or the message itself is rejected — the connection is closed and the +"authenticated" state is forgotten. The next `send()` opens a new connection and +starts again from the greeting, `STARTTLS` and `AUTH`, so credentials are never +sent over a connection that did not finish upgrading to TLS. + ```php $mailer = Mailer::newInstance([ 'protocol' => 'smtp', @@ -102,7 +109,9 @@ foreach ($recipients as $to) { ## Delivery Status Notifications (DSN) `'DSN' => true` appends `NOTIFY=SUCCESS,DELAY,FAILURE` and an `ORCPT` to each -`RCPT TO`, asking the server for delivery notifications (if it supports DSN). +`RCPT TO`, asking the server for delivery notifications (if it supports DSN). The +address in `ORCPT` is encoded as RFC 3461 `xtext` (a space, `+`, `=` or any byte +outside `!`..`~` becomes `+XX`), so an address cannot add parameters. ## Timeouts @@ -117,7 +126,9 @@ to socket reads/writes. | Auth enabled but no username/password | `ConfigurationException` | | Connection refused / cannot open socket | `TransportException` | | Unexpected SMTP reply (e.g. `550`, `535`) | `TransportException` (code = reply code) | -| TLS negotiation fails | `TransportException` | +| The server's greeting is not `220` | `TransportException` (code = reply code) | +| TLS negotiation fails, or bytes arrived in clear text together with the `STARTTLS` reply | `TransportException` | +| A recipient contains a CR, LF, NUL, `<` or `>`, or the client hostname contains a CR, LF or NUL | `InvalidAddressException` / `TransportException`, before connecting | ```php use InitPHP\Mailer\Exception\TransportException; diff --git a/docs/Sending-Mail.md b/docs/Sending-Mail.md index f3958f4..541c0e3 100644 --- a/docs/Sending-Mail.md +++ b/docs/Sending-Mail.md @@ -71,11 +71,22 @@ try { ``` Disable validation with `'validate' => false` only if you need to accept -addresses the PHP filter rejects, and only for addresses you control. The -mailer then no longer rejects a CR/LF inside an address, so a request-supplied -address could inject headers or recipients; reject line breaks yourself — see +addresses the PHP filter rejects, and only for addresses you control. A CR, LF, +NUL, `<` or `>` inside an address, or a CR, LF or NUL in a display name, is +rejected with an `InvalidAddressException` even then, so a request-supplied +address cannot start another header or add parameters to an SMTP command — see [Error Handling](Error-Handling.md#fail-fast-on-bad-input). +That check does **not** stop a request-supplied *string* from naming several +recipients: `setTo()` splits a string on commas and whitespace, so +`"victim@example.com,other@example.com"` is two recipients (with validation off, +a comma inside an array item is not split either, and the `To` header then lists +both). Pass a single untrusted address as an array item and keep `validate` on: + +```php +$mailer->setTo([$_POST['email']]); // one address; validation rejects "a@x.com,b@x.com" +``` + ## Subject and body ```php @@ -108,9 +119,31 @@ repeatedly. If any batch fails, the failure is thrown. ## Custom headers -Add any header with `setHeader()`. CR/LF are stripped from the value to prevent -header injection, and headers the library manages (From, To, Subject, …) take -precedence: +Add any header with `setHeader()`. CR, LF and NUL are stripped from the value to +prevent header injection (a trailing newline in a value is harmless; it is just +removed). A header *name* must be printable ASCII without `:` or spaces, or +`setHeader()` throws a `MailerException`. + +If the library writes a header itself for this message, its value wins over a +custom header of the same name, whatever the case of the name: a custom `from` +is dropped, not added next to the real `From`. That covers From, Reply-To, +Return-Path, Date, Message-ID, MIME-Version, User-Agent, X-Mailer, X-Sender, +X-Priority, Content-Type and Content-Transfer-Encoding; `Subject`; `To` when you +called `setTo()`; `Cc` when you called `setCC()`; and `Bcc` when you called +`setBCC()` (sendmail and `mail()` write it; SMTP never does). A header the +library does **not** write is passed through as you set it: `setHeader('Cc', …)` +with no `setCC()`, or `setHeader('To', 'undisclosed-recipients:;')` on a message +that only has BCC recipients, adds that header. + +Use `setTo()`, `setCC()` and `setBCC()` for recipients, and know what a header +set by hand does on each transport. With `mail()` and `sendmail` the MTA reads +the recipients from the headers, so a `To`, `Cc` or `Bcc` header set by hand +**does** add a recipient (and a `Bcc` header set by hand on `sendmail` is removed +from the delivered copy like any other `Bcc`). With BCC batching the header is +repeated in every batch, so that address gets one copy per batch. A group such as +`undisclosed-recipients:;` adds no recipient. With `smtp` only the `RCPT TO` list counts: +a hand-set `To`, `Cc` or `Bcc` header adds no recipient, and a hand-set `Bcc` stays +**visible** in the message every recipient receives: ```php $mailer->setHeader('List-Unsubscribe', ''); diff --git a/docs/Transports.md b/docs/Transports.md index f4099b8..84c7297 100644 --- a/docs/Transports.md +++ b/docs/Transports.md @@ -88,7 +88,9 @@ each transport does the right thing: - **`sendmail`** — `To`, `Cc` and `Bcc` go in the headers; the MTA strips `Bcc` thanks to `-t`. - **`smtp`** — `To` and `Cc` are visible headers; every recipient (including - BCC) is delivered with `RCPT TO`, and **`Bcc` never appears in the headers**. + BCC) is delivered with `RCPT TO`, and the **recipients you set with `setBCC()` + never appear in the headers** (a `Bcc` header you add by hand with + `setHeader()` does; see [Sending Mail](Sending-Mail.md#custom-headers)). ## Supplying your own transport diff --git a/src/Encoding/QEncoder.php b/src/Encoding/QEncoder.php index d60c28e..b12d8e1 100644 --- a/src/Encoding/QEncoder.php +++ b/src/Encoding/QEncoder.php @@ -20,6 +20,7 @@ use function iconv_strlen; use function iconv_substr; use function implode; +use function mb_scrub; use function mb_strlen; use function mb_substr; use function str_replace; @@ -41,10 +42,13 @@ public function __construct( public function encode(string $str): string { - $str = str_replace(["\r", "\n"], '', $str); + $str = str_replace(["\r", "\n", "\0"], '', $str); $chars = null; if ($this->charset === 'UTF-8') { + // Bytes that are not valid UTF-8 make the iconv functions raise + // notices and produce garbage; replace them with "?" first. + $str = mb_scrub($str, 'UTF-8'); $output = @iconv_mime_encode('', $str, [ 'scheme' => 'Q', 'line-length' => 76, @@ -71,7 +75,7 @@ public function encode(string $str): string $slice = iconv_substr($str, $i, 1, $this->charset); $chr = '=' . implode('=', str_split(strtoupper(bin2hex($slice === false ? '' : $slice)), 2)); } else { - $chr = strtoupper(bin2hex($str[$i])); + $chr = '=' . strtoupper(bin2hex($str[$i])); } $chrLength = mb_strlen($chr, '8bit'); diff --git a/src/Mailer.php b/src/Mailer.php index 44f4845..a499ef0 100644 --- a/src/Mailer.php +++ b/src/Mailer.php @@ -22,6 +22,7 @@ use InitPHP\Mailer\Exception\AttachmentException; use InitPHP\Mailer\Exception\ConfigurationException; use InitPHP\Mailer\Exception\InvalidAddressException; +use InitPHP\Mailer\Exception\MailerException; use InitPHP\Mailer\Message\Address; use InitPHP\Mailer\Message\Attachment; use InitPHP\Mailer\Message\HeaderRenderer; @@ -81,6 +82,15 @@ class Mailer private const PROTOCOLS = ['mail', 'sendmail', 'smtp']; + /** + * Lower-cased names of the content headers every message gets from the MIME + * builder; a custom header with one of these names is always dropped. The + * other headers the library writes are known only while the message is built + * (see {@see buildGeneralHeaders()}): `Cc` is written only when there are CC + * recipients, and `To`, `Subject` and `Bcc` are left to the transport. + */ + private const CONTENT_HEADERS = ['content-type', 'content-transfer-encoding']; + /* ----- Mutable settings (initialised from config, changeable via setters) ----- */ private string $protocol; @@ -205,13 +215,28 @@ public function clear(bool $clearAttachments = false): self } /** - * Adds an arbitrary header (for example `List-Unsubscribe`). CR/LF are - * stripped from the value to prevent header injection. Reserved headers - * managed by the library (From, To, Subject, …) take precedence. + * Adds an arbitrary header (for example `List-Unsubscribe`). CR, LF and NUL + * are stripped from the value to prevent header injection; a header name + * that is not made of printable ASCII characters other than `:` is + * rejected. A header the library writes itself for the message (From, + * Reply-To, Date, Message-ID, Cc when there are CC recipients, To, Subject, + * Bcc when there are BCC recipients, …) takes precedence over a custom header + * of the same name, whatever the case; use setCC() and setBCC() for + * recipients. A custom `Cc`, `Bcc` or `To` the library does not write (no CC, + * BCC or To recipients) is passed through unchanged. + * + * @throws MailerException When the header name is not a valid field name. */ public function setHeader(string $header, string $value): self { - $this->customHeaders[$header] = (string) preg_replace('/[\r\n]+/', '', $value); + if (!HeaderRenderer::isValidName($header)) { + throw new MailerException( + 'A header name must be made of printable ASCII characters other than ":" ' + . '(no spaces, line breaks or NUL).', + ); + } + + $this->customHeaders[$header] = (string) preg_replace('/[\r\n\0]+/', '', $value); return $this; } @@ -229,6 +254,7 @@ public function setFrom(string $from, string $name = '', ?string $returnPath = n if ($returnPath !== null) { $returnPath = trim($returnPath, "<> \t\n\r\0\x0B"); + EmailValidator::assertSafeAddresses([$returnPath]); $this->assertValid($returnPath); } @@ -352,7 +378,7 @@ public function setAttachmentCID(string $fileName): string public function setAltMessage(string $str): self { - $this->altMessage = trim($str); + $this->altMessage = trim((string) preg_replace('/\r/', '', $str)); return $this; } @@ -427,11 +453,18 @@ public function setBoundaryFactory(callable $factory): self /** * Builds a unique Message-ID based on the sender domain. + * + * @throws InvalidAddressException When the configured sender address is unsafe. */ public function getMessageID(): string { - $from = $this->returnPath ?? $this->from?->getEmail() ?? $this->config->fromEmail; - $domain = strstr($from, '@'); + $from = $this->returnPath ?? $this->from?->getEmail(); + if ($from === null && $this->config->fromEmail !== '') { + // Parsed (and so checked) like the sender that send() will use, not + // read raw from the configuration. + $from = Address::parse($this->config->fromEmail, $this->config->fromName)->getEmail(); + } + $domain = $from === null ? false : strstr($from, '@'); return '<' . uniqid('', true) . ($domain === false ? '@localhost' : $domain) . '>'; } @@ -640,7 +673,7 @@ private function createSmtpTransport(): SmtpTransport */ private function buildGeneralHeaders(Address $from, Address $replyTo): array { - $headers = $this->customHeaders; + $headers = []; $headers['Date'] = $this->date; $headers['From'] = $this->formatAddressHeader($from); $headers['Return-Path'] = '<' . ($this->returnPath ?? $from->getEmail()) . '>'; @@ -655,7 +688,22 @@ private function buildGeneralHeaders(Address $from, Address $replyTo): array $headers['Message-ID'] = $this->getMessageID(); $headers['MIME-Version'] = '1.0'; - return $headers; + // A custom header the library also writes loses, whatever the case of + // its name. One the library does not write for this message is kept. + $managed = HeaderRenderer::names($headers); + if ($this->to !== []) { + // The transport writes To (or passes it to mail()) for the whole message. + $managed['to'] = true; + } + $custom = []; + foreach ($this->customHeaders as $name => $value) { + $key = strtolower(trim((string) $name)); + if (!isset($managed[$key]) && !\in_array($key, self::CONTENT_HEADERS, true)) { + $custom[(string) $name] = $value; + } + } + + return $custom + $headers; } /** @@ -737,6 +785,7 @@ private function normalizeAddressList(string|array $value): array foreach ($value as $item) { $item = trim((string) $item, "<> \t\r\n\0\x0B"); if ($item !== '') { + EmailValidator::assertSafeAddresses([$item]); $list[] = $item; } } diff --git a/src/MailerConfig.php b/src/MailerConfig.php index f9bfad5..8a25b5e 100644 --- a/src/MailerConfig.php +++ b/src/MailerConfig.php @@ -15,6 +15,9 @@ namespace InitPHP\Mailer; +use InitPHP\Mailer\Exception\ConfigurationException; +use InitPHP\Mailer\Validation\EmailValidator; + use function strtolower; use function strtoupper; @@ -110,6 +113,10 @@ final class MailerConfig /** * @param array $config + * + * @throws ConfigurationException When `userAgent` or `charset`, which are + * written into message headers, contain a + * CR, LF or NUL character. */ public function __construct(array $config = []) { @@ -150,6 +157,14 @@ public function __construct(array $config = []) // path is reached; leaving it lower-cased was a 1.x bug. $this->charset = strtoupper($this->str($config, 'charset', 'UTF-8')); + foreach (['userAgent' => $this->userAgent, 'charset' => $this->charset] as $option => $value) { + if (EmailValidator::hasLineBreakOrNul($value)) { + throw new ConfigurationException( + \sprintf('The "%s" option must not contain a line break or a NUL character.', $option), + ); + } + } + $priority = $this->int($config, 'priority', 3); $this->priority = ($priority >= 1 && $priority <= 5) ? $priority : 3; diff --git a/src/Message/Address.php b/src/Message/Address.php index 065dd35..6e819da 100644 --- a/src/Message/Address.php +++ b/src/Message/Address.php @@ -15,6 +15,9 @@ namespace InitPHP\Mailer\Message; +use InitPHP\Mailer\Exception\InvalidAddressException; +use InitPHP\Mailer\Validation\EmailValidator; + use function preg_match; use function trim; @@ -26,18 +29,37 @@ */ final class Address { + /** + * @throws InvalidAddressException When the address contains a CR, LF, NUL, + * `<` or `>`, or the name a CR, LF or NUL. + * This is checked even when address + * validation is off. + */ public function __construct( private readonly string $email, private readonly string $name = '', - ) {} + ) { + EmailValidator::assertSafeAddresses([$email]); + if (EmailValidator::hasLineBreakOrNul($name)) { + throw new InvalidAddressException('A display name must not contain a line break or a NUL character.'); + } + } /** * Parses `"Name" `, `` or `email` into an Address. A display * name passed explicitly takes precedence over one embedded in `$raw`. + * + * @throws InvalidAddressException When the address contains a CR, LF, NUL, + * `<` or `>`, or the name a CR, LF or NUL. */ public static function parse(string $raw, string $name = ''): self { $raw = trim($raw); + // Checked before the display name is split off, so a line break cannot + // hide in the part that is discarded when an explicit name wins. + if (EmailValidator::hasLineBreakOrNul($raw)) { + throw new InvalidAddressException('An e-mail address must not contain a line break or a NUL character.'); + } if (preg_match('/^(.*)<(.+)>$/', $raw, $matches) === 1) { if ($name === '') { $name = trim($matches[1], " \t\""); diff --git a/src/Message/Attachment.php b/src/Message/Attachment.php index 431ac3d..b4ef86f 100644 --- a/src/Message/Attachment.php +++ b/src/Message/Attachment.php @@ -16,6 +16,7 @@ namespace InitPHP\Mailer\Message; use InitPHP\Mailer\Exception\AttachmentException; +use InitPHP\Mailer\Validation\EmailValidator; use function base64_encode; use function basename; @@ -24,6 +25,7 @@ use function is_file; use function is_readable; use function mime_content_type; +use function preg_replace; use function uniqid; /** @@ -51,13 +53,23 @@ private function __construct( private readonly string $disposition, private readonly string $mimeType, private readonly string $content, - ) {} + ) { + // The name, disposition and MIME type are written into MIME headers. + foreach ([$name, $disposition, $mimeType] as $value) { + if (EmailValidator::hasLineBreakOrNul($value)) { + throw new AttachmentException( + 'An attachment name, disposition or MIME type must not contain a line break or a NUL character.', + ); + } + } + } /** * Builds an attachment from a file on disk. * - * @throws AttachmentException When the file cannot be read or its type - * cannot be detected. + * @throws AttachmentException When the file cannot be read, its type + * cannot be detected, or the name, disposition + * or MIME type contains a CR, LF or NUL. */ public static function fromPath( string $path, @@ -85,6 +97,9 @@ public static function fromPath( /** * Builds an attachment from raw, in-memory content (for example a rendered * PDF). For a stream, pass `stream_get_contents($handle)`. + * + * @throws AttachmentException When the name, disposition or MIME type + * contains a CR, LF or NUL. */ public static function fromContent( string $content, @@ -108,7 +123,8 @@ public static function fromContent( public function makeInline(): string { $this->multipart = self::MULTIPART_RELATED; - $this->cid = uniqid(basename($this->name) . '@', true); + // The name is user-supplied; keep only characters that are safe inside `<...>`. + $this->cid = uniqid((string) preg_replace('/[^A-Za-z0-9._-]/', '_', basename($this->name)) . '@', true); return $this->cid; } diff --git a/src/Message/HeaderRenderer.php b/src/Message/HeaderRenderer.php index f37ef98..dd09e40 100644 --- a/src/Message/HeaderRenderer.php +++ b/src/Message/HeaderRenderer.php @@ -15,16 +15,30 @@ namespace InitPHP\Mailer\Message; +use InitPHP\Mailer\Exception\MailerException; + +use function preg_match; +use function preg_replace; +use function strtolower; use function trim; /** * Renders an ordered map of header name => value into a header block. Empty * values are skipped, and each line is terminated with the given line ending. + * + * Every name and value is checked on the way out, so a transport never writes a + * header that was built by hand (a `PreparedEmail` is public) with a line break + * that would start another header. The only line break a value may contain is a + * fold: a line ending directly followed by a space or tab, as the Q-encoder + * produces for a long subject. */ final class HeaderRenderer { /** * @param array $headers + * + * @throws MailerException When a header name is not a valid field name, or a + * value contains a line break other than a fold, or a NUL. */ public static function render(array $headers, string $newline): string { @@ -32,10 +46,80 @@ public static function render(array $headers, string $newline): string foreach ($headers as $key => $value) { $value = trim($value); if ($value !== '') { + self::assertSafe((string) $key, $value); $out .= $key . ': ' . $value . $newline; } } return $out; } + + /** + * The set of header names in `$headers`, lower-cased and trimmed, as the keys + * of an array (`['from' => true, …]`). + * + * @param array $headers + * + * @return array + */ + public static function names(array $headers): array + { + $names = []; + foreach ($headers as $name => $_) { + $names[strtolower(trim((string) $name))] = true; + } + + return $names; + } + + /** + * `$headers` without the headers named in `$names`, compared without regard + * to case or surrounding whitespace. Transports use it to drop a custom + * header they are about to write themselves. + * + * @param array $headers + * @param list $names + * + * @return array + */ + public static function without(array $headers, array $names): array + { + $drop = []; + foreach ($names as $name) { + $drop[strtolower(trim($name))] = true; + } + + $kept = []; + foreach ($headers as $name => $value) { + if (!isset($drop[strtolower(trim((string) $name))])) { + $kept[(string) $name] = $value; + } + } + + return $kept; + } + + /** + * Whether `$name` is usable as a header field name: printable ASCII other + * than `:`, so no space, line break, NUL or colon. + */ + public static function isValidName(string $name): bool + { + return preg_match('/\A[\x21-\x39\x3B-\x7E]+\z/', $name) === 1; + } + + /** + * @throws MailerException + */ + public static function assertSafe(string $name, string $value): void + { + if (!self::isValidName($name)) { + throw new MailerException('A header name must be made of printable ASCII characters other than ":".'); + } + + $unfolded = (string) preg_replace('/(?:\r\n|\n\r|\n|\r)(?=[ \t])/', '', $value); + if (preg_match('/[\r\n\0]/', $unfolded) === 1) { + throw new MailerException(\sprintf('The "%s" header value must not contain a line break or a NUL character.', $name)); + } + } } diff --git a/src/Mime/MimeBuilder.php b/src/Mime/MimeBuilder.php index da4c84b..8b9b1ce 100644 --- a/src/Mime/MimeBuilder.php +++ b/src/Mime/MimeBuilder.php @@ -17,8 +17,10 @@ use InitPHP\Mailer\Encoding\QuotedPrintableEncoder; use InitPHP\Mailer\Encoding\WordWrapper; +use InitPHP\Mailer\Exception\MailerException; use InitPHP\Mailer\Message\Attachment; +use function addcslashes; use function mb_strlen; use function preg_match; use function preg_replace; @@ -117,7 +119,7 @@ private function buildHtml(string $html, string $altMessage, string $encoding): ]; } - $boundary = ($this->boundaryFactory)('B_ALT_'); + $boundary = $this->boundary('B_ALT_'); $body = $this->mimePreamble() . $nl . $nl . '--' . $boundary . $nl . 'Content-Type: text/plain; charset=' . $this->charset . $nl @@ -143,7 +145,7 @@ private function buildHtml(string $html, string $altMessage, string $encoding): private function buildPlainAttach(string $body, array $attachments, string $encoding): array { $nl = $this->newline; - $boundary = ($this->boundaryFactory)('B_ATC_'); + $boundary = $this->boundary('B_ATC_'); $out = $this->mimePreamble() . $nl . $nl . '--' . $boundary . $nl @@ -166,7 +168,7 @@ private function buildPlainAttach(string $body, array $attachments, string $enco private function buildHtmlAttach(string $html, string $altMessage, array $attachments, string $encoding): array { $nl = $this->newline; - $altBoundary = ($this->boundaryFactory)('B_ALT_'); + $altBoundary = $this->boundary('B_ALT_'); $body = ''; $contentHeaders = ''; $lastBoundary = null; @@ -174,12 +176,12 @@ private function buildHtmlAttach(string $html, string $altMessage, array $attach $atcBoundary = null; if ($this->hasMultipart($attachments, Attachment::MULTIPART_MIXED)) { - $atcBoundary = ($this->boundaryFactory)('B_ATC_'); + $atcBoundary = $this->boundary('B_ATC_'); $contentHeaders = 'Content-Type: multipart/mixed; boundary="' . $atcBoundary . '"'; $lastBoundary = $atcBoundary; } if ($this->hasMultipart($attachments, Attachment::MULTIPART_RELATED)) { - $relBoundary = ($this->boundaryFactory)('B_REL_'); + $relBoundary = $this->boundary('B_REL_'); $relHeader = 'Content-Type: multipart/related; boundary="' . $relBoundary . '"'; if ($lastBoundary !== null) { $body .= '--' . $lastBoundary . $nl . $relHeader; @@ -190,7 +192,7 @@ private function buildHtmlAttach(string $html, string $altMessage, array $attach $lastBoundary = $relBoundary; } if ($lastBoundary === null) { - $atcBoundary = ($this->boundaryFactory)('B_ATC_'); + $atcBoundary = $this->boundary('B_ATC_'); $contentHeaders = 'Content-Type: multipart/mixed; boundary="' . $atcBoundary . '"'; $lastBoundary = $atcBoundary; } @@ -249,7 +251,7 @@ private function appendAttachments(string &$body, string $boundary, ?string $mul } $cid = $attachment->getCid(); $body .= '--' . $boundary . $this->newline - . 'Content-Type: ' . $attachment->getMimeType() . '; name="' . $attachment->getName() . '"' . $this->newline + . 'Content-Type: ' . $attachment->getMimeType() . '; name="' . addcslashes($attachment->getName(), '"\\') . '"' . $this->newline . 'Content-Disposition: ' . $attachment->getDisposition() . ';' . $this->newline . 'Content-Transfer-Encoding: base64' . $this->newline . ($cid !== null ? 'Content-ID: <' . $cid . '>' . $this->newline : '') @@ -262,6 +264,22 @@ private function appendAttachments(string &$body, string $boundary, ?string $mul } } + /** + * Asks the factory for a boundary and refuses one that could break out of + * the quoted `boundary="..."` parameter or start another header. + * + * @throws MailerException + */ + private function boundary(string $prefix): string + { + $boundary = ($this->boundaryFactory)($prefix); + if ($boundary === '' || preg_match('/[\r\n\0"]/', $boundary) === 1) { + throw new MailerException('A MIME boundary must not be empty or contain a quote, a line break or a NUL character.'); + } + + return $boundary; + } + private function mimePreamble(): string { return 'This is a multi-part message in MIME format.' . $this->newline diff --git a/src/Transport/MailTransport.php b/src/Transport/MailTransport.php index 57838a4..ac3e684 100644 --- a/src/Transport/MailTransport.php +++ b/src/Transport/MailTransport.php @@ -56,7 +56,19 @@ public function __construct( public function send(PreparedEmail $email): void { - $headers = $email->headers; + EmailValidator::assertSafeAddresses([...$email->to, ...$email->bcc]); + HeaderRenderer::assertSafe('Subject', $email->subject); + + // To (when there are recipients) and Subject travel as mail() arguments, + // so a custom header of that name would only duplicate them. + $drop = ['Subject']; + if ($email->to !== []) { + $drop[] = 'To'; + } + if ($email->bcc !== []) { + $drop[] = 'Bcc'; + } + $headers = HeaderRenderer::without($email->headers, $drop); if ($email->bcc !== []) { $headers['Bcc'] = implode(', ', $email->bcc); } diff --git a/src/Transport/SendmailTransport.php b/src/Transport/SendmailTransport.php index 9b62d38..cdaad3e 100644 --- a/src/Transport/SendmailTransport.php +++ b/src/Transport/SendmailTransport.php @@ -50,11 +50,23 @@ public function __construct( public function send(PreparedEmail $email): void { + EmailValidator::assertSafeAddresses([...$email->to, ...$email->bcc]); + $from = $email->from->getEmail(); $fromArg = $this->validator->isShellSafe($from) ? '-f ' . $from : ''; - $headers = $email->headers; - $headers['To'] = implode(', ', $email->to); + // A custom To or Bcc only gives way when the library writes one. + $drop = ['Subject']; + if ($email->to !== []) { + $drop[] = 'To'; + } + if ($email->bcc !== []) { + $drop[] = 'Bcc'; + } + $headers = HeaderRenderer::without($email->headers, $drop); + if ($email->to !== []) { + $headers['To'] = implode(', ', $email->to); + } $headers['Subject'] = $email->subject; if ($email->bcc !== []) { $headers['Bcc'] = implode(', ', $email->bcc); diff --git a/src/Transport/Smtp/SocketClientInterface.php b/src/Transport/Smtp/SocketClientInterface.php index 6e2809b..7da753c 100644 --- a/src/Transport/Smtp/SocketClientInterface.php +++ b/src/Transport/Smtp/SocketClientInterface.php @@ -47,7 +47,9 @@ public function write(string $bytes): void; public function readLine(int $length = 512): string|false; /** - * Enables TLS on the open connection. + * Enables TLS on the open connection. Returns false when the handshake + * fails, or when unread plain-text bytes are still buffered (see + * {@see StreamSocketClient::enableCrypto()}). */ public function enableCrypto(int $cryptoMethod): bool; diff --git a/src/Transport/Smtp/StreamSocketClient.php b/src/Transport/Smtp/StreamSocketClient.php index e41f714..d1af147 100644 --- a/src/Transport/Smtp/StreamSocketClient.php +++ b/src/Transport/Smtp/StreamSocketClient.php @@ -21,6 +21,7 @@ use function fgets; use function fsockopen; use function fwrite; +use function stream_get_meta_data; use function stream_set_timeout; use function stream_socket_enable_crypto; use function substr; @@ -104,8 +105,19 @@ public function readLine(int $length = 512): string|false public function enableCrypto(int $cryptoMethod): bool { - return \is_resource($this->socket) - && stream_socket_enable_crypto($this->socket, true, $cryptoMethod) === true; + if (!\is_resource($this->socket)) { + return false; + } + + // Bytes that arrived in clear text together with the STARTTLS reply are + // still in PHP's read buffer and would be read after the handshake as + // if the TLS peer had sent them (STARTTLS response injection). A server + // never sends anything between its "220" and the handshake, so refuse. + if (stream_get_meta_data($this->socket)['unread_bytes'] > 0) { + return false; + } + + return stream_socket_enable_crypto($this->socket, true, $cryptoMethod) === true; } public function close(): void diff --git a/src/Transport/SmtpTransport.php b/src/Transport/SmtpTransport.php index 0b8d7d6..7d2f5f9 100644 --- a/src/Transport/SmtpTransport.php +++ b/src/Transport/SmtpTransport.php @@ -20,12 +20,14 @@ use InitPHP\Mailer\Message\HeaderRenderer; use InitPHP\Mailer\Message\PreparedEmail; use InitPHP\Mailer\Transport\Smtp\SocketClientInterface; +use InitPHP\Mailer\Validation\EmailValidator; use Throwable; use function array_merge; use function base64_encode; use function implode; use function preg_replace; +use function preg_replace_callback; use function strncmp; use function strstr; use function substr; @@ -63,32 +65,60 @@ public function send(PreparedEmail $email): void throw new ConfigurationException('No SMTP host has been configured.'); } - $this->connect(); - $this->authenticate(); - - $this->command('MAIL FROM:<' . $email->from->getEmail() . '>', 250); - foreach (array_merge($email->to, $email->cc, $email->bcc) as $recipient) { - if ($recipient !== '') { - $this->command($this->rcpt($recipient), 250); - } + // Everything that is written to the wire is checked, and the message is + // rendered, before a connection is opened: a bad recipient, hostname or + // header never reaches the socket, and never leaves a half-open + // connection behind. The sender is an Address, which already refuses + // unsafe characters. + EmailValidator::assertSafeAddresses([...$email->to, ...$email->cc, ...$email->bcc]); + if (EmailValidator::hasLineBreakOrNul($this->hostname)) { + throw new TransportException('The SMTP client hostname must not contain a line break or a NUL character.'); } - $this->command('DATA', 354); - $headers = $email->headers; - $headers['To'] = implode(', ', $email->to); + // A custom To only gives way when the library writes one. + $headers = HeaderRenderer::without($email->headers, $email->to === [] ? ['Subject'] : ['To', 'Subject']); + if ($email->to !== []) { + $headers['To'] = implode(', ', $email->to); + } $headers['Subject'] = $email->subject; $message = HeaderRenderer::render($headers, $this->newline) . $email->contentHeaders . $this->newline . $this->newline . $email->body; - // Dot-stuffing: any line starting with "." must be escaped to "..". - $message = (string) preg_replace('/^\./m', '..', $message); + // Dot-stuffing: any line starting with "." must be escaped to "..". A line + // starts at the beginning of the message and after any CR or LF, because + // the configured newline may be a bare "\r" or "\n\r". + $message = (string) preg_replace('/(?client->write($message . $this->newline . '.' . $this->newline); - $reply = $this->readReply(); - if (strncmp($reply, '250', 3) !== 0) { - throw new TransportException('The SMTP server rejected the message: ' . trim($reply), $this->code($reply)); - } + try { + $this->connect(); + $this->authenticate(); + + $this->command('MAIL FROM:<' . $email->from->getEmail() . '>', 250); + foreach (array_merge($email->to, $email->cc, $email->bcc) as $recipient) { + if ($recipient !== '') { + $this->command($this->rcpt($recipient), 250); + } + } + $this->command('DATA', 354); + + $this->client->write($message . $this->newline . '.' . $this->newline); + $reply = $this->readReply(); + if (strncmp($reply, '250', 3) !== 0) { + throw new TransportException( + 'The SMTP server rejected the message: ' . trim($reply), + $this->code($reply), + ); + } + + $this->finish(); + } catch (Throwable $e) { + // The state of the conversation is unknown. Drop the connection so + // the next send() starts from a fresh greeting, EHLO, STARTTLS and + // AUTH instead of reusing a socket that never finished (or failed) + // its TLS upgrade and sending the credentials in clear text. + $this->disconnect(); - $this->finish(); + throw $e; + } } public function __destruct() @@ -118,7 +148,13 @@ private function connect(): void } $this->client->open($prefix . $this->host, $this->port, $this->timeout); - $this->readReply(); + $greeting = $this->readReply(); + if (strncmp($greeting, '220', 3) !== 0) { + throw new TransportException( + 'The SMTP server did not greet the connection: ' . trim($greeting), + $this->code($greeting), + ); + } if ($this->crypto === 'tls') { $this->command($this->hello(), 250); @@ -171,7 +207,18 @@ private function finish(): void } $this->client->write('QUIT' . $this->newline); $this->readReply(); - $this->client->close(); + $this->disconnect(); + } + + /** + * Closes the connection and forgets that it was authenticated. + */ + private function disconnect(): void + { + $this->authenticated = false; + if ($this->client->isOpen()) { + $this->client->close(); + } } private function hello(): string @@ -182,12 +229,26 @@ private function hello(): string private function rcpt(string $address): string { if ($this->dsn) { - return 'RCPT TO:<' . $address . '> NOTIFY=SUCCESS,DELAY,FAILURE ORCPT=rfc822;' . $address; + return 'RCPT TO:<' . $address . '> NOTIFY=SUCCESS,DELAY,FAILURE ORCPT=rfc822;' . $this->xtext($address); } return 'RCPT TO:<' . $address . '>'; } + /** + * Encodes an address as RFC 3461 `xtext` for the `ORCPT` parameter: every + * byte outside `!`..`~`, and `+` and `=` themselves, becomes `+XX`, so a + * space or another delimiter in an address cannot start a new parameter. + */ + private function xtext(string $value): string + { + return (string) preg_replace_callback( + '/[^\x21-\x2A\x2C-\x3C\x3E-\x7E]/', + static fn(array $match): string => \sprintf('+%02X', \ord($match[0])), + $value, + ); + } + private function command(string $command, int $expected): string { $this->client->write($command . $this->newline); diff --git a/src/Validation/EmailValidator.php b/src/Validation/EmailValidator.php index 32abb7e..ca89089 100644 --- a/src/Validation/EmailValidator.php +++ b/src/Validation/EmailValidator.php @@ -62,6 +62,45 @@ public function assertAllValid(iterable $emails): void } } + /** + * Whether the value contains a CR, LF or NUL character. Such a character + * ends a header line or an SMTP command, so it must never reach either; the + * check does not depend on the `validate` option. + */ + public static function hasLineBreakOrNul(string $value): bool + { + return preg_match('/[\r\n\0]/', $value) === 1; + } + + /** + * Whether the address contains a character that would end or extend an SMTP + * path or a header line: CR, LF, NUL, `<` or `>`. An address that has one + * could add parameters (` SIZE=1`) to `MAIL FROM` / `RCPT TO`. + */ + public static function hasUnsafeAddressChar(string $value): bool + { + return preg_match('/[\r\n\0<>]/', $value) === 1; + } + + /** + * Throws when any address contains a character that {@see hasUnsafeAddressChar()} + * reports. Checked whether or not address validation is on. + * + * @param iterable $emails + * + * @throws InvalidAddressException + */ + public static function assertSafeAddresses(iterable $emails): void + { + foreach ($emails as $email) { + if (self::hasUnsafeAddressChar($email)) { + throw new InvalidAddressException( + 'An e-mail address must not contain a line break, a NUL character, "<" or ">".', + ); + } + } + } + /** * Whether the address is safe to pass to a shell as a `-f` envelope sender. * It must both pass the e-mail filter unchanged and match a conservative diff --git a/tests/CustomRecipientHeadersTest.php b/tests/CustomRecipientHeadersTest.php new file mode 100644 index 0000000..85cf719 --- /dev/null +++ b/tests/CustomRecipientHeadersTest.php @@ -0,0 +1,250 @@ + "\n"])->setTransport(new SendmailTransport( + '/usr/sbin/sendmail', + new EmailValidator(), + static function (string $command, string $raw) use (&$message): int { + $message = $raw; + + return 0; + }, + )); + $mailer->setFrom('s@example.com')->setSubject('Subject')->setMessage('Body'); + $setup($mailer); + $mailer->send(); + + return $message; + } + + /** + * @param callable(Mailer): mixed $setup + */ + private function viaSmtp(callable $setup, int $recipients): string + { + $replies = ["220 hi\r\n", "250 ehlo\r\n", "250 from\r\n"]; + for ($i = 0; $i < $recipients; ++$i) { + $replies[] = "250 rcpt\r\n"; + } + $replies = [...$replies, "354 data\r\n", "250 queued\r\n", "221 bye\r\n"]; + $client = new FakeSocketClient($replies); + + $mailer = Mailer::newInstance(['newline' => "\n"])->setTransport(new SmtpTransport( + $client, + 'mx.example.com', + 25, + 5, + '', + false, + '', + '', + false, + false, + true, + 'localhost', + "\n", + )); + $mailer->setFrom('s@example.com')->setSubject('Subject')->setMessage('Body'); + $setup($mailer); + $mailer->send(); + + return $client->conversation(); + } + + /** + * @param callable(Mailer): mixed $setup + */ + private function viaMail(callable $setup): string + { + $captured = ''; + $mailer = Mailer::newInstance(['newline' => "\n"])->setTransport(new MailTransport( + new EmailValidator(), + static function (string $to, string $subject, string $message, string $headers) use (&$captured): bool { + $captured = $headers; + + return true; + }, + )); + $mailer->setFrom('s@example.com')->setSubject('Subject')->setMessage('Body'); + $setup($mailer); + $mailer->send(); + + return $captured; + } + + /** + * The header lines of `$message` whose name is `$name` (case-insensitive). + * + * @return list + */ + private function lines(string $message, string $name): array + { + return array_values(array_filter( + explode("\n", $message), + static fn(string $line): bool => preg_match('/^' . $name . ':/i', $line) === 1, + )); + } + + public function testSendmailKeepsACustomCcAndBccWhenThereAreNoRecipientsOfThatKind(): void + { + $message = $this->viaSendmail( + static fn(Mailer $m) => $m->setTo('t@example.com')->setHeader('Bcc', 'archive@co.example')->setHeader('Cc', 'c@co.example'), + ); + + // Same lines as 3.0.0. + self::assertSame(['Bcc: archive@co.example'], $this->lines($message, 'Bcc')); + self::assertSame(['Cc: c@co.example'], $this->lines($message, 'Cc')); + } + + public function testSendmailRealBccWinsOverACustomBcc(): void + { + $message = $this->viaSendmail( + static fn(Mailer $m) => $m->setTo('t@example.com')->setBCC('real@example.com')->setHeader('Bcc', 'archive@co.example'), + ); + + // Same single line as 3.0.0. + self::assertSame(['Bcc: real@example.com'], $this->lines($message, 'Bcc')); + } + + public function testSendmailRealBccWinsWhateverTheCaseOfTheCustomName(): void + { + $message = $this->viaSendmail( + static fn(Mailer $m) => $m->setTo('t@example.com')->setBCC('real@example.com')->setHeader('bCC', 'archive@co.example'), + ); + + // 3.0.0 wrote both a "bCC:" and a "Bcc:" line. + self::assertSame(['Bcc: real@example.com'], $this->lines($message, 'Bcc')); + } + + public function testSendmailRealCcToAndSubjectWinWhateverTheCase(): void + { + $message = $this->viaSendmail( + static fn(Mailer $m) => $m->setTo('t@example.com')->setCC('real@example.com') + ->setHeader('CC', 'archive@co.example') + ->setHeader('to', 'other@co.example') + ->setHeader('SUBJECT', 'evil'), + ); + + self::assertSame(['Cc: real@example.com'], $this->lines($message, 'Cc')); + self::assertSame(['To: t@example.com'], $this->lines($message, 'To')); + self::assertCount(1, $this->lines($message, 'Subject')); + self::assertStringNotContainsString('evil', $message); + } + + public function testSmtpKeepsACustomCcAndBccTheTransportDoesNotWrite(): void + { + $data = $this->viaSmtp( + static fn(Mailer $m) => $m->setTo('t@example.com')->setHeader('Bcc', 'archive@co.example')->setHeader('Cc', 'c@co.example'), + 1, + ); + + // Same lines as 3.0.0 (SMTP never writes a Bcc header itself). + self::assertSame(['Bcc: archive@co.example'], $this->lines($data, 'Bcc')); + self::assertSame(['Cc: c@co.example'], $this->lines($data, 'Cc')); + } + + public function testSmtpRealCcToAndSubjectWinWhateverTheCase(): void + { + $data = $this->viaSmtp( + static fn(Mailer $m) => $m->setTo('t@example.com')->setCC('real@example.com') + ->setHeader('cC', 'archive@co.example') + ->setHeader('tO', 'other@co.example') + ->setHeader('subject', 'evil'), + 2, + ); + + self::assertSame(['Cc: real@example.com'], $this->lines($data, 'Cc')); + self::assertSame(['To: t@example.com'], $this->lines($data, 'To')); + self::assertCount(1, $this->lines($data, 'Subject')); + self::assertStringNotContainsString('evil', $data); + } + + public function testMailKeepsACustomCcAndRealBccWins(): void + { + $headers = $this->viaMail( + static fn(Mailer $m) => $m->setTo('t@example.com')->setBCC('real@example.com') + ->setHeader('bcc', 'archive@co.example') + ->setHeader('Cc', 'c@co.example'), + ); + + self::assertSame(['Bcc: real@example.com'], $this->lines($headers, 'Bcc')); + self::assertSame(['Cc: c@co.example'], $this->lines($headers, 'Cc')); + } + + public function testBccBatchesAfterTheFirstDoNotCarryACustomToWhenTheMessageHasATo(): void + { + $messages = []; + $mailer = Mailer::newInstance(['newline' => "\n"])->setTransport(new SendmailTransport( + '/usr/sbin/sendmail', + new EmailValidator(), + static function (string $command, string $raw) use (&$messages): int { + $messages[] = $raw; + + return 0; + }, + )); + $mailer->setFrom('s@example.com')->setSubject('Subject')->setMessage('Body') + ->setTo('t@example.com') + ->setBCC(['b1@example.com', 'b2@example.com', 'b3@example.com'], 2) + ->setHeader('To', 'other@co.example') + ->send(); + + self::assertCount(2, $messages); + self::assertSame(['To: t@example.com'], $this->lines($messages[0], 'To')); + self::assertSame([], $this->lines($messages[1], 'To')); + } + + public function testBccOnlyBatchesKeepACustomTo(): void + { + $messages = []; + $mailer = Mailer::newInstance(['newline' => "\n"])->setTransport(new SendmailTransport( + '/usr/sbin/sendmail', + new EmailValidator(), + static function (string $command, string $raw) use (&$messages): int { + $messages[] = $raw; + + return 0; + }, + )); + $mailer->setFrom('s@example.com')->setSubject('Subject')->setMessage('Body') + ->setBCC(['b1@example.com', 'b2@example.com', 'b3@example.com'], 2) + ->setHeader('To', 'undisclosed-recipients:;') + ->send(); + + self::assertCount(2, $messages); + foreach ($messages as $message) { + self::assertSame(['To: undisclosed-recipients:;'], $this->lines($message, 'To')); + } + } +} diff --git a/tests/Encoding/QEncoderTest.php b/tests/Encoding/QEncoderTest.php index bf0b0af..07dda2e 100644 --- a/tests/Encoding/QEncoderTest.php +++ b/tests/Encoding/QEncoderTest.php @@ -62,4 +62,50 @@ public function testLongInputIsFoldedWithinTheLineLimit(): void $this->assertLessThanOrEqual(78, \strlen($line)); } } + + public function testStripsLineBreaksAndNul(): void + { + $encoded = $this->utf8()->encode("Hello\r\nBcc: x@example.test\0"); + + $this->assertSame('HelloBcc: x@example.test', iconv_mime_decode($encoded, 0, 'UTF-8')); + $this->assertStringNotContainsString("\0", $encoded); + } + + public function testInvalidUtf8IsReplacedWithoutNotices(): void + { + $encoded = $this->utf8()->encode("Caf\xE9 ok \xFF"); + + $this->assertSame('Caf? ok ?', iconv_mime_decode($encoded, 0, 'UTF-8')); + } + + public function testInvalidUtf8InALongValueStillFolds(): void + { + $encoded = $this->utf8()->encode(str_repeat("\xFF ab", 40)); + + $this->assertSame(str_repeat('? ab', 40), iconv_mime_decode($encoded, 0, 'UTF-8')); + } + + public function testANonUtf8CharsetProducesValidEncodedWords(): void + { + $encoder = new QEncoder('ISO-8859-1', "\r\n"); + + $encoded = $encoder->encode("Caf\xE9"); + + $this->assertStringStartsWith('=?ISO-8859-1?Q?', $encoded); + $this->assertSame("Caf\xE9", iconv_mime_decode($encoded, 0, 'ISO-8859-1')); + } + + public function testANonUtf8CharsetFoldsLongValuesIntoDecodableLines(): void + { + $encoder = new QEncoder('ISO-8859-9', "\r\n"); + $subject = str_repeat("\xFE ok ", 30); + + $encoded = $encoder->encode($subject); + + $this->assertStringContainsString("\r\n =?ISO-8859-9?Q?", $encoded); + foreach (explode("\r\n", $encoded) as $line) { + $this->assertLessThanOrEqual(78, \strlen($line)); + } + $this->assertSame($subject, iconv_mime_decode($encoded, 0, 'ISO-8859-9')); + } } diff --git a/tests/HeaderInjectionTest.php b/tests/HeaderInjectionTest.php new file mode 100644 index 0000000..1211ee8 --- /dev/null +++ b/tests/HeaderInjectionTest.php @@ -0,0 +1,429 @@ + $config + */ + private function mailer(array $config = []): Mailer + { + $this->transport = new RecordingTransport(); + + return Mailer::newInstance($config)->setTransport($this->transport); + } + + /** + * @return array + */ + public static function validationModes(): array + { + return ['validation on' => [true], 'validation off' => [false]]; + } + + /** + * @return array + */ + public static function unsafeAddresses(): array + { + return [ + 'CRLF header injection' => ["a@example.com\r\nBcc: attacker@example.test"], + 'LF only' => ["a@example.com\nBcc: attacker@example.test"], + 'CR only' => ["a@example.com\rBcc: attacker@example.test"], + 'NUL' => ["a@example.com\0.evil"], + ]; + } + + /** + * @dataProvider validationModes + */ + public function testSetFromRejectsAnUnsafeAddressRegardlessOfValidate(bool $validate): void + { + $this->expectException(InvalidAddressException::class); + + $this->mailer(['validate' => $validate])->setFrom("a@example.com\r\nBcc: attacker@example.test"); + } + + /** + * @dataProvider validationModes + */ + public function testSetFromRejectsAnUnsafeNameRegardlessOfValidate(bool $validate): void + { + $this->expectException(InvalidAddressException::class); + + $this->mailer(['validate' => $validate])->setFrom('a@example.com', "Name\r\nBcc: attacker@example.test"); + } + + /** + * @dataProvider validationModes + */ + public function testSetFromRejectsAnUnsafeReturnPathRegardlessOfValidate(bool $validate): void + { + $this->expectException(InvalidAddressException::class); + + $this->mailer(['validate' => $validate]) + ->setFrom('a@example.com', '', "bounce@example.com>\r\nBcc: attacker@example.test"); + } + + /** + * @dataProvider validationModes + */ + public function testSetReplyToRejectsAnUnsafeAddressRegardlessOfValidate(bool $validate): void + { + $this->expectException(InvalidAddressException::class); + + $this->mailer(['validate' => $validate])->setReplyTo("a@example.com\r\nBcc: attacker@example.test"); + } + + /** + * @dataProvider unsafeAddresses + */ + public function testRecipientArraysRejectUnsafeAddressesWithValidationOff(string $address): void + { + foreach (['setTo', 'setCC', 'setBCC'] as $method) { + try { + $this->mailer(['validate' => false])->{$method}([$address]); + self::fail($method . '() accepted an unsafe address.'); + } catch (InvalidAddressException) { + $this->addToAssertionCount(1); + } + } + } + + public function testRejectedRecipientLeavesThePreviousListUntouched(): void + { + $mailer = $this->mailer(['validate' => false])->setFrom('s@example.com')->setTo('ok@example.com'); + + try { + $mailer->setTo(["x@example.com\r\nBcc: attacker@example.test"]); + self::fail('Expected an InvalidAddressException.'); + } catch (InvalidAddressException) { + // Expected. + } + $mailer->send(); + + self::assertSame(['ok@example.com'], $this->transport->last()->to); + } + + public function testRecipientStringWithLineBreaksIsStillSplitIntoSeparateAddresses(): void + { + $this->mailer()->setFrom('s@example.com')->setTo("a@example.com\nb@example.com")->send(); + + self::assertSame(['a@example.com', 'b@example.com'], $this->transport->last()->to); + } + + public function testTrailingLineBreakOfARecipientIsTrimmedNotRejected(): void + { + $this->mailer()->setFrom('s@example.com')->setTo(["a@example.com\r\n"])->send(); + + self::assertSame(['a@example.com'], $this->transport->last()->to); + } + + public function testSetHeaderRejectsAnUnsafeName(): void + { + $this->expectException(MailerException::class); + + $this->mailer()->setHeader("X-Custom\r\nBcc: attacker@example.test", 'value'); + } + + public function testSetHeaderRejectsANulInTheName(): void + { + $this->expectException(MailerException::class); + + $this->mailer()->setHeader("X-Custom\0", 'value'); + } + + /** + * The value keeps the pre-existing, documented behaviour: line breaks are + * stripped rather than rejected, so a value with a trailing newline keeps + * working. Either way no header can be injected. + */ + public function testSetHeaderStillStripsLineBreaksAndNulFromTheValue(): void + { + $this->mailer(['validate' => false]) + ->setFrom('s@example.com') + ->setTo('a@example.com') + ->setHeader('X-Custom', "value\r\nBcc: attacker@example.test\0\n") + ->send(); + + $value = $this->transport->last()->headers['X-Custom']; + self::assertSame('valueBcc: attacker@example.test', $value); + } + + public function testSubjectLineBreaksAndNulAreStrippedFromTheHeader(): void + { + $this->mailer(['validate' => false]) + ->setFrom('s@example.com') + ->setTo('a@example.com') + ->setSubject("Hello\r\nBcc: attacker@example.test\0") + ->send(); + + // Decoding shows what the header says: with the line breaks left in, the + // Q-encoded value would decode to "Hello\r\nBcc: ...". + $subject = $this->transport->last()->subject; + self::assertSame('HelloBcc: attacker@example.test', iconv_mime_decode($subject, 0, 'UTF-8')); + self::assertStringNotContainsString("\0", $subject); + } + + public function testAnUnsafeConfiguredSenderIsRejectedAtSendTime(): void + { + $mailer = $this->mailer(['validate' => false, 'fromEmail' => "a@example.com\r\nBcc: attacker@example.test"]) + ->setTo('rcpt@example.com'); + + $this->expectException(InvalidAddressException::class); + + $mailer->send(); + } + + /** + * @return array + */ + public static function configuredSenders(): array + { + $cases = [ + 'trailing LF' => ["a@example.com\n", ''], + 'trailing CRLF CRLF' => ["a@example.com\r\n\r\n", ''], + 'trailing NUL' => ["a@example.com\0", ''], + ]; + $out = []; + foreach ($cases as $label => [$email, $name]) { + $out[$label . ', validate on'] = [$email, $name, true]; + $out[$label . ', validate off'] = [$email, $name, false]; + } + + return $out; + } + + /** + * @dataProvider configuredSenders + */ + public function testMessageIdIsBuiltFromTheParsedConfiguredSender(string $email, string $name, bool $validate): void + { + $mailer = $this->mailer(['fromEmail' => $email, 'fromName' => $name, 'validate' => $validate]); + + self::assertSame(1, preg_match('/\A<[^\r\n\0]+@example\.com>\z/', $mailer->getMessageID())); + + $mailer->setTo('rcpt@example.com')->send(); + $messageId = $this->transport->last()->headers['Message-ID']; + self::assertSame(1, preg_match('/\A<[^\r\n\0]+@example\.com>\z/', $messageId)); + } + + /** + * @dataProvider validationModes + */ + public function testAHiddenLineBreakInTheConfiguredSenderIsRejected(bool $validate): void + { + // The explicit name wins, so the part of the address that carries the line + // breaks is the discarded "display name" of the embedded form. + $mailer = $this->mailer([ + 'fromName' => 'App', + 'fromEmail' => "x@y\rBcc: evil@z.com\rX: ", + 'validate' => $validate, + ]); + + try { + $mailer->getMessageID(); + self::fail('getMessageID() accepted an unsafe configured sender.'); + } catch (InvalidAddressException) { + $this->addToAssertionCount(1); + } + + $this->expectException(InvalidAddressException::class); + $mailer->setTo('rcpt@example.com')->send(); + } + + /** + * @return array + */ + public static function angleBracketAddresses(): array + { + return [ + 'RCPT parameter' => ['v@x.com> NOTIFY=NEVER'], + 'MAIL parameter' => ['a@example.com> SIZE=1'], + 'opening bracket' => ['v@x.com ['v@x.com'], + ]; + } + + /** + * @dataProvider angleBracketAddresses + */ + public function testAnglesBracketsCannotAddSmtpParametersWithValidationOff(string $address): void + { + foreach (['setTo', 'setCC', 'setBCC'] as $method) { + try { + $this->mailer(['validate' => false])->{$method}([$address]); + self::fail($method . '() accepted "' . $address . '".'); + } catch (InvalidAddressException) { + $this->addToAssertionCount(1); + } + } + + try { + $this->mailer(['validate' => false])->setFrom('s@example.com', '', $address); + self::fail('setFrom() accepted the return path "' . $address . '".'); + } catch (InvalidAddressException) { + $this->addToAssertionCount(1); + } + + $this->expectException(InvalidAddressException::class); + $this->mailer(['validate' => false])->setFrom($address); + } + + public function testASurroundingAngleBracketPairStillWorks(): void + { + $this->mailer(['validate' => false])->setFrom('')->setTo([''])->send(); + + self::assertSame(['a@example.com'], $this->transport->last()->to); + } + + public function testSetAltMessageStripsCarriageReturns(): void + { + $this->mailer()->setFrom('s@example.com')->setTo('a@example.com') + ->setMailType('html')->setMessage('

x

')->setAltMessage("one\r\ntwo\r.three\r")->send(); + + self::assertStringNotContainsString("\r", $this->transport->last()->body); + self::assertStringContainsString("one\ntwo.three", $this->transport->last()->body); + } + + /** + * @return array + */ + public static function reservedHeaderNames(): array + { + return [ + 'lower-case from' => ['from'], + 'message-id' => ['message-id'], + 'content-type' => ['Content-Type'], + 'return-path' => ['RETURN-PATH'], + 'x-mailer' => ['x-mailer'], + ]; + } + + /** + * @dataProvider reservedHeaderNames + */ + public function testReservedHeadersWinWhateverTheCaseOfTheName(string $name): void + { + $this->mailer() + ->setFrom('s@example.com') + ->setTo('a@example.com') + ->setHeader($name, 'evil@example.test') + ->setHeader('X-Keep', 'kept') + ->send(); + + $headers = $this->transport->last()->headers; + $lower = array_map('strtolower', array_keys($headers)); + self::assertSame(array_unique($lower), $lower, 'No header may appear twice.'); + self::assertNotContains('evil@example.test', $headers); + self::assertSame('kept', $headers['X-Keep']); + } + + /** + * @return array + */ + public static function invalidHeaderNames(): array + { + return [ + 'trailing space' => ['From '], + 'inner space' => ['X Y'], + 'colon' => ['X: y'], + 'trailing colon' => ['X-A:'], + 'tab' => ["X\tY"], + 'empty' => [''], + 'non-ASCII' => ['X-Ünï'], + 'DEL' => ["X\x7F"], + ]; + } + + /** + * @dataProvider invalidHeaderNames + */ + public function testSetHeaderRejectsNamesThatAreNotFieldNames(string $name): void + { + $this->expectException(MailerException::class); + + $this->mailer()->setHeader($name, 'value'); + } + + public function testAQuoteInAnAttachmentNameCannotBreakOutOfTheParameter(): void + { + $this->mailer()->setFrom('s@example.com')->setTo('a@example.com') + ->attachContent('x', 'a"; filename="evil.exe', 'attachment', 'text/plain')->send(); + + $body = $this->transport->last()->body; + self::assertStringContainsString('name="a\\"; filename=\\"evil.exe"', $body); + } + + public function testABoundaryFactoryCannotInjectHeaders(): void + { + $mailer = $this->mailer()->setFrom('s@example.com')->setTo('a@example.com') + ->attachContent('x', 'a.txt') + ->setBoundaryFactory(static fn(string $prefix): string => "b\"\r\nBcc: e@z.com"); + + $this->expectException(MailerException::class); + + $mailer->send(); + } + + public function testAnEmptyBoundaryIsRejected(): void + { + $mailer = $this->mailer()->setFrom('s@example.com')->setTo('a@example.com') + ->attachContent('x', 'a.txt') + ->setBoundaryFactory(static fn(string $prefix): string => ''); + + $this->expectException(MailerException::class); + + $mailer->send(); + } + + public function testACustomHeaderTheLibraryDoesNotWriteIsKept(): void + { + $this->mailer() + ->setFrom('s@example.com') + ->setTo('a@example.com') + ->setHeader('Cc', 'c@co.example') + ->setHeader('Bcc', 'archive@co.example') + ->setHeader('X-Keep', 'kept') + ->send(); + + $headers = $this->transport->last()->headers; + self::assertSame('c@co.example', $headers['Cc']); + self::assertSame('archive@co.example', $headers['Bcc']); + } + + public function testACustomCcLosesToTheRealCcWhateverTheCase(): void + { + $this->mailer() + ->setFrom('s@example.com') + ->setTo('a@example.com') + ->setCC('real@example.com') + ->setHeader('cc', 'archive@co.example') + ->send(); + + $headers = $this->transport->last()->headers; + self::assertSame('real@example.com', $headers['Cc']); + self::assertArrayNotHasKey('cc', $headers); + } +} diff --git a/tests/MailerConfigTest.php b/tests/MailerConfigTest.php index ffabca1..c170904 100644 --- a/tests/MailerConfigTest.php +++ b/tests/MailerConfigTest.php @@ -4,6 +4,7 @@ namespace InitPHP\Mailer\Tests; +use InitPHP\Mailer\Exception\ConfigurationException; use InitPHP\Mailer\MailerConfig; use PHPUnit\Framework\TestCase; @@ -76,4 +77,26 @@ public function testIgnoresInvalidNewline(): void $this->assertSame(\PHP_EOL, (new MailerConfig(['newline' => 'xx']))->newline); $this->assertSame("\r\n", (new MailerConfig(['newline' => "\r\n"]))->newline); } + + /** + * @dataProvider unsafeHeaderOptions + */ + public function testRejectsALineBreakOrNulInAHeaderOption(string $option, string $value): void + { + $this->expectException(ConfigurationException::class); + + new MailerConfig([$option => $value]); + } + + /** + * @return array + */ + public static function unsafeHeaderOptions(): array + { + return [ + 'CRLF in userAgent' => ['userAgent', "Agent\r\nBcc: x@example.test"], + 'NUL in userAgent' => ['userAgent', "Agent\0"], + 'LF in charset' => ['charset', "utf-8\nBcc: x@example.test"], + ]; + } } diff --git a/tests/Message/AddressTest.php b/tests/Message/AddressTest.php index b096def..b2fd3f7 100644 --- a/tests/Message/AddressTest.php +++ b/tests/Message/AddressTest.php @@ -4,6 +4,7 @@ namespace InitPHP\Mailer\Tests\Message; +use InitPHP\Mailer\Exception\InvalidAddressException; use InitPHP\Mailer\Message\Address; use PHPUnit\Framework\TestCase; @@ -49,4 +50,80 @@ public function testExplicitNameWinsOverEmbeddedName(): void $this->assertSame('user@example.com', $address->getEmail()); $this->assertSame('Explicit', $address->getName()); } + + /** + * @dataProvider unsafeParts + */ + public function testRejectsALineBreakOrNulInTheAddressOrName(string $email, string $name): void + { + $this->expectException(InvalidAddressException::class); + + new Address($email, $name); + } + + /** + * @return array + */ + public static function unsafeParts(): array + { + return [ + 'CRLF in the address' => ["a@example.com\r\nBcc: x@example.test", ''], + 'LF in the address' => ["a@example.com\nBcc: x@example.test", ''], + 'CR in the address' => ["a@example.com\rBcc: x@example.test", ''], + 'NUL in the address' => ["a@example.com\0", ''], + 'CRLF in the name' => ['a@example.com', "Name\r\nBcc: x@example.test"], + 'NUL in the name' => ['a@example.com', "Na\0me"], + ]; + } + + public function testParseRejectsALineBreakInsideAnEmbeddedNameOrAddress(): void + { + $this->expectException(InvalidAddressException::class); + + Address::parse("Name "); + } + + public function testParseStillTrimsASurroundingLineBreak(): void + { + $address = Address::parse(" a@example.com\r\n"); + + $this->assertSame('a@example.com', $address->getEmail()); + } + + public function testParseRejectsALineBreakHiddenInTheNameThatWouldBeDiscarded(): void + { + $this->expectException(InvalidAddressException::class); + + // The explicit name wins, so the embedded "name" is thrown away; the + // line break must be caught before that. + Address::parse("Evil\rBcc: x@example.test ", 'Explicit'); + } + + /** + * @dataProvider angleBrackets + */ + public function testRejectsAnAngleBracketInsideTheAddress(string $email): void + { + $this->expectException(InvalidAddressException::class); + + new Address($email); + } + + /** + * @return array + */ + public static function angleBrackets(): array + { + return [ + 'closing' => ['v@x.com> NOTIFY=NEVER'], + 'opening' => ['v@x.comexpectException(InvalidAddressException::class); + + Address::parse('Name SIZE=1>'); + } } diff --git a/tests/Message/AttachmentTest.php b/tests/Message/AttachmentTest.php index b4cdb0a..93c0dd9 100644 --- a/tests/Message/AttachmentTest.php +++ b/tests/Message/AttachmentTest.php @@ -97,4 +97,49 @@ private function createFile(string $contents, string $name): string return $path; } + + /** + * @dataProvider unsafeMetadata + */ + public function testFromContentRejectsALineBreakOrNulInTheMetadata(string $name, string $disposition, string $mime): void + { + $this->expectException(AttachmentException::class); + + Attachment::fromContent('PAYLOAD', $name, $disposition, $mime); + } + + /** + * @return array + */ + public static function unsafeMetadata(): array + { + return [ + 'CRLF in the name' => ["a.txt\r\nBcc: x@example.test", 'attachment', 'text/plain'], + 'NUL in the name' => ["a\0.txt", 'attachment', 'text/plain'], + 'LF in the disposition' => ['a.txt', "attachment\nBcc: x@example.test", 'text/plain'], + 'CRLF in the MIME type' => ['a.txt', 'attachment', "text/plain\r\nBcc: x@example.test"], + ]; + } + + public function testFromPathRejectsALineBreakInTheNewName(): void + { + $dir = sys_get_temp_dir() . '/initphp-mailer-' . uniqid('', true); + mkdir($dir); + $this->tempDirs[] = $dir; + file_put_contents($dir . '/a.txt', 'x'); + + $this->expectException(AttachmentException::class); + + Attachment::fromPath($dir . '/a.txt', '', "b.txt\r\nBcc: x@example.test", 'text/plain'); + } + + public function testTheContentIdKeepsOnlySafeCharactersOfTheName(): void + { + $attachment = Attachment::fromContent('x', 'my logo">.png', 'inline'); + + $cid = $attachment->makeInline(); + + $this->assertSame(1, preg_match('/\A[A-Za-z0-9._-]+@[0-9a-f.]+\z/', $cid)); + $this->assertStringStartsWith('my_logo__.png@', $cid); + } } diff --git a/tests/Message/HeaderRendererTest.php b/tests/Message/HeaderRendererTest.php index c59fe76..324a06b 100644 --- a/tests/Message/HeaderRendererTest.php +++ b/tests/Message/HeaderRendererTest.php @@ -4,6 +4,7 @@ namespace InitPHP\Mailer\Tests\Message; +use InitPHP\Mailer\Exception\MailerException; use InitPHP\Mailer\Message\HeaderRenderer; use PHPUnit\Framework\TestCase; @@ -27,4 +28,62 @@ public function testReturnsEmptyStringForNoHeaders(): void { $this->assertSame('', HeaderRenderer::render([], "\r\n")); } + + public function testAcceptsAFoldedValue(): void + { + $out = HeaderRenderer::render(['Subject' => "=?UTF-8?Q?a?=\r\n =?UTF-8?Q?b?="], "\r\n"); + + $this->assertSame("Subject: =?UTF-8?Q?a?=\r\n =?UTF-8?Q?b?=\r\n", $out); + } + + /** + * @dataProvider unsafeValues + */ + public function testRejectsAValueThatWouldStartAnotherHeader(string $value): void + { + $this->expectException(MailerException::class); + + HeaderRenderer::render(['X-A' => $value], "\r\n"); + } + + /** + * @return array + */ + public static function unsafeValues(): array + { + return [ + 'CRLF' => ["v\r\nBcc: e@z.com"], + 'LF' => ["v\nBcc: e@z.com"], + 'CR' => ["v\rBcc: e@z.com"], + 'NUL' => ["v\0w"], + 'blank line, then fold' => ["v\r\n\r\n x"], + ]; + } + + /** + * @dataProvider invalidNames + */ + public function testRejectsAnInvalidName(string $name): void + { + $this->expectException(MailerException::class); + + HeaderRenderer::render([$name => 'v'], "\r\n"); + } + + /** + * @return array + */ + public static function invalidNames(): array + { + return [ + 'CRLF' => ["X\r\nBcc"], + 'space' => ['X A'], + 'colon' => ['X:A'], + ]; + } + + public function testDoesNotCheckAnEmptyValue(): void + { + $this->assertSame('', HeaderRenderer::render(['X-A' => "\n"], "\r\n")); + } } diff --git a/tests/RecipientHeaderMatrixTest.php b/tests/RecipientHeaderMatrixTest.php new file mode 100644 index 0000000..a6dbb6f --- /dev/null +++ b/tests/RecipientHeaderMatrixTest.php @@ -0,0 +1,187 @@ +, list}> + */ + public static function matrix(): array + { + return [ + 'mail, custom To, library writes it' => ['mail', 'To', true, 'To', [], ['To: custom@co.example']], + 'mail, custom to, library writes it' => ['mail', 'To', true, 'to', [], ['to: custom@co.example']], + 'mail, custom To, library does not' => ['mail', 'To', false, 'To', ['Bcc: b@x.com', 'To: custom@co.example'], ['Bcc: b@x.com', 'To: custom@co.example']], + 'mail, custom to, library does not' => ['mail', 'To', false, 'to', ['Bcc: b@x.com', 'to: custom@co.example'], ['Bcc: b@x.com', 'to: custom@co.example']], + 'mail, custom Cc, library writes it' => ['mail', 'Cc', true, 'Cc', ['Cc: c@x.com'], ['Cc: c@x.com']], + 'mail, custom cc, library writes it' => ['mail', 'Cc', true, 'cc', ['Cc: c@x.com'], ['Cc: c@x.com', 'cc: custom@co.example']], + 'mail, custom Cc, library does not' => ['mail', 'Cc', false, 'Cc', ['Cc: custom@co.example'], ['Cc: custom@co.example']], + 'mail, custom cc, library does not' => ['mail', 'Cc', false, 'cc', ['cc: custom@co.example'], ['cc: custom@co.example']], + 'mail, custom Bcc, library writes it' => ['mail', 'Bcc', true, 'Bcc', ['Bcc: b@x.com'], ['Bcc: b@x.com']], + 'mail, custom bcc, library writes it' => ['mail', 'Bcc', true, 'bcc', ['Bcc: b@x.com'], ['Bcc: b@x.com', 'bcc: custom@co.example']], + 'mail, custom Bcc, library does not' => ['mail', 'Bcc', false, 'Bcc', ['Bcc: custom@co.example'], ['Bcc: custom@co.example']], + 'mail, custom bcc, library does not' => ['mail', 'Bcc', false, 'bcc', ['bcc: custom@co.example'], ['bcc: custom@co.example']], + 'sendmail, custom To, library writes it' => ['sendmail', 'To', true, 'To', ['To: t@x.com'], ['To: t@x.com']], + 'sendmail, custom to, library writes it' => ['sendmail', 'To', true, 'to', ['To: t@x.com'], ['To: t@x.com', 'to: custom@co.example']], + 'sendmail, custom To, library does not' => ['sendmail', 'To', false, 'To', ['Bcc: b@x.com', 'To: custom@co.example'], ['Bcc: b@x.com']], + 'sendmail, custom to, library does not' => ['sendmail', 'To', false, 'to', ['Bcc: b@x.com', 'to: custom@co.example'], ['Bcc: b@x.com', 'to: custom@co.example']], + 'sendmail, custom Cc, library writes it' => ['sendmail', 'Cc', true, 'Cc', ['Cc: c@x.com', 'To: t@x.com'], ['Cc: c@x.com', 'To: t@x.com']], + 'sendmail, custom cc, library writes it' => ['sendmail', 'Cc', true, 'cc', ['Cc: c@x.com', 'To: t@x.com'], ['Cc: c@x.com', 'To: t@x.com', 'cc: custom@co.example']], + 'sendmail, custom Cc, library does not' => ['sendmail', 'Cc', false, 'Cc', ['Cc: custom@co.example', 'To: t@x.com'], ['Cc: custom@co.example', 'To: t@x.com']], + 'sendmail, custom cc, library does not' => ['sendmail', 'Cc', false, 'cc', ['To: t@x.com', 'cc: custom@co.example'], ['To: t@x.com', 'cc: custom@co.example']], + 'sendmail, custom Bcc, library writes it' => ['sendmail', 'Bcc', true, 'Bcc', ['Bcc: b@x.com', 'To: t@x.com'], ['Bcc: b@x.com', 'To: t@x.com']], + 'sendmail, custom bcc, library writes it' => ['sendmail', 'Bcc', true, 'bcc', ['Bcc: b@x.com', 'To: t@x.com'], ['Bcc: b@x.com', 'To: t@x.com', 'bcc: custom@co.example']], + 'sendmail, custom Bcc, library does not' => ['sendmail', 'Bcc', false, 'Bcc', ['Bcc: custom@co.example', 'To: t@x.com'], ['Bcc: custom@co.example', 'To: t@x.com']], + 'sendmail, custom bcc, library does not' => ['sendmail', 'Bcc', false, 'bcc', ['To: t@x.com', 'bcc: custom@co.example'], ['To: t@x.com', 'bcc: custom@co.example']], + 'smtp, custom To, library writes it' => ['smtp', 'To', true, 'To', ['To: t@x.com'], ['To: t@x.com']], + 'smtp, custom to, library writes it' => ['smtp', 'To', true, 'to', ['To: t@x.com'], ['To: t@x.com', 'to: custom@co.example']], + 'smtp, custom To, library does not' => ['smtp', 'To', false, 'To', ['To: custom@co.example'], []], + 'smtp, custom to, library does not' => ['smtp', 'To', false, 'to', ['to: custom@co.example'], ['to: custom@co.example']], + 'smtp, custom Cc, library writes it' => ['smtp', 'Cc', true, 'Cc', ['Cc: c@x.com', 'To: t@x.com'], ['Cc: c@x.com', 'To: t@x.com']], + 'smtp, custom cc, library writes it' => ['smtp', 'Cc', true, 'cc', ['Cc: c@x.com', 'To: t@x.com'], ['Cc: c@x.com', 'To: t@x.com', 'cc: custom@co.example']], + 'smtp, custom Cc, library does not' => ['smtp', 'Cc', false, 'Cc', ['Cc: custom@co.example', 'To: t@x.com'], ['Cc: custom@co.example', 'To: t@x.com']], + 'smtp, custom cc, library does not' => ['smtp', 'Cc', false, 'cc', ['To: t@x.com', 'cc: custom@co.example'], ['To: t@x.com', 'cc: custom@co.example']], + 'smtp, custom Bcc, library writes it' => ['smtp', 'Bcc', true, 'Bcc', ['Bcc: custom@co.example', 'To: t@x.com'], ['Bcc: custom@co.example', 'To: t@x.com']], + 'smtp, custom bcc, library writes it' => ['smtp', 'Bcc', true, 'bcc', ['To: t@x.com', 'bcc: custom@co.example'], ['To: t@x.com', 'bcc: custom@co.example']], + 'smtp, custom Bcc, library does not' => ['smtp', 'Bcc', false, 'Bcc', ['Bcc: custom@co.example', 'To: t@x.com'], ['Bcc: custom@co.example', 'To: t@x.com']], + 'smtp, custom bcc, library does not' => ['smtp', 'Bcc', false, 'bcc', ['To: t@x.com', 'bcc: custom@co.example'], ['To: t@x.com', 'bcc: custom@co.example']], + ]; + } + + /** + * @dataProvider matrix + * + * @param list $expected The header lines now. + * @param list $expectedBase The header lines 3.0.0 produced. + */ + public function testCustomRecipientHeaders( + string $transport, + string $header, + bool $libraryWrites, + string $customName, + array $expected, + array $expectedBase, + ): void { + $captured = ''; + $client = null; + $mailer = Mailer::newInstance(['newline' => "\n"]); + + if ($transport === 'mail') { + $mailer->setTransport(new MailTransport( + new EmailValidator(), + static function (string $to, string $subject, string $message, string $headers) use (&$captured): bool { + $captured = $headers; + + return true; + }, + )); + } elseif ($transport === 'sendmail') { + $mailer->setTransport(new SendmailTransport( + '/usr/sbin/sendmail', + new EmailValidator(), + static function (string $command, string $message) use (&$captured): int { + $captured = $message; + + return 0; + }, + )); + } else { + $recipients = $header === 'To' || !$libraryWrites ? 1 : 2; + $replies = ["220 hi\r\n", "250 ehlo\r\n", "250 from\r\n"]; + for ($i = 0; $i < $recipients; ++$i) { + $replies[] = "250 rcpt\r\n"; + } + $client = new FakeSocketClient([...$replies, "354 data\r\n", "250 queued\r\n", "221 bye\r\n"]); + $mailer->setTransport( + new SmtpTransport($client, 'mx.example.com', 25, 5, '', false, '', '', false, false, true, 'localhost', "\n"), + ); + } + + $mailer->setFrom('s@example.com')->setSubject('Subject')->setMessage('Body'); + if ($header === 'To') { + $libraryWrites ? $mailer->setTo('t@x.com') : $mailer->setBCC('b@x.com'); + } else { + $mailer->setTo('t@x.com'); + if ($libraryWrites) { + $header === 'Cc' ? $mailer->setCC('c@x.com') : $mailer->setBCC('b@x.com'); + } + } + $mailer->setHeader($customName, 'custom@co.example'); + $mailer->send(); + + if ($client !== null) { + $captured = $client->conversation(); + } + + $lines = array_map('rtrim', array_values(array_filter( + explode("\n", $captured), + static fn(string $line): bool => preg_match('/^(to|cc|bcc):/i', $line) === 1, + ))); + sort($lines); + + self::assertSame($expected, $lines); + } + + /** + * Compares the two recorded columns (it does not run the mailer) and allows + * the difference from 3.0.0 to be only of the two intended kinds, so a changed + * expectation that drops or adds anything else shows up here. + * + * @dataProvider matrix + * + * @param list $expected + * @param list $expectedBase + */ + public function testTheOutputDiffersFromThe300OutputOnlyWhereIntended( + string $transport, + string $header, + bool $libraryWrites, + string $customName, + array $expected, + array $expectedBase, + ): void { + $removed = array_diff($expectedBase, $expected); + $added = array_diff($expected, $expectedBase); + $customLine = $customName . ': custom@co.example'; + + // Only the custom header's own line may disappear, and only when the + // library writes that header (it used to come out as a duplicate)... + $mayRemove = $libraryWrites ? [$customLine] : []; + // ...and the only line that may appear is a custom To that 3.0.0 lost on + // sendmail and SMTP although the library wrote no To. + $mayAdd = $header === 'To' && !$libraryWrites && $transport !== 'mail' ? [$customLine] : []; + + self::assertSame([], array_values(array_diff($removed, $mayRemove)), 'Unexpected line removed.'); + self::assertSame([], array_values(array_diff($added, $mayAdd)), 'Unexpected line added.'); + } +} diff --git a/tests/Support/FakeSocketClient.php b/tests/Support/FakeSocketClient.php index 67fb773..e347bce 100644 --- a/tests/Support/FakeSocketClient.php +++ b/tests/Support/FakeSocketClient.php @@ -21,6 +21,9 @@ final class FakeSocketClient implements SocketClientInterface public bool $cryptoEnabled = false; + /** Whether {@see enableCrypto()} reports a successful handshake. */ + public bool $cryptoResult = true; + public ?string $openedHost = null; public int $openCount = 0; @@ -69,9 +72,9 @@ public function readLine(int $length = 512): string|false public function enableCrypto(int $cryptoMethod): bool { - $this->cryptoEnabled = true; + $this->cryptoEnabled = $this->cryptoResult; - return true; + return $this->cryptoResult; } public function close(): void diff --git a/tests/Transport/MailTransportTest.php b/tests/Transport/MailTransportTest.php index e1346fd..cfd40e8 100644 --- a/tests/Transport/MailTransportTest.php +++ b/tests/Transport/MailTransportTest.php @@ -4,6 +4,7 @@ namespace InitPHP\Mailer\Tests\Transport; +use InitPHP\Mailer\Exception\MailerException; use InitPHP\Mailer\Exception\TransportException; use InitPHP\Mailer\Message\Address; use InitPHP\Mailer\Message\PreparedEmail; @@ -88,4 +89,89 @@ public function testThrowsWhenMailReturnsFalse(): void $this->transport(false)->send($this->email()); } + + /** + * @return array, string, array, 3?: list}> + */ + public static function unsafeEmails(): array + { + return [ + 'recipient with a line break' => [["t@x.com\nBcc: e@z.com"], 'Subject', ['X-A' => 'v']], + 'recipient with an angle bracket' => [['t@x.com> NOTIFY=NEVER'], 'Subject', ['X-A' => 'v']], + 'bcc with an angle bracket' => [['t@x.com'], 'Subject', ['X-A' => 'v'], ['b@x.com> NOTIFY=NEVER']], + 'bcc with a NUL' => [['t@x.com'], 'Subject', ['X-A' => 'v'], ["b@x.com\0x"]], + 'subject with a line break' => [['t@x.com'], "s\nX-Inj: 1", ['X-A' => 'v']], + 'header value with a line break' => [['t@x.com'], 'Subject', ['X-A' => "v\nX-B: 1"]], + 'header name with a line break' => [['t@x.com'], 'Subject', ["X-A\nX-B" => 'v']], + ]; + } + + /** + * @dataProvider unsafeEmails + * + * @param list $to + * @param array $headers + * @param list $bcc + */ + public function testRefusesAnEmailBuiltByHandWithInjectableFields(array $to, string $subject, array $headers, array $bcc = []): void + { + $email = new PreparedEmail( + new Address('from@example.com'), + $to, + [], + $bcc, + $subject, + $headers, + 'Content-Type: text/plain; charset=UTF-8', + 'Body', + "\n", + ); + + try { + $this->transport()->send($email); + $this->fail('Expected the transport to refuse the message.'); + } catch (MailerException) { + $this->assertSame([], $this->captured, 'mail() must not be called.'); + } + } + + public function testAFoldedSubjectIsAccepted(): void + { + $email = new PreparedEmail( + new Address('from@example.com'), + ['a@example.com'], + [], + [], + "=?UTF-8?Q?a?=\r\n =?UTF-8?Q?b?=", + ['From' => ''], + 'Content-Type: text/plain; charset=UTF-8', + 'Body', + "\n", + ); + + $this->transport()->send($email); + + $this->assertSame("=?UTF-8?Q?a?=\r\n =?UTF-8?Q?b?=", $this->captured['subject']); + } + + public function testACustomSubjectHeaderIsDroppedBecauseSubjectIsAMailArgument(): void + { + $email = new PreparedEmail( + new Address('from@example.com'), + ['a@example.com'], + [], + [], + 'Real subject', + ['From' => '', 'subject' => 'Evil subject', 'SUBJECT' => 'Evil too'], + 'Content-Type: text/plain; charset=UTF-8', + 'Body', + "\n", + ); + + $this->transport()->send($email); + + $this->assertSame('Real subject', $this->captured['subject']); + $this->assertStringNotContainsString('ubject', $this->captured['headers']); + $this->assertStringNotContainsString('Evil', $this->captured['headers']); + } } diff --git a/tests/Transport/SendmailTransportTest.php b/tests/Transport/SendmailTransportTest.php index f139cc7..1638585 100644 --- a/tests/Transport/SendmailTransportTest.php +++ b/tests/Transport/SendmailTransportTest.php @@ -4,6 +4,7 @@ namespace InitPHP\Mailer\Tests\Transport; +use InitPHP\Mailer\Exception\MailerException; use InitPHP\Mailer\Exception\TransportException; use InitPHP\Mailer\Message\Address; use InitPHP\Mailer\Message\PreparedEmail; @@ -71,4 +72,49 @@ public function testThrowsOnNonZeroExitStatus(): void $this->transport(127)->send($this->email()); } + + /** + * @return array, string, array, 3?: list}> + */ + public static function unsafeEmails(): array + { + return [ + 'recipient with a line break' => [["t@x.com\nBcc: e@z.com"], 'Subject', ['X-A' => 'v']], + 'recipient with an angle bracket' => [['t@x.com> NOTIFY=NEVER'], 'Subject', ['X-A' => 'v']], + 'bcc with an angle bracket' => [['t@x.com'], 'Subject', ['X-A' => 'v'], ['b@x.com> NOTIFY=NEVER']], + 'bcc with a NUL' => [['t@x.com'], 'Subject', ['X-A' => 'v'], ["b@x.com\0x"]], + 'subject with a line break' => [['t@x.com'], "s\nX-Inj: 1", ['X-A' => 'v']], + 'header value with a line break' => [['t@x.com'], 'Subject', ['X-A' => "v\nX-B: 1"]], + 'header name with a line break' => [['t@x.com'], 'Subject', ["X-A\nX-B" => 'v']], + ]; + } + + /** + * @dataProvider unsafeEmails + * + * @param list $to + * @param array $headers + * @param list $bcc + */ + public function testRefusesAnEmailBuiltByHandWithInjectableFields(array $to, string $subject, array $headers, array $bcc = []): void + { + $email = new PreparedEmail( + new Address('from@example.com'), + $to, + [], + $bcc, + $subject, + $headers, + 'Content-Type: text/plain; charset=UTF-8', + 'Body', + "\n", + ); + + try { + $this->transport()->send($email); + $this->fail('Expected the transport to refuse the message.'); + } catch (MailerException) { + $this->assertSame('', $this->command, 'Nothing may be piped to sendmail.'); + } + } } diff --git a/tests/Transport/SmtpTransportTest.php b/tests/Transport/SmtpTransportTest.php index 8e3a545..db34977 100644 --- a/tests/Transport/SmtpTransportTest.php +++ b/tests/Transport/SmtpTransportTest.php @@ -5,6 +5,7 @@ namespace InitPHP\Mailer\Tests\Transport; use InitPHP\Mailer\Exception\ConfigurationException; +use InitPHP\Mailer\Exception\InvalidAddressException; use InitPHP\Mailer\Exception\TransportException; use InitPHP\Mailer\Message\Address; use InitPHP\Mailer\Message\PreparedEmail; @@ -196,4 +197,232 @@ public function testThrowsWhenHostIsNotConfigured(): void $transport->send($this->email()); } + + /** + * @return array + */ + public static function unsafeRecipients(): array + { + return [ + 'CRLF command injection' => ["rcpt@example.com>\r\nRSET\r\nMAIL FROM: ["rcpt@example.com\nRSET"], + 'NUL' => ["rcpt@example.com\0"], + ]; + } + + /** + * @dataProvider unsafeRecipients + */ + public function testRejectsAnUnsafeRecipientBeforeConnecting(string $recipient): void + { + $client = new FakeSocketClient([]); + + try { + $this->transport($client)->send($this->email(to: ['ok@example.com'], bcc: [$recipient])); + $this->fail('Expected an InvalidAddressException.'); + } catch (InvalidAddressException) { + $this->assertSame([], $client->writes); + $this->assertSame(0, $client->openCount); + } + } + + public function testRefusesAHostnameWithALineBreakBeforeConnecting(): void + { + $client = new FakeSocketClient(["220 hi\r\n"]); + $transport = new SmtpTransport( + $client, + 'mx.example.com', + 25, + 5, + '', + false, + '', + '', + false, + false, + true, + "host\r\nRSET", + "\r\n", + ); + + try { + $transport->send($this->email()); + $this->fail('Expected a TransportException.'); + } catch (TransportException) { + $this->assertSame(0, $client->openCount, 'No connection may be left open.'); + $this->assertSame([], $client->writes); + } + } + + public function testAFailedStarttlsClosesTheConnectionAndTheNextSendNeverSendsAuthInTheClear(): void + { + $client = new FakeSocketClient([ + // First send: STARTTLS is refused. + "220 hi\r\n", "250 ehlo\r\n", "454 TLS not available\r\n", + // Second send: it must start over from the greeting. + "220 hi\r\n", "250 ehlo\r\n", "454 TLS not available\r\n", + ]); + $transport = $this->transport($client, crypto: 'tls', auth: true, user: 'user', pass: 'secret'); + + foreach ([1, 2] as $attempt) { + try { + $transport->send($this->email()); + $this->fail('Expected a TransportException on attempt ' . $attempt . '.'); + } catch (TransportException $e) { + $this->assertSame(454, $e->getCode()); + $this->assertFalse($client->isOpen(), 'The connection must be closed after a failure.'); + } + } + + $this->assertSame(2, $client->openCount); + $this->assertSame(2, substr_count($client->conversation(), 'STARTTLS')); + $this->assertStringNotContainsString('AUTH', $client->conversation()); + $this->assertStringNotContainsString(base64_encode('secret'), $client->conversation()); + } + + public function testAFailedTlsHandshakeClosesTheConnectionAndTheNextSendNeverSendsAuthInTheClear(): void + { + $client = new FakeSocketClient([ + "220 hi\r\n", "250 ehlo\r\n", "220 go ahead\r\n", + "220 hi\r\n", "250 ehlo\r\n", "220 go ahead\r\n", + ]); + $client->cryptoResult = false; + $transport = $this->transport($client, crypto: 'tls', auth: true, user: 'user', pass: 'secret'); + + foreach ([1, 2] as $attempt) { + try { + $transport->send($this->email()); + $this->fail('Expected a TransportException on attempt ' . $attempt . '.'); + } catch (TransportException) { + $this->assertFalse($client->isOpen()); + } + } + + $this->assertSame(2, $client->openCount); + $this->assertStringNotContainsString('AUTH', $client->conversation()); + } + + public function testABadGreetingClosesTheConnection(): void + { + $client = new FakeSocketClient(["554 no service\r\n"]); + + try { + $this->transport($client)->send($this->email()); + $this->fail('Expected a TransportException.'); + } catch (TransportException $e) { + $this->assertSame(554, $e->getCode()); + } + + $this->assertFalse($client->isOpen()); + $this->assertSame([], $client->writes, 'Nothing may be sent to a server that did not greet us.'); + } + + public function testAFailedEhloClosesTheConnection(): void + { + $client = new FakeSocketClient(["220 hi\r\n", "502 not implemented\r\n"]); + + try { + $this->transport($client)->send($this->email()); + $this->fail('Expected a TransportException.'); + } catch (TransportException) { + $this->assertFalse($client->isOpen()); + } + } + + public function testAFailedAuthClosesTheKeptAliveConnectionAndAuthenticatesAgain(): void + { + $client = new FakeSocketClient([ + "220 hi\r\n", "250 ehlo\r\n", "334 VXNlcm5hbWU6\r\n", "334 UGFzc3dvcmQ6\r\n", "535 bad credentials\r\n", + "220 hi\r\n", "250 ehlo\r\n", "334 VXNlcm5hbWU6\r\n", "334 UGFzc3dvcmQ6\r\n", "535 bad credentials\r\n", + ]); + $transport = $this->transport($client, auth: true, user: 'user', pass: 'wrong', keepAlive: true); + + foreach ([1, 2] as $attempt) { + try { + $transport->send($this->email()); + $this->fail('Expected a TransportException on attempt ' . $attempt . '.'); + } catch (TransportException $e) { + $this->assertSame(535, $e->getCode()); + $this->assertFalse($client->isOpen()); + } + } + + $this->assertSame(2, $client->openCount); + $this->assertSame(2, substr_count($client->conversation(), 'AUTH LOGIN')); + } + + public function testARejectedMessageClosesTheKeptAliveConnection(): void + { + $client = new FakeSocketClient([ + "220 hi\r\n", "250 ehlo\r\n", "250 from\r\n", "250 rcpt\r\n", "354 data\r\n", "554 rejected\r\n", + ]); + + try { + $this->transport($client, keepAlive: true)->send($this->email()); + $this->fail('Expected a TransportException.'); + } catch (TransportException) { + $this->assertFalse($client->isOpen()); + } + } + + public function testDotStuffingFollowsABareCarriageReturnNewline(): void + { + $client = new FakeSocketClient([ + "220 hi\r", "250 ehlo\r", "250 from\r", "250 rcpt\r", "354 data\r", "250 queued\r", "221 bye\r", + ]); + $transport = new SmtpTransport($client, 'mx.example.com', 25, 5, '', false, '', '', false, false, true, 'localhost', "\r"); + + $email = new PreparedEmail( + new Address('sender@example.com'), + ['rcpt@example.com'], + [], + [], + 'Subject', + ['From' => ''], + 'Content-Type: text/plain; charset=UTF-8', + "first\r.second\r..third\r.", + "\r", + ); + $transport->send($email); + + $this->assertStringContainsString("first\r..second\r...third\r..\r.\r", $client->conversation()); + } + + public function testAKeptAliveConnectionAuthenticatesAgainAfterAFailureFollowingASuccessfulAuth(): void + { + $client = new FakeSocketClient([ + // First send: AUTH succeeds, MAIL FROM is rejected. + "220 hi\r\n", "250 ehlo\r\n", "334 VXNlcm5hbWU6\r\n", "334 UGFzc3dvcmQ6\r\n", "235 ok\r\n", "550 no\r\n", + // Second send: a new connection must authenticate again. + "220 hi\r\n", "250 ehlo\r\n", "334 VXNlcm5hbWU6\r\n", "334 UGFzc3dvcmQ6\r\n", "235 ok\r\n", "550 no\r\n", + ]); + $transport = $this->transport($client, auth: true, user: 'user', pass: 'secret', keepAlive: true); + + foreach ([1, 2] as $attempt) { + try { + $transport->send($this->email()); + $this->fail('Expected a TransportException on attempt ' . $attempt . '.'); + } catch (TransportException $e) { + $this->assertSame(550, $e->getCode()); + } + } + + $this->assertSame(2, $client->openCount); + $this->assertSame(2, substr_count($client->conversation(), 'AUTH LOGIN')); + } + + public function testTheOrcptParameterIsXtextEncodedSoAnAddressCannotAddParameters(): void + { + $client = new FakeSocketClient([ + "220 hi\r\n", "250 ehlo\r\n", "250 from\r\n", "250 rcpt\r\n", "354 data\r\n", "250 queued\r\n", "221 bye\r\n", + ]); + + $this->transport($client, dsn: true)->send($this->email(to: ['v@x.com NOTIFY=NEVER+a=b'])); + + $this->assertStringContainsString( + 'ORCPT=rfc822;v@x.com+20NOTIFY+3DNEVER+2Ba+3Db' . "\r\n", + $client->conversation(), + ); + $this->assertStringNotContainsString('ORCPT=rfc822;v@x.com NOTIFY', $client->conversation()); + } } diff --git a/tests/Transport/StreamSocketClientTest.php b/tests/Transport/StreamSocketClientTest.php new file mode 100644 index 0000000..5368cb0 --- /dev/null +++ b/tests/Transport/StreamSocketClientTest.php @@ -0,0 +1,61 @@ +peer, $this->server] as $stream) { + if (is_resource($stream)) { + fclose($stream); + } + } + } + + public function testRefusesToStartTlsWhileClearTextBytesAreStillBuffered(): void + { + $server = stream_socket_server('tcp://127.0.0.1:0', $errno, $errstr); + if ($server === false) { + $this->markTestSkipped('Cannot open a loopback listener: ' . $errstr); + } + $this->server = $server; + $address = (string) stream_socket_get_name($server, false); + [$host, $port] = explode(':', $address); + + $client = new StreamSocketClient(); + $client->open($host, (int) $port, 2); + $peer = stream_socket_accept($server, 2); + $this->assertNotFalse($peer); + $this->peer = $peer; + + // A MITM (or server) sends the STARTTLS reply and an injected reply in + // one segment; the second line stays in the client's read buffer. + fwrite($peer, "220 Ready to start TLS\r\n250 injected before the handshake\r\n"); + + $this->assertSame("220 Ready to start TLS\r\n", $client->readLine()); + $this->assertFalse($client->enableCrypto(STREAM_CRYPTO_METHOD_TLS_CLIENT)); + + $client->close(); + } +} diff --git a/tests/Validation/EmailValidatorTest.php b/tests/Validation/EmailValidatorTest.php index 0baa39e..363c3e7 100644 --- a/tests/Validation/EmailValidatorTest.php +++ b/tests/Validation/EmailValidatorTest.php @@ -61,4 +61,15 @@ public function testShellSafeRejectsAddressesWithMetacharacters(): void $this->assertFalse($this->validator->isShellSafe('"a b"@example.com')); $this->assertFalse($this->validator->isShellSafe('user@example.com -X/tmp/x')); } + + public function testHasLineBreakOrNulDetectsCrLfAndNul(): void + { + $this->assertTrue(EmailValidator::hasLineBreakOrNul("a\rb")); + $this->assertTrue(EmailValidator::hasLineBreakOrNul("a\nb")); + $this->assertTrue(EmailValidator::hasLineBreakOrNul("a\0b")); + $this->assertTrue(EmailValidator::hasLineBreakOrNul("a@example.com\n")); + $this->assertFalse(EmailValidator::hasLineBreakOrNul('a@example.com')); + $this->assertFalse(EmailValidator::hasLineBreakOrNul("a\tb")); + $this->assertFalse(EmailValidator::hasLineBreakOrNul('')); + } }