Skip to content

Commit

Permalink
Update ForwardedParser to validate the port
Browse files Browse the repository at this point in the history
(cherry picked from commit 2ef45c5)
  • Loading branch information
sberyozkin authored and gsmet committed Feb 7, 2023
1 parent aec9d78 commit e0f6985
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;

Expand Down Expand Up @@ -221,9 +224,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 e0f6985

Please sign in to comment.