Codebase list framework2 / master msfconsole
master

Tree @master (Download .tar.gz)

msfconsole @masterraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
#!/usr/bin/perl
###############

##
#         Name: msfconsole
#       Author: H D Moore <hdm [at] metasploit.com>
#       Author: spoonm <ninjatools [at] hush.com>
#  Description: Console shell interface to the Metasploit Exploit Framework
#      Version: $Revision: 2296 $
#      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 vars qw($VERSION);
use IO::Socket;
use POSIX;
use Getopt::Std;
use Sys::Hostname;

use Pex::PsuedoShell;
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: 2296 $';

$SIG{'CHLD'} = sub { while (waitpid(-1, WNOHANG) == 0) { } };

my $exploitsIndex;
my $payloadsIndex;
my $encodersIndex;
my $nopsIndex;

my $exploits;
my $eclasses;
my $payloads;
my $encoders;
my $nops;

my %opts;
getopts('hvqs:', \%opts);

Usage() if($opts{'h'});
Version() if($opts{'v'});

my $state = {'Mode' => 'Main'};

# load the modules
Load();

my $console = Pex::PsuedoShell->new('Metasploit Console', 'msf > ', 0);
$console->tabCompletion(\&xTabCompletion);

# configure the last exploit
if ( (my $le = $ui->GetEnv('LastModule')) ) {
	$state->{'Mode'} = 'Exploit';
	$state->{'Exploit'}->{'Name'} = $le;
	gUse('use', $le);
}
		
# virtual command table
my %virtualCmds = ();

# global command tables
my %globalCmds =
(
    'version'   => [\&gVersion,       "Show console version"],
    'help'      => [\&gHelp,          "Show the main console help"],
    '?'         => [\&gHelp,          "Show the main console help"],
    'quit'      => [\&gExit,          "Exit the console"],
    'exit'      => [\&gExit,          "Exit the console"],
    'use'       => [\&gUse,           "Select an exploit by name"],
    'info'      => [\&gInfo,          "Display detailed exploit or payload information"],
    'cd'        => [\&gChdir,         "Change working directory"],
    'save'      => [\&gSave,          "Save configuration to disk"],
    'setg'      => [\&gSet,           "Set a global environment variable"],
    'unsetg'    => [\&gUnset,         "Remove a global environment variable"],
    'reload'    => [\&Load,           "Reload exploits and payloads"],
);


# main mode commands
my %mainCmds =
(
    'show'      => [\&mShow,   "Show available exploits and payloads"],
);

# exploit mode commands
my %exploitCmds = 
(
    'set'       => [\&eSet,           "Set a temporary environment variable"],
    'unset'     => [\&eUnset,         "Remove a temporary environment variable"],
    'back'      => [\&eBack,          "Drop back to the main menu"],
    'show'      => [\&eShow,          "Show options, advanced, payloads, or targets"],
    'check'     => [\&eCheck,         "Perform vulnerability check"],
    'rcheck'    => [\&eReloadCheck,   "Perform vulnerability check"],	
    'exploit'   => [\&eExploit,       "Launch the actual exploit"],
    'rexploit'  => [\&eReloadExploit, "Reload and exploit, for us tester types"],
);


$state->{'LocalAddress'} = Pex::Utils::SourceIP();
xAddAddressCache($state->{'LocalAddress'});

if (! defined($opts{'q'})) {

    my $username = ($ENV{'USER'} || $ENV{'USERNAME'} || 'unknown');
    Msf::Logging->PrintLine('[' . localtime(time()) . '] msfconsole started on host ' . hostname() . ' by user ' . $username );
    Msf::TextUI::PrintAsciiLogo();

    printf("\n+ -- --=[ msfconsole v%s [%d exploits - %d payloads]\n\n", 
           $FRAMEVERSION, 
           scalar(keys(%{$exploits})),
           scalar(keys(%{$payloads}))
    );
}

ProcessCmd('use', shift(@ARGV)) if(@ARGV);
ProcessScript($opts{'s'}) if(exists($opts{'s'}));

while (1)
{
    SetupCmds();
    last if(!ProcessCmd($console->readCommand()));
}
print "\n";

sub SetupCmds {
  %virtualCmds = %globalCmds;
  
  my $stateMode = $state->{'Mode'};
    
  if ($stateMode eq 'Main')    { foreach (keys(%mainCmds)){ $virtualCmds{$_} = $mainCmds{$_} } }
  if ($stateMode eq 'Exploit') { foreach (keys(%exploitCmds)){ $virtualCmds{$_} = $exploitCmds{$_} } }
}

sub ProcessCmd {
  my $cmd = shift;
  my @args = @_;

  SetupCmds();

  return(0) if(!defined($cmd));

  if(exists($virtualCmds{$cmd})) {
    $virtualCmds{$cmd}->[0]($cmd, @args);
  }
  else {
    gUnknown($cmd, @args);
  }
  return(1);
}

sub ProcessScript {
  my $file = shift;
  open(INFILE, "<$file") or die("Cannot open script: $file: $!\n");
  local $/;
  my $data = <INFILE>;
  close(INFILE);
  foreach my $line (split("\n", $data)) {
    ProcessCmd(Pex::PsuedoShell->parseCommands($line));
  }
}

sub Load {
	my $genv = $ui->_Env;
	my $senv = $ui->_TempEnvs;
	my $tenv = $ui->_TempEnv;

    $exploitsIndex = $ui->LoadExploits;
    $payloadsIndex = $ui->LoadPayloads;
    $encodersIndex = $ui->LoadEncoders;
    $nopsIndex     = $ui->LoadNops;
    $exploits = { };
    $eclasses = { };
    $payloads = { };
    $encoders = { };
    $nops     = { };
    
    foreach my $key (sort(keys(%{$exploitsIndex}))) {
        $exploits->{$exploitsIndex->{$key}->SelfEndName} = $exploitsIndex->{$key};
        $eclasses->{$exploitsIndex->{$key}->ModuleClass}++;
    }
    
    foreach my $key (sort(keys(%{$encodersIndex}))) {
        $encoders->{$encodersIndex->{$key}->SelfEndName} = $encodersIndex->{$key};
    } 
       
    foreach my $key (sort(keys(%{$nopsIndex}))) {
        $nops->{$nopsIndex->{$key}->SelfEndName} = $nopsIndex->{$key};
    }    
    
    foreach my $key (keys(%{$payloadsIndex})) {
        $payloads->{$payloadsIndex->{$key}->SelfEndName} = $payloadsIndex->{$key};
    }


    # Important, reload the exploit object in state
    if($state->{'Mode'} eq 'Exploit') {
      my $exploit = $exploits->{$state->{'Exploit'}->{'Name'}};

      # check to make sure the module reloaded, it could have had errors..
      if(!$exploit) {
        xMsg('reload', 'Error reloading current exploit, moving back to Main.');
        eBack();
      }
      # ok, call gUse to reload tab completion, etc
      else {
        gUse('use', $state->{'Exploit'}->{'Name'});
      }
    }
	
	$ui->_Env($genv);
	$ui->_TempEnvs($senv);
	$ui->_TempEnv($tenv);
}

sub gSave {
    my $cmd = shift;
	if($state->{'Mode'} eq 'Exploit') {
		$ui->SetGlobalEnv('LastModule', $state->{'Exploit'}->{'Name'});
		$ui->SaveTempEnv($state->{'Exploit'}->{'Name'});
	} else {
		$ui->UnsetGlobalEnv('LastModule');
	}
	
    $ui->SaveConfig;
    print "Saved configuration to: " . $ui->ConfigFile . "\n";
}

sub gVersion { print "msfconsole version ". Pex::Utils::Rev2Ver($VERSION)."\n" }

sub gSet {
    my $cmd = shift;
    if(@_ == 1) {
        print "$_[0]: " . $ui->GetGlobalEnv($_[0]) . "\n";
    }
    elsif(@_ == 2) {
        print "$_[0] -> $_[1]\n";
        $ui->SetGlobalEnv($_[0], $_[1]);
    }
    else {
        foreach (sort(keys(%{$ui->GetGlobalEnv}))) {
            print "$_: " . $ui->GetGlobalEnv($_) . "\n";
        }
    }
}

sub gUnset
{
    my ($cmd, $key) = @_;

    if(!defined($key))
    {
        my $ok = xAskYN('Clear env? [yes/no]: ');
		return if $ok ne 'yes';
        $ui->UnsetGlobalEnv;
    }
    $ui->UnsetGlobalEnv($key);
}

sub eSet {
    my $cmd = shift;
    if(@_ == 1) {
        print "$_[0]: " . $ui->GetTempEnv($_[0]) . "\n";
    }
    elsif(@_ == 2) {
        print "$_[0] -> $_[1]\n";
        $ui->SetTempEnv($_[0], $_[1]);
    }
    else {
        foreach (sort(keys(%{$ui->GetTempEnv}))) {
            print "$_: " . $ui->GetTempEnv($_) . "\n";
        }
    }
    
    my $prompt = 'msf '.$state->{'Exploit'}->{'Name'};
    if ($ui->GetEnv('PAYLOAD') && $state->{'Exploit'}->{'Exploit'}->Payload) {
        $prompt .= '('.$ui->GetEnv('PAYLOAD').')';
    }
    $prompt .= ' > ';
    $console->_prompt($prompt);
}

sub eUnset
{
    my ($cmd, $key) = @_;

    if(!defined($key))
    {
        my $ok = xAskYN('Clear temporary env? [yes/no]: ');
		return if $ok ne 'yes';
        $ui->UnsetTempEnv;
    }
    $ui->UnsetTempEnv($key);
    
    my $prompt = 'msf '.$state->{'Exploit'}->{'Name'};
    if ($ui->GetEnv('PAYLOAD') && $state->{'Exploit'}->{'Exploit'}->Payload) {
        $prompt .= '('.$ui->GetEnv('PAYLOAD').')';
    }
    $prompt .= ' > ';
    $console->_prompt($prompt);
}


sub gExit
{
    Msf::Logging->PrintLine('[' . localtime(time()) . '] msfconsole closed' );
    POSIX::_exit(0) if($ui->GetEnv('AlternateExit') == 1);
    if($ui->GetEnv('AlternateExit') == 2) {
      exec('true');
    }
    exit(0);
}

sub gUnknown
{
    my ($cmd, @args) = @_;
    
    if (! xCheckSystemCommand($cmd)) 
    {
        xMsg($cmd, "command not found");
    } else {
		my $cmdline = "$cmd ". join(" ", @args);
		Msf::Logging->PrintLine('[' . localtime(time()) . "] executing system command line '$cmdline'");	
        system($cmdline);
    }
}

sub gHelp
{
    my ($cmd, @args) = @_;
    
    my $col = Msf::ColPrint->new(8, 6);
    print "\nMetasploit Framework " . $state->{'Mode'}  . " Console Help\n";
    print   "======================================\n\n";
    foreach my $cmd (sort(keys(%virtualCmds)))
    {
        $col->AddRow($cmd, $virtualCmds{$cmd}->[1]);
    }
    print $col->GetOutput . "\n";
}

sub gUse 
{
    my ($cmd, @args) = @_;
    if (! exists($exploits->{$args[0]}))
    {
        xMsg("use", "please specify a valid exploit name");
        return;
    }
    
    my $exploit = $exploits->{$args[0]};
    
    # switch to exploit mode
    $state->{'Mode'} = 'Exploit';
    
    # wipe out any previous exploit state
    delete($state->{'Exploit'});
    
    $state->{'Exploit'}->{'Exploit'} = $exploit;
    $state->{'Exploit'}->{'Name'} = $args[0];
    $state->{'Exploit'}->{'Payloads'} = xValidPayloads($exploit);

    $ui->LoadTempEnv($args[0]);

    if(defined($exploit->UseMessage)) {
      print $exploit->UseMessage . "\n";
    }
    
    my $prompt = 'msf '.$state->{'Exploit'}->{'Name'};
    if ($ui->GetEnv('PAYLOAD') && $state->{'Exploit'}->{'Exploit'}->Payload)
    {
        $prompt .= '('.$ui->GetEnv('PAYLOAD').')';
    }
    $prompt .= ' > ';
    $console->_prompt($prompt);
}

sub eBack
{
    $ui->SaveTempEnv($state->{'Exploit'}->{'Name'});
    $ui->UnsetTempEnv;
    $state->{'Mode'} = 'Main';
    $console->_prompt("msf > ");
}

sub gChdir
{
    my ($cmd, @args) = @_;
    
    if (! $args[0])
    {
        chdir($ENV{'HOME'});
        return;
    }
    
    if (chdir($args[0]))
    {
        xMsg("chdir", "changed to directory $args[0]");
    } else {
        xMsg("chdir", "failed to change directory $!");
    }
}

sub gInfo {
  my $cmd = shift;
  my @args = @_;
  my $module;
  my $type;

  # Support old info exploit/payload syntax
  if(@args == 2) {
    $module = $args[1];
    $type = $args[0];
  }
  elsif(@args == 1) {
    $module = $args[0];
  }
    
  if(!defined($module) || ($type ? $type !~ /^(encoder|exploit|payload|nop)$/ : 0)) {
    xMsg("info", "usage: info [type] <module name>");
    return;
  }

  if($exploits->{$module} && ($type ? $type eq 'exploit' : 1)) {
    print "\n" . $ui->DumpExploitSummary($exploits->{$module});
  }
  elsif($payloads->{$module} && ($type ? $type eq 'payload' : 1)) {
    print "\n" . $ui->DumpPayloadSummary($payloads->{$module});
  }

  # Kinda a hack, we rebuild the keys for exploits and payloads, but
  # not for nops or encoders...
  elsif($encoders->{$module} && ($type ? $type eq 'encoder' : 1)) {
    print "\n" . $ui->DumpEncoderSummary($encoders->{$module});
  }
  elsif($nops->{$module} && ($type ? $type eq 'nop' : 1)) {
    print "\n" . $ui->DumpNopSummary($nops->{$module});
  }
  
  else {
    xMsg("info", "invalid module name");
  }
}

sub mShow 
{
    my ($cmd, @args) = @_;
    my $c = $state->{'CONF'};
    
    if (lc($args[0]) eq "exploits")
    {
        print "\nMetasploit Framework Loaded Exploits\n";
        print   "====================================\n\n";
        
        print $ui->DumpExploits(2, $exploits, $args[1]) . "\n";
        return;
    }
    
    if (lc($args[0]) eq "payloads")
    {
        print "\nMetasploit Framework Loaded Payloads\n";
        print   "====================================\n\n";
        
        print $ui->DumpPayloads(2, $payloads) . "\n";
        return;
    }

    if (lc($args[0]) eq "encoders")
    {
        print "\nMetasploit Framework Loaded Encoders\n";
        print   "====================================\n\n";
        
        print $ui->DumpEncoders(2, $encoders) . "\n";
        return;
    }

    if (lc($args[0]) eq "nops")
    {
        print "\nMetasploit Framework Loaded Nop Engines\n";
        print   "=======================================\n\n";
        
        print $ui->DumpNops(2, $nops) . "\n";
        return;
    }

    if (lc($args[0]) eq "config")
    {
        print "\nMetasploit Framework Configuration\n";
        print   "====================================\n\n";
        
        foreach my $v (sort(keys(%{$c}))) {
            print "  $v" . (" " x (30-length($v))) . $c->{$v} ."\n";
        }
        print "\n";
        return;
    }

    xMsg("show", "requires an option: 'exploits', 'payloads', 'encoders', or 'nops'");
}


sub eShow 
{
    my ($cmd, @args) = @_;
    if (lc($args[0]) eq 'options')  { eOptions();  return }
    if (lc($args[0]) eq 'advanced') { eAdvanced(); return }
    if (lc($args[0]) eq 'targets')  { eTargets();  return }
    if (lc($args[0]) eq 'payloads') { ePayloads(); return }

    xMsg("show", "specify 'targets', 'payloads', 'options', or 'advanced'");

}

sub ePayloads {
  SaveTemp();
  FillTemp();
  $ui->Payloads;
  RestoreTemp();
}
sub eOptions {
  SaveTemp();
  FillTemp();
  $ui->Options;
  RestoreTemp();
}
sub eAdvanced {
  SaveTemp();
  FillTemp();
  $ui->AdvancedOptions;
  RestoreTemp();
}
sub eTargets  {
  SaveTemp();
  FillTemp();
  $ui->Targets;
  RestoreTemp();
}

sub eCheck {
  return if($state->{'Mode'} ne 'Exploit');
  xUpdateAddrCache();
  SaveTemp();
  FillTemp();
  $ui->Check;
  RestoreTemp();
}

sub eReloadCheck {
  Load();
  return eCheck(@_);
}

sub eExploit {
  return if($state->{'Mode'} ne 'Exploit');
  xUpdateAddrCache();
  SaveTemp();
  FillTemp();
  $ui->Exploit;
  RestoreTemp();
}

sub eReloadExploit {
  Load();
  return eExploit(@_);
}

sub xMsg
{
    my ($loc, $msg) = @_;
    print STDERR "msfconsole: $loc: $msg\n";
}

sub xValidPayloads
{
    my $exploit = shift;
    if($exploit->Payload) {
      $state->{'Exploit'}->{'Payloads'} = $ui->MatchPayloads($exploit, $payloads);
      return $state->{'Exploit'}->{'Payloads'};
    }
    return;
}

sub xCheckSystemCommand
{
    my $cmd = shift;
    return(1) if -e $cmd;
    foreach my $d (split(/:/, $ENV{'PATH'})) { 
    
        if ($^O eq 'cygwin') {
            return(1) if -e "$d/$cmd";
        } else {
            return(1) if -x "$d/$cmd";
        }
    }
    return(0);
}

sub xGetAddressCache
{
    my $cache = $state->{'CacheAddress'};
    return keys(%{$cache});
}

sub xAddAddressCache
{
    my $addr = shift;
    $state->{'CacheAddress'}->{$addr}++
}

sub xUpdateAddrCache 
{
    my $x = $state->{'Exploit'}->{'Exploit'};
    my $p = $ui->GetEnv('PAYLOAD');
    my %options = ();

    
    # create a list of all exploit options of type ADDR
    foreach (keys(%{$x->UserOpts})) {
        next if $x->UserOpts->{$_}->[1] ne 'ADDR';
        $options{$_}++;
    }
    foreach (keys(%{$x->Advanced})) {
        next if $x->Advanced->{$_}->[1] ne 'ADDR';
        $options{$_}++;
    }  

    # create a list of all payload options of type ADDR
    if ($x->Payload && $p && exists($payloads->{$p}))
    {
        $p = $payloads->{$p};
	$p->_Load;
        foreach (keys(%{$p->UserOpts})) {
            next if $p->UserOpts->{$_}->[1] ne 'ADDR';
            $options{$_}++;
        }        
        foreach (keys(%{$p->Advanced})) {
            next if $p->Advanced->{$_}->[1] ne 'ADDR';
            $options{$_}++;
        }
    }
    
    # scan environments and add to the cache
    foreach (keys(%options)) {
        my $value = $ui->GetTempEnv($_) || $ui->GetEnv($_) || undef;
        next if ! $value;
        $state->{'CacheAddress'}->{$value}++;
    }
}

sub xAskYN {
	my $quest	= shift;
	my $cinp	= IO::Handle->new_from_fd(0, '<');
	my $cout	= IO::Handle->new_from_fd(1, '>');
	my $iblock	= $cinp->blocking;
	
	$cinp->blocking(1);

	my $res = 'run';
	while ($res && $res ne 'yes' && $res ne 'no') {
		$cout->printflush($quest);
		if ( defined($res = $cinp->getline)) {
			chomp($res);
			$res = lc($res);
		} 
		else { $cout->printflush("\nError reading from input: $!\n"); }
	}
	$cinp->blocking($iblock);
	return $res;
}


#
# TAB COMPLETION ROUTINES
#

sub xCreateSetList
{
    if ($state->{"Mode"} eq "Main") { return keys(%{$ui->GetGlobalEnv}) } 
    
    if ($state->{"Mode"} eq "Exploit") 
    {
        my %options = ();
        
        my $x = $state->{'Exploit'}->{'Exploit'};
        my $p = $ui->GetEnv('PAYLOAD');
        
        foreach (keys(%{$x->UserOpts})) { $options{$_}++ }
        foreach (keys(%{$x->Advanced})) { $options{$_}++ }
        
        if ($x->Payload && $p && exists($payloads->{$p}))
        {
            $p = $payloads->{$p};
	    $p->_Load;
            foreach (keys(%{$p->UserOpts})) { $options{$_}++ }
            foreach (keys(%{$p->Advanced})) { $options{$_}++ }
        }
         
        if ($x->Payload) { $options{"PAYLOAD"}++ }
        if ($x->TargetsList) { $options{"TARGET"}++  }

        foreach my $e (keys(%{ $ui->GetEnv })) {
            $options{$e}++;
        }
        
        foreach my $e (keys(%{ $ui->GetTempEnv })) {
            $options{$e}++;
        }   

        return(keys(%options));
    }
}

sub xCreateSetValueList
{
    if ($state->{"Mode"} eq "Main") { return ' ' } 
    
    if ($state->{"Mode"} eq "Exploit") 
    {
        my %results = ();
        
        my $n = $state->{'SetName'};
        my $x = $state->{'Exploit'}->{'Exploit'};
        my $v = $state->{'Exploit'}->{'Payloads'};
        my $p = $ui->GetEnv('PAYLOAD');

        if ($x->Payload && $p && exists($payloads->{$p})) { $p = $payloads->{$p} }
        
        if (uc($n) eq "PAYLOAD") { return keys(%{$v}) }
        
        if (uc($n) eq "TARGET")
        {
            my $tidx = 0;
            foreach ($x->TargetsList) { $results{$tidx}++ ; $tidx++;}
            return keys(%results);
        }
        
        my ($req, $type, $desc, $dflt);
        
        if (exists($x->UserOpts->{$n})) {
            ($req, $type, $desc, $dflt) = @{$x->UserOpts->{$n}};  
        }
        
        if (exists($x->Advanced->{$n})) {
            ($req, $type) = (0, 'DATA');
            ($dflt, $desc) = @{$x->Advanced->{$n}};
        }
                
        if ($x->Payload && $p && exists($p->UserOpts->{$n})) {
            ($req, $type, $desc, $dflt) = @{$p->UserOpts->{$n}};  
        }
                
        if ($x->Payload && $p && exists($p->Advanced->{$n})) {
            ($req, $type) = (0, 'DATA');
            ($dflt, $desc) = @{$p->Advanced->{$n}};
        }
        
        if ($dflt) { return ($dflt) }
        
        if ($type eq "ADDR") { return xGetAddressCache() }
        if ($type eq "BOOL") { return ("TRUE", "FALSE") }
        if ($type eq "FILE") { return undef }
        if ($type eq "PATH") { return undef }
        return ' ';
    }
}

sub xTabCompletion
{
    my ($text, $line, $start, $end) = @_;
    my ($cmd, @args) = split(/\s+/, $line);
    
    # default to match of space
    $state->{'TabVals'} = [' '];
    
    # this handles command matching
    if ($start == 0) { $state->{'TabVals'} = [sort(keys(%virtualCmds))] }
    
    if (lc($cmd) eq "use") { $state->{'TabVals'} = [sort(keys(%{$exploits}))] }
    
    if (lc($cmd) eq "show")
    {
        if ($state->{'Mode'} eq 'Main') {
            
            # Handle ModuleClass tab completion stuff
            if ($args[0] eq 'exploits') {
                $state->{'TabVals'} = [sort(keys(%{$eclasses}))];
            }
            # Default to the standard show options
            else {
                $state->{'TabVals'} = ['exploits', 'payloads', 'encoders', 'nops'];
            }
        }
		
        if ($state->{'Mode'} eq 'Exploit') {
            $state->{'TabVals'} = ['advanced', 'options', 'targets', 'payloads'] 
        }
    }
    
    if (lc($cmd) eq "info")
    {
        # display variables if no args are specified
        if (! $args[0] || (! $args[1] && ($args[0] && $text))) { 
            
            my %allmods;
            for (keys(%{$exploits}), keys(%{$payloads}), keys(%{$encoders}), keys(%{$nops})) {
                $allmods{$_}++;
            }
            
            $state->{'TabVals'} = ['exploit', 'payload', 'encoder', 'nop', sort(keys(%allmods))] 
        }
        if (! $args[1] || (! $args[2] && ($args[1] && $text)))
        {
            if ($args[0] eq "exploit") { $state->{'TabVals'} = [sort(keys(%{$exploits}))] }
            if ($args[0] eq "payload") { $state->{'TabVals'} = [sort(keys(%{$payloads}))] }
            if ($args[0] eq "encoder") { $state->{'TabVals'} = [sort(keys(%{$encoders}))] }
            if ($args[0] eq "nop"    ) { $state->{'TabVals'} = [sort(keys(%{$nops}))] }            
        }
    }
        
    if (
        ($state->{'Mode'} eq "Main"    && lc($cmd) =~ /^(un|)setg$/) ||
        ($state->{'Mode'} eq "Exploit" && lc($cmd) =~ /^(un|)set$/)
       )
    {
        # display variables if no args are specified
        if (! $args[0] || (! $args[1] && ($args[0] && $text)))
        {
            $state->{'TabVals'} = [sort(xCreateSetList())];
        } elsif (! $args[1] || (! $args[2] && ($args[1] && $text)))
        {
            $state->{'SetName'} = $args[0];
            $state->{'TabVals'} = [sort(xCreateSetValueList())];
        }
    }
    
    # revert to file completion for non-commands
    if (! scalar(@{$state->{'TabVals'}}) && ! exists($virtualCmds{$cmd})) {
        $state->{'TabVals'} = []; 
    }
    
    

    my @matches = $console->_term->completion_matches($text, \&xTabCompletionMatcher);
    return(@matches); 
}


# This is a localized closure for matching speed, this routine has been borrowed
# from http://lists.n0i.net/pipermail/perl/2003-October/000015.html
{
    my $list_index;
    my @name;
    
    sub xTabCompletionMatcher
    {
        my ($text, $mstate) = @_;
        $text = quotemeta($text);

        # If this is a new word to complete, initialize now.  This
        # includes saving the length of TEXT for efficiency, and
        # initializing the index variable to 0.

        unless ($mstate) {
	        $list_index = 0;
            @name = @{$state->{'TabVals'}};
            return undef if (scalar(@name) == 0);
        }

        # Return the next name which partially matches from the
        # command list.
        while ($list_index <= $#name) {
	        $list_index++;
	        return $name[$list_index - 1]
                if ($name[$list_index - 1] =~ /^$text/);
        }

        # If no names matched, then return NULL.
        return undef;
    }
}

sub SaveTemp {
  $ui->SaveTempEnv('_Save');
}

sub RestoreTemp {
  $ui->LoadTempEnv('_Save');
  $ui->DeleteTempEnv('_Save');
}

sub FillTemp {
  $ui->SetTempEnv('_ExploitsIndex', $exploitsIndex);
  $ui->SetTempEnv('_PayloadsIndex', $payloadsIndex);
  $ui->SetTempEnv('_Encoders', $encodersIndex);
  $ui->SetTempEnv('_Nops', $nopsIndex);

  $ui->SetTempEnv('_Exploits', $exploits);
  $ui->SetTempEnv('_Payloads', $payloads);

  my $exploit = $state->{'Exploit'}->{'Exploit'};
  $ui->SetTempEnv('_Exploit', $exploit);
  
  $ui->SetTempEnv('_UI', $ui);

  # XXX added by spoon, maybe this should be looked at...
  # applying the AutoOpts settings to the local temp env we have setup,
  # specifically this fixes things like the EXITFUNC display issues
  # this will later get called again in Exploit::Prepare, maybe we should
  # look into just having it done once....
  $exploit->ApplyAutoOpts;

  # setup payload data if exploit requires a payload
  if($exploit->Payload) {
    my $payloadName = $ui->GetEnv('PAYLOAD');
    $ui->SetTempEnv('_PayloadName', $payloadName);
    my $validPayloads = $ui->MatchPayloads($exploit, $payloads);
    my $payload = $validPayloads->{$payloadName};
    # make sure the OO stuff is good for whoever might use this...
    $payload->_Load if($payload);
    $ui->SetTempEnv('_Payload', $payload);
    $ui->SetTempEnv('_ValidPayloads', $validPayloads);
  }
  else {
    $ui->SetTempEnv('_PayloadName', undef);
    $ui->SetTempEnv('_Payload', undef);
    $ui->SetTempEnv('_ValidPayloads', undef);
  }
}

sub Usage {
    print STDERR qq{
  Usage: $0 <options> <exploit>
Options:
         -h             You're looking at me baby
         -v             List version information
         -s   <file>    Process file of console commands
         -q             No splash screen on startup

};
    exit(0);
}

sub Version {
    my $ver = Pex::Utils::Rev2Ver($VERSION);
    print STDERR qq{
   Framework Version:  $FRAMEVERSION
  Msfconsole Version:  $ver

};

  exit(0);
}