From e92d84244ce20d308063379f16d99e7fc2ed13f7 Mon Sep 17 00:00:00 2001 From: John Okely Date: Tue, 11 Nov 2014 16:06:30 +0800 Subject: [PATCH] MDL-43987 core: Remove port numbers in cleanremoteaddr --- lib/moodlelib.php | 18 ++++++++++++++++-- lib/tests/moodlelib_test.php | 20 ++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/lib/moodlelib.php b/lib/moodlelib.php index b00833dd653..5b31e135abc 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -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; } } diff --git a/lib/tests/moodlelib_test.php b/lib/tests/moodlelib_test.php index 40953cd7bec..004cc071ad5 100644 --- a/lib/tests/moodlelib_test.php +++ b/lib/tests/moodlelib_test.php @@ -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; + } }