From fe4abc934115986323f470f0ea086fd1828007b5 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Mon, 16 Nov 2026 17:21:08 -0500 Subject: [PATCH 1/2] Prevent IMAP command injection in UIDs and flags --- src/Connection/ImapCommand.php | 8 ++ src/Connection/ImapConnection.php | 4 +- src/Support/Assert.php | 40 ++++++++++ src/Support/Str.php | 35 +++++--- tests/Integration/MessagesTest.php | 38 +++++++++ tests/Unit/Connection/ImapCommandTest.php | 24 ++++++ tests/Unit/Connection/ImapConnectionTest.php | 80 +++++++++++++++++++ .../Unit/Connection/ImapQueryBuilderTest.php | 7 ++ tests/Unit/Support/AssertTest.php | 35 ++++++++ tests/Unit/Support/StrTest.php | 28 +++++++ 10 files changed, 286 insertions(+), 13 deletions(-) create mode 100644 src/Support/Assert.php create mode 100644 tests/Unit/Support/AssertTest.php diff --git a/src/Connection/ImapCommand.php b/src/Connection/ImapCommand.php index 1ae85e7b..e9791613 100644 --- a/src/Connection/ImapCommand.php +++ b/src/Connection/ImapCommand.php @@ -2,6 +2,7 @@ namespace DirectoryTree\ImapEngine\Connection; +use DirectoryTree\ImapEngine\Support\Assert; use Stringable; class ImapCommand implements Stringable @@ -59,6 +60,9 @@ public function compile(): array $lines = []; + Assert::isToken($this->tag); + Assert::isToken($this->command); + $line = trim("{$this->tag} {$this->command}"); foreach ($this->tokens as $token) { @@ -68,6 +72,8 @@ public function compile(): array // The second element holds the actual literal content. [$length, $literal] = $token; + Assert::isToken($length); + $lines[] = new ImapCommandLine( value: "{$line} {$length}", synchronizing: ! str_contains($length, '+'), @@ -75,6 +81,8 @@ public function compile(): array $line = $literal; } else { + Assert::isToken($token); + $line .= " {$token}"; } } diff --git a/src/Connection/ImapConnection.php b/src/Connection/ImapConnection.php index 84589d93..fd3d04f3 100644 --- a/src/Connection/ImapConnection.php +++ b/src/Connection/ImapConnection.php @@ -374,7 +374,7 @@ public function append(string $folder, string $message, ?array $flags = null): T $tokens[] = Str::literal($folder); if ($flags) { - $tokens[] = Str::list($flags); + $tokens[] = Str::flags($flags); } $tokens[] = Str::literal($message); @@ -417,7 +417,7 @@ public function store(array|string $flags, array|int $from, ?int $to = null, ?st { $set = Str::set($from, $to); - $flags = Str::list((array) $flags); + $flags = Str::flags((array) $flags); $item = ($mode == '-' ? '-' : '+').(is_null($item) ? 'FLAGS' : $item).($silent ? '.SILENT' : ''); diff --git a/src/Support/Assert.php b/src/Support/Assert.php new file mode 100644 index 00000000..02fdbe1e --- /dev/null +++ b/src/Support/Assert.php @@ -0,0 +1,40 @@ +delete(); }); +test('uid rejects command injection through the public query API', function (int|string|array $uid) { + $folder = folder(); + $id = $folder->messages()->append(new DraftMessage(from: 'foo@example.com', text: 'Original message')); + + expect(fn () => $folder->messages()->uid($uid)->withHeaders()->withBody()->get()) + ->toThrow(InvalidArgumentException::class); + + expect($folder->messages()->uid($id)->withHeaders()->withBody()->firstOrFail()->text())->toBe('Original message'); + expect($folder->messages()->count())->toBe(1); +})->with([ + ["1\r\nX1 SELECT Secret\r\nX2 NOOP"], + ["2\r\nX1 UID STORE 1:* +FLAGS.SILENT (\\Deleted)\r\nX2 EXPUNGE\r\nX3 NOOP"], + [["1\r\nX1 NOOP"]], +]); + +test('flag rejects command injection through the public message APIs', function (bool $query) { + $folder = folder(); + $id = $folder->messages()->append(new DraftMessage(from: 'foo@example.com', text: 'Original message')); + $target = $query ? $folder->messages()->uid($id) : $folder->messages()->findOrFail($id); + + expect(fn () => $target->flag("Seen2)\r\nX1 UID STORE 1:* +FLAGS.SILENT (\\Deleted)\r\nX2 EXPUNGE\r\nX3 NOOP (", '+')) + ->toThrow(InvalidArgumentException::class); + + expect($folder->messages()->count())->toBe(1); + expect($folder->messages()->findOrFail($id)->flags())->not->toContain('\\Deleted'); +})->with([false, true]); + +test('append rejects injected flags through the public query API', function () { + $folder = folder(); + + expect(fn () => $folder->messages()->append( + new DraftMessage(from: 'foo@example.com', text: 'Original message'), + ["Seen)\r\nX1 NOOP ("], + ))->toThrow(InvalidArgumentException::class); + + expect($folder->messages()->count())->toBe(0); +}); + test('messages selects folder', function () { $folder = folder(); diff --git a/tests/Unit/Connection/ImapCommandTest.php b/tests/Unit/Connection/ImapCommandTest.php index a3a71b37..6ee27118 100644 --- a/tests/Unit/Connection/ImapCommandTest.php +++ b/tests/Unit/Connection/ImapCommandTest.php @@ -3,6 +3,30 @@ use DirectoryTree\ImapEngine\Connection\ImapCommand; use DirectoryTree\ImapEngine\Connection\ImapCommandLine; +test('compile rejects control characters in command syntax', function (string $tag, string $command, array $tokens) { + expect(fn () => (new ImapCommand($tag, $command, $tokens))->compile()) + ->toThrow(InvalidArgumentException::class); +})->with([ + ["A001\r\nX1 NOOP", 'NOOP', []], + ['A001', "NOOP\r\nX1 NOOP", []], + ['A001', 'UID SEARCH', ["UID 1\r\nX1 SELECT Secret"]], + ['A001', 'NOOP', ["foo\rbar"]], + ['A001', 'NOOP', ["foo\nbar"]], + ['A001', 'NOOP', ["foo\0bar"]], + ['A001', 'APPEND', [["{5}\r\nX1 NOOP", 'hello']]], + ['A001', 'APPEND', [['{5}', 'hello'], "foo\r\nX1 NOOP"]], +]); + +test('compile preserves control characters in literal content', function () { + $literal = "Subject: Test\r\n\r\nX1 NOOP\r\n"; + $command = new ImapCommand('A001', 'APPEND', ['"INBOX"', ['{'.strlen($literal).'}', $literal]]); + + $lines = $command->compile(); + + expect($lines)->toHaveCount(2); + expect($lines[1]->value)->toBe($literal); +}); + test('compile returns correct command lines for no tokens', function () { $cmd = new ImapCommand('A001', 'NOOP'); diff --git a/tests/Unit/Connection/ImapConnectionTest.php b/tests/Unit/Connection/ImapConnectionTest.php index b77bdda1..d8f2573d 100644 --- a/tests/Unit/Connection/ImapConnectionTest.php +++ b/tests/Unit/Connection/ImapConnectionTest.php @@ -2,6 +2,7 @@ use DirectoryTree\ImapEngine\Collections\ResponseCollection; use DirectoryTree\ImapEngine\Connection\ImapConnection; +use DirectoryTree\ImapEngine\Connection\ImapQueryBuilder; use DirectoryTree\ImapEngine\Connection\Streams\FakeStream; use DirectoryTree\ImapEngine\Enums\ImapFetchIdentifier; use DirectoryTree\ImapEngine\Exceptions\ImapCommandException; @@ -9,6 +10,85 @@ use DirectoryTree\ImapEngine\Exceptions\ImapConnectionFailedException; use DirectoryTree\ImapEngine\Support\Str; +test('store rejects injected flags before writing to the stream', function () { + $stream = new FakeStream; + $stream->open(); + + $connection = new ImapConnection($stream); + + expect(fn () => $connection->store(["Seen)\r\nX1 CREATE Injected\r\nX2 NOOP ("], 1)) + ->toThrow(InvalidArgumentException::class); + + $stream->assertNotWritten('TAG1'); +}); + +test('append rejects injected flags before writing to the stream', function () { + $stream = new FakeStream; + $stream->open(); + + $connection = new ImapConnection($stream); + + expect(fn () => $connection->append('INBOX', "Subject: Test\r\n\r\nBody", ["Seen)\r\nX1 NOOP ("])) + ->toThrow(InvalidArgumentException::class); + + $stream->assertNotWritten('TAG1'); +}); + +test('send validates all tokens before writing a literal command', function () { + $stream = new FakeStream; + $stream->open(); + + $connection = new ImapConnection($stream); + + expect(fn () => $connection->send('APPEND', [['{5}', 'hello'], "\r\nX1 NOOP"])) + ->toThrow(InvalidArgumentException::class); + + $stream->assertNotWritten('TAG1'); +}); + +test('store accepts system flags and custom keywords', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome to IMAP', 'TAG1 OK STORE completed']); + + $connection = new ImapConnection($stream); + $connection->connect('imap.example.com'); + $connection->store(['\\Seen', 'Important', '$Junk'], 1); + + $stream->assertWritten('TAG1 UID STORE 1 +FLAGS.SILENT (\\Seen Important $Junk)'); +}); + +test('raw command arguments reject injected commands before writing', function (string $method, array $arguments) { + $stream = new FakeStream; + $stream->open(); + + $connection = new ImapConnection($stream); + + expect(fn () => $connection->{$method}(...$arguments))->toThrow(InvalidArgumentException::class); + + $stream->assertNotWritten('TAG1'); +})->with([ + ['status', ['INBOX', ["MESSAGES)\r\nX1 NOOP"]]], + ['bodyPart', ["1]\r\nX1 NOOP", 1]], + ['fetch', [['FLAGS'], ["1\r\nX1 NOOP"]]], + ['copy', ['Archive', ["1\r\nX1 NOOP"]]], + ['move', ['Archive', ["1\r\nX1 NOOP"]]], + ['store', [['\\Seen'], ["1\r\nX1 NOOP"]]], + ['store', [['\\Seen'], 1, null, '+', true, "FLAGS\r\nX1 NOOP"]], +]); + +test('header names reject injected commands before writing', function () { + $stream = new FakeStream; + $stream->open(); + + $connection = new ImapConnection($stream); + $query = (new ImapQueryBuilder)->header("Subject\r\nX1 NOOP", 'test'); + + expect(fn () => $connection->search([$query->toImap()]))->toThrow(InvalidArgumentException::class); + + $stream->assertNotWritten('TAG1'); +}); + test('connect success', function () { $stream = new FakeStream; diff --git a/tests/Unit/Connection/ImapQueryBuilderTest.php b/tests/Unit/Connection/ImapQueryBuilderTest.php index 9c10c806..95a401d2 100644 --- a/tests/Unit/Connection/ImapQueryBuilderTest.php +++ b/tests/Unit/Connection/ImapQueryBuilderTest.php @@ -5,6 +5,13 @@ use DirectoryTree\ImapEngine\Connection\RawQueryValue; use DirectoryTree\ImapEngine\Enums\ImapSearchKey; +test('uid rejects injected commands', function () { + $builder = new ImapQueryBuilder; + + expect(fn () => $builder->uid("1\r\nX1 SELECT Secret\r\nX2 NOOP")) + ->toThrow(InvalidArgumentException::class); +}); + test('returns an empty string if no conditions are provided', function () { $builder = new ImapQueryBuilder; diff --git a/tests/Unit/Support/AssertTest.php b/tests/Unit/Support/AssertTest.php new file mode 100644 index 00000000..d908800c --- /dev/null +++ b/tests/Unit/Support/AssertTest.php @@ -0,0 +1,35 @@ + Assert::isToken($token))->not->toThrow(InvalidArgumentException::class); +})->with(['TAG1', 'UID SEARCH', 'UID 1:5', '(\\Seen Important)', '{5}', '{5+}', '"INBOX"']); + +test('isToken rejects control characters', function (string $token) { + expect(fn () => Assert::isToken($token))->toThrow(InvalidArgumentException::class); +})->with([ + "UID 1\r\nX1 SELECT Secret", "foo\rbar", "foo\nbar", "foo\0bar", "foo\tbar", "foo\x7Fbar", +]); + +test('isFlag accepts system flags and keywords', function (string $flag) { + expect(fn () => Assert::isFlag($flag))->not->toThrow(InvalidArgumentException::class); +})->with(['\\Seen', '\\Draft', '\\Custom', 'Important', '$Junk']); + +test('isFlag rejects invalid atoms', function (string $flag) { + expect(fn () => Assert::isFlag($flag))->toThrow(InvalidArgumentException::class); +})->with([ + '', '\\', 'two flags', '(Seen)', '{5}', '%', '*', '"Seen"', + 'foo\\bar', '\\\\Seen', 'Seen]', "Seen\0", "Seen\t", "Seen\r", "Seen\n", "Seen\x7F", 'é', + "Seen)\r\nX1 NOOP (", +]); + +test('isSequenceSet accepts message numbers and ranges', function (string $set) { + expect(fn () => Assert::isSequenceSet($set))->not->toThrow(InvalidArgumentException::class); +})->with(['1', '*', '1:*', '*:4', '9:3', '1,3:5,*']); + +test('isSequenceSet rejects invalid sequence sets', function (string $set) { + expect(fn () => Assert::isSequenceSet($set))->toThrow(InvalidArgumentException::class); +})->with([ + "1\r\nX1 NOOP", '1e2', '01', '1 ALL', '1,,2', '1:2:3', '', '0', '-1', '1.5', +]); diff --git a/tests/Unit/Support/StrTest.php b/tests/Unit/Support/StrTest.php index 630ccf2a..8825f615 100644 --- a/tests/Unit/Support/StrTest.php +++ b/tests/Unit/Support/StrTest.php @@ -23,6 +23,34 @@ expect(Str::set([1, '*']))->toBe('1,*'); }); +test('set preserves valid sequence set strings', function (string $value) { + expect(Str::set($value))->toBe($value); +})->with(['1', '*', '1:*', '*:4', '9:3', '1,3:5,*']); + +test('set validates inputs before and after formatting', function (mixed $from, mixed $to) { + expect(fn () => Str::set($from, $to))->toThrow(InvalidArgumentException::class); +})->with([ + ["1\r\nX1 NOOP", null], + [["1\r\nX1 NOOP"], null], + [['1e2', 101], null], + [['01', 2], null], + [[], null], + [1, "2\r\nX1 NOOP"], + [1, 1.5], +]); + +test('flags preserves system flags and keywords', function () { + expect(Str::flags(['\\Seen', '\\Draft', '\\Custom', 'Important', '$Junk'])) + ->toBe('(\\Seen \\Draft \\Custom Important $Junk)'); + + expect(Str::flags([]))->toBe('()'); +}); + +test('flags validates each flag before formatting', function () { + expect(fn () => Str::flags(['\\Seen', "Important\r\nX1 NOOP"])) + ->toThrow(InvalidArgumentException::class); +}); + test('credentials', function () { expect(Str::credentials('foo', 'bar'))->toBe('dXNlcj1mb28BYXV0aD1CZWFyZXIgYmFyAQE='); }); From 62555ca2e92b3e9a06d8ffdcb5e7822e07890b42 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Mon, 16 Nov 2026 17:25:28 -0500 Subject: [PATCH 2/2] Clarify IMAP assertion method names --- src/Connection/ImapCommand.php | 8 ++++---- src/Support/Assert.php | 6 +++--- src/Support/Str.php | 4 ++-- tests/Unit/Support/AssertTest.php | 24 ++++++++++++------------ 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Connection/ImapCommand.php b/src/Connection/ImapCommand.php index e9791613..507c534b 100644 --- a/src/Connection/ImapCommand.php +++ b/src/Connection/ImapCommand.php @@ -60,8 +60,8 @@ public function compile(): array $lines = []; - Assert::isToken($this->tag); - Assert::isToken($this->command); + Assert::hasNoControlCharacters($this->tag); + Assert::hasNoControlCharacters($this->command); $line = trim("{$this->tag} {$this->command}"); @@ -72,7 +72,7 @@ public function compile(): array // The second element holds the actual literal content. [$length, $literal] = $token; - Assert::isToken($length); + Assert::hasNoControlCharacters($length); $lines[] = new ImapCommandLine( value: "{$line} {$length}", @@ -81,7 +81,7 @@ public function compile(): array $line = $literal; } else { - Assert::isToken($token); + Assert::hasNoControlCharacters($token); $line .= " {$token}"; } diff --git a/src/Support/Assert.php b/src/Support/Assert.php index 02fdbe1e..2d166b21 100644 --- a/src/Support/Assert.php +++ b/src/Support/Assert.php @@ -9,7 +9,7 @@ class Assert /** * Ensure command syntax cannot contain control characters. */ - public static function isToken(string $token): void + public static function hasNoControlCharacters(string $token): void { if (preg_match('/[\x00-\x1F\x7F]/', $token)) { throw new InvalidArgumentException('IMAP command syntax cannot contain control characters.'); @@ -19,7 +19,7 @@ public static function isToken(string $token): void /** * Ensure a flag contains a valid IMAP atom. */ - public static function isFlag(string $flag): void + public static function isValidFlag(string $flag): void { $atom = str_starts_with($flag, '\\') ? substr($flag, 1) : $flag; @@ -31,7 +31,7 @@ public static function isFlag(string $flag): void /** * Ensure a sequence set contains valid message numbers and ranges. */ - public static function isSequenceSet(string $set): void + public static function isValidSequenceSet(string $set): void { if (! preg_match('/\A(?:[1-9][0-9]*|\*)(?::(?:[1-9][0-9]*|\*))?(?:,(?:[1-9][0-9]*|\*)(?::(?:[1-9][0-9]*|\*))?)*\z/', $set)) { throw new InvalidArgumentException('Invalid IMAP sequence set.'); diff --git a/src/Support/Str.php b/src/Support/Str.php index 433297f8..7b515979 100644 --- a/src/Support/Str.php +++ b/src/Support/Str.php @@ -31,7 +31,7 @@ public static function list(array $list): string public static function flags(array $flags): string { foreach ($flags as $flag) { - Assert::isFlag($flag); + Assert::isValidFlag($flag); } return static::list($flags); @@ -106,7 +106,7 @@ public static function set(int|string|array $from, int|float|string|null $to = n } } - Assert::isSequenceSet($set); + Assert::isValidSequenceSet($set); return $set; } diff --git a/tests/Unit/Support/AssertTest.php b/tests/Unit/Support/AssertTest.php index d908800c..f408eb04 100644 --- a/tests/Unit/Support/AssertTest.php +++ b/tests/Unit/Support/AssertTest.php @@ -2,34 +2,34 @@ use DirectoryTree\ImapEngine\Support\Assert; -test('isToken accepts command syntax', function (string $token) { - expect(fn () => Assert::isToken($token))->not->toThrow(InvalidArgumentException::class); +test('hasNoControlCharacters accepts command syntax', function (string $token) { + expect(fn () => Assert::hasNoControlCharacters($token))->not->toThrow(InvalidArgumentException::class); })->with(['TAG1', 'UID SEARCH', 'UID 1:5', '(\\Seen Important)', '{5}', '{5+}', '"INBOX"']); -test('isToken rejects control characters', function (string $token) { - expect(fn () => Assert::isToken($token))->toThrow(InvalidArgumentException::class); +test('hasNoControlCharacters rejects control characters', function (string $token) { + expect(fn () => Assert::hasNoControlCharacters($token))->toThrow(InvalidArgumentException::class); })->with([ "UID 1\r\nX1 SELECT Secret", "foo\rbar", "foo\nbar", "foo\0bar", "foo\tbar", "foo\x7Fbar", ]); -test('isFlag accepts system flags and keywords', function (string $flag) { - expect(fn () => Assert::isFlag($flag))->not->toThrow(InvalidArgumentException::class); +test('isValidFlag accepts system flags and keywords', function (string $flag) { + expect(fn () => Assert::isValidFlag($flag))->not->toThrow(InvalidArgumentException::class); })->with(['\\Seen', '\\Draft', '\\Custom', 'Important', '$Junk']); -test('isFlag rejects invalid atoms', function (string $flag) { - expect(fn () => Assert::isFlag($flag))->toThrow(InvalidArgumentException::class); +test('isValidFlag rejects invalid atoms', function (string $flag) { + expect(fn () => Assert::isValidFlag($flag))->toThrow(InvalidArgumentException::class); })->with([ '', '\\', 'two flags', '(Seen)', '{5}', '%', '*', '"Seen"', 'foo\\bar', '\\\\Seen', 'Seen]', "Seen\0", "Seen\t", "Seen\r", "Seen\n", "Seen\x7F", 'é', "Seen)\r\nX1 NOOP (", ]); -test('isSequenceSet accepts message numbers and ranges', function (string $set) { - expect(fn () => Assert::isSequenceSet($set))->not->toThrow(InvalidArgumentException::class); +test('isValidSequenceSet accepts message numbers and ranges', function (string $set) { + expect(fn () => Assert::isValidSequenceSet($set))->not->toThrow(InvalidArgumentException::class); })->with(['1', '*', '1:*', '*:4', '9:3', '1,3:5,*']); -test('isSequenceSet rejects invalid sequence sets', function (string $set) { - expect(fn () => Assert::isSequenceSet($set))->toThrow(InvalidArgumentException::class); +test('isValidSequenceSet rejects invalid sequence sets', function (string $set) { + expect(fn () => Assert::isValidSequenceSet($set))->toThrow(InvalidArgumentException::class); })->with([ "1\r\nX1 NOOP", '1e2', '01', '1 ALL', '1,,2', '1:2:3', '', '0', '-1', '1.5', ]);