#!/usr/bin/perl
# whois, a HTTPush plugin by Lluis Mora
# Looks up WHOIS information on a domain
#
# $Id: whois,v 1.7 2001/10/28 22:13:03 jfs Exp $

use plugins::httpush;
use IO::Socket;

$|=1;

my %req;
my @kvl;
my @TLDS_2LEVELS=('uk','jp','au','us');

while($line=<STDIN>) {

  chomp($line);

# print STDERR "whois> $line\n";

  if(! $line) {
    ProcessRequest(\%req);
    # Clean req;
    %req=undef;
    @kvl=();
  }

  if(! $req{'opcode'}) {
    if($line=~/(\w+)\s+(\d+)\.(\d+)/) {
      $req{'opcode'}=$1;
      $req{'version'}="$2.$3";
    }
  } else {
    ($key, $val) = split(":",$line,2);
    $val=httpush::decode($val);
  
    if($key && $val) {
		  my %kv;
      $kv{'k'}=$key;
      $kv{'v'}=$val;

      push (@{$req{kv}}, \%kv);
    }
  }
}

sub ProcessRequest {
  my %req=%{shift(@_)};
  my @kvl;
  my $fqdn, $id;

#  print STDERR "whois! processing request...\n";

  if($req{'opcode'} eq "identify") {
    my $plugin_name=httpush::encode("whois");
    my $plugin_description=httpush::encode("Gets domain information from WHOIS databases");
    my $plugin_event=httpush::encode("fqdn");
    my $plugin_noise=httpush::encode("0");

    print "register 1.0\n";
    print "name:$plugin_name\n";
    print "description:$plugin_description\n";
    print "event:$plugin_event\n";
    print "noise:$plugin_noise\n";
    print "\n";
  } elsif($req{'opcode'} eq "fqdn") {
    my ($fqdn);
    foreach $x (@{$req{'kv'}}) {
      %kv=%$x;

      if($kv{'k'} eq "content") {
        $fqdn=$kv{'v'};
      } elsif($kv{'k'} eq "id") {
        $id=$kv{'v'};
      }
    }

    if($fqdn) {
      # We are probably looking at something like: www.example.com, but we could also see www.example.co.uk or blah.bleh.example.com
      # Try to be a bit smart

      my @names = split(/\./,$fqdn);
      my $num = @names;

      if(grep (/@names[$num-1]/, @TLDS_2LEVELS)) {
        if($num > 3) {
          $fqdn=join('.',@names[$num-3 .. $num-1]);
        }
      } else {
        if($num > 2) {
          $fqdn=join('.',@names[$num-2 .. $num-1]);
        }
      }

    }

    if($fqdn) {
      # Get WHOIS data
      $sock = IO::Socket::INET->new(PeerAddr => 'whois.geektools.com',
                                    PeerPort => 'whois',
                                    Proto    => 'tcp');

      print $sock "$fqdn\r\n";

      my @whois_data=<$sock>;
      my $whois=join("<BR>",@whois_data);

      my $vuln=httpush::encode($whois);
      my $zero=httpush::encode('0');
      my $title=httpush::encode("WHOIS information");
      $id=httpush::encode($id);

      print "vuln 1.0\n";
      print "level:$zero\n";
      print "title:$title\n";
      print "content:$vuln\n";
      print "id:$id\n";
      print "\n";
    }

    print "end 1.0\n\n";
  }
}

