Skip to content

Commit e052d71

Browse files
authored
Merge pull request #208 from DirectoryTree/fix/imap-command-injection
Prevent IMAP command injection in UID values and message flags
2 parents 136f415 + 62555ca commit e052d71

10 files changed

Lines changed: 286 additions & 13 deletions

File tree

‎src/Connection/ImapCommand.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace DirectoryTree\ImapEngine\Connection;
44

5+
use DirectoryTree\ImapEngine\Support\Assert;
56
use Stringable;
67

78
class ImapCommand implements Stringable
@@ -59,6 +60,9 @@ public function compile(): array
5960

6061
$lines = [];
6162

63+
Assert::hasNoControlCharacters($this->tag);
64+
Assert::hasNoControlCharacters($this->command);
65+
6266
$line = trim("{$this->tag} {$this->command}");
6367

6468
foreach ($this->tokens as $token) {
@@ -68,13 +72,17 @@ public function compile(): array
6872
// The second element holds the actual literal content.
6973
[$length, $literal] = $token;
7074

75+
Assert::hasNoControlCharacters($length);
76+
7177
$lines[] = new ImapCommandLine(
7278
value: "{$line} {$length}",
7379
synchronizing: ! str_contains($length, '+'),
7480
);
7581

7682
$line = $literal;
7783
} else {
84+
Assert::hasNoControlCharacters($token);
85+
7886
$line .= " {$token}";
7987
}
8088
}

‎src/Connection/ImapConnection.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ public function append(string $folder, string $message, ?array $flags = null): T
374374
$tokens[] = Str::literal($folder);
375375

376376
if ($flags) {
377-
$tokens[] = Str::list($flags);
377+
$tokens[] = Str::flags($flags);
378378
}
379379

380380
$tokens[] = Str::literal($message);
@@ -417,7 +417,7 @@ public function store(array|string $flags, array|int $from, ?int $to = null, ?st
417417
{
418418
$set = Str::set($from, $to);
419419

420-
$flags = Str::list((array) $flags);
420+
$flags = Str::flags((array) $flags);
421421

422422
$item = ($mode == '-' ? '-' : '+').(is_null($item) ? 'FLAGS' : $item).($silent ? '.SILENT' : '');
423423

‎src/Support/Assert.php‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace DirectoryTree\ImapEngine\Support;
4+
5+
use InvalidArgumentException;
6+
7+
class Assert
8+
{
9+
/**
10+
* Ensure command syntax cannot contain control characters.
11+
*/
12+
public static function hasNoControlCharacters(string $token): void
13+
{
14+
if (preg_match('/[\x00-\x1F\x7F]/', $token)) {
15+
throw new InvalidArgumentException('IMAP command syntax cannot contain control characters.');
16+
}
17+
}
18+
19+
/**
20+
* Ensure a flag contains a valid IMAP atom.
21+
*/
22+
public static function isValidFlag(string $flag): void
23+
{
24+
$atom = str_starts_with($flag, '\\') ? substr($flag, 1) : $flag;
25+
26+
if ($atom === '' || preg_match('/[^\x21-\x7E]/', $atom) || strpbrk($atom, '(){%*"\\]') !== false) {
27+
throw new InvalidArgumentException('Invalid IMAP flag.');
28+
}
29+
}
30+
31+
/**
32+
* Ensure a sequence set contains valid message numbers and ranges.
33+
*/
34+
public static function isValidSequenceSet(string $set): void
35+
{
36+
if (! preg_match('/\A(?:[1-9][0-9]*|\*)(?::(?:[1-9][0-9]*|\*))?(?:,(?:[1-9][0-9]*|\*)(?::(?:[1-9][0-9]*|\*))?)*\z/', $set)) {
37+
throw new InvalidArgumentException('Invalid IMAP sequence set.');
38+
}
39+
}
40+
}

‎src/Support/Str.php‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@ public static function list(array $list): string
2525
return sprintf('(%s)', implode(' ', $values));
2626
}
2727

28+
/**
29+
* Make a list of IMAP flags.
30+
*/
31+
public static function flags(array $flags): string
32+
{
33+
foreach ($flags as $flag) {
34+
Assert::isValidFlag($flag);
35+
}
36+
37+
return static::list($flags);
38+
}
39+
2840
/**
2941
* Make one or more literals.
3042
*/
@@ -81,21 +93,22 @@ public static function enum(BackedEnum|string $enum): string
8193
public static function set(int|string|array $from, int|float|string|null $to = null): string
8294
{
8395
if (is_array($from)) {
84-
return static::toSequenceSet($from);
85-
}
96+
foreach ($from as $value) {
97+
static::set($value);
98+
}
8699

87-
// At this point, $from is an integer. No upper bound provided, return $from as a string.
88-
if (is_null($to)) {
89-
return (string) $from;
90-
}
100+
$set = static::toSequenceSet($from);
101+
} else {
102+
$set = (string) $from;
91103

92-
// If the upper bound is infinite, use the '*' notation.
93-
if ($to == INF) {
94-
return $from.':*';
104+
if (! is_null($to)) {
105+
$set .= ':'.($to === INF ? '*' : $to);
106+
}
95107
}
96108

97-
// Otherwise, return a typical range string.
98-
return $from.':'.$to;
109+
Assert::isValidSequenceSet($set);
110+
111+
return $set;
99112
}
100113

101114
/**

‎tests/Integration/MessagesTest.php‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,44 @@ function folder(): Folder
2323
folder()->delete();
2424
});
2525

26+
test('uid rejects command injection through the public query API', function (int|string|array $uid) {
27+
$folder = folder();
28+
$id = $folder->messages()->append(new DraftMessage(from: 'foo@example.com', text: 'Original message'));
29+
30+
expect(fn () => $folder->messages()->uid($uid)->withHeaders()->withBody()->get())
31+
->toThrow(InvalidArgumentException::class);
32+
33+
expect($folder->messages()->uid($id)->withHeaders()->withBody()->firstOrFail()->text())->toBe('Original message');
34+
expect($folder->messages()->count())->toBe(1);
35+
})->with([
36+
["1\r\nX1 SELECT Secret\r\nX2 NOOP"],
37+
["2\r\nX1 UID STORE 1:* +FLAGS.SILENT (\\Deleted)\r\nX2 EXPUNGE\r\nX3 NOOP"],
38+
[["1\r\nX1 NOOP"]],
39+
]);
40+
41+
test('flag rejects command injection through the public message APIs', function (bool $query) {
42+
$folder = folder();
43+
$id = $folder->messages()->append(new DraftMessage(from: 'foo@example.com', text: 'Original message'));
44+
$target = $query ? $folder->messages()->uid($id) : $folder->messages()->findOrFail($id);
45+
46+
expect(fn () => $target->flag("Seen2)\r\nX1 UID STORE 1:* +FLAGS.SILENT (\\Deleted)\r\nX2 EXPUNGE\r\nX3 NOOP (", '+'))
47+
->toThrow(InvalidArgumentException::class);
48+
49+
expect($folder->messages()->count())->toBe(1);
50+
expect($folder->messages()->findOrFail($id)->flags())->not->toContain('\\Deleted');
51+
})->with([false, true]);
52+
53+
test('append rejects injected flags through the public query API', function () {
54+
$folder = folder();
55+
56+
expect(fn () => $folder->messages()->append(
57+
new DraftMessage(from: 'foo@example.com', text: 'Original message'),
58+
["Seen)\r\nX1 NOOP ("],
59+
))->toThrow(InvalidArgumentException::class);
60+
61+
expect($folder->messages()->count())->toBe(0);
62+
});
63+
2664
test('messages selects folder', function () {
2765
$folder = folder();
2866

‎tests/Unit/Connection/ImapCommandTest.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,30 @@
33
use DirectoryTree\ImapEngine\Connection\ImapCommand;
44
use DirectoryTree\ImapEngine\Connection\ImapCommandLine;
55

6+
test('compile rejects control characters in command syntax', function (string $tag, string $command, array $tokens) {
7+
expect(fn () => (new ImapCommand($tag, $command, $tokens))->compile())
8+
->toThrow(InvalidArgumentException::class);
9+
})->with([
10+
["A001\r\nX1 NOOP", 'NOOP', []],
11+
['A001', "NOOP\r\nX1 NOOP", []],
12+
['A001', 'UID SEARCH', ["UID 1\r\nX1 SELECT Secret"]],
13+
['A001', 'NOOP', ["foo\rbar"]],
14+
['A001', 'NOOP', ["foo\nbar"]],
15+
['A001', 'NOOP', ["foo\0bar"]],
16+
['A001', 'APPEND', [["{5}\r\nX1 NOOP", 'hello']]],
17+
['A001', 'APPEND', [['{5}', 'hello'], "foo\r\nX1 NOOP"]],
18+
]);
19+
20+
test('compile preserves control characters in literal content', function () {
21+
$literal = "Subject: Test\r\n\r\nX1 NOOP\r\n";
22+
$command = new ImapCommand('A001', 'APPEND', ['"INBOX"', ['{'.strlen($literal).'}', $literal]]);
23+
24+
$lines = $command->compile();
25+
26+
expect($lines)->toHaveCount(2);
27+
expect($lines[1]->value)->toBe($literal);
28+
});
29+
630
test('compile returns correct command lines for no tokens', function () {
731
$cmd = new ImapCommand('A001', 'NOOP');
832

‎tests/Unit/Connection/ImapConnectionTest.php‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,93 @@
22

33
use DirectoryTree\ImapEngine\Collections\ResponseCollection;
44
use DirectoryTree\ImapEngine\Connection\ImapConnection;
5+
use DirectoryTree\ImapEngine\Connection\ImapQueryBuilder;
56
use DirectoryTree\ImapEngine\Connection\Streams\FakeStream;
67
use DirectoryTree\ImapEngine\Enums\ImapFetchIdentifier;
78
use DirectoryTree\ImapEngine\Exceptions\ImapCommandException;
89
use DirectoryTree\ImapEngine\Exceptions\ImapConnectionException;
910
use DirectoryTree\ImapEngine\Exceptions\ImapConnectionFailedException;
1011
use DirectoryTree\ImapEngine\Support\Str;
1112

13+
test('store rejects injected flags before writing to the stream', function () {
14+
$stream = new FakeStream;
15+
$stream->open();
16+
17+
$connection = new ImapConnection($stream);
18+
19+
expect(fn () => $connection->store(["Seen)\r\nX1 CREATE Injected\r\nX2 NOOP ("], 1))
20+
->toThrow(InvalidArgumentException::class);
21+
22+
$stream->assertNotWritten('TAG1');
23+
});
24+
25+
test('append rejects injected flags before writing to the stream', function () {
26+
$stream = new FakeStream;
27+
$stream->open();
28+
29+
$connection = new ImapConnection($stream);
30+
31+
expect(fn () => $connection->append('INBOX', "Subject: Test\r\n\r\nBody", ["Seen)\r\nX1 NOOP ("]))
32+
->toThrow(InvalidArgumentException::class);
33+
34+
$stream->assertNotWritten('TAG1');
35+
});
36+
37+
test('send validates all tokens before writing a literal command', function () {
38+
$stream = new FakeStream;
39+
$stream->open();
40+
41+
$connection = new ImapConnection($stream);
42+
43+
expect(fn () => $connection->send('APPEND', [['{5}', 'hello'], "\r\nX1 NOOP"]))
44+
->toThrow(InvalidArgumentException::class);
45+
46+
$stream->assertNotWritten('TAG1');
47+
});
48+
49+
test('store accepts system flags and custom keywords', function () {
50+
$stream = new FakeStream;
51+
$stream->open();
52+
$stream->feed(['* OK Welcome to IMAP', 'TAG1 OK STORE completed']);
53+
54+
$connection = new ImapConnection($stream);
55+
$connection->connect('imap.example.com');
56+
$connection->store(['\\Seen', 'Important', '$Junk'], 1);
57+
58+
$stream->assertWritten('TAG1 UID STORE 1 +FLAGS.SILENT (\\Seen Important $Junk)');
59+
});
60+
61+
test('raw command arguments reject injected commands before writing', function (string $method, array $arguments) {
62+
$stream = new FakeStream;
63+
$stream->open();
64+
65+
$connection = new ImapConnection($stream);
66+
67+
expect(fn () => $connection->{$method}(...$arguments))->toThrow(InvalidArgumentException::class);
68+
69+
$stream->assertNotWritten('TAG1');
70+
})->with([
71+
['status', ['INBOX', ["MESSAGES)\r\nX1 NOOP"]]],
72+
['bodyPart', ["1]\r\nX1 NOOP", 1]],
73+
['fetch', [['FLAGS'], ["1\r\nX1 NOOP"]]],
74+
['copy', ['Archive', ["1\r\nX1 NOOP"]]],
75+
['move', ['Archive', ["1\r\nX1 NOOP"]]],
76+
['store', [['\\Seen'], ["1\r\nX1 NOOP"]]],
77+
['store', [['\\Seen'], 1, null, '+', true, "FLAGS\r\nX1 NOOP"]],
78+
]);
79+
80+
test('header names reject injected commands before writing', function () {
81+
$stream = new FakeStream;
82+
$stream->open();
83+
84+
$connection = new ImapConnection($stream);
85+
$query = (new ImapQueryBuilder)->header("Subject\r\nX1 NOOP", 'test');
86+
87+
expect(fn () => $connection->search([$query->toImap()]))->toThrow(InvalidArgumentException::class);
88+
89+
$stream->assertNotWritten('TAG1');
90+
});
91+
1292
test('connect success', function () {
1393
$stream = new FakeStream;
1494

‎tests/Unit/Connection/ImapQueryBuilderTest.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@
55
use DirectoryTree\ImapEngine\Connection\RawQueryValue;
66
use DirectoryTree\ImapEngine\Enums\ImapSearchKey;
77

8+
test('uid rejects injected commands', function () {
9+
$builder = new ImapQueryBuilder;
10+
11+
expect(fn () => $builder->uid("1\r\nX1 SELECT Secret\r\nX2 NOOP"))
12+
->toThrow(InvalidArgumentException::class);
13+
});
14+
815
test('returns an empty string if no conditions are provided', function () {
916
$builder = new ImapQueryBuilder;
1017

‎tests/Unit/Support/AssertTest.php‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
use DirectoryTree\ImapEngine\Support\Assert;
4+
5+
test('hasNoControlCharacters accepts command syntax', function (string $token) {
6+
expect(fn () => Assert::hasNoControlCharacters($token))->not->toThrow(InvalidArgumentException::class);
7+
})->with(['TAG1', 'UID SEARCH', 'UID 1:5', '(\\Seen Important)', '{5}', '{5+}', '"INBOX"']);
8+
9+
test('hasNoControlCharacters rejects control characters', function (string $token) {
10+
expect(fn () => Assert::hasNoControlCharacters($token))->toThrow(InvalidArgumentException::class);
11+
})->with([
12+
"UID 1\r\nX1 SELECT Secret", "foo\rbar", "foo\nbar", "foo\0bar", "foo\tbar", "foo\x7Fbar",
13+
]);
14+
15+
test('isValidFlag accepts system flags and keywords', function (string $flag) {
16+
expect(fn () => Assert::isValidFlag($flag))->not->toThrow(InvalidArgumentException::class);
17+
})->with(['\\Seen', '\\Draft', '\\Custom', 'Important', '$Junk']);
18+
19+
test('isValidFlag rejects invalid atoms', function (string $flag) {
20+
expect(fn () => Assert::isValidFlag($flag))->toThrow(InvalidArgumentException::class);
21+
})->with([
22+
'', '\\', 'two flags', '(Seen)', '{5}', '%', '*', '"Seen"',
23+
'foo\\bar', '\\\\Seen', 'Seen]', "Seen\0", "Seen\t", "Seen\r", "Seen\n", "Seen\x7F", 'é',
24+
"Seen)\r\nX1 NOOP (",
25+
]);
26+
27+
test('isValidSequenceSet accepts message numbers and ranges', function (string $set) {
28+
expect(fn () => Assert::isValidSequenceSet($set))->not->toThrow(InvalidArgumentException::class);
29+
})->with(['1', '*', '1:*', '*:4', '9:3', '1,3:5,*']);
30+
31+
test('isValidSequenceSet rejects invalid sequence sets', function (string $set) {
32+
expect(fn () => Assert::isValidSequenceSet($set))->toThrow(InvalidArgumentException::class);
33+
})->with([
34+
"1\r\nX1 NOOP", '1e2', '01', '1 ALL', '1,,2', '1:2:3', '', '0', '-1', '1.5',
35+
]);

0 commit comments

Comments
 (0)