Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding efficiency my ip blacklist-whitelist script

Tags:

algorithm

php

My script opens two files: whitelist.txt and blacklist.txt filled with ip addresses.

I want to add all instances of ip's in blacklist.txt that do not exist in whitelist.txt to a variable.

This script accounts for up to 2 wildcards.

It runs at 37 mins right now, and I would love for this to be faster.

$blacklist = file_get_contents("blacklist.txt");
$whitelist = file_get_contents("whitelist.txt");

$black_ips = explode("\n", $blacklist);
$white_ips = explode("\n", $whitelist);

$wildcard = array();
for($i = 0; $i < 256; $i++) {
  $wildcard[] = $i;
}

foreach($black_ips as $bkey => $black) {
  if(stristr($black, ".")) {

    foreach ($white_ips as $wkey => $white) {
      $count = substr_count($white, '*');

      if($count) {
        switch($count){
          case 1:
            foreach ($wildcard as $i) {
              if(substr($white, 0, strlen($white) - 1) . $i == $black){
                continue 4;
              }
            }
            break;
          case 2:
            foreach ($wildcard as $i) {
              foreach ($wildcard as $k) {
                if(substr($white, 0, strlen($white) - 3) . $i . '.' . $k == $black){
                  continue 5;
                }
              }
            }
            break;
        }
      }
      else if($black == $white) {
        continue 2;
      }
    }
    $nginxdeny .= "deny " . $black . ";\n";
  }
}
like image 974
Brandacus Avatar asked Oct 20 '22 22:10

Brandacus


1 Answers

Does this code do what you need?

$white = array(
    '192.168.*.*',
    '10.10.10.*',
);

$black = array(
    '192.168.8.8',
    '10.10.10.3',
    '10.10.1.2',
);

$patterns = array();
foreach ($white as $subnetwork) {
    $patterns[] = str_replace(array('.', '*'), array('\\.', '(\d{1,3})'), $subnetwork);
}

$notMatched = array();
foreach ($black as $ip) {
    foreach ($patterns as $pattern) {
        if (preg_match("/^{$pattern}$/", $ip)) {
            continue 2;
        }
    }
    $notMatched[] = $ip;
}

var_dump($notMatched);

It outputs:

array(1) {
  [0]=>
  string(9) "10.10.1.2"
}
like image 78
Valera Leontyev Avatar answered Oct 29 '22 19:10

Valera Leontyev