#!/usr/bin/perl
use strict;
BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
use Socket;
use Carp;

#
# As a windows program, Leaves/Sub7 uses windows CR.
#
my $EOL = "\015\012";

#
# This log file will log the honeypot - worm interaction.
#
open (LOG,">> fake_sub7.log");
sub spawn;  # forward declaration

#
# Little sub to write to the log file. Very verbose
# Format:
# programname, pid: message at time
#
sub logmsg { print LOG "$0 $$: @_ at ", scalar localtime, "\n" }

$|=1;

#
# can listen on any port, but uses Sub7 port by default.
#
my $port = shift || 27374;
my $proto = getprotobyname('tcp');
$port = $1 if $port =~ /(\d+)/; # untaint port number

socket(Server, PF_INET, SOCK_STREAM, $proto)        || die "socket: $!";
setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
           pack("l", 1))   || die "setsockopt: $!";
bind(Server, sockaddr_in($port, INADDR_ANY))        || die "bind: $!";
listen(Server,SOMAXCONN)                            || die "listen: $!";

logmsg "server started on port $port";

my $waitedpid = 0;
my $paddr;

sub REAPER {
    $waitedpid = wait;
    $SIG{CHLD} = \&REAPER;  # loathe sysV
    logmsg "reaped $waitedpid" . ($? ? " with exit $?" : '');
}

$SIG{CHLD} = \&REAPER;
for ( $waitedpid = 0;
      ($paddr = accept(Client,Server)) || $waitedpid;
                 $waitedpid = 0, close Client)
{
    next if $waitedpid and not $paddr;
    my($port,$iaddr) = sockaddr_in($paddr);
    my $name = gethostbyaddr($iaddr,AF_INET);

               logmsg "connection from $name [",
                       inet_ntoa($iaddr), "]
                       at port $port";

    spawn \&subseven

}

sub subseven {

    my $date=`date +"%T - %B %d, %Y, %A"`;
    chomp $date;

#
# The 'login' string that is sent after a client connects
#
    my $login="connected. time/date: $date, version: BoNuS 2.1";

    print_line($login);
    read_line();

#
# The 'response' after the command is received.
#

    print_line("downloading file. file successfully downloaded. [11020 
bytes]");    

#
# Read another line if there is one.
# 

read_line();
}

sub print_line {
    my $line=shift;
    print "$line\n";
    print LOG "> $line\n";
}

sub read_line {
    my $line=<STDIN>;
    print LOG "< $line";
}

sub spawn {
    my $coderef = shift;

    unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') {
        confess "usage: spawn CODEREF";
    }

    my $pid;
    if (!defined($pid = fork)) {
        logmsg "cannot fork: $!";
        return;
    } elsif ($pid) {
        logmsg "begat $pid";
        return; # I'm the parent
    }
               # else I'm the child -- go spawn

    open(STDIN,  "<&Client")   || die "can't dup client to stdin";
    open(STDOUT, ">&Client")   || die "can't dup client to stdout";
    open(STDERR, ">&STDOUT") || die "can't dup stdout to stderr";
    exit &$coderef();
}
