Skip to content

Commit

Permalink
Merge pull request #30755 from sberyozkin/forwarded_parser_port_check
Browse files Browse the repository at this point in the history
Update ForwardedParser to validate the port
  • Loading branch information
sberyozkin authored Feb 1, 2023
2 parents 1d3814d + 2ef45c5 commit f004214
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
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

0 comments on commit f004214

Please sign in to comment.