Skip to content

Commit a18e7b6

Browse files
authored
Use X-Forwarded-Proto to determine port
Using `X-Forwarded-Port` seems to be discouraged as it allows spoofing according to the Caddy proxy devs [0]: "For these X-Forwarded-* headers, by default, the proxy will ignore their values from incoming requests, to prevent spoofing." Instead we should use the X-Forwarded-Proto header to infer the port that the proxy was called at. So https indicates port 443, while http indicates port 80. Fixes #633 [0]: https://caddyserver.com/docs/caddyfile/directives/reverse_proxy?utm_source=chatgpt.com#defaults
1 parent b4a2533 commit a18e7b6

1 file changed

Lines changed: 19 additions & 2 deletions

File tree

lib/Saml2/Utils.php

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -573,8 +573,8 @@ public static function getSelfPort()
573573
$portnumber = null;
574574
if (self::$_port) {
575575
$portnumber = self::$_port;
576-
} else if (self::getProxyVars() && isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
577-
$portnumber = $_SERVER["HTTP_X_FORWARDED_PORT"];
576+
} else if (self::getProxyVars() && self::determinePortFromProxyVars() !== null) {
577+
$portnumber = self::determinePortFromProxyVars();
578578
} else if (isset($_SERVER["SERVER_PORT"])) {
579579
$portnumber = $_SERVER["SERVER_PORT"];
580580
} else {
@@ -591,6 +591,23 @@ public static function getSelfPort()
591591
return $portnumber;
592592
}
593593

594+
/**
595+
* @return null|string The port number inferred from the proxy variables (HTTP_X_FORWARDED_...)
596+
*/
597+
private static function determinePortFromProxyVars()
598+
{
599+
if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
600+
return $_SERVER["HTTP_X_FORWARDED_PORT"];
601+
} else if (isset($_SERVER["HTTP_X_FORWARDED_PROTO"])) {
602+
if ($_SERVER["HTTP_X_FORWARDED_PROTO"] == 'https') {
603+
return '443';
604+
} elseif ($_SERVER["HTTP_X_FORWARDED_PROTO"] == 'http') {
605+
return '80';
606+
}
607+
}
608+
return null;
609+
}
610+
594611
/**
595612
* Checks if https or http.
596613
*

0 commit comments

Comments
 (0)