Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 40 additions & 16 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,48 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### 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()`).
- A CR, LF or NUL in an address or return path is now rejected with an
`InvalidAddressException` **whether or not** the `validate` option is on
(`Address`, `setFrom()`, `setReplyTo()`, `setTo()`, `setCC()`, `setBCC()`). A
display name is not rejected: as in 3.0.0, an ASCII name is quoted with its
control characters backslash-escaped and a non-ASCII name is Q-encoded with the
line breaks removed, so it cannot start another header.
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.
and NUL is now stripped too. The subject keeps its behaviour too: CR and LF are
removed and a NUL is Q-encoded (`=00`), never written raw.
- 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.

### Changed

Behaviours that differ from 3.0.0 and are not security fixes in themselves:

- `setHeader()` throws a `MailerException` for a header name that is empty, has a
tab or other whitespace, an inner space, a colon, or a non-ASCII or control
character. 3.0.0 wrote `X: y: value` or a name with a tab as given; a colon or
empty name produced a broken header. Spaces around a name are still accepted.
- A custom header with the same name as one the library writes is no longer
written as a second line: `from`, `date`, `message-id`, `user-agent`, `x-mailer`,
`x-sender`, `x-priority`, `mime-version`, `reply-to`, `return-path`,
`content-type`, `content-transfer-encoding` (any case), `cc` next to
`setCC()`, `bcc` next to `setBCC()` on sendmail and `mail()`, and `subject` (any case,
and also the exact `Subject` on `mail()`). Before, 3.0.0 wrote both. A custom `cc`/`bcc` that followed a real CC
or BCC list used to add that address as a recipient on sendmail and `mail()`;
it no longer does. `To` is not affected.
- A header the library overrides keeps the position it has in the library's own
list instead of the custom header's position.
- `"a>b"@example.com`-style addresses (a `<` or `>` inside the address) are
rejected; the SMTP server greeting must be `220`.

### Fixed

- **SMTP connection state after a failure.** A failed greeting, `EHLO`, `STARTTLS`,
Expand All @@ -37,20 +62,19 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- `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.
`fromEmail` option, so a CR, LF or NUL in that option cannot reach the header.
- A `<` or `>` inside an address is rejected (even with `validate` off): it could
close the SMTP path and add parameters (`RCPT TO:<a@x.com> 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`.
- `setHeader()`: a header the library writes itself for the message (`Cc` with CC
recipients, `Bcc` with BCC recipients, `Subject`, `From`, …) wins over a custom
one of the same name whatever the case or the spacing (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. `To` is not special-cased:
a custom `To` behaves exactly as in 3.0.0 on `mail()`, sendmail and SMTP,
including in BCC batches, so it adds no recipient that 3.0.0 did not, for every
spelling of the name that is still accepted (letter case, and spaces around
it). A name with a tab or other whitespace, an inner space, a colon, or any
non-printable or non-ASCII character throws a `MailerException` (see Changed).
- `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`
Expand Down
15 changes: 8 additions & 7 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ with that batch size. **Throws** `InvalidAddressException` (same line-break rule

### `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.
CR and LF are removed when the message is built; a NUL is Q-encoded (`=00`).

### `setMessage(string $body): self`
Sets the body (plain text or HTML depending on the mail type). Carriage returns
Expand Down Expand Up @@ -85,13 +85,14 @@ Promotes a previously added attachment (matched by its path/name) to an inline

### `setHeader(string $header, string $value): self`
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.
library writes for the message itself (From, Subject, 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 or spacing; one it does not write
is kept as you set it. `To` is not special-cased and behaves as it always did
(see [Custom headers](Sending-Mail.md#custom-headers)). Use
`setTo()`/`setCC()`/`setBCC()` for recipients, not headers.
**Throws** `MailerException` when the header name is not printable ASCII
without `:` or spaces.
without `:`, a tab or an inner space.

### `setPriority(int $n = 3): self`
`X-Priority`, 1 (highest)–5 (lowest); out-of-range → 3.
Expand Down
17 changes: 10 additions & 7 deletions docs/Encoding-and-Headers.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ $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
Line breaks are removed from a subject (a NUL is Q-encoded as `=00`). A display
name with a line break or NUL is made safe the same way it always was: an ASCII
name is quoted with the control characters backslash-escaped, a non-ASCII name is
Q-encoded with the line breaks removed; it is not rejected. 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).
Expand Down Expand Up @@ -89,11 +91,12 @@ Out-of-range values fall back to 3.
## Custom headers

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
prevent header injection, and a header name that is not printable ASCII without
`:`, a tab or an inner space throws a `MailerException`. The headers the library
writes itself (From, 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 or spacing; a header the library does not write is kept. `To`
is not special-cased and behaves as it always did. See
[Sending Mail](Sending-Mail.md#custom-headers).

```php
Expand Down
8 changes: 5 additions & 3 deletions docs/Error-Handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ MailerException (extends \RuntimeException)

| Exception | Thrown when | Thrown by |
| --- | --- | --- |
| `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()` |
| `InvalidAddressException` | An address fails validation (and validation is on), or an address or return path contains a CR, LF, NUL, `<` or `>` (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()` |
Expand Down Expand Up @@ -58,12 +58,14 @@ $mailer = Mailer::newInstance(['validate' => false]);
```

> **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
> not the character check. A CR, LF or NUL inside an address
> (`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
> a leading or trailing line break is trimmed. A display name is never rejected:
> a line break or NUL in it is escaped or Q-encoded when the header is written,
> so it cannot start another header either. 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])`.
Expand Down
6 changes: 4 additions & 2 deletions docs/FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,14 @@ $mailer = Mailer::newInstance(['validate' => false]);
```

> **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
> not the character check. A CR, LF or NUL inside an address
> (`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
> a leading or trailing line break is trimmed. A display name is never rejected:
> a line break or NUL in it is escaped or Q-encoded when the header is written,
> so it cannot start another header either. 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])`.
Expand Down
39 changes: 24 additions & 15 deletions docs/Sending-Mail.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,10 @@ try {

Disable validation with `'validate' => false` only if you need to accept
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
NUL, `<` or `>` inside an address is rejected with an `InvalidAddressException`
even then, so a request-supplied address cannot start another header or add
parameters to an SMTP command (a display name is not rejected; a line break or
NUL in it is escaped or Q-encoded when the header is written) — see
[Error Handling](Error-Handling.md#fail-fast-on-bad-input).

That check does **not** stop a request-supplied *string* from naming several
Expand Down Expand Up @@ -121,24 +122,32 @@ repeatedly. If any batch fails, the failure is thrown.

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`.
removed). A header *name* must be printable ASCII without `:`, a tab or an inner
space (spaces around the name are allowed), 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.
custom header of the same name, whatever the case or the spacing 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, Content-Transfer-Encoding and `Subject`;
`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()` adds that
header.

**`To` is the exception: it is not treated specially.** A custom `To` behaves as
it always did. With `sendmail` and `smtp` the library's own `To` line replaces a
custom header named exactly `To` (so a message with no To recipient loses it),
and a custom header spelled differently (`to`, `TO`, `To `) is written next to
it. With `mail()` the recipients go in the function's own argument and a custom
`To` is written as an extra header. Do not use `setHeader('To', …)` to add
recipients; use `setTo()`.

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
**can** 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:
Expand Down
6 changes: 6 additions & 0 deletions docs/Transports.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ each transport does the right thing:
never appear in the headers** (a `Bcc` header you add by hand with
`setHeader()` does; see [Sending Mail](Sending-Mail.md#custom-headers)).

A `To`, `Cc` or `Bcc` header you add by hand with `setHeader()` is not a recipient
on `smtp`, but `mail()` and `sendmail` read recipients from the headers, so there
it can be one. A custom `To` is never replaced case-insensitively: it behaves as it
always did on every transport. See
[Custom headers](Sending-Mail.md#custom-headers) before passing untrusted input.

## Supplying your own transport

Any object implementing `TransportInterface` can be injected with
Expand Down
2 changes: 1 addition & 1 deletion src/Encoding/QEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function __construct(

public function encode(string $str): string
{
$str = str_replace(["\r", "\n", "\0"], '', $str);
$str = str_replace(["\r", "\n"], '', $str);
$chars = null;

if ($this->charset === 'UTF-8') {
Expand Down
Loading
Loading