#!/usr/bin/perl
###############

##
#         Name: msfpayload
#       Author: H D Moore <hdm [at] metasploit.com>
#      Version: $Revision: 1.35 $
#  Description: Command line interface for generating Metasploit payloads
#      License:
#
#      This file is part of the Metasploit Exploit Framework
#      and is subject to the same licenses and copyrights as
#      the rest of this package.
#
##

require 5.6.0;

use strict;
use FindBin qw{$RealBin};
use lib "$RealBin/lib";

use Getopt::Std;
use POSIX;

use Msf::TextUI;
use Pex;

no utf8;
no locale;

Msf::UI::ActiveStateSucks();
Msf::UI::BrokenUTF8();

my $ui = Msf::TextUI->new($RealBin);
my $FRAMEVERSION = $ui->Version;
my $VERSION = '$Revision: 1.35 $';

my %opts;
getopts('hv', \%opts);
Version() if($opts{'v'});

$ui->SetTempEnv('_MsfPayload', 1);
$ui->SetTempEnv('DebugLevel', 0);

my $exploits = { };
my $payloads = { };
my $payloadsIndex = $ui->LoadPayloads;

foreach my $key (keys(%{$payloadsIndex})) {
    $payloads->{$payloadsIndex->{$key}->SelfEndName} = $payloadsIndex->{$key};
}

$ui->SetTempEnv('_Payloads', $payloadsIndex);

my $sel = shift(@ARGV);
my $p = $payloads->{$sel};
Usage() if($opts{'h'});
Usage() if ! $p;

my $action = uc(pop(@ARGV));

foreach my $opt (@ARGV) {
  $ui->SetTempEnv(split('=', $opt));
}

$p->_Load;
$ui->SetTempEnv('_PayloadName', $sel);
$ui->SetTempEnv('_Payload', $p);

if (! $action || $action =~ /^S/)
{
    print "\n" . $ui->DumpPayloadSummary($p);
    exit(0);
}

Usage() if $action !~ /^C|^P|^R/;

if ($action =~ /^R/) { print $p->Build; exit; }

if ($p->Multistage)
{
    print STDERR "Warning: Multistage payloads only return first stage\n\n";
}

my $r = $action =~ /^C/ ? Pex::Text::BufferC($p->Build) : Pex::Text::BufferPerl($p->Build);

print $r;
exit(0);

sub Usage
{
    print STDERR "\n   Usage: $0 <payload> [var=val] <S|C|P|R>\n\n";
    print STDERR "Payloads: \n";
    print STDERR $ui->DumpPayloads(2, $payloads);
    print STDERR "\n";
    exit(0);
}
sub Version {
    my $ver = Pex::Utils::Rev2Ver($VERSION);
    print STDERR qq{
   Framework Version:  $FRAMEVERSION
  Msfpayload Version:  $ver

};
  exit(0);
}
