Skip to content

Commit

Permalink
Merge pull request #126 from pantheon-systems/124-enhance-get-client-ip
Browse files Browse the repository at this point in the history
Fix handling of 'X-Forwarded-For' header in `get_client_ip_server()`
  • Loading branch information
danielbachhuber authored Aug 19, 2019
2 parents 458b0c6 + 4d8055a commit e315394
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
23 changes: 19 additions & 4 deletions inc/class-session.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,8 @@ public function set_data( $data ) {
*/
public static function get_client_ip_server() {
// Set default.
$ipaddress = '127.0.0.1';
$ip_address = apply_filters( 'pantheon_sessions_client_ip_default', '127.0.0.1' );
$ip_source = null;

$keys = [
'HTTP_CLIENT_IP',
Expand All @@ -204,18 +205,32 @@ public static function get_client_ip_server() {
'REMOTE_ADDR',
];

$ip_filter_flags = apply_filters( 'pantheon_sessions_client_ip_filter_flags', FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6 | FILTER_FLAG_NO_RES_RANGE );

foreach ( $keys as $key ) {
if ( array_key_exists( $key, $_SERVER )
&& $_SERVER[ $key ]
) {
$ipaddress = $_SERVER[ $key ];
$_ip_address = $_SERVER[ $key ];

if ( false !== strpos( $_ip_address, ',' ) ) {
$_ip_address = trim( strstr( $_ip_address, ',', true ) );
}

if ( false === filter_var( $_ip_address, FILTER_VALIDATE_IP, $ip_filter_flags ) ) {
continue;
}

$ip_address = $_ip_address;
$ip_source = $key;
break;
}
}

return apply_filters(
'pantheon_client_ip',
preg_replace( '/[^0-9a-fA-F:., ]/', '', $ipaddress )
'pantheon_sessions_client_ip',
preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip_address ),
$ip_source
);
}

Expand Down
8 changes: 8 additions & 0 deletions tests/phpunit/test-sessions.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,14 @@ public function test_get_client_ip_server() {
$_SERVER['HTTP_CLIENT_IP'] = '192.168.1.2';
$_SERVER['HTTP_X_FORWARDED'] = '192.168.1.3';
$this->assertEquals( '192.168.1.2', Session::get_client_ip_server() );
// Reset $_SERVER.
$_SERVER = [
'HTTP_CLIENT_IP' => null,
'HTTP_X_FORWARDED' => null,
] + $_SERVER;
// 'HTTP_X_FORWARDED_FOR' should be in an comma seperated format. Return first value.
$_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.1.4, 5.6.7.8, 9.10.11.12';
$this->assertEquals( '192.168.1.4', Session::get_client_ip_server() );
}

/**
Expand Down

0 comments on commit e315394

Please sign in to comment.