-
Notifications
You must be signed in to change notification settings - Fork 115
/
pentest.rb
2603 lines (2368 loc) · 91.6 KB
/
pentest.rb
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2017, Carlos Perez <carlos_perez[at]darkoperator.com
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this list of conditions and
# the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this list of conditions
# and the following disclaimer in the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module Msf
class Plugin::Pentest < Msf::Plugin
# Post Exploitation command class
################################################################################################
class PostautoCommandDispatcher
include Msf::Auxiliary::Report
include Msf::Ui::Console::CommandDispatcher
def name
"Postauto"
end
def commands
{
'multi_post' => "Run a post module against specified sessions.",
'multi_post_rc' => "Run resource file with post modules and options against specified sessions.",
'multi_meter_cmd' => "Run a Meterpreter Console Command against specified sessions.",
'multi_meter_cmd_rc'=> "Run resource file with Meterpreter Console Commands against specified sessions.",
"multi_cmd" => "Run shell command against several sessions",
"sys_creds" => "Run system password collection modules against specified sessions.",
"app_creds" => "Run application password collection modules against specified sessions.",
"get_lhost" => "List local IP addresses that can be used for LHOST."
}
end
def cmd_get_lhost(*args)
opts = Rex::Parser::Arguments.new(
"-h" => [ false, "Command help."]
)
opts.parse(args) do |opt, idx, val|
case opt
when "-h"
print_line("Command for listing local IP Addresses that can be used with LHOST.")
print_line(opts.usage)
return
else
print_line(opts.usage)
return
end
end
print_status("Local host IP addresses:")
Socket.ip_address_list.each do |a|
if !(a.ipv4_loopback?()|a.ipv6_linklocal?()|a.ipv6_loopback?())
print_good("\t#{a.ip_address}")
end
end
print_line
end
# Multi shell command
def cmd_multi_cmd(*args)
# Define options
opts = Rex::Parser::Arguments.new(
"-s" => [ true, "Comma separated list sessions to run modules against."],
"-c" => [ true, "Shell command to run."],
"-p" => [ true, "Platform to run the command against. If none given it will run against all."],
"-h" => [ false, "Command Help."]
)
# set variables for options
sessions = []
command = ""
plat = ""
# Parse options
opts.parse(args) do |opt, idx, val|
case opt
when "-s"
if val =~ /all/i
sessions = framework.sessions.keys
else
sessions = val.split(",")
end
when "-c"
command = val
when "-p"
plat = val
when "-h"
print_line(opts.usage)
return
else
print_line(opts.usage)
return
end
end
# Make sure that proper values where provided
if not sessions.empty? and not command.empty?
# Iterate thru the session IDs
sessions.each do |s|
# Set the session object
session = framework.sessions[s.to_i]
if session.platform =~ /#{plat}/i || plat.empty?
host = session.tunnel_peer.split(":")[0]
print_line("Running #{command} against session #{s}")
# Run the command
cmd_out = session.shell_command_token(command)
# Print good each line of the command output
if not cmd_out.nil?
cmd_out.each_line do |l|
print_line(l.chomp)
end
file_name = "#{File.join(Msf::Config.loot_directory,"#{Time.now.strftime("%Y%m%d%H%M%S")}_command.txt")}"
framework.db.report_loot({ :host=> host,
:path => file_name,
:ctype => "text/plain",
:ltype => "host.command.shell",
:data => cmd_out,
:name => "#{host}.txt",
:info => "Output of command #{command}" })
else
print_error("No output or error when running the command.")
end
end
end
else
print_error("You must specify both a session and a command.")
print_line(opts.usage)
return
end
end
# browser_creds Command
#-------------------------------------------------------------------------------------------
def cmd_app_creds(*args)
opts = Rex::Parser::Arguments.new(
"-s" => [ true, "Sessions to run modules against. Example <all> or <1,2,3,4>"],
"-h" => [ false, "Command Help"]
)
cred_mods = [
{"mod" => "windows/gather/credentials/wsftp_client", "opt" => nil},
{"mod" => "windows/gather/credentials/winscp", "opt" => nil},
{"mod" => "windows/gather/credentials/windows_autologin", "opt" => nil},
{"mod" => "windows/gather/credentials/vnc", "opt" => nil},
{"mod" => "windows/gather/credentials/trillian", "opt" => nil},
{"mod" => "windows/gather/credentials/total_commander", "opt" => nil},
{"mod" => "windows/gather/credentials/smartftp", "opt" => nil},
{"mod" => "windows/gather/credentials/outlook", "opt" => nil},
{"mod" => "windows/gather/credentials/nimbuzz", "opt" => nil},
{"mod" => "windows/gather/credentials/mremote", "opt" => nil},
{"mod" => "windows/gather/credentials/imail", "opt" => nil},
{"mod" => "windows/gather/credentials/idm", "opt" => nil},
{"mod" => "windows/gather/credentials/flashfxp", "opt" => nil},
{"mod" => "windows/gather/credentials/filezilla_server", "opt" => nil},
{"mod" => "windows/gather/credentials/meebo", "opt" => nil},
{"mod" => "windows/gather/credentials/razorsql", "opt" => nil},
{"mod" => "windows/gather/credentials/coreftp", "opt" => nil},
{"mod" => "windows/gather/credentials/imvu", "opt" => nil},
{"mod" => "windows/gather/credentials/epo_sql", "opt" => nil},
{"mod" => "windows/gather/credentials/gpp", "opt" => nil},
{"mod" => "windows/gather/credentials/enum_picasa_pwds", "opt" => nil},
{"mod" => "windows/gather/credentials/tortoisesvn", "opt" => nil},
{"mod" => "windows/gather/credentials/ftpnavigator", "opt" => nil},
{"mod" => "windows/gather/credentials/dyndns", "opt" => nil},
{"mod" => "windows/gather/credentials/bulletproof_ftp", "opt" => nil},
{"mod" => "windows/gather/credentials/enum_cred_store", "opt" => nil},
{"mod" => "windows/gather/credentials/ftpx", "opt" => nil},
{"mod" => "windows/gather/credentials/razer_synapse", "opt" => nil},
{"mod" => "windows/gather/credentials/sso", "opt" => nil},
{"mod" => "windows/gather/credentials/steam", "opt" => nil},
{"mod" => "windows/gather/enum_ie", "opt" => nil},
{"mod" => "multi/gather/ssh_creds", "opt" => nil},
{"mod" => "multi/gather/pidgin_cred", "opt" => nil},
{"mod" => "multi/gather/firefox_creds", "opt" => nil},
{"mod" => "multi/gather/filezilla_client_cred", "opt" => nil},
{"mod" => "multi/gather/fetchmailrc_creds", "opt" => nil},
{"mod" => "multi/gather/thunderbird_creds", "opt" => nil},
{"mod" => "multi/gather/netrc_creds", "opt" => nil},
{"mod" => "/multi/gather/gpg_creds", "opt" => nil}
]
# Parse options
if args.length == 0
print_line(opts.usage)
return
end
sessions = ""
opts.parse(args) do |opt, idx, val|
case opt
when "-s"
sessions = val
when "-h"
print_line(opts.usage)
return
else
print_line(opts.usage)
return
end
end
if not sessions.empty?
cred_mods.each do |p|
m = framework.post.create(p["mod"])
next if m == nil
# Set Sessions to be processed
if sessions =~ /all/i
session_list = m.compatible_sessions
else
session_list = sessions.split(",")
end
session_list.each do |s|
begin
if m.session_compatible?(s.to_i)
m.datastore['SESSION'] = s.to_i
if p['opt']
opt_pair = p['opt'].split("=",2)
m.datastore[opt_pair[0]] = opt_pair[1]
end
m.options.validate(m.datastore)
print_line("")
print_line("Running #{p['mod']} against #{s}")
m.run_simple(
'LocalInput' => driver.input,
'LocalOutput' => driver.output
)
end
rescue
print_error("Could not run post module against sessions #{s}.")
end
end
end
else
print_line(opts.usage)
return
end
end
# sys_creds Command
#-------------------------------------------------------------------------------------------
def cmd_sys_creds(*args)
opts = Rex::Parser::Arguments.new(
"-s" => [ true, "Sessions to run modules against. Example <all> or <1,2,3,4>"],
"-h" => [ false, "Command Help"]
)
cred_mods = [
{"mod" => "windows/gather/cachedump", "opt" => nil},
{"mod" => "windows/gather/smart_hashdump", "opt" => "GETSYSTEM=true"},
{"mod" => "windows/gather/credentials/gpp", "opt" => nil},
{"mod" => "osx/gather/hashdump", "opt" => nil},
{"mod" => "linux/gather/hashdump", "opt" => nil},
{"mod" => "solaris/gather/hashdump", "opt" => nil},
]
# Parse options
sessions = ""
opts.parse(args) do |opt, idx, val|
case opt
when "-s"
sessions = val
when "-h"
print_line(opts.usage)
return
else
print_line(opts.usage)
return
end
end
if not sessions.empty?
cred_mods.each do |p|
m = framework.post.create(p["mod"])
# Set Sessions to be processed
if sessions =~ /all/i
session_list = m.compatible_sessions
else
session_list = sessions.split(",")
end
session_list.each do |s|
if m.session_compatible?(s.to_i)
m.datastore['SESSION'] = s.to_i
if p['opt']
opt_pair = p['opt'].split("=",2)
m.datastore[opt_pair[0]] = opt_pair[1]
end
m.options.validate(m.datastore)
print_line("")
print_line("Running #{p['mod']} against #{s}")
m.run_simple(
'LocalInput' => driver.input,
'LocalOutput' => driver.output
)
end
end
end
else
print_line(opts.usage)
return
end
end
# Multi_post Command
#-------------------------------------------------------------------------------------------
# Function for doing auto complete on module name
def tab_complete_module(str, words)
res = []
framework.modules.module_types.each do |mtyp|
mset = framework.modules.module_names(mtyp)
mset.each do |mref|
res << mtyp + '/' + mref
end
end
return res.sort
end
# Function to do tab complete on modules for multi_post
def cmd_multi_post_tabs(str, words)
tab_complete_module(str, words)
end
# Function for the multi_post command
def cmd_multi_post(*args)
opts = Rex::Parser::Arguments.new(
"-s" => [ true, "Sessions to run module against. Example <all> or <1,2,3,4>"],
"-m" => [ true, "Module to run against sessions."],
"-o" => [ true, "Module options."],
"-h" => [ false, "Command Help."]
)
post_mod = ""
mod_opts = nil
sessions = ""
# Parse options
opts.parse(args) do |opt, idx, val|
case opt
when "-s"
sessions = val
when "-m"
post_mod = val.gsub(/^post\//,"")
when "-o"
mod_opts = val
when "-h"
print_line opts.usage
return
else
print_status "Please specify a module to run with the -m option."
return
end
end
# Make sure that proper values where provided
if not sessions.empty? and not post_mod.empty?
# Set and execute post module with options
print_line("Loading #{post_mod}")
m = framework.post.create(post_mod)
if sessions =~ /all/i
session_list = m.compatible_sessions
else
session_list = sessions.split(",")
end
if session_list
session_list.each do |s|
if m.session_compatible?(s.to_i)
print_line("Running against #{s}")
m.datastore['SESSION'] = s.to_i
if mod_opts
mod_opts.each do |o|
opt_pair = o.split("=",2)
print_line("\tSetting Option #{opt_pair[0]} to #{opt_pair[1]}")
m.datastore[opt_pair[0]] = opt_pair[1]
end
end
m.options.validate(m.datastore)
m.run_simple(
'LocalInput' => driver.input,
'LocalOutput' => driver.output
)
else
print_error("Session #{s} is not compatible with #{post_mod}.")
end
end
else
print_error("No compatible sessions were found.")
end
else
print_error("A session or Post Module where not specified.")
print_line(opts.usage)
return
end
end
# Multi_post_rc Command
#-------------------------------------------------------------------------------------------
def cmd_multi_post_rc_tabs(str, words)
tab_complete_filenames(str, words)
end
def cmd_multi_post_rc(*args)
opts = Rex::Parser::Arguments.new(
"-rc" => [ true, "Resource file with space separate values <session> <module> <options>, per line."],
"-h" => [ false, "Command Help."]
)
post_mod = nil
session_list = nil
mod_opts = nil
entries = []
opts.parse(args) do |opt, idx, val|
case opt
when "-rc"
script = val
if not ::File.exists?(script)
print_error "Resource File does not exists!"
return
else
::File.open(script, "r").each_line do |line|
# Empty line
next if line.strip.length < 1
# Comment
next if line[0,1] == "#"
entries << line.chomp
end
end
when "-h"
print_line opts.usage
return
else
print_line opts.usage
return
end
end
if entries
entries.each do |l|
values = l.split
sessions = values[0]
post_mod = values[1]
if values.length == 3
mod_opts = values[2].split(",")
end
print_line("Loading #{post_mod}")
m= framework.post.create(post_mod.gsub(/^post\//,""))
if sessions =~ /all/i
session_list = m.compatible_sessions
else
session_list = sessions.split(",")
end
session_list.each do |s|
if m.session_compatible?(s.to_i)
print_line("Running Against #{s}")
m.datastore['SESSION'] = s.to_i
if mod_opts
mod_opts.each do |o|
opt_pair = o.split("=",2)
print_line("\tSetting Option #{opt_pair[0]} to #{opt_pair[1]}")
m.datastore[opt_pair[0]] = opt_pair[1]
end
end
m.options.validate(m.datastore)
m.run_simple(
'LocalInput' => driver.input,
'LocalOutput' => driver.output
)
else
print_error("Session #{s} is not compatible with #{post_mod}")
end
end
end
else
print_error("Resource file was empty!")
end
end
# Multi_meter_cmd Command
#-------------------------------------------------------------------------------------------
def cmd_multi_meter_cmd(*args)
opts = Rex::Parser::Arguments.new(
"-s" => [ true, "Sessions to run Meterpreter Console Command against. Example <all> or <1,2,3,4>"],
"-c" => [ true, "Meterpreter Console Command to run against sessions."],
"-h" => [ false, "Command Help."]
)
command = nil
session = nil
# Parse options
opts.parse(args) do |opt, idx, val|
case opt
when "-s"
session = val
when "-c"
command = val
when "-h"
print_line opts.usage
return
else
print_status "Please specify a command to run with the -m option."
return
end
end
current_sessions = framework.sessions.keys.sort
if session =~/all/i
sessions = current_sessions
else
sessions = session.split(",")
end
sessions.each do |s|
# Check if session is in the current session list.
next if not current_sessions.include?(s.to_i)
# Get session object
session = framework.sessions.get(s.to_i)
# Check if session is meterpreter and run command.
if (session.type == "meterpreter")
print_line("Running command #{command} against session #{s}")
session.console.run_single(command)
else
print_line("Session #{s} is not a Meterpreter session!")
end
end
end
# Multi_post_rc Command
#-------------------------------------------------------------------------------------------
def cmd_multi_meter_cmd_rc(*args)
opts = Rex::Parser::Arguments.new(
"-rc" => [ true, "Resource file with space separate values <session> <command>, per line."],
"-h" => [ false, "Command Help"]
)
entries = []
script = nil
opts.parse(args) do |opt, idx, val|
case opt
when "-rc"
script = val
if not ::File.exists?(script)
print_error "Resource File does not exists"
return
else
::File.open(script, "r").each_line do |line|
# Empty line
next if line.strip.length < 1
# Comment
next if line[0,1] == "#"
entries << line.chomp
end
end
when "-h"
print_line opts.usage
return
else
print_line opts.usage
return
end
end
entries.each do |entrie|
session_parm,command = entrie.split(" ", 2)
current_sessions = framework.sessions.keys.sort
if session_parm =~ /all/i
sessions = current_sessions
else
sessions = session_parm.split(",")
end
sessions.each do |s|
# Check if session is in the current session list.
next if not current_sessions.include?(s.to_i)
# Get session object
session = framework.sessions.get(s.to_i)
# Check if session is meterpreter and run command.
if (session.type == "meterpreter")
print_line("Running command #{command} against session #{s}")
session.console.run_single(command)
else
print_line("Session #{s} is not a Meterpreter sessions.")
end
end
end
end
end
# Project handling commands
################################################################################################
class ProjectCommandDispatcher
include Msf::Ui::Console::CommandDispatcher
# Set name for command dispatcher
def name
"Project"
end
# Define Commands
def commands
{
"project" => "Command for managing projects.",
}
end
def cmd_project(*args)
# variable
project_name = ""
create = false
delete = false
history = false
switch = false
archive = false
arch_path = ::File.join(Msf::Config.log_directory,"archives")
# Define options
opts = Rex::Parser::Arguments.new(
"-c" => [ false, "Create a new Metasploit project and sets logging for it."],
"-d" => [ false, "Delete a project created by the plugin."],
"-s" => [ false, "Switch to a project created by the plugin."],
"-a" => [ false, "Export all history and DB and archive it in to a zip file for current project."],
"-p" => [ true, "Path to save archive, if none provide default ~/.msf4/archives will be used."],
"-r" => [ false, "Create time stamped RC files of Meterpreter Sessions and console history for current project."],
"-ph" => [ false, "Generate resource files for sessions and console. Generate time stamped session logs for current project."],
"-l" => [ false, "List projects created by plugin."],
"-h" => [ false, "Command Help"]
)
opts.parse(args) do |opt, idx, val|
case opt
when "-p"
if ::File.directory?(val)
arch_path = val
else
print_error("Path provided for archive does not exists!")
return
end
when "-d"
delete = true
when "-s"
switch = true
when "-a"
archive = true
when "-c"
create = true
when "-r"
make_console_rc
make_sessions_rc
when "-h"
print_line(opts.usage)
return
when "-l"
list
return
when "-ph"
history = true
else
project_name = val.gsub(" ","_").chomp
end
end
if project_name and create
project_create(project_name)
elsif project_name and delete
project_delete(project_name)
elsif project_name and switch
project_switch(project_name)
elsif archive
project_archive(arch_path)
elsif history
project_history
else
list
end
end
def project_delete(project_name)
# Check if project exists
if project_list.include?(project_name)
current_workspace = framework.db.workspace.name
if current_workspace == project_name
driver.init_ui(driver.input, Rex::Ui::Text::Output::Stdio.new)
end
workspace = framework.db.find_workspace(project_name)
if workspace.default?
workspace.destroy
workspace = framework.db.add_workspace(project_name)
print_line("Deleted and recreated the default workspace")
else
# switch to the default workspace if we're about to delete the current one
framework.db.workspace = framework.db.default_workspace if framework.db.workspace.name == workspace.name
# now destroy the named workspace
workspace.destroy
print_line("Deleted workspace: #{project_name}")
end
project_path = ::File.join(Msf::Config.log_directory,"projects",project_name)
::FileUtils.rm_rf(project_path)
print_line("Project folder #{project_path} has been deleted")
else
print_error("Project was not found on list of projects!")
end
return true
end
# Switch to another project created by the plugin
def project_switch(project_name)
# Check if project exists
if project_list.include?(project_name)
print_line("Switching to #{project_name}")
# Disable spooling for current
driver.init_ui(driver.input, Rex::Ui::Text::Output::Stdio.new)
# Switch workspace
workspace = framework.db.find_workspace(project_name)
framework.db.workspace = workspace
print_line("Workspace: #{workspace.name}")
# Spool
spool_path = ::File.join(Msf::Config.log_directory,"projects",framework.db.workspace.name)
spool_file = ::File.join(spool_path,"#{project_name}_spool.log")
# Start spooling for new workspace
driver.init_ui(driver.input, Rex::Ui::Text::Output::Tee.new(spool_file))
print_line("Spooling to file #{spool_file}...")
print_line("Successfully migrated to #{project_name}")
else
print_error("Project was not found on list of projects!")
end
return true
end
# List current projects created by the plugin
def list
current_workspace = framework.db.workspace.name
print_line("List of projects:")
project_list.each do |p|
if current_workspace == p
print_line("\t* #{p}")
else
print_line("\t#{p}")
end
end
return true
end
# Archive project in to a zip file
def project_archive(archive_path)
# Set variables for options
project_name = framework.db.workspace.name
project_path = ::File.join(Msf::Config.log_directory,"projects",project_name)
archive_name = "#{project_name}_#{::Time.now.strftime("%Y%m%d.%M%S")}.zip"
db_export_name = "#{project_name}_#{::Time.now.strftime("%Y%m%d.%M%S")}.xml"
db_out = ::File.join(project_path,db_export_name)
format = "xml"
print_line("Exporting DB Workspace #{project_name}")
exporter = Msf::DBManager::Export.new(framework.db.workspace)
exporter.send("to_#{format}_file".intern,db_out) do |mtype, mstatus, mname|
if mtype == :status
if mstatus == "start"
print_line(" >> Starting export of #{mname}")
end
if mstatus == "complete"
print_line(" >> Finished export of #{mname}")
end
end
end
print_line("Finished export of workspace #{framework.db.workspace.name} to #{db_out} [ #{format} ]...")
print_line("Disabling spooling for #{project_name}")
driver.init_ui(driver.input, Rex::Ui::Text::Output::Stdio.new)
print_line("Spooling disabled for archiving")
archive_full_path = ::File.join(archive_path,archive_name)
make_console_rc
make_sessions_rc
make_sessions_logs
compress(project_path,archive_full_path)
print_line("MD5 for archive is #{digestmd5(archive_full_path)}")
# Spool
spool_path = ::File.join(Msf::Config.log_directory,"projects",framework.db.workspace.name)
spool_file = ::File.join(spool_path,"#{project_name}_spool.log")
print_line("Spooling re-enabled")
# Start spooling for new workspace
driver.init_ui(driver.input, Rex::Ui::Text::Output::Tee.new(spool_file))
print_line("Spooling to file #{spool_file}...")
return true
end
# Export Command History for Sessions and Console
#-------------------------------------------------------------------------------------------
def project_history
make_console_rc
make_sessions_rc
make_sessions_logs
return true
end
# Create a new project Workspace and enable logging
#-------------------------------------------------------------------------------------------
def project_create(project_name)
# Make sure that proper values where provided
spool_path = ::File.join(Msf::Config.log_directory,"projects",project_name)
::FileUtils.mkdir_p(spool_path)
spool_file = ::File.join(spool_path,"#{project_name}_spool.log")
if framework.db and framework.db.active
print_line("Creating DB Workspace named #{project_name}")
workspace = framework.db.add_workspace(project_name)
framework.db.workspace = workspace
print_line("Added workspace: #{workspace.name}")
driver.init_ui(driver.input, Rex::Ui::Text::Output::Tee.new(spool_file))
print_line("Spooling to file #{spool_file}...")
else
print_error("A database most be configured and connected to create a project")
end
return true
end
# Method for creating a console resource file from all commands entered in the console
#-------------------------------------------------------------------------------------------
def make_console_rc
# Set RC file path and file name
rc_file = "#{framework.db.workspace.name}_#{::Time.now.strftime("%Y%m%d.%M%S")}.rc"
consonle_rc_path = ::File.join(Msf::Config.log_directory,"projects",framework.db.workspace.name)
rc_full_path = ::File.join(consonle_rc_path,rc_file)
# Create folder
::FileUtils.mkdir_p(consonle_rc_path)
con_rc = ""
framework.db.workspace.events.each do |e|
if not e.info.nil? and e.info.has_key?(:command) and not e.info.has_key?(:session_type)
con_rc << "# command executed at #{e.created_at}\n"
con_rc << "#{e.info[:command]}\n"
end
end
# Write RC console file
print_line("Writing Console RC file to #{rc_full_path}")
file_write(rc_full_path, con_rc)
print_line("RC file written")
return rc_full_path
end
# Method for creating individual rc files per session using the session uuid
#-------------------------------------------------------------------------------------------
def make_sessions_rc
sessions_uuids = []
sessions_info = []
info = ""
rc_file = ""
rc_file_name = ""
rc_list =[]
framework.db.workspace.events.each do |e|
if not e.info.nil? and e.info.has_key?(:command) and e.info[:session_type] =~ /meter/
if e.info[:command] != "load stdapi"
if not sessions_uuids.include?(e.info[:session_uuid])
sessions_uuids << e.info[:session_uuid]
sessions_info << {:uuid => e.info[:session_uuid],
:type => e.info[:session_type],
:id => e.info[:session_id],
:info => e.info[:session_info]}
end
end
end
end
sessions_uuids.each do |su|
sessions_info.each do |i|
if su == i[:uuid]
print_line("Creating RC file for Session #{i[:id]}")
rc_file_name = "#{framework.db.workspace.name}_session_#{i[:id]}_#{::Time.now.strftime("%Y%m%d.%M%S")}.rc"
i.each do |k,v|
info << "#{k.to_s}: #{v.to_s} "
end
break
end
end
rc_file << "# Info: #{info}\n"
info = ""
framework.db.workspace.events.each do |e|
if not e.info.nil? and e.info.has_key?(:command) and e.info.has_key?(:session_uuid)
if e.info[:session_uuid] == su
rc_file << "# command executed at #{e.created_at}\n"
rc_file << "#{e.info[:command]}\n"
end
end
end
# Set RC file path and file name
consonle_rc_path = ::File.join(Msf::Config.log_directory,"projects",framework.db.workspace.name)
rc_full_path = ::File.join(consonle_rc_path,rc_file_name)
print_line("Saving RC file to #{rc_full_path}")
file_write(rc_full_path, rc_file)
rc_file = ""
print_line("RC file written")
rc_list << rc_full_path
end
return rc_list
end
# Method for exporting session history with output
#-------------------------------------------------------------------------------------------
def make_sessions_logs
sessions_uuids = []
sessions_info = []
info = ""
hist_file = ""
hist_file_name = ""
log_list = []
# Create list of sessions with base info
framework.db.workspace.events.each do |e|
if not e.info.nil? and e.info[:session_type] =~ /shell/ or e.info[:session_type] =~ /meter/
if e.info[:command] != "load stdapi"
if not sessions_uuids.include?(e.info[:session_uuid])
sessions_uuids << e.info[:session_uuid]
sessions_info << {:uuid => e.info[:session_uuid],
:type => e.info[:session_type],
:id => e.info[:session_id],
:info => e.info[:session_info]}
end
end
end
end
sessions_uuids.each do |su|
sessions_info.each do |i|
if su == i[:uuid]
print_line("Exporting Session #{i[:id]} history")
hist_file_name = "#{framework.db.workspace.name}_session_#{i[:id]}_#{::Time.now.strftime("%Y%m%d.%M%S")}.log"
i.each do |k,v|
info << "#{k.to_s}: #{v.to_s} "
end
break
end
end
hist_file << "# Info: #{info}\n"
info = ""
framework.db.workspace.events.each do |e|
if not e.info.nil? and e.info.has_key?(:command) or e.info.has_key?(:output)
if e.info[:session_uuid] == su
if e.info.has_key?(:command)
hist_file << "#{e.updated_at}\n"
hist_file << "#{e.info[:command]}\n"
elsif e.info.has_key?(:output)
hist_file << "#{e.updated_at}\n"
hist_file << "#{e.info[:output]}\n"
end
end
end
end
# Set RC file path and file name
session_hist_path = ::File.join(Msf::Config.log_directory,"projects",framework.db.workspace.name)
session_hist_fullpath = ::File.join(session_hist_path,hist_file_name)
# Create folder
::FileUtils.mkdir_p(session_hist_path)
print_line("Saving log file to #{session_hist_fullpath}")
file_write(session_hist_fullpath, hist_file)
hist_file = ""
print_line("Log file written")
log_list << session_hist_fullpath
end
return log_list
end
# Compress a given folder given it's path
#-------------------------------------------------------------------------------------------
def compress(path,archive)
require 'zip/zip'
require 'zip/zipfilesystem'
path.sub!(%r[/$],'')
::Zip::ZipFile.open(archive, 'w') do |zipfile|
Dir["#{path}/**/**"].reject{|f|f==archive}.each do |file|
print_line("Adding #{file} to archive")
zipfile.add(file.sub(path+'/',''),file)
end
end
print_line("All files saved to #{archive}")
end
# Method to write string to file
def file_write(file2wrt, data2wrt)
if not ::File.exists?(file2wrt)
::FileUtils.touch(file2wrt)
end
output = ::File.open(file2wrt, "a")
data2wrt.each_line do |d|
output.puts(d)
end
output.close
end