Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to trust $_SERVER['REMOTE_ADDR']?

Is it safe to trust $_SERVER['REMOTE_ADDR']? Can it be substituted by changing the header of request or something like that?

Is it safe to write something like that?

if ($_SERVER['REMOTE_ADDR'] == '222.222.222.222') { // my ip address     $grant_all_admin_rights = true; } 
like image 985
Silver Light Avatar asked Jan 23 '11 13:01

Silver Light


People also ask

What is $_ server [' Remote_addr ']?

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page. $_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page. $_SERVER['REMOTE_PORT']

What is Remote_addr?

Returns the IP address of the remote host making the request. This variable is specific to the current gateway program request. Type and Usage.

What is remote addr in PHP?

The simplest way to collect the visitor IP address in PHP is the REMOTE_ADDR. Pass the 'REMOTE_ADDR' in PHP $_SERVER variable. It will return the IP address of the visitor who is currently viewing the webpage.


2 Answers

Yes, it's safe. It is the source IP of the TCP connection and can't be substituted by changing an HTTP header.

One case you may want to be worry of is if you are behind a reverse proxy in which case the REMOTE_ADDR will always be the IP of the proxy server and the user IP will be provided in an HTTP header (such as X-Forwarded-For). But for the normal use case reading REMOTE_ADDR is fine.

like image 164
sagi Avatar answered Sep 29 '22 05:09

sagi


$_SERVER['REMOTE_ADDR'] is the IP address the TCP connection came in on. While it is technically possible to bidirectionally spoof IP addresses on the Internet (by announcing foul routes via BGP), such attacks are likely to be spotted and not available to the typical attacker - basically, your attacker must have control over an ISP or carrier. There are no feasible unidirectional spoofing attacks against TCP (yet). Bidirectional IP spoofing is trivial on a LAN though.

Also be aware that it may be not be an IPv4, but an IPv6 address. Your current check is fine in that regard, but if you would check that 1.2.3.4 only occurs anywhere within $_SERVER['REMOTE_ADDR'], an attacker could simply connect from 2001:1234:5678::1.2.3.4.

Summarily, for anything other than critical (banking/military/potential damage >50.000€) applications, you can use the remote IP address if you can exclude attackers in your local network.

like image 37
phihag Avatar answered Sep 29 '22 06:09

phihag