Skip to content
Open
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
7 changes: 7 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,13 @@ following redirects. Reusing an arguments object shares that flag across its
submitted requests; use separate arguments objects for independently cancellable
requests. HTTP connection reuse is not provided by this behavior.

Automatic HTTP and WebSocket redirects retain caller-supplied `Authorization` and `Cookie`
headers only while the scheme, hostname and port stay the same. Once a redirect
changes origin, these headers remain removed for the rest of that redirect chain.
The caller's original request arguments are preserved. Other custom headers are
forwarded; applications should avoid putting credentials in those headers when
following redirects to untrusted destinations.

See this [issue](https://github.com/machinezone/IXWebSocket/issues/209) for links about uploading files with HTTP multipart.

## HTTP server API
Expand Down
13 changes: 9 additions & 4 deletions ixwebsocket/IXHttpClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -453,11 +453,16 @@ namespace ix
downloadSize);
}

// Recurse
std::string location = headers["Location"];
const std::string& location = headers.at("Location");
auto redirected = snapshotRequest(*args);
// Credentials are scoped to the same scheme, host and port.
if (!UrlParser::isSameOrigin(url, location))
{
redirected->extraHeaders.erase("Authorization");
redirected->extraHeaders.erase("Cookie");
}
if (code == 303 && verb != kHead)
{
auto redirected = snapshotRequest(*args);
redirected->extraHeaders.erase("Content-Length");
redirected->extraHeaders.erase("Content-Type");
redirected->extraHeaders.erase("Content-Encoding");
Expand All @@ -466,7 +471,7 @@ namespace ix
return requestImpl(
location, kGet, std::string(), redirected, cancel, redirects + 1);
}
return requestImpl(location, verb, body, args, cancel, redirects + 1);
return requestImpl(location, verb, body, redirected, cancel, redirects + 1);
}

if (verb == "HEAD")
Expand Down
13 changes: 13 additions & 0 deletions ixwebsocket/IXUrlParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

#include "IXUrlParser.h"

#include "IXStrCaseCompare.h"
#include <algorithm>
#include <cctype>
#include <cstring>
Expand Down Expand Up @@ -405,6 +406,18 @@ namespace

namespace ix
{
bool UrlParser::isSameOrigin(const std::string& first, const std::string& second)
{
std::string firstProtocol, firstHost, firstPath, firstQuery;
std::string secondProtocol, secondHost, secondPath, secondQuery;
int firstPort, secondPort;
return parse(first, firstProtocol, firstHost, firstPath, firstQuery, firstPort) &&
parse(second, secondProtocol, secondHost, secondPath, secondQuery, secondPort) &&
firstProtocol == secondProtocol && firstPort == secondPort &&
!CaseInsensitiveLess::cmp(firstHost, secondHost) &&
!CaseInsensitiveLess::cmp(secondHost, firstHost);
}

bool UrlParser::parse(const std::string& url,
std::string& protocol,
std::string& host,
Expand Down
3 changes: 3 additions & 0 deletions ixwebsocket/IXUrlParser.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ namespace ix
class UrlParser
{
public:
// Compare scheme, case-insensitive hostname and effective port.
static bool isSameOrigin(const std::string& first, const std::string& second);

static bool parse(const std::string& url,
std::string& protocol,
std::string& host,
Expand Down
8 changes: 7 additions & 1 deletion ixwebsocket/IXWebSocketTransport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ namespace ix
std::string protocol, host, path, query;
int port;
std::string remoteUrl(url);
WebSocketHttpHeaders requestHeaders(headers);

WebSocketInitResult result;
const int maxRedirections = 10;
Expand Down Expand Up @@ -147,7 +148,7 @@ namespace ix
_enablePerMessageDeflate);

result = webSocketHandshake.clientHandshake(remoteUrl,
headers,
requestHeaders,
protocol,
host,
path,
Expand All @@ -167,6 +168,11 @@ namespace ix
break;
}

if (!UrlParser::isSameOrigin(remoteUrl, it->second))
{
requestHeaders.erase("Authorization");
requestHeaders.erase("Cookie");
}
remoteUrl = it->second;
continue;
}
Expand Down
137 changes: 137 additions & 0 deletions test/IXHttpClientResponseTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <ixwebsocket/IXGetFreePort.h>
#include <ixwebsocket/IXHttpClient.h>
#include <ixwebsocket/IXSocketServer.h>
#include <ixwebsocket/IXWebSocket.h>
#include <mutex>

namespace
Expand Down Expand Up @@ -164,6 +165,142 @@ TEST_CASE("307 and 308 redirects preserve the request method and body", "[http][
CHECK(requests[1]->body == "body");
}

TEST_CASE("HTTP redirects keep credentials within the original origin",
"[http][redirect_credentials]")
{
const bool crossOrigin = GENERATE(false, true);
const int status = GENERATE(301, 302, 303, 307, 308);
const std::string ok = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n";
ResponseServer target([&](const ix::HttpRequestPtr&, size_t) { return ok; });
target.startServing();
std::string location;
ResponseServer source(
[&](const ix::HttpRequestPtr&, size_t index)
{
return index == 0
? "HTTP/1.1 " + std::to_string(status) +
" Redirect\r\nLocation: " + location + "\r\nContent-Length: 0\r\n\r\n"
: ok;
});
location = crossOrigin ? target.url() : source.url();
source.startServing();
ix::HttpClient client;
auto args = options(client);
args->extraHeaders["authorization"] = "Bearer secret";
args->extraHeaders["cOoKiE"] = "session=secret";
args->extraHeaders["X-Trace"] = "trace";
auto response = client.request(source.url(), "POST", "body", args);
REQUIRE(response->errorCode == ix::HttpErrorCode::Ok);
CHECK(response->statusCode == 200);
const auto initial = source.requests();
REQUIRE(initial.size() == (crossOrigin ? 1 : 2));
CHECK(initial[0]->headers.at("Authorization") == "Bearer secret");
CHECK(initial[0]->headers.at("Cookie") == "session=secret");
const auto redirected = crossOrigin ? target.requests() : initial;
REQUIRE_FALSE(redirected.empty());
CHECK(redirected.back()->headers.count("Authorization") == (crossOrigin ? 0 : 1));
CHECK(redirected.back()->headers.count("Cookie") == (crossOrigin ? 0 : 1));
CHECK(redirected.back()->headers.at("X-Trace") == "trace");
CHECK(args->extraHeaders.at("Authorization") == "Bearer secret");
CHECK(args->extraHeaders.at("Cookie") == "session=secret");
}

TEST_CASE("WebSocket redirects keep credentials within the original origin",
"[websocket][redirect_credentials]")
{
const bool crossOrigin = GENERATE(false, true);
const std::string rejected = "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
ResponseServer target([&](const ix::HttpRequestPtr&, size_t) { return rejected; });
target.startServing();
std::string location;
ResponseServer source(
[&](const ix::HttpRequestPtr&, size_t index)
{
return index == 0 ? "HTTP/1.1 302 Found\r\nLocation: " + location +
"\r\nContent-Length: 0\r\n\r\n"
: rejected;
});
std::string originalUrl = source.url();
originalUrl.replace(0, 4, "ws");
location = crossOrigin ? target.url() : source.url();
location.replace(0, 4, "ws");
source.startServing();
ix::WebSocket client;
client.setUrl(originalUrl);
const ix::WebSocketHttpHeaders headers = {
{"authorization", "Bearer secret"}, {"cOoKiE", "session=secret"}, {"X-Trace", "trace"}};
client.setExtraHeaders(headers);
auto result = client.connect(1);
CHECK_FALSE(result.success);
CHECK(result.http_status == 401);
const auto initial = source.requests();
REQUIRE(initial.size() == (crossOrigin ? 1 : 2));
CHECK(initial[0]->headers.at("Authorization") == "Bearer secret");
CHECK(initial[0]->headers.at("Cookie") == "session=secret");
const auto redirected = crossOrigin ? target.requests() : initial;
REQUIRE_FALSE(redirected.empty());
CHECK(redirected.back()->headers.count("Authorization") == (crossOrigin ? 0 : 1));
CHECK(redirected.back()->headers.count("Cookie") == (crossOrigin ? 0 : 1));
CHECK(redirected.back()->headers.at("X-Trace") == "trace");
CHECK(client.connect(1).http_status == 401);
const auto retried = source.requests();
CHECK(retried.back()->headers.at("Authorization") == "Bearer secret");
CHECK(retried.back()->headers.at("Cookie") == "session=secret");
}

TEST_CASE("Returning to the original origin does not restore redirect credentials",
"[http][redirect_credentials]")
{
const bool websocket = GENERATE(false, true);
std::string originalUrl;
ResponseServer target(
[&](const ix::HttpRequestPtr&, size_t)
{
return "HTTP/1.1 302 Found\r\nLocation: " + originalUrl +
"\r\nContent-Length: 0\r\n\r\n";
});
REQUIRE(target.listen().first);
std::string targetUrl = target.url();
if (websocket) targetUrl.replace(0, 4, "ws");
ResponseServer source(
[&](const ix::HttpRequestPtr&, size_t index)
{
return index == 0 ? "HTTP/1.1 302 Found\r\nLocation: " + targetUrl +
"\r\nContent-Length: 0\r\n\r\n"
: "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n";
});
originalUrl = source.url();
if (websocket) originalUrl.replace(0, 4, "ws");
REQUIRE(source.listen().first);
target.start();
source.start();
ix::HttpClient client;
auto args = options(client);
args->extraHeaders["Authorization"] = "Bearer secret";
args->extraHeaders["Cookie"] = "session=secret";
if (websocket)
{
ix::WebSocket webSocket;
webSocket.setUrl(originalUrl);
webSocket.setExtraHeaders(args->extraHeaders);
CHECK(webSocket.connect(1).http_status == 200);
}
else
{
REQUIRE(client.get(originalUrl, args)->errorCode == ix::HttpErrorCode::Ok);
}
const auto requests = source.requests();
REQUIRE(requests.size() == 2);
CHECK(requests[0]->headers.count("Authorization") == 1);
CHECK(requests[0]->headers.count("Cookie") == 1);
CHECK(requests[1]->headers.count("Authorization") == 0);
CHECK(requests[1]->headers.count("Cookie") == 0);
const auto targetRequests = target.requests();
REQUIRE(targetRequests.size() == 1);
CHECK(targetRequests[0]->headers.count("Authorization") == 0);
CHECK(targetRequests[0]->headers.count("Cookie") == 0);
}

TEST_CASE("Invalid HTTP content lengths are rejected", "[http][response]")
{
const std::string length = GENERATE(std::string("-1"),
Expand Down
27 changes: 27 additions & 0 deletions test/IXUrlParserTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -316,3 +316,30 @@ TEST_CASE("URLs reject raw whitespace and control characters", "[url][components
ix::UrlParser::parse(prefix + character + "text", protocol, host, path, query, port));
CHECK(ix::UrlParser::parse("http://example.com/a%20b", protocol, host, path, query, port));
}

TEST_CASE("URL origins compare scheme, hostname and effective port", "[url][origin]")
{
struct Example
{
const char* first;
const char* second;
bool same;
};
const Example examples[] = {
{"HTTP://EXAMPLE.com/a", "http://example.COM:80/b?query#fragment", true},
{"https://example.com/a", "https://example.com:443/b", true},
{"ws://example.com", "ws://example.com:80/", true},
{"wss://[FE80::ABCD]", "wss://[fe80::abcd]:443/", true},
{"https://example.com", "http://example.com:443", false},
{"http://example.com", "http://other.example.com", false},
{"http://example.com", "http://example.com:8080", false},
{"ws://example.com", "http://example.com", false},
{"http://example.com", "http://example.com:0", false},
{"invalid", "invalid", false}};
for (const auto& example : examples)
{
CAPTURE(example.first, example.second);
CHECK(ix::UrlParser::isSameOrigin(example.first, example.second) == example.same);
CHECK(ix::UrlParser::isSameOrigin(example.second, example.first) == example.same);
}
}
Loading