Skip to content
Permalink
Browse files

[FIXED JENKINS-23294] Interpret X-Forwarded-Port

- Also fixed handling of X-Forwarded-Proto and added support for X-Forwarded-Host

- Additional complexity is that there can be multiple headers with the same name (which was handled by default by accident) and
  that a header value may contain a comma separated list if there were multiple forwarding hops.
  • Loading branch information...
stephenc committed Jun 19, 2014
2 parents cffe9df + 5bad446 commit 333b05e356c70e90a7a1eeab9cb7d964c00fcd02
Showing with 30 additions and 8 deletions.
  1. +30 −8 core/src/main/java/jenkins/model/Jenkins.java
@@ -1891,22 +1891,44 @@ public boolean isRootUrlSecure() {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = req.getScheme();
String forwardedScheme = req.getHeader("X-Forwarded-Proto");
if (forwardedScheme != null) {
scheme = forwardedScheme;
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
buf.append(host);
int port = req.getServerPort();
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
buf.append(scheme+"://");
buf.append(req.getServerName());
int forwardedPort = req.getIntHeader("X-Forwarded-Port");
int port = forwardedPort == -1 ? req.getServerPort() : forwardedPort;
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}

/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}

public File getRootDir() {
return root;
}

0 comments on commit 333b05e

Please sign in to comment.
You can’t perform that action at this time.