5

I have a script where payment processors come with payment confirmations. To make the page secure, as it can access order information and other user related stuff, I had to limit the acces by ip(/24) as it follows:

$ipAllowed = array(
'192.192.192',
'172.172.172'
);
$ipAllowed = str_replace(".", "\.", implode("|", $ipAllowed));

if(!preg_match("/^($ipAllowed)\.[0-9]{1,3}$/", $_SERVER['REMOTE_ADDR'])){
     header('HTTP/1.0 403 Forbidden');
     die('You are not allowed to access this file.');
}

*the ip's are just as an example

Before i used:

if(!in_array(@$_SERVER['REMOTE_ADDR'], array('ips here'))); //only works with full ip

The !in_array was much neater then the one I use now, but i need something that works with /24 ips, or even with both!

Do you know something that works better/faster, is reliable and much neater?

@rap-2-h As you stated this is the neater version that works with full ip, /24 or even /16

$ipAllowed = array( '192.168.1.153' '172.172.172'); 
$allowed = false; 

foreach($ipAllowed as $ip): 
    if(strpos($_SERVER['REMOTE_ADDR'], $ip) === 0) $allowed = true; 
endforeach; 

if (!$allowed) { 
    header('HTTP/1.0 403 Forbidden'); 
    die('You are not allowed to access this file.'); 
}
hakre
  • 193,403
  • 52
  • 435
  • 836
amstegraf
  • 597
  • 1
  • 5
  • 11
  • I hope you have other security measures too. IP is nice as defense in depth, but I'd avoid relying on it as sole measure. – CodesInChaos Jul 10 '12 at 10:31
  • yes! after, the entire method starts computing the POST parameters and acts accordingly(also a hash of all the parameters are sent with a cypher key). I could rely just on that, but I want to be safe. – amstegraf Jul 10 '12 at 10:47
  • "also a hash of all the parameters are sent with a cypher key" How does the keyed hash work? Is it something good, such as HMAC, or something broken like H(k||m)? – CodesInChaos Jul 10 '12 at 11:28
  • except this ip check part all are well! – amstegraf Jul 10 '12 at 11:32

3 Answers3

16

You can try something like this :

$ipAllowed = array('192.192.192', '172.172.172');

$allowed = false;
foreach($ipAllowed as $ip) {
     if (strpos($_SERVER['REMOTE_ADDR'], $ip) !== false) {
         $allowed = true;
     }
}
if (!$allowed) {
    header('HTTP/1.0 403 Forbidden');
    die('You are not allowed to access this file.');     
}

So you can have only ip fragment in your $ipAllowed array. It's not very elegant but it should work...

rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • Using strpos is actually a better solution than blindly hacking off the last octet, like I did. – Berry Langerak Jul 10 '12 at 10:32
  • this seems suitable but it also gives access to the entire ip class as 172.0.0.0 returns also true or 0. No? – amstegraf Jul 10 '12 at 11:39
  • `172.172.172.1` and `1.172.172.172` will be allowed with this code. If you want only `172.172.172.X` you can replace condition like this `if (strpos($_SERVER['REMOTE_ADDR'], $ip) === 0)` – rap-2-h Jul 10 '12 at 14:30
  • 1
    based on your answer this is the final version which works with all type of ips, and it is rather neat. Thank you! – amstegraf Jul 10 '12 at 19:29
1

Use this function to check if you're ip is in Specified network :

eg: is 192.168.1.25 in network 192.168.1.0/24

<?php

/*
 * ip_in_range.php - Function to determine if an IP is located in a
 *                   specific range as specified via several alternative
 *                   formats.
 *
 * Network ranges can be specified as:
 * 1. Wildcard format:     1.2.3.*
 * 2. CIDR format:         1.2.3/24  OR  1.2.3.4/255.255.255.0
 * 3. Start-End IP format: 1.2.3.0-1.2.3.255
 *
 * Return value BOOLEAN : ip_in_range($ip, $range);
 *
 * Copyright 2008: Paul Gregg <pgregg@pgregg.com>
 * 10 January 2008
 * Version: 1.2
 *
 * Source website: http://www.pgregg.com/projects/php/ip_in_range/
 * Version 1.2
 *
 * This software is Donationware - if you feel you have benefited from
 * the use of this tool then please consider a donation. The value of
 * which is entirely left up to your discretion.
 * http://www.pgregg.com/donate/
 *
 * Please do not remove this header, or source attibution from this file.
 */


// decbin32
// In order to simplify working with IP addresses (in binary) and their
// netmasks, it is easier to ensure that the binary strings are padded
// with zeros out to 32 characters - IP addresses are 32 bit numbers
Function decbin32 ($dec) {
  return str_pad(decbin($dec), 32, '0', STR_PAD_LEFT);
}

// ip_in_range
// This function takes 2 arguments, an IP address and a "range" in several
// different formats.
// Network ranges can be specified as:
// 1. Wildcard format:     1.2.3.*
// 2. CIDR format:         1.2.3/24  OR  1.2.3.4/255.255.255.0
// 3. Start-End IP format: 1.2.3.0-1.2.3.255
// The function will return true if the supplied IP is within the range.
// Note little validation is done on the range inputs - it expects you to
// use one of the above 3 formats.
Function ip_in_range($ip, $range) {
  if (strpos($range, '/') !== false) {
    // $range is in IP/NETMASK format
    list($range, $netmask) = explode('/', $range, 2);
    if (strpos($netmask, '.') !== false) {
      // $netmask is a 255.255.0.0 format
      $netmask = str_replace('*', '0', $netmask);
      $netmask_dec = ip2long($netmask);
      return ( (ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec) );
    } else {
      // $netmask is a CIDR size block
      // fix the range argument
      $x = explode('.', $range);
      while(count($x)<4) $x[] = '0';
      list($a,$b,$c,$d) = $x;
      $range = sprintf("%u.%u.%u.%u", empty($a)?'0':$a, empty($b)?'0':$b,empty($c)?'0':$c,empty($d)?'0':$d);
      $range_dec = ip2long($range);
      $ip_dec = ip2long($ip);

      # Strategy 1 - Create the netmask with 'netmask' 1s and then fill it to 32 with 0s
      #$netmask_dec = bindec(str_pad('', $netmask, '1') . str_pad('', 32-$netmask, '0'));

      # Strategy 2 - Use math to create it
      $wildcard_dec = pow(2, (32-$netmask)) - 1;
      $netmask_dec = ~ $wildcard_dec;

      return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
    }
  } else {
    // range might be 255.255.*.* or 1.2.3.0-1.2.3.255
    if (strpos($range, '*') !==false) { // a.b.*.* format
      // Just convert to A-B format by setting * to 0 for A and 255 for B
      $lower = str_replace('*', '0', $range);
      $upper = str_replace('*', '255', $range);
      $range = "$lower-$upper";
    }

    if (strpos($range, '-')!==false) { // A-B format
      list($lower, $upper) = explode('-', $range, 2);
      $lower_dec = (float)sprintf("%u",ip2long($lower));
      $upper_dec = (float)sprintf("%u",ip2long($upper));
      $ip_dec = (float)sprintf("%u",ip2long($ip));
      return ( ($ip_dec>=$lower_dec) && ($ip_dec<=$upper_dec) );
    }

    echo 'Range argument is not in 1.2.3.4/24 or 1.2.3.4/255.255.255.0 format';
    return false;
  }

}
?>
Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
  • 2
    Don't forget he said that they are /24 subnets not complete IP addresses. I think you'd probably have to loop the ipAllowed and check if the address was valid based on `strpos`? – Paul Bain Jul 10 '12 at 10:25
  • no, because "192.192.192" will never be the REMOTE_ADDR, as IP addresses contain four octets. – Berry Langerak Jul 10 '12 at 10:26
  • and note that $_SERVER['REMOTE_ADDR'] can be fake, so be careful of this to get rid of attacks – jondinham Jul 10 '12 at 10:27
  • From what i know in_array doesn't search for parts of the haystack or parts of the needle, it must match the entire word! No? – amstegraf Jul 10 '12 at 10:32
  • It probably works, but I want something simple and neat, I don't want to benchmark it. – amstegraf Jul 10 '12 at 10:42
0
<?php

$ips = array(
    '192.160.0',
    '172.0.0'
);

/** 
 * Strip off the last number.
 */
$_SERVER['REMOTE_ADDR'] = '192.160.0.254';
$ip = preg_replace( '~\.(\d+)$~', '', $_SERVER['REMOTE_ADDR'] );

if( in_array( $ip, $ips ) ) {
    var_dump( 'allowed' );
}
Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
  • yes! it does what it should, but that was exactly my problem that it should work smarter and faster. As strpos is faster then preg and chopping the last part, as I also did, doesn't work in any case. – amstegraf Jul 10 '12 at 10:44