Skip to content
Closed
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
71 changes: 71 additions & 0 deletions Tests/Transport/HeaderInjectionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

/**
* @copyright Copyright (C) 2005 - 2026 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/

namespace Joomla\Http\Tests\Transport;

use Joomla\Http\AbstractTransport;
use Joomla\Http\Transport\Curl;
use Joomla\Http\Transport\Socket;
use Joomla\Http\Transport\Stream;
use Joomla\Uri\Uri;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

/**
* Test class for the rejection of header injection by the transports.
*/
#[CoversClass(AbstractTransport::class)]
#[CoversClass(Curl::class)]
#[CoversClass(Socket::class)]
#[CoversClass(Stream::class)]
class HeaderInjectionTest extends TestCase
{
public static function transportAndHeadersProvider(): \Generator
{
$headers = [
'CRLF in a value' => [['X-Test' => "a\r\nX-Injected: 1"], null],
'LF in a value' => [['X-Test' => "a\nX-Injected: 1"], null],
'CR in a value' => [['X-Test' => "a\rX-Injected: 1"], null],
'NUL in a value' => [['X-Test' => "a\0b"], null],
'CRLF in a list value' => [['X-Test' => ['ok', "a\r\nX-Injected: 1"]], null],
'colon in a name' => [['X-Test: 1' . "\r\n" . 'X-Injected' => '1'], null],
'space in a name' => [['X Test' => '1'], null],
'empty name' => [['' => '1'], null],
'CRLF in the user agent' => [[], "agent\r\nX-Injected: 1"],
];

foreach ([Curl::class, Socket::class, Stream::class] as $transport) {
foreach ($headers as $name => [$requestHeaders, $userAgent]) {
yield substr(strrchr($transport, '\\'), 1) . ', ' . $name => [$transport, $requestHeaders, $userAgent];
}
}
}

#[DataProvider('transportAndHeadersProvider')]
public function testHeadersThatWouldInjectFurtherHeadersAreRejected(string $transportClass, array $headers, ?string $userAgent): void
{
if (!$transportClass::isSupported()) {
$this->markTestSkipped(sprintf('The "%s" adapter is not supported in this environment.', $transportClass));
}

// The socket transport connects before it builds the request, so it needs a server.
$url = \defined('JTEST_HTTP_STUB') ? JTEST_HTTP_STUB : (string) getenv('JTEST_HTTP_STUB');

if ($url === '') {
if ($transportClass === Socket::class) {
$this->markTestSkipped('The Transport test stub has not been configured');
}

$url = 'http://127.0.0.1:1/';
}

$this->expectException(\InvalidArgumentException::class);

(new $transportClass([]))->request('GET', new Uri($url), null, $headers, null, $userAgent);
}
}
5 changes: 5 additions & 0 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ $headers = ['Accept' => 'application/foo'];
$pull = $http->get('https://api.github.com/repos/joomla-framework/http/pulls/1', $headers);
```

Header names must be valid HTTP tokens, and header values (including the user agent) must not contain
line breaks or NUL bytes. Every transport throws an `InvalidArgumentException` for a header that
would otherwise split the request and inject further headers, so validate or strip such input when
it comes from users.

## Things to know before you build on this

**There is no SSRF protection.** Any URI is accepted and fetched, including private address ranges
Expand Down
30 changes: 30 additions & 0 deletions src/AbstractTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,36 @@ protected function getOption(string $key, $default = null)
return $this->options[$key] ?? $default;
}

/**
* Validate the names and values of request headers.
*
* Header names must be RFC 9110 tokens and values must not contain line breaks or NUL bytes, which would
* otherwise allow injecting further headers into the request.
*
* @param array $headers The request headers, with a string or a list of strings per name.
*
* @return void
*
* @since __DEPLOY_VERSION__
* @throws \InvalidArgumentException
*/
protected function validateHeaders(array $headers): void
{
foreach ($headers as $name => $value) {
if (!preg_match('/^[!#$%&\'*+.^_`|~0-9A-Za-z-]+$/D', (string) $name)) {
throw new \InvalidArgumentException(sprintf('"%s" is not a valid header name.', $name));
}

foreach ((array) $value as $item) {
if (strpbrk((string) $item, "\r\n\0") !== false) {
throw new \InvalidArgumentException(
sprintf('The value of the "%s" header must not contain line breaks or NUL bytes.', $name)
);
}
}
}
}

/**
* Processes the headers from a transport's response data.
*
Expand Down
4 changes: 4 additions & 0 deletions src/Transport/Curl.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ class Curl extends AbstractTransport
*/
public function request($method, UriInterface $uri, $data = null, array $headers = [], $timeout = null, $userAgent = null)
{
// Reject header names and values that would inject further headers.
$this->validateHeaders($headers);
$this->validateHeaders(['User-Agent' => (string) $userAgent]);

// Setup the cURL handle.
$ch = curl_init();

Expand Down
4 changes: 4 additions & 0 deletions src/Transport/Socket.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ public function request($method, UriInterface $uri, $data = null, array $headers
throw new \RuntimeException('Server connection timed out.');
}

// Reject header names and values that would inject further headers.
$this->validateHeaders($headers);
$this->validateHeaders(['User-Agent' => (string) $userAgent]);

// Get the request path from the URI object.
$path = $uri->toString(['path', 'query']);

Expand Down
4 changes: 4 additions & 0 deletions src/Transport/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ public function request(
$timeout = null,
$userAgent = null
) {
// Reject header names and values that would inject further headers.
$this->validateHeaders($headers);
$this->validateHeaders(['User-Agent' => (string) $userAgent]);

// Create the stream context options array with the required method offset.
$options = ['method' => strtoupper($method)];

Expand Down
Loading