22
Mar 10

Prevent Access to LAN

In writing an app that communicates notifications via HTTP requests, to a user specified URL, it brought up an interesting security question. How do you block them from requesting a URL that accesses the LAN ?.

The function below was created to do just that.



function isOnLAN($url)
{

$urlParts = parse_url($url);

$domainName = $urlParts[‘host’];

$ip = gethostbyname($domainName);

if (ip_in_network($ip,"172.16.0.0", 12))
return true;

if (ip_in_network($ip,"192.168.0.0", 16))
return true;

if (ip_in_network($ip,"10.0.0.0", 8))
return true; //true

return false;

}

// Taken from php.net - http://jm2.php.net/manual/en/function.ip2long.php#92544
function ip_in_network($ip, $net_addr, $net_mask){
if($net_mask <= 0){ return false; }
$ip_binary_string = sprintf("%032b",ip2long($ip));
$net_binary_string = sprintf("%032b",ip2long($net_addr));
return (substr_compare($ip_binary_string,$net_binary_string,0,$net_mask) === 0);
}


Usage:



if (isOnLAN("http://192.168.1.1"))
  echo "Address on LAN";
else
  echo "Address on INTERNET";