stop-spammers icon indicating copy to clipboard operation
stop-spammers copied to clipboard

Using HTTP_X_FORWARDED_FOR for getting real user IPs

Open samgabrail opened this issue 6 years ago • 1 comments

I'm using nginx in front of wordpress and they are both in Docker containers. Nginx is passing the real IPs via X-Forwarded-for. I see that $_SERVER['REMOTE_ADDR'] is identified in two functions: ss_get_ip() and ss_log_user_ip. I updated these two functions to use $_SERVER['HTTP_X_FORWARDED_FOR'] instead of $_SERVER['REMOTE_ADDR']. Now I can see the real IPs in the log report.

Below is what I did.

function ss_get_ip() {
	$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

	return $ip;
}

function ss_log_user_ip( $user_login = "", $user = "" ) {
	if ( empty( $user ) ) {
		return;
	}
	if ( empty( $user_login ) ) {
		return;
	}
// add the user's IP to new users
	if ( ! isset( $user->ID ) ) {
		return;
	}
	$user_id = $user->ID;
// $ip=ss_get_ip();
	$ip    = $_SERVER['HTTP_X_FORWARDED_FOR'];
	$oldip = get_user_meta( $user_id, 'signup_ip', true );
	if ( empty( $oldip ) || $ip != $oldip ) {
		update_user_meta( $user_id, 'signup_ip', $ip );
	}
}

A better way is to use something like this:

function get_the_user_ip() {
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//check ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//to check ip is passed from a proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return apply_filters( 'wpb_get_ip', $ip );
}

samgabrail avatar Sep 25 '19 17:09 samgabrail

I've already answered in #144:

If you are using Apache behind NGINX then I recommend to you install module mod_remoteip. If it isn't possible then you could set proper IP address in wp-config.php. On this way, all plugins will get correct address.

This code could be potential security issue because it's easy to spoof this header if the request isn't coming from "trusted proxy". Also, I see many cases where X-Forwarded-For: contains private IP addresses. At the end, this code doesn't handle case when more proxies are in the chain...

So, it's could be possible only if user activate this option and set valid proxies. There are more complications with IPv6 which we need to handle... I'm working as system administrator and I'm trying to fix something similar... I highly recommend to you install server side solution, must use plugin, ...

stodorovic avatar Jan 13 '20 08:01 stodorovic