#!/usr/bin/perl

#Smoothwall Tor auto blacklister v1 (c) 2008 Andy Dixon - andy@andydixon.com

use LWP::Simple;
@torarray=();
$torserver = "128.31.0.34";   
$port = 9031;
$content = get("http://$torserver:$port/tor/status/all") or die("Error getting Tor Directory Listing.\n");
@lines = split(/\n/,$content);
foreach $router (@lines) {
@rarray = split(/\ /,$router);
  if($rarray[0] =~ /^r$/) {
      $ip=$rarray[6];
      $hostname=$rarray[1];
      #We want to keep the Initial Tor Server available so that we can still query it in the future
      @torarray=(@torarray,"0.0.0.0/0,$ip,off,DROP,on,(ajdtorlist) Tor Server $hostname $ip\n") unless ($ip =~/$torserver/);      
      
  }
}

# Remove duplicates - for some reason they appear..
my %seen = ();
my @unique = grep { ! $seen{ $_ }++ } @torarray;
@torarray = @unique;


# Read config
open(FILE,"</settings/ipblock/config") or die ("Error opening ipblock config for read.\n");
@config = <FILE>;
close(FILE);


# Get rid of old tor entries

open(FILE,">/settings/ipblock/config") or die ("Error opening ipblock config for write.\n");
foreach $entry (@config) {
	if ($entry =~ /\(ajdtorlist\)/) {
		#Discard the entry
	} else {
		print FILE $entry; 
	}
}

# Add new tor entries

foreach $torservice (@torarray) {
	print FILE $torservice or die ("Unable to write to ipblock config file.\n");
	}
close (FILE);

# Tell SmoothWall that it needs to update the ipblock
system("/usr/bin/smoothcom setipblock") or die("Unable to call smoothcom.\n");
