Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update ForwardedParser to validate the port #30755

Merged
merged 1 commit into from
Feb 1, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,19 @@ public void test() {
.body(Matchers.equalTo("https|somehost|backend:4444"));
}

@Test
public void testInvalidPort() {
assertThat(RestAssured.get("/forward").asString()).startsWith("http|");

RestAssured.given().header("X-Forwarded-Proto", "https").header("X-Forwarded-For", "backend:-4444")
.header("X-Forwarded-Host", "somehost").get("/forward").then()
.body(Matchers.not(Matchers.endsWith(":44444444")));

RestAssured.given().header("X-Forwarded-Proto", "https").header("X-Forwarded-For", "backend:-4444")
.header("X-Forwarded-Host", "somehost").get("/forward").then()
.body(Matchers.not(Matchers.endsWith(":44444444")));
}

@Test
public void testIPV4WithPort() {
assertThat(RestAssured.get("/forward").asString()).startsWith("http|");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ class ForwardedParser {
private static final Pattern FORWARDED_PROTO_PATTERN = Pattern.compile("proto=\"?([^;,\"]+)\"?");
private static final Pattern FORWARDED_FOR_PATTERN = Pattern.compile("for=\"?([^;,\"]+)\"?");

private final static int PORT_MIN_VALID_VALUE = 0;
private final static int PORT_MAX_VALID_VALUE = 65535;

private final HttpServerRequest delegate;
private final ForwardingProxyOptions forwardingProxyOptions;
private final TrustedProxyCheck trustedProxyCheck;
Expand Down Expand Up @@ -226,9 +229,15 @@ private String[] parseHostAndPort(String hostToParse) {
private int parsePort(String portToParse, int defaultPort) {
if (portToParse != null && portToParse.length() > 0) {
try {
return Integer.parseInt(portToParse);
int port = Integer.parseInt(portToParse);
if (port < PORT_MIN_VALID_VALUE || port > PORT_MAX_VALID_VALUE) {
log.errorf("Failed to validate a port from \"forwarded\"-type headers, using the default port %d",
defaultPort);
return defaultPort;
}
return port;
} catch (NumberFormatException ignored) {
log.error("Failed to parse a port from \"forwarded\"-type headers.");
log.errorf("Failed to parse a port from \"forwarded\"-type headers, using the default port %d", defaultPort);
}
}
return defaultPort;
Expand Down