MDL-43987 core: Remove port numbers in cleanremoteaddr

This commit is contained in:
John Okely
2014-11-17 09:48:32 +08:00
parent b1dd1c8656
commit e92d84244c
2 changed files with 36 additions and 2 deletions
+16 -2
View File
@@ -8650,8 +8650,22 @@ function getremoteaddr($default='0.0.0.0') {
}
if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$hdr = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
$address = cleanremoteaddr($hdr[0]);
$forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
$address = $forwardedaddresses[0];
if (substr_count($address, ":") > 1) {
// Remove port and brackets from IPv6.
if (preg_match("/\[(.*)\]:/", $address, $matches)) {
$address = $matches[1];
}
} else {
// Remove port from IPv4.
if (substr_count($address, ":") == 1) {
$address = explode(":", $address)[0];
}
}
$address = cleanremoteaddr($address);
return $address ? $address : $default;
}
}
+20
View File
@@ -2821,6 +2821,8 @@ class core_moodlelib_testcase extends advanced_testcase {
* Tests the getremoteaddr() function.
*/
public function test_getremoteaddr() {
$xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
$_SERVER['HTTP_X_FORWARDED_FOR'] = '';
$noip = getremoteaddr('1.1.1.1');
$this->assertEquals('1.1.1.1', $noip);
@@ -2841,5 +2843,23 @@ class core_moodlelib_testcase extends advanced_testcase {
$threeip = getremoteaddr();
$this->assertEquals('127.0.0.1', $threeip);
$_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1:65535,127.0.0.2';
$portip = getremoteaddr();
$this->assertEquals('127.0.0.1', $portip);
$_SERVER['HTTP_X_FORWARDED_FOR'] = '0:0:0:0:0:0:0:1,127.0.0.2';
$portip = getremoteaddr();
$this->assertEquals('0:0:0:0:0:0:0:1', $portip);
$_SERVER['HTTP_X_FORWARDED_FOR'] = '0::1,127.0.0.2';
$portip = getremoteaddr();
$this->assertEquals('0:0:0:0:0:0:0:1', $portip);
$_SERVER['HTTP_X_FORWARDED_FOR'] = '[0:0:0:0:0:0:0:1]:65535,127.0.0.2';
$portip = getremoteaddr();
$this->assertEquals('0:0:0:0:0:0:0:1', $portip);
$_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
}
}