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
8 changes: 8 additions & 0 deletions src/Connection/ImapCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace DirectoryTree\ImapEngine\Connection;

use DirectoryTree\ImapEngine\Support\Assert;
use Stringable;

class ImapCommand implements Stringable
Expand Down Expand Up @@ -59,6 +60,9 @@ public function compile(): array

$lines = [];

Assert::hasNoControlCharacters($this->tag);
Assert::hasNoControlCharacters($this->command);

$line = trim("{$this->tag} {$this->command}");

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

Assert::hasNoControlCharacters($length);

$lines[] = new ImapCommandLine(
value: "{$line} {$length}",
synchronizing: ! str_contains($length, '+'),
);

$line = $literal;
} else {
Assert::hasNoControlCharacters($token);

$line .= " {$token}";
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Connection/ImapConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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' : '');

Expand Down
40 changes: 40 additions & 0 deletions src/Support/Assert.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace DirectoryTree\ImapEngine\Support;

use InvalidArgumentException;

class Assert
{
/**
* Ensure command syntax cannot contain control characters.
*/
public static function hasNoControlCharacters(string $token): void
{
if (preg_match('/[\x00-\x1F\x7F]/', $token)) {
throw new InvalidArgumentException('IMAP command syntax cannot contain control characters.');
}
}

/**
* Ensure a flag contains a valid IMAP atom.
*/
public static function isValidFlag(string $flag): void
{
$atom = str_starts_with($flag, '\\') ? substr($flag, 1) : $flag;

if ($atom === '' || preg_match('/[^\x21-\x7E]/', $atom) || strpbrk($atom, '(){%*"\\]') !== false) {
throw new InvalidArgumentException('Invalid IMAP flag.');
}
}

/**
* Ensure a sequence set contains valid message numbers and ranges.
*/
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.');
}
}
}
35 changes: 24 additions & 11 deletions src/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ public static function list(array $list): string
return sprintf('(%s)', implode(' ', $values));
}

/**
* Make a list of IMAP flags.
*/
public static function flags(array $flags): string
{
foreach ($flags as $flag) {
Assert::isValidFlag($flag);
}

return static::list($flags);
}

/**
* Make one or more literals.
*/
Expand Down Expand Up @@ -81,21 +93,22 @@ public static function enum(BackedEnum|string $enum): string
public static function set(int|string|array $from, int|float|string|null $to = null): string
{
if (is_array($from)) {
return static::toSequenceSet($from);
}
foreach ($from as $value) {
static::set($value);
}

// At this point, $from is an integer. No upper bound provided, return $from as a string.
if (is_null($to)) {
return (string) $from;
}
$set = static::toSequenceSet($from);
} else {
$set = (string) $from;

// If the upper bound is infinite, use the '*' notation.
if ($to == INF) {
return $from.':*';
if (! is_null($to)) {
$set .= ':'.($to === INF ? '*' : $to);
}
}

// Otherwise, return a typical range string.
return $from.':'.$to;
Assert::isValidSequenceSet($set);

return $set;
}

/**
Expand Down
38 changes: 38 additions & 0 deletions tests/Integration/MessagesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,44 @@ function folder(): Folder
folder()->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();

Expand Down
24 changes: 24 additions & 0 deletions tests/Unit/Connection/ImapCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down
80 changes: 80 additions & 0 deletions tests/Unit/Connection/ImapConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,93 @@

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;
use DirectoryTree\ImapEngine\Exceptions\ImapConnectionException;
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;

Expand Down
7 changes: 7 additions & 0 deletions tests/Unit/Connection/ImapQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
35 changes: 35 additions & 0 deletions tests/Unit/Support/AssertTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

use DirectoryTree\ImapEngine\Support\Assert;

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('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('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('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('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('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',
]);
Loading
Loading