#!/opt/perl58/bin/perl
#########################################
#    Written by Russell Widger    #
#    submitsh v.2            #
#    A tool used to analyze and     #
#    submit malicious material    #
#    for review.            #
#########################################

use warnings;
use strict;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha256);
use Sys::Hostname;
use POSIX qw(strftime);
use File::Copy;
use File::Basename;
use File::HomeDir;
use IPC::Open3;
use IO::Select;
use Symbol;
use Cwd;
use IO::Compress::Gzip qw(gzip $GzipError);
use LWP::UserAgent 'https';
use HTTP::Request::Common;
use MIME::Base64;
use Term::ANSIColor;
use Getopt::Long;
use JSON;
use YAML;

my $url = "https://test.russellgregorymusic.com/submitsh/accept.cgi";

my $q;
GetOptions('quarantine|q'    => \$q,
           'help|h'        => \&help);

sub help {
  print <<"USAGE";
submitsh usage:
    submitsh <file> [<flags>]

    -q, --quarantine
    Uses amc to quarantine the file
USAGE

exit 42;
}

# Scalars
my @input = @ARGV;
my $length = @ARGV;

my %fid = ('Any'  => "0",
   'Windows_exe'  => "1",
   'OLEZ'         => "2",
   'html'         => "3",
   'mail_file'    => "4",
   'graphics'     => "5",
   'ELF'          => "6",
   'ascii_test'   => "7",
   'unused'       => "8",
   'mach-0'       => "9",
   'pdf'          => "10",
   'flash'        => "11",
   'java'         => "12");

# Main Code

print "** Running submitsh v2.. Starting\n";
my $ruser;
if ( defined $ENV{'RUSER'} ) {
    $ruser = $ENV{'RUSER'};
} elsif ( defined $ENV{'SYSADMIN'} ) {
    $ruser = $ENV{'SYSADMIN'};
} else { 
    $ruser = "submitsh";
}

my $end = ($length - 1);
my $ph = 0;

while ($ph <= $end) {
  my $input = $input[$ph];
  my ($sh, $chpath, $cwd, $hn) = name($input);
  chomp $sh;
  if ( -d $sh ) {
    print "Cannot submit directories!\n";
  }
  if ( -e $sh && -f $sh) {
      my ($dt, $date) = &time;
      my ($sh, $uid, $size, $owner, $zip, $mtime, $ctime) = fileinfo($sh);
          if ( $size > 5242880 ) {
            print color('bold red');
            print "[FATAL] Cannot accept files larger than 5 MB\n";
            print color('reset');
            exit 42;
         }
      my ($fpath, $home) = path($cwd, $sh, $owner);
      my $ftype = ftype($sh);
      my $fid = fid($ftype, $size, $sh);
      my $brand = brand($hn);
      my @subsample = sample($size, $sh, $zip);
      my ($sample_status, $tmp) = @subsample;    
      my ($auth, $uuid) = auth($url);
      my @all = ($dt, $ruser, $sh, $owner, $fpath, $hn, $brand, $ftype, $fid, $size, $auth, $sample_status, $zip, $date, $mtime, $ctime, $uuid, $tmp, $cwd, $chpath);
      send_deets(@all, $url);
      sub_log(@all);
      out(@all);
          if ( $q ) {
                  quarantine($sh);
          }
      print "\nShell Submitted!\n";
  } else {
      print "\nThe file $sh doesn't exist\n";
  }
  $ph++;
}


# Subroutines

sub time {
    my $json = JSON->new->allow_nonref;
    my $date = localtime();
    my $etime = time;
    my $dt = $json->encode(strftime("%Y\-%m\-%d %H:%M:%S", localtime($etime)));
    return ($dt, $date);
}

sub name {
    my $input = shift;
    chomp $input;
    my ($cwd, $hn) = info();
    my ($file, $dir, $suffix) = fileparse($input);
    my $sh = $file;
    chomp $sh;
    my $chpath;
    my $cwd_n = $cwd . "/";
    if ( $dir eq "./" ) {
        $dir = $cwd_n;
    }
    if ( $dir ne $cwd_n ) {
        chdir $dir;
        print color('bold red');
        print "** WARNING: Your working directory has changed to $dir!!\n";
        print color('reset');
        $chpath = "1";
    } else {
        $chpath = "0";
    }
    return ($sh, $chpath, $cwd, $hn);
}

sub info {
    my $cwd = getcwd;
    my $hn = hostname;    
    return ($cwd, $hn);
}

sub fileinfo {
    my $sh = shift;
    my @stat = stat($sh);
    my $uid = $stat[4];
    my $size = $stat[7];
    my $mtime = $stat[9];
    my $ctime = $stat[10];
    my $owner = getpwuid($uid);
    my $zip = "$sh.gz";
    return ($sh, $uid, $size, $owner, $zip, $mtime, $ctime);
}

sub path {
    my ($cwd, $sh, $owner) = @_;
    my $fpath = "$cwd" . "/$sh";
    my $home = File::HomeDir->users_home($owner);
    return ($fpath, $home);
}

sub ftype {
    my ($sh) = shift;
    my ($in, $out, $err);
    my ($output, $errors);
    my $pid = open3( $in, $out, $err = gensym(), "/usr/bin/file $sh");
    print $in "$sh";
    close ($in);
    my $sel = IO::Select->new();
    $sel->add( $out, $err );

    while ( my @handles = $sel->can_read() ) {
        for my $fh (@handles) {
            my $ftype = <$fh>;
            unless ( defined $ftype) {
                $sel->remove($fh);
                close $fh;
                next;
            }
            $output .= $ftype if ( $fh == $out );
            $errors .= $ftype if ( $fh == $err );
        }
    }
    waitpid $pid, 0;
    my @split = split(" ", $output);
    $output = $split[1];
    return $output;
}

sub fid {
    my ($ftype, $size, $sh) = @_;
    chomp $ftype;
    $ftype = lc($ftype);
    my $fid;
    if ( $ftype eq 'php' ) {
           $fid = '0';
       } elsif ( $ftype =~ /^pe32/ ) {
           $fid = '1';
       } elsif ( $ftype eq 'ole' ) {
           $fid = '2';
       } elsif ( $ftype eq 'html' ) {
           $fid = '3';
       } elsif ( $ftype eq 'smtp'    ||
             $ftype eq 'pop3'    ||
         $ftype eq 'mail'    ||
         $ftype eq 'sendmail') {
           $fid = '4';
       } elsif ( $ftype =~ /graphic/ ) {
           $fid = '5';
       } elsif ( $ftype eq 'elf' ) {
           $fid = '6';
       } elsif ( $ftype eq 'ascii' ) {
           if ( $size >= '5242880' ) {
               my @split = split('', $sh);
               if ( $split[-1] eq 'js' ) {
                   $fid = '12';
               } else {
                   $fid = '7';
                   print "This might be a Javascript file but the file size exceeds 5M so I won't scan it\n";
               }
           } else {
               open my $fh, '<', $sh or die "ASCII file found but could not determine the type...\n";
               if (grep{/jQuery/} <$fh>) {
                   $fid = '12';
                   close($fh);
               } else {
                   $fid = '7';
               }
           }
       } elsif ( $ftype eq 'mach-o' ) {
           $fid = '9';
       } elsif ( $ftype eq 'pdf' ) {
           $fid = '10';
       } elsif ( $ftype eq 'flash'    ||
             $ftype eq 'macromedia' ) {
           $fid = '11';
       } else {
           $fid = '0';
       }
}

sub brand {
    my $hn = shift;
    my $brand;
    if ( $hn =~ /\.(arvixe(cloud|dedicated|shared|vps)\.com|(mysitehosted|webeasyserve)\.com)$/ ) {
        $brand = "Arvixe";
    } elsif ( $hn =~ /\.(asoshared|asmallorange)\.com$/ ) {
        $brand = "ASO";
    } elsif ( $hn =~ /\.(hostgator|websitewelcome)\.com$/ ) {
            $brand = "HostGator";
    } elsif ( $hn =~ /\.(hostgator|prodns)\.com\.br$/ ) {
        $brand = "HostGator_Brazil";
    } elsif ( $hn =~ /\.(hostgator|websitedns)\.in$/ ) {
        $brand = "HostGator_India";
    } elsif ( $hn =~ /\.(hostgator\.com\.tr|webhostsunucusu\.com)$/ ) {
        $brand = "HostGator_Turkey";
    } elsif ( $hn =~ /hostgator\.mx$/ ) {
        $brand = "HostGator_Mexico";
    } elsif ( $hn =~ /hostgator\.sg$/ ) {
        $brand = "HostGator_Singapore";
    } elsif ( $hn =~ /hostclear\.com$/ ) {
        $brand = "HostClear";
    } elsif ( $hn =~ /ideahost\.com/ ) {
        $brand = "IdeaHost";
    } elsif ( $hn =~ /ehost\.com/ ) {
        $brand = "eHost";
    } elsif ( $hn =~ /bluehost/ ) {
        $brand = "BlueHost";
    } elsif ( $hn =~ /(seoboxes\.net|seowebhosting\.com)/ ) {
        $brand = "Seo_Hosting";
    } elsif ( $hn =~ /(accountservergroup|accountsupportgroup|apthost|bluefur|gteinterlink|sistemsunucu|siteshostedhere|weblimitsiz|webserversystems)\.com$/ ) {
        $brand = "Site5";
    } elsif ( $hn =~ /(hostv|myserverhost)\.com/ ) {
        $brand = "HostNine";
    } elsif ( $hn =~ /(rhostjh|justhost)\.com/ ) {
        $brand = "JustHost";
    } else {
        $brand = "Undetermined";
    }
    return $brand;
}

sub sample {
    my ($size, $sh, $zip) = @_;
    print "** Generating Sample... ";
    my ($extract, $sample_status);
    my $tmp = "$sh-sbmtsh_temp";
    if ( $size > "800" ) {
        $zip = "$sh.gz";
        my $pid = open my $fh, '-|', "/usr/bin/gzip -c $sh >> $zip";
        waitpid $pid, 0;
        close($fh);
        $sample_status = "1";
        print "Done\n";
        return ($sample_status, $zip);
    } else {
        open my $fh, '<', "$sh" or die "Couldn't open file to get sample!";
        while (<$fh>) {
            $extract .= $_;
        }
        close($fh);
        my $extract2 = encode_base64($extract);
        open my $sfh, ">>", $tmp or die "Couldn't open file to return sample in base64!\n";
        print $sfh "$extract2";
        close($sfh);
        $sample_status = 0;
        print "Done\n";
        return ($sample_status, $tmp);
    }
}

sub auth {
    print "** Establishing connection to remote server... ";
    my $url = shift;
    my $uid = uid();
    my $ua = LWP::UserAgent->new();
    $ua->protocols_allowed(['http', 'https']);
    $ua->agent('Submitsh');
    my $auth = $ua->post(
        "$url",
        Content                    => [
        'uid'                    => $uid,
        'val'                    => 'null',
        ]
    );
    if ( $auth->is_success ) {
        print "Done\n";
        $auth = $auth->content();
        return ($auth, $uid);
    } else {
        die $auth->status_line;
        print "Failed!\n";
        print "Couldn't connect to remote server!\n";
        exit 42;
    }    
}

sub uid {
    my $n = 8;
    my $uid;
    my @a = split('', "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBN1234567890");

    for ( my $c = 0; $c < $n; $c++) {
        $uid .= $a[rand @a];
        next;
    }
    return $uid;
}

sub send_deets {
    print "** Sending shell information now... ";
    my ($dt, $ruser, $sh, $owner, $fpath, $hn, $brand, $ftype, $fid, $size, $auth, $sample_status, $zip, $date, $mtime, $ctime, $uuid, $tmp, $cwd, $chpath, $url) = @_;
    my $response;
    my $ua = LWP::UserAgent->new();
    my @protocols = ('http', 'https');
    $ua->protocols_allowed(['http', 'https']);
    $ua->agent('Submitsh');
    if ( $sample_status == 1 ) {
        $response = $ua->post(
            "$url",
            Content_Type            => 'multipart/form-data',
            Content_Encoding        => 'gzip',
             Content                => [
            'time'                  => $dt,
            'ruser'                 => $ruser,
            'file'                  => $sh,
            'owner'                 => $owner,
            'path'                  => $fpath,
            'host'                  => $hn,
            'brand'                 => $brand,
            'ftype'                 => $ftype,
            'fid'                   => $fid,
            'size'                  => $size,
            'app'                   => "no",
            'del'                   => "no",
            'auth'                  => "$auth",
            'status'                => "$sample_status",
            'sample'                => [$zip],
            'uid'                   => "$uuid",
            ]
        );
    } else {
        $response = $ua->post(
            "$url",
            Content_Type                 => 'multipart/form-data',
            Content_Transfer_Encoding    => 'base64',
            Content                      => [
            'time'                       => "$dt",
            'ruser'                      => $ruser,
            'file'                       => $sh,
            'owner'                      => $owner,
            'path'                       => $fpath,
            'host'                       => $hn,
            'brand'                      => $brand,
            'ftype'                      => $ftype,
            'fid'                        => $fid,
            'size'                       => $size,
            'app'                        => "no",
            'del'                        => "no",
            'auth'                       => "$auth",
            'status'                     => "$sample_status",
            'sample'                     => [$tmp],
            'uid'                        => "$uuid",
            ]
        );
    }
    print "Done\n";
    print "** Information sent to the mothership!\n";
    if ( $response->is_success ) {
        my $return = $response->content();
        print "** Remote server says: \"$return\"\n";
    }
}


sub quarantine {
    my $sh = shift;
    my $pid = open my $fh, "-|", "/root/bin/amc $sh" or die "Unable to quarantine the file\n";
    waitpid $pid, 0;
    close($fh);
}

sub sub_log {
    my ($dt, $ruser, $sh, $owner, $fpath, $hn, $brand, $ftype, $fid, $size, $auth, $sample_status, $zip, $date, $mtime, $ctime, $uuid, $tmp, $cwd, $chpath) = @_;
    my $logfile = "/root/.security/submitsh.log";
    print "** Logging to $logfile... ";
    if  ( ! -e "/root/.security" ) {
        mkdir "/root/.security";
    }
    open my $fn, '>>', $logfile or die "\nUnable to access log file $logfile\n";
    print $fn "-------------------------------------\n";
    print $fn "$date : $owner : BEGIN LOGGING\n";
    print $fn "$date : $owner : Submitted by: $ruser\n";
    print $fn "$date : $owner : Full Path: $fpath\n";
    print $fn "$date : $owner : ctime: $ctime mtime: $mtime\n";
    close($fn);
    print "Done\n";
}

sub out {
    my ($dt, $ruser, $sh, $owner, $fpath, $hn, $brand, $ftype, $fid, $size, $auth, $sample_status, $zip, $date, $mtime, $ctime, $uuid, $tmp, $cwd, $chpath) = @_;
    if ( $chpath == "1" ) {
        print color('bold red');
        print "** Moving you back to your original directory... ";
        chdir $cwd;
        print "Done\n";
        print color('reset');
    }
    print "\nSubmitted by $ruser on $date\n\n";
    print "File:\t\t\t$sh\n";
    print "Size:\t\t\t$size\n";
    print "Owner:\t\t\t$owner\n";
    print "Originating Host:\t$hn\n";
    print "Brand:\t\t\t$brand\n";
    print "File ID:\t\t$fid\n";
    if ( $sample_status == 1 ) {
        unlink $zip;
    } else {
        unlink $tmp;
    }
}
