#!/usr/bin/perl
#
# Everscan 0.8.2 release
#

use IO::Socket;
use DBI;

$debug=0;
$log=0;
@ports = qw(" 21 22 23 25 110 143 3306 8000 10000 31337");

sub scan {
        foreach $port (@ports) {
                $sock = new IO::Socket::INET (
                PeerAddr => $host ,
                PeerPort => $port ,
                Proto => "tcp" ,
                Timeout => 5 ,
                );
                if ($sock && $hostfound==0) {
			if ($debug==1) { print "$host found\n"; }
                        $hostfound=1;
			if ($debug==1) { print "TCP Scan Begun on host $host\n"; }
                        if ($log==1) { dolog("TCP Scan Begun on host $host\n"); }
                }
                if ($sock) {
			if ($debug==1) { print "$port open\n"; }
                        if ($log==1) { dolog("$port: open\n"); }
                        $portsopen="$portsopen $port";
                }
                close($sock);
        }
	if ($hostfound) {
		if (isexists()) {
			updatehost();
		} else {
			savescan();
		}
	}
}

sub dolog {
        chomp;
        open (LOG,">>ips.log");
        print LOG "$_[0]";
        close(LOG);
}

sub dorandom {
        while (1) {
                $host=randomip();
                $hostfound=0;
		$portsopen="";
                scan();
        }
}

sub isexists {
	if ($debug==1) { print "Checking if already exists\n"; }
	$sql = "select host_ip, host_num, ports from scan where host_ip=\"$host\";";
	$query = $dbh->prepare($sql);
	$query->execute || die("sql error: $dbh::errstr");
	($host_ip, $host_num, $ports)=$query->fetchrow_array;
	if ($host_ip != "") { $hostexists=1; }
	if ($hostexists != "") {
		if ($debug) { print "$host already exists\n"; }
		return 1;
	} else { 
		return 0;
	}
}

sub randomip {
        my $oc1=int (rand(255)+1);
        my $oc2=int (rand(255)+1);
        my $oc3=int (rand(255)+1);
        my $oc4=int (rand(255)+1);
        return "$oc1.$oc2.$oc3.$oc4";
}

sub startsql {
	$dbh = DBI->connect('DBI:mysql:basic_scan:203.26.137.9','scanner','h0h0h0');
}

sub updatehost {
	if ($debug==1) { print "replacing record number $host_num\n"; }
	$sql = "replace into scan ( host_ip, host_num, ports ) values ( '$host', '$host_num', '$portsopen');";
	$query = $dbh->prepare($sql);
	$query->execute || die("sql error: $dbh::errstr");
	if ($debug==1) { print "Host Updated: $host\n"; }
}

sub savescan {
	$sql = "insert into scan ( host_ip, ports) values ( '$host', '$portsopen' )";
	$query = $dbh->prepare($sql);
	$query->execute || die("sql error: $dbh::errstr");
	if ($debug==1) { print "Host Saved: $host\n"; }
}

sub main {
	startsql();
	dorandom();
}

main();

