forked from danielbohannon/Invoke-DOSfuscation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Invoke-DOSfuscationMenu.psm1
2268 lines (1945 loc) · 112 KB
/
Invoke-DOSfuscationMenu.psm1
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
# This file is part of Invoke-DOSfuscation.
#
# Copyright 2018 Daniel Bohannon <@danielhbohannon>
# while at Mandiant <http://www.mandiant.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#########################################################################################################################################################################
## All functions in this module are solely for the menu-driven Invoke-DOSfuscation exploratory experience and do not provide any additional obfuscation functionality. ##
## This menu-driven experience is included to more easily enable Red and Blue Teamers to explore the DOSfuscation options in a quick and visual manner. ##
#########################################################################################################################################################################
function Invoke-DOSfuscation
{
<#
.SYNOPSIS
Master function that orchestrates the application of all obfuscation functions to provided Cmd or PowerShell command or command path/URL contents. Interactive mode enables one to explore all available obfuscation functions, while interacting with the functions directly (outside of this Invoke-DOSfuscation function) gives the user insanely more flexibility and tuning capabilities.
Invoke-DOSfuscation Function: Invoke-DOSfuscation
Author: Daniel Bohannon (@danielhbohannon)
License: Apache License, Version 2.0
Required Dependencies: Show-DosAsciiArt, Show-DosHelpMenu, Show-DosMenu, Show-DosOptionsMenu, Show-DosTutorial and Out-DosCommandContent (all located in Invoke-DOSfuscation.psm1)
Optional Dependencies: None
.DESCRIPTION
Master function that orchestrates the application of all obfuscation functions to provided Cmd or PowerShell command or command path/URL contents. Interactive mode enables one to explore all available obfuscation functions, while interacting with the functions directly (outside of this Invoke-DOSfuscation function) gives the user insanely more flexibility and tuning capabilities.
.PARAMETER Command
Specifies Cmd or PowerShell command.
.PARAMETER CommandPath
Specifies path to Cmd or PowerShell command (can be local file, UNC-path, or remote URI).
.PARAMETER CliCommand
Specifies obfuscation commands to run against the input Command or CommandPath parameter.
.PARAMETER FinalBinary
(Optional) Specifies the obfuscated command should be executed by a child process of powershell.exe, cmd.exe or no unnecessary child process (default). Some command escaping scenarios require at least one child process to avoid errors and will automatically be converted to such necessary syntax.
.PARAMETER NoExit
(Optional - only works if Command is specified) Specifices that the function does not exit after running obfuscation commands defined in CliCommand parameter.
.PARAMETER Quiet
(Optional) Specifices that the function output only the final obfuscated result via stdout, or at a minimum skips animated ASCII art introduction (but why would anybody want to do that?!?).
.EXAMPLE
C:\PS> Import-Module .\Invoke-DOSfuscation.psd1; Invoke-DOSfuscation
.EXAMPLE
C:\PS> Import-Module .\Invoke-DOSfuscation.psd1; Invoke-DOSfuscation -Command 'dir C:\Windows\System32\ | findstr calc\.exe'
.EXAMPLE
C:\PS> Import-Module .\Invoke-DOSfuscation.psd1; Invoke-DOSfuscation -Command 'dir C:\Windows\System32\ | findstr calc\.exe' -CliCommand 'ENCODING\*' -Quiet
dir C%SystemRoot:~1,-8%%TMP:~-11,-10%W%CommonProgramFiles(x86):~-23,1%ndows%TMP:~-5,-4%Sy%SystemRoot:~-1%t%TEMP:~-3,1%%APPDATA:~-4,1%32%ProgramFiles:~-14,-13%%CommonProgramFiles:~10,-18%| fin%SystemRoot:~6,1%str ca%CommonProgramW6432:~-3,1%%PUBLIC:~-1%\.e%ProgramFiles(x86):~18,-3%%ProgramFiles:~-2,-1%
.EXAMPLE
C:\PS> Import-Module .\Invoke-DOSfuscation.psd1; Invoke-DOSfuscation -CommandPath https://bit.ly/L3g1t -CliCommand 'PAYLOAD\*\1' -FinalBinary powershell -Quiet
cmd /V:ON/C"set 4Ih=neerG roloCdnuorgeroF- NOITACOL ETOMER MORF EDOC LLEHSREWOP DETUCEXE YLLUFSSECCUS tsoH-etirW&&for /L %c in (91,-1,0)do set MPJf=!MPJf!!4Ih:~%c,1!&&if %c==0 powershell.exe "!MPJf:~6!" "
.NOTES
Invoke-DOSfuscation orchestrates the application of all obfuscation functions to provided Cmd or PowerShell command or command path contents to evade basic command-line detections and static signatures. This framework was developed to enable defenders to automate the generation of randomly-obfuscated payloads to develop and tune new detection approaches for highly obfuscated cmd.exe commands.
This is a personal project developed by Daniel Bohannon while an employee at MANDIANT, A FireEye Company.
.LINK
http://www.danielbohannon.com
#>
[CmdletBinding(DefaultParameterSetName = 'Command')]
param (
[Parameter(Position = 0, Mandatory = $false, ValueFromPipeline = $true, ParameterSetName = 'Command')]
[ValidateNotNullOrEmpty()]
[System.String]
$Command,
[Parameter(Position = 0, Mandatory = $false, ParameterSetName = 'CommandPath')]
[ValidateNotNullOrEmpty()]
[System.String]
$CommandPath,
[Parameter(Position = 0, Mandatory = $false)]
[ValidateSet('cmd','powershell','none')]
[System.String]
$FinalBinary = 'none',
[Parameter(Position = 0, Mandatory = $false)]
[System.String]
$CliCommand,
[Parameter(Position = 0, Mandatory = $false)]
[Switch]
$NoExit,
[Parameter(Position = 0, Mandatory = $false)]
[Switch]
$Quiet
)
# Define variables for CLI functionality.
$script:cliCommands = @()
$script:compoundCommand = @()
$script:quietWasSpecified = $false
$cliWasSpecified = $false
$noExitWasSpecified = $false
# Either convert Command to a string or convert script at $Path to a string.
if ($PSBoundParameters['Command'])
{
$script:cliCommands += ('set command ' + $Command)
}
if ($PSBoundParameters['CommandPath'])
{
$script:cliCommands += ('set commandpath ' + $CommandPath)
}
# Add set FinalBinary command if -FinalBinary argument is specified.
if ($PSBoundParameters['FinalBinary'])
{
$script:cliCommands += ('set finalbinary ' + $FinalBinary)
}
elseif ($FinalBinary -eq 'none')
{
$script:FinalBinary = ''
}
if ($PSBoundParameters['Quiet'])
{
$script:quietWasSpecified = $true
}
# Append Command to cliCommands if specified by user input.
if ($PSBoundParameters['CliCommand'])
{
$script:cliCommands += $CliCommand.Split(',')
$cliWasSpecified = $true
if ($PSBoundParameters['NoExit'])
{
$noExitWasSpecified = $true
}
if ($PSBoundParameters['Quiet'])
{
# Create empty Write-Host and Start-Sleep proxy functions to cause any Write-Host or Start-Sleep invocations to not do anything until non-interactive -Command values are finished being processed.
function Write-Host { [CmdletBinding(SupportsShouldProcess = $true)] param($Object, [Switch] $NoNewline, $Separator, $ForegroundColor, $BackgroundColor) if ($PSCmdlet.ShouldProcess("Temporarily overriding of Write-Host cmdlet successful")) {} }
function Start-Sleep { [CmdletBinding(SupportsShouldProcess = $true)] param($Seconds, $Milliseconds) if ($PSCmdlet.ShouldProcess("Temporarily overriding of Start-Sleep cmdlet successful")) {} }
$script:quietWasSpecified = $true
}
}
########################################
## Script-wide variable instantiation ##
########################################
# Script-level array of Show Options menu, set as SCRIPT-level so it can be set from within any of the functions.
# Build out menu for Show Options selection from user in Show-DosOptionsMenu menu.
$script:CommandPath = ''
$script:Command = ''
$script:cliSyntax = @()
$script:executionCommands = @()
$script:obfuscatedCommand = ''
$script:obfuscatedCommandHistory = @()
$script:obfuscationLength = ''
$script:optionsMenu = @()
$script:optionsMenu += , @('Command' , $script:Command , $true)
$script:optionsMenu += , @('CommandPath' , $script:CommandPath , $true)
$script:optionsMenu += , @('FinalBinary' , $script:CommandPath , $true)
$script:optionsMenu += , @('CommandLineSyntax' , $script:cliSyntax , $false)
$script:optionsMenu += , @('ExecutionCommands' , $script:executionCommands , $false)
$script:optionsMenu += , @('ObfuscatedCommand' , $script:obfuscatedCommand , $false)
$script:optionsMenu += , @('ObfuscationLength' , $script:obfuscatedCommand , $false)
# Build out $settableInputOptions from above items set as $true (as settable).
$settableInputOptions = @()
foreach ($option in $script:optionsMenu)
{
if ($option[2])
{
$settableInputOptions += ([System.String] $option[0]).ToLower().Trim()
}
}
# Ensure Invoke-DOSfuscation module was properly imported before continuing.
if (-not (Get-Module Invoke-DOSfuscation | where-object {$_.ModuleType -eq 'Script'}))
{
$pathToPsd1 = "$scriptDir\Invoke-DOSfuscation.psd1"
if ($pathToPsd1.Contains(' '))
{
$pathToPsd1 = '"' + $pathToPsd1 + '"'
}
Write-Host "`n`nERROR: Invoke-DOSfuscation module is not loaded. You must run:" -ForegroundColor Red
Write-Host " Import-Module $pathToPsd1`n`n" -ForegroundColor Yellow
Start-Sleep -Seconds 1
exit
}
# Build interactive menus.
$lineSpacing = '[*] '
# Main Menu.
$menuLevel = @()
$menuLevel += , @($lineSpacing , 'BINARY ' , 'Obfuscated <binary> syntax for cmd.exe & powershell.exe')
$menuLevel += , @($lineSpacing , 'ENCODING' , 'Environment variable <encoding>')
$menuLevel += , @($lineSpacing , 'PAYLOAD ' , 'Obfuscated <payload> via DOSfuscation')
# Main\Binary Menu.
$menuLevel_Binary = @()
$menuLevel_Binary += , @($lineSpacing , 'CMD' , "`tObfuscated syntax for <cmd.exe>")
$menuLevel_Binary += , @($lineSpacing , 'PS' , "`tObfuscated syntax for <powershell.exe> (if applicable)")
$menuLevel_Binary_Cmd = @()
$menuLevel_Binary_Cmd += , @($lineSpacing , '1' , 'Env var encoding' , @('Get-ObfuscatedCmd' , , 1))
$menuLevel_Binary_Cmd += , @($lineSpacing , '2' , 'FOR loop + sub-command' , @('Get-ObfuscatedCmd' , , 2))
$menuLevel_Binary_Cmd += , @($lineSpacing , '3' , 'FOR loop + sub-command + obfuscation' , @('Get-ObfuscatedCmd' , , 3))
$menuLevel_Binary_PS = @()
$menuLevel_Binary_PS += , @($lineSpacing , '1' , "`tEnv var encoding" , @('Get-ObfuscatedPowerShell' , , 1))
$menuLevel_Binary_PS += , @($lineSpacing , '2' , "`tFOR loop + sub-command" , @('Get-ObfuscatedPowerShell' , , 2))
$menuLevel_Binary_PS += , @($lineSpacing , '3' , "`tFOR loop + sub-command + obfuscation" , @('Get-ObfuscatedPowerShell' , , 3))
# Main\Encoding Menu.
$menuLevel_Encoding = @()
$menuLevel_Encoding += , @($lineSpacing , '1' , "`t<Basic> env var encoding" , @('Out-EnvVarEncodedCommand' , , 1))
$menuLevel_Encoding += , @($lineSpacing , '2' , "`t<Medium> env var encoding" , @('Out-EnvVarEncodedCommand' , , 2))
$menuLevel_Encoding += , @($lineSpacing , '3' , "`t<Intense> env var encoding" , @('Out-EnvVarEncodedCommand' , , 3))
# Main\Payload Menu.
$menuLevel_Payload = @()
$menuLevel_Payload += , @($lineSpacing , 'CONCAT ' , '<Concat>enation obfuscation')
$menuLevel_Payload += , @($lineSpacing , 'REVERSE ' , '<Reverse> command FOR-loop obfuscation')
$menuLevel_Payload += , @($lineSpacing , 'FORCODE ' , '<FOR>-loop encoding obfuscation')
$menuLevel_Payload += , @($lineSpacing , 'FINCODE ' , '<FIN>-style string replacement obfuscation')
$menuLevel_Payload_Concat = @()
$menuLevel_Payload_Concat += , @($lineSpacing , '1' , '<Basic> obfuscation' , @('Out-DosConcatenatedCommand' , , 1))
$menuLevel_Payload_Concat += , @($lineSpacing , '2' , '<Medium> obfuscation' , @('Out-DosConcatenatedCommand' , , 2))
$menuLevel_Payload_Concat += , @($lineSpacing , '3' , '<Intense> obfuscation' , @('Out-DosConcatenatedCommand' , , 3))
$menuLevel_Payload_Reverse = @()
$menuLevel_Payload_Reverse += , @($lineSpacing , '1' , '<Basic> obfuscation' , @('Out-DosReversedCommand' , , 1))
$menuLevel_Payload_Reverse += , @($lineSpacing , '2' , '<Medium> obfuscation' , @('Out-DosReversedCommand' , , 2))
$menuLevel_Payload_Reverse += , @($lineSpacing , '3' , '<Intense> obfuscation' , @('Out-DosReversedCommand' , , 3))
$menuLevel_Payload_FORcode = @()
$menuLevel_Payload_FORcode += , @($lineSpacing , '1' , '<Basic> obfuscation' , @('Out-DosFORcodedCommand' , , 1))
$menuLevel_Payload_FORcode += , @($lineSpacing , '2' , '<Medium> obfuscation' , @('Out-DosFORcodedCommand' , , 2))
$menuLevel_Payload_FORcode += , @($lineSpacing , '3' , '<Intense> obfuscation' , @('Out-DosFORcodedCommand' , , 3))
$menuLevel_Payload_FINcode = @()
$menuLevel_Payload_FINcode += , @($lineSpacing , '1' , '<Basic> obfuscation' , @('Out-DosFINcodedCommand' , , 1))
$menuLevel_Payload_FINcode += , @($lineSpacing , '2' , '<Medium> obfuscation' , @('Out-DosFINcodedCommand' , , 2))
$menuLevel_Payload_FINcode += , @($lineSpacing , '3' , '<Intense> obfuscation' , @('Out-DosFINcodedCommand' , , 3))
# Input options to display non-interactive menus or perform actions.
$tutorialInputOptions = @(@('tutorial') , "<Tutorial> of how to use this tool `t " )
$menuInputOptionsShowHelp = @(@('help','get-help','?','-?','/?','menu') , "Show this <Help> Menu `t " )
$menuInputOptionsShowOptions = @(@('show options','show','options') , "<Show options> for payload to obfuscate `t " )
$clearScreenInputOptions = @(@('clear','clear-host','cls') , "<Clear> screen `t " )
$copyToClipboardInputOptions = @(@('copy','clip','clipboard') , "<Copy> ObfuscatedCommand to clipboard `t " )
$outputToDiskInputOptions = @(@('out') , "Write ObfuscatedCommand <Out> to disk `t " )
$executionInputOptions = @(@('exec','execute','test','run') , "<Execute> ObfuscatedCommand locally `t " )
$resetObfuscationInputOptions = @(@('reset') , "<Reset> ALL obfuscation for ObfuscatedCommand ")
$undoObfuscationInputOptions = @(@('undo') , "<Undo> LAST obfuscation for ObfuscatedCommand ")
$backCommandInputOptions = @(@('back','cd ..') , "Go <Back> to previous obfuscation menu `t " )
$exitCommandInputOptions = @(@('quit','exit') , "<Quit> Invoke-DOSfuscation `t " )
$homeMenuInputOptions = @(@('home','main') , "return to <Home> Menu `t " )
# For Version 1.0 ASCII art is not necessary.
#$showAsciiArtInputOptions = @(@('ascii') , "Display random <ASCII> art for the lulz :)`t")
# Add all above input options lists to be displayed in SHOW OPTIONS menu.
$allAvailableInputOptionsLists = @()
$allAvailableInputOptionsLists += , $tutorialInputOptions
$allAvailableInputOptionsLists += , $menuInputOptionsShowHelp
$allAvailableInputOptionsLists += , $menuInputOptionsShowOptions
$allAvailableInputOptionsLists += , $clearScreenInputOptions
$allAvailableInputOptionsLists += , $executionInputOptions
$allAvailableInputOptionsLists += , $copyToClipboardInputOptions
$allAvailableInputOptionsLists += , $outputToDiskInputOptions
$allAvailableInputOptionsLists += , $resetObfuscationInputOptions
$allAvailableInputOptionsLists += , $undoObfuscationInputOptions
$allAvailableInputOptionsLists += , $backCommandInputOptions
$allAvailableInputOptionsLists += , $exitCommandInputOptions
$allAvailableInputOptionsLists += , $homeMenuInputOptions
# For Version 1.0 ASCII art is not necessary.
#$allAvailableInputOptionsLists += , $showAsciiArtInputOptions
# Input options to change interactive menus.
$exitInputOptions = $exitCommandInputOptions[0]
$menuInputOptions = $backCommandInputOptions[0]
# Obligatory ASCII Art.
Show-DosAsciiArt -Quiet:$script:quietWasSpecified
Start-Sleep -Seconds 2
# Show Help Menu once at beginning of script.
Show-DosHelpMenu
# Main loop for user interaction. Show-DosMenu function displays current function along with acceptable input options (defined in arrays instantiated above).
# User input and validation is handled within Show-DosMenu.
$userResponse = ''
while ($exitInputOptions -notcontains ([System.String] $userResponse).ToLower())
{
$userResponse = ([System.String] $userResponse).Trim()
if ($homeMenuInputOptions[0] -contains ([System.String] $userResponse).ToLower())
{
$userResponse = ''
}
# Display menu if it is defined in a menu variable with $userResponse in the variable name.
if (Test-Path ('Variable:' + "MenuLevel$userResponse"))
{
$userResponse = Show-DosMenu -Menu (Get-Variable "MenuLevel$userResponse").Value -MenuName $userResponse
}
else
{
Write-Error "The variable MenuLevel$userResponse does not exist."
$userResponse = 'quit'
}
if (($userResponse -eq 'quit') -and $cliWasSpecified -and -not $noExitWasSpecified)
{
Write-Output $script:obfuscatedCommand.Trim("`n")
$userResponse = 'quit'
}
}
$menuInputOptions = $null
}
# Get location of this script no matter what the current directory is for the process executing this script.
$scriptDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
function Show-DosMenu
{
<#
.SYNOPSIS
HELPER function :: Displays current menu with obfuscation navigation and application options for Invoke-DOSfuscation.
Invoke-DOSfuscation Function: Show-DosMenu
Author: Daniel Bohannon (@danielhbohannon)
License: Apache License, Version 2.0
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Show-DosMenu displays current menu with obfuscation navigation and application options for Invoke-DOSfuscation.
.PARAMETER Menu
Specifies the menu options to display, with acceptable input options parsed out of this array.
.PARAMETER MenuName
Specifies the menu header display and the breadcrumb used in the interactive prompt display.
.NOTES
This is a personal project developed by Daniel Bohannon while an employee at MANDIANT, A FireEye Company.
.LINK
http://www.danielbohannon.com
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[System.Object[]]
$Menu,
[Parameter(Position = 0, Mandatory = $false)]
[System.String]
$MenuName
)
# Extract all acceptable values from $Menu.
$acceptableInput = @()
$selectionContainsCommand = $false
foreach ($line in $Menu)
{
# If there are 4 items in each $line in $Menu then the fourth item is a command to exec if selected.
if ($line.Count -eq 4)
{
$selectionContainsCommand = $true
}
$acceptableInput += ($line[1]).Trim(' ')
}
$userInput = $null
while ($acceptableInput -notcontains $userInput)
{
# Format custom breadcrumb prompt.
Write-Host "`n"
$breadCrumb = $MenuName.Trim('_')
if ($breadCrumb.Length -gt 1)
{
if ($breadCrumb.ToLower() -eq 'show options')
{
$breadCrumb = 'Show Options'
}
if ($MenuName -ne '')
{
# Handle specific case substitutions from what is ALL CAPS in interactive menu and then correct casing we want to appear in the Breadcrumb.
$breadCrumbOCD = @()
$breadCrumbOCD += , @('ps' ,'PS')
$breadCrumbOCD += , @('forcode' ,'FORcode')
$breadCrumbOCD += , @('fincode' ,'FINcode')
$breadCrumbArray = @()
foreach ($crumb in $breadCrumb.Split('_'))
{
# Perform casing substitutions for any matches in $breadCrumbOCD array.
$stillLookingForSubstitution = $true
foreach ($substitution in $breadCrumbOCD)
{
if ($crumb.ToLower() -eq $substitution[0])
{
$breadCrumbArray += $substitution[1]
$stillLookingForSubstitution = $false
}
}
# If no substitution occurred above then simply upper-case the first character and lower-case all the remaining characters.
if ($stillLookingForSubstitution)
{
$breadCrumbArray += $crumb.Substring(0,1).ToUpper() + $crumb.Substring(1).ToLower()
}
}
$breadCrumb = $breadCrumbArray -Join '\'
}
$breadCrumb = '\' + $breadCrumb
}
# Output menu heading.
$firstLine = "Choose one of the below "
if ($breadCrumb -ne '')
{
$firstLine = $firstLine + $breadCrumb.Trim('\') + ' '
}
Write-Host "$firstLine" -NoNewline
# Change color and verbiage if selection will execute command.
if ($selectionContainsCommand)
{
Write-Host "options" -NoNewline -ForegroundColor Green
Write-Host " to" -NoNewline
Write-Host " APPLY" -NoNewline -ForegroundColor Green
Write-Host " to current payload" -NoNewline
}
else
{
Write-Host "options" -NoNewline -ForegroundColor Yellow
}
Write-Host ":`n"
foreach ($line in $Menu)
{
$lineSpace = $line[0]
$lineOption = $line[1]
$lineValue = $line[2]
Write-Host $lineSpace -NoNewline
# If not empty then include breadcrumb in $lineOption output (is not colored and won't affect user input syntax).
if (($breadCrumb -ne '') -and ($lineSpace.StartsWith('[')))
{
Write-Host ($breadCrumb.ToUpper().Trim('\') + '\') -NoNewline
}
# Change color if selection will execute command.
if ($selectionContainsCommand)
{
Write-Host $lineOption -NoNewline -ForegroundColor Green
}
else
{
Write-Host $lineOption -NoNewline -ForegroundColor Yellow
}
# Add additional coloring to string encapsulated by <> if it exists in $lineValue.
if ($lineValue.Contains('<') -and $lineValue.Contains('>'))
{
$firstPart = $lineValue.Substring(0,$lineValue.IndexOf('<'))
$middlePart = $lineValue.Substring($firstPart.Length + 1)
$middlePart = $middlePart.Substring(0,$middlePart.IndexOf('>'))
$lastPart = $lineValue.Substring($firstPart.Length+$middlePart.Length + 2)
Write-Host "`t$firstPart" -NoNewline
Write-Host $middlePart -NoNewline -ForegroundColor Cyan
# Handle if more than one term needs to be output in different color.
if ($lastPart.Contains('<') -and $lastPart.Contains('>'))
{
$lineValue = $lastPart
$firstPart = $lineValue.Substring(0,$lineValue.IndexOf('<'))
$middlePart = $lineValue.Substring($firstPart.Length + 1)
$middlePart = $middlePart.Substring(0,$middlePart.IndexOf('>'))
$lastPart = $lineValue.Substring($firstPart.Length+$middlePart.Length + 2)
Write-Host $firstPart -NoNewline
Write-Host $middlePart -NoNewline -ForegroundColor Cyan
}
Write-Host $lastPart
}
else
{
Write-Host "`t$lineValue"
}
}
# Prompt for user input with custom breadcrumb prompt.
Write-Host ''
if ($userInput -ne '')
{
Write-Host ''
}
$userInput = ''
while (($userInput -eq '') -and ($script:compoundCommand.Count -eq 0))
{
# Output custom prompt.
Write-Host "Invoke-DOSfuscation$breadCrumb> " -NoNewline -ForegroundColor Magenta
# Get interactive user input if cliCommands input variable was not specified by user.
if ($script:cliCommands -or ($script:cliCommands.Count -gt 0))
{
if ($script:cliCommands.GetType().Name -eq 'String')
{
$nextCliCommand = $script:cliCommands.Trim()
$script:cliCommands = @()
}
else
{
$nextCliCommand = ([System.String] $script:cliCommands[0]).Trim()
$script:cliCommands = for ($i=1; $i -lt $script:cliCommands.Count; $i++) { $script:cliCommands[$i] }
}
$userInput = $nextCliCommand
}
else
{
# If Command was defined on command line and -NoExit switch was not defined then output final ObfuscatedCommand to stdout and then quit. Otherwise continue with interactive Invoke-DOSfuscation.
if ($cliWasSpecified -and ($script:cliCommands.Count -lt 1) -and ($script:compoundCommand.Count -lt 1) -and ($script:quietWasSpecified -or -not $noExitWasSpecified))
{
if ($script:quietWasSpecified)
{
# Remove Write-Host and Start-Sleep proxy functions so that Write-Host and Start-Sleep cmdlets will be called during the remainder of the interactive Invoke-DOSfuscation session.
Remove-Item -Path Function:Write-Host
Remove-Item -Path Function:Start-Sleep
$script:quietWasSpecified = $false
# Automatically run 'Show Options' so the user has context of what has successfully been executed.
$userInput = 'show options'
$breadCrumb = 'Show Options'
}
# -NoExit was not specified and -Command was, so we will output the result back in the main While loop.
if (-not $noExitWasSpecified)
{
$userInput = 'quit'
}
}
else
{
$userInput = (Read-Host).Trim()
}
# Process interactive UserInput using CLI syntax, so comma-delimited and slash-delimited commands can be processed interactively.
if (($script:cliCommands.Count -eq 0) -and -not $userInput.ToLower().StartsWith('set ') -and $userInput.Contains(','))
{
$script:cliCommands = $userInput.Split(',')
# Reset $userInput so current While loop will be traversed once more and process UserInput command as a CliCommand.
$userInput = ''
}
}
}
# Trim any leading trailing slashes so it doesn't misinterpret it as a compound command unnecessarily.
$userInput = $userInput.Trim('/\')
# If input is for home menu option and not in home menu then prepend 'Home\' to
$homeMenuOptions = $menuLevel | foreach-object { ($_[1]).ToLower().Trim() }
if (($homeMenuOptions -contains $userInput.Split('/\')[0]) -and ($breadCrumb -ne ''))
{
$userInput = 'Home\' + $userInput
}
# If current command contains \ or / and does not start with SET or OUT then we are dealing with a compound command.
# Setting $script:CompounCommand in below IF block.
if (($script:compoundCommand.Count -eq 0) -and -not $userInput.ToLower().StartsWith('set ') -and -not $userInput.ToLower().StartsWith('out ') -and ($userInput.Contains('\') -or $userInput.Contains('/')))
{
$script:compoundCommand = $userInput.Split('/\')
}
# If current command contains \ or / and does not start with SET then we are dealing with a compound command.
# Parsing out next command from $script:compoundCommand in below IF block.
if ($script:compoundCommand.Count -gt 0)
{
$userInput = ''
while (($userInput -eq '') -and ($script:compoundCommand.Count -gt 0))
{
# If last compound command then it will be a String.
if ($script:compoundCommand.GetType().Name -eq 'String')
{
$nextcompoundCommand = $script:compoundCommand.Trim()
$script:compoundCommand = @()
}
else
{
# If there are more commands left in compound command then it won't be a String (above IF block).
# In this else block we get the next command from compoundCommand array.
$nextcompoundCommand = ([System.String] $script:compoundCommand[0]).Trim()
# Set remaining commands back into compoundCommand.
$compoundCommandTemp = $script:compoundCommand
$script:compoundCommand = @()
for ($i=1; $i -lt $compoundCommandTemp.Count; $i++)
{
$script:compoundCommand += $compoundCommandTemp[$i]
}
}
$userInput = $nextcompoundCommand
}
}
# Handle new RegEx functionality.
# Identify if there is any regex in current UserInput by removing all alphanumeric characters.
$tempUserInput = $userInput.ToLower() -replace '[a-z0-9\s\-\?\/\\]',''
if (($tempUserInput.Length -gt 0) -and -not ($userInput.Trim().ToLower().StartsWith('set ')) -and -not ($userInput.Trim().ToLower().StartsWith('out ')))
{
# Replace any simple wildcard with .* syntax.
$userInput = $userInput.Replace('.*','_____').Replace('*','.*').Replace('_____','.*')
# Prepend UserInput with ^ and append with $ if not already there.
if (-not $userInput.Trim().StartsWith('^') -and -not $userInput.Trim().StartsWith('.*'))
{
$userInput = '^' + $userInput
}
if (-not $userInput.Trim().EndsWith('$') -and -not $userInput.Trim().EndsWith('.*'))
{
$userInput = $userInput + '$'
}
# See if there are any filtered matches in the current menu.
try
{
$menuFiltered = ($Menu | where-object {($_[1].Trim() -match $userInput) -and ($_[1].Trim().Length -gt 0)} | foreach-object {$_[1].Trim()})
}
catch
{
# Output error message if Regular Expression causes error in above filtering step.
# E.g. Using *+ instead of *[+]
Write-Host "`n`nERROR:" -NoNewline -ForegroundColor Red
Write-Host ' The current Regular Expression caused the following error:'
write-host " $_" -ForegroundColor Red
}
# If there are filtered matches in the current menu then randomly choose one for the UserInput value.
if ($menuFiltered)
{
# Randomly select UserInput from filtered options.
$userInput = (Get-Random -Input $menuFiltered).Trim()
# Output randomly chosen option (and filtered options selected from) if more than one option were returned from regex.
if ($menuFiltered.Count -gt 1)
{
# Change color and verbiage if acceptable options will execute an obfuscation function.
if ($selectionContainsCommand)
{
$colorToOutput = 'Green'
}
else
{
$colorToOutput = 'Yellow'
}
Write-Host "`n`nRandomly selected " -NoNewline
Write-Host $userInput -NoNewline -ForegroundColor $colorToOutput
write-host " from the following filtered options: " -NoNewline
for ($i=0; $i -lt $menuFiltered.Count-1; $i++)
{
Write-Host $menuFiltered[$i].Trim() -NoNewline -ForegroundColor $colorToOutput
Write-Host ', ' -NoNewline
}
Write-Host $menuFiltered[$menuFiltered.Count-1].Trim() -NoNewline -ForegroundColor $colorToOutput
}
}
}
if ($exitInputOptions -contains $userInput.ToLower())
{
return $exitInputOptions[0]
}
elseif (($menuInputOptions -contains $userInput.ToLower()) -or ($menuInputOptions -contains $userInput.ToLower().Trim('^$')))
{
# Commands like 'back' that will return user to previous interactive menu.
if ($breadCrumb.Contains('\'))
{
$userInput = $breadCrumb.Substring(0,$breadCrumb.LastIndexOf('\')).Replace('\','_')
}
else
{
$userInput = ''
}
return $userInput.ToLower()
}
elseif ($homeMenuInputOptions[0] -contains $userInput.ToLower())
{
return $userInput.ToLower()
}
elseif ($userInput.ToLower().StartsWith('set '))
{
# Extract $userInputOptionName and $userInputOptionValue from $userInput SET command.
$userInputOptionName = $null
$userInputOptionValue = $null
$hasError = $false
$userInputMinusSet = $userInput.Substring(4).Trim()
if ($userInputMinusSet.IndexOf(' ') -eq -1)
{
$hasError = $true
$userInputOptionName = $userInputMinusSet.Trim()
}
else
{
$userInputOptionName = $userInputMinusSet.Substring(0,$userInputMinusSet.IndexOf(' ')).Trim().ToLower()
$userInputOptionValue = $userInputMinusSet.Substring($userInputMinusSet.IndexOf(' ')).Trim()
}
# Validate that $userInputOptionName is defined in $settableInputOptions.
if ($settableInputOptions -contains $userInputOptionName)
{
# Perform separate validation for $userInputOptionValue before setting value. Set to 'emptyvalue' if no value was entered.
if ($userInputOptionValue.Length -eq 0)
{
$userInputOptionName = 'emptyvalue'
}
switch ($userInputOptionName.ToLower())
{
'commandpath' {
if ($userInputOptionValue -and ((Test-Path $userInputOptionValue) -or ($userInputOptionValue -match '(http|https)://')))
{
# Reset Command in case it contained a value.
$script:Command = ''
# Check if user-input CommandPath is a URL or a directory.
if ($userInputOptionValue -match '(http|https)://')
{
# CommandPath is a URL.
# Download content.
$script:Command = (New-Object Net.WebClient).DownloadString($userInputOptionValue)
# Set script-wide variables for future reference.
$script:CommandPath = $userInputOptionValue
$script:obfuscatedCommand = $script:Command
$script:obfuscatedCommandHistory = @()
$script:obfuscatedCommandHistory += $script:Command
$script:cliSyntax = @()
$script:executionCommands = @()
Write-Host "`n`nSuccessfully set CommandPath (as URL):" -ForegroundColor Cyan
Write-Host $script:CommandPath -ForegroundColor Magenta
}
elseif ((Get-Item $userInputOptionValue) -is [System.IO.DirectoryInfo])
{
# CommandPath does not exist.
Write-Host "`n`nERROR:" -NoNewline -ForegroundColor Red
Write-Host ' Path is a directory instead of a file (' -NoNewline
Write-Host "$userInputOptionValue" -NoNewline -ForegroundColor Cyan
Write-Host ").`n" -NoNewline
}
else
{
# Read contents from user-input CommandPath value.
Get-ChildItem $userInputOptionValue -ErrorAction Stop | Out-Null
$script:Command = [IO.File]::ReadAllText((Resolve-Path $userInputOptionValue))
# Set script-wide variables for future reference.
$script:CommandPath = $userInputOptionValue
$script:obfuscatedCommand = $script:Command
$script:obfuscatedCommandHistory = @()
$script:obfuscatedCommandHistory += $script:Command
$script:cliSyntax = @()
$script:executionCommands = @()
Write-Host "`n`nSuccessfully set CommandPath:" -ForegroundColor Cyan
Write-Host $script:CommandPath -ForegroundColor Magenta
}
}
else
{
# CommandPath not found (failed Test-Path).
Write-Host "`n`nERROR:" -NoNewline -ForegroundColor Red
Write-Host ' Path not found (' -NoNewline
Write-Host "$userInputOptionValue" -NoNewline -ForegroundColor Cyan
Write-Host ").`n" -NoNewline
}
}
'command' {
# Remove evenly paired {} '' or "" if user includes it around their command input.
foreach ($char in @(@('{','}'),@('"','"'),@("'","'")))
{
while ($userInputOptionValue.StartsWith($char[0]) -and $userInputOptionValue.EndsWith($char[1]))
{
$userInputOptionValue = $userInputOptionValue.Substring(1,$userInputOptionValue.Length - 2).Trim()
}
}
# Check if input is PowerShell encoded command syntax so we can decode for Command.
if ($userInputOptionValue -match 'powershell(.exe | )\s*-(e |ec |en |enc |enco |encod |encode |encoded |encodedc |encodedco |encodedcom |encodedcomm |encodedcomma |encodedcomman |encodedcommand)\s*["'']*[a-z+=/\\]')
{
# Extract encoded command.
$encodedCommand = $userInputOptionValue.Substring($userInputOptionValue.ToLower().IndexOf(' -e') + 3)
$encodedCommand = $encodedCommand.Substring($encodedCommand.IndexOf(' ')).Trim(" '`"")
# Decode Unicode-encoded $encodedCommand
$userInputOptionValue = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encodedCommand))
}
# Set script-wide variables for future reference.
$script:CommandPath = 'N/A'
$script:Command = $userInputOptionValue
$script:obfuscatedCommand = $userInputOptionValue
$script:obfuscatedCommandHistory = @()
$script:obfuscatedCommandHistory += $userInputOptionValue
$script:cliSyntax = @()
$script:executionCommands = @()
Write-Host "`n`nSuccessfully set Command:" -ForegroundColor Cyan
Write-Host $script:Command -ForegroundColor Magenta
}
'finalbinary' {
# Store the "base" breadcrumb values for all previous Payload commands in an array for easier warning message for FinalBinary values being set.
$warningMessage = ''
$prevPayloadCommandsBaseArray = @()
if ($script:cliSyntax)
{
$prevPayloadCommandsBaseArray += ($script:cliSyntax | foreach-object { $_.Split('\')[0] }) | where-object { $_ -match '^Payload$' }
}
if ($prevPayloadCommandsBaseArray.Count -eq 1)
{
$warningMessage = ' (though previous Payload obfuscation needs to be re-run)'
}
elseif ($prevPayloadCommandsBaseArray.Count -gt 1)
{
$warningMessage = ' (though previous Payload obfuscations need to be re-run)'
}
# Validate acceptable value entered for SET FINALBINARY command.
switch ($userInputOptionValue)
{
'cmd' {
$script:FinalBinary = 'Cmd'
Write-Host "`n`nSuccessfully set FinalBinary" -NoNewline -ForegroundColor Cyan
Write-Host $warningMessage -NoNewline -ForegroundColor Yellow
Write-Host ":" -ForegroundColor Cyan
Write-Host $script:FinalBinary -ForegroundColor Magenta
}
'powershell' {
$script:FinalBinary = 'PowerShell'
# Store the "base" breadcrumb values for all previous Encoding commands in an array for easier warning message for when FinalBinary "powershell" value is set.
$prevEncodingCommandsBaseArray = ($script:cliSyntax | foreach-object { $_.Split('\')[0] }) | where-object { $_ -match '^Encoding$' }
if ($prevEncodingCommandsBaseArray)
{
if (-not $warningMessage)
{
if ($prevEncodingCommandsBaseArray.Count -eq 1)
{
$warningMessage = ' (though Encoding obfuscation layer needs to be removed since PowerShell cannot interpret cmd.exe-style env var resolutions)'
}
else
{
$warningMessage = ' (though Encoding obfuscation layers need to be removed since PowerShell cannot interpret cmd.exe-style env var resolutions)'
}
}
else
{
if ($prevEncodingCommandsBaseArray.Count -eq 1)
{
$warningMessage = $warningMessage.TrimEnd(')') + ' and Encoding obfuscation layer needs to be removed since PowerShell cannot interpret cmd.exe-style env var resolutions)'
}
else
{
$warningMessage = $warningMessage.TrimEnd(')') + ' and Encoding obfuscation layers need to be removed since PowerShell cannot interpret cmd.exe-style env var resolutions)'
}
}
}
Write-Host "`n`nSuccessfully set FinalBinary" -NoNewline -ForegroundColor Cyan
Write-Host $warningMessage -NoNewline -ForegroundColor Yellow
Write-Host ":" -ForegroundColor Cyan
Write-Host $script:FinalBinary -ForegroundColor Magenta
}
'none' {
$script:FinalBinary = ''
Write-Host "`n`nSuccessfully removed FinalBinary value" -NoNewline -ForegroundColor Cyan
Write-Host $warningMessage -NoNewline -ForegroundColor Yellow
Write-Host ":" -ForegroundColor Cyan
}
default {
Write-Host "`n`nERROR:" -NoNewline -ForegroundColor Red
Write-Host ' Invalid option entered for' -NoNewline
Write-Host ' FINALBINARY' -NoNewline -ForegroundColor Cyan
Write-Host ". `n Valid options include " -NoNewline
Write-Host 'CMD' -NoNewline -ForegroundColor Green
Write-Host ', ' -NoNewline
Write-Host 'POWERSHELL ' -NoNewline -ForegroundColor Green
Write-Host '& ' -NoNewline
Write-Host 'NONE' -NoNewline -ForegroundColor Green
Write-Host '.' -NoNewline
}
}
}
'emptyvalue' {
# No OPTIONVALUE was entered after OPTIONNAME.
$hasError = $true
Write-Host "`n`nERROR:" -NoNewline -ForegroundColor Red
Write-Host ' No value was entered after' -NoNewline
Write-Host ' COMMAND/COMMANDPATH' -NoNewline -ForegroundColor Cyan
Write-Host '.' -NoNewline
}
default
{
Write-Error "An invalid OPTIONNAME ($userInputOptionName) was passed to switch block."
exit
}
}
}
else
{
$hasError = $true
Write-Host "`n`nERROR:" -NoNewline -ForegroundColor Red
Write-Host ' OPTIONNAME' -NoNewline
Write-Host " $userInputOptionName" -NoNewline -ForegroundColor Cyan
Write-Host " is not a settable option." -NoNewline
}
if ($hasError)
{
Write-Host "`n Correct syntax is" -NoNewline
Write-Host ' SET OPTIONNAME VALUE' -NoNewline -ForegroundColor Green
Write-Host '.' -NoNewline
Write-Host "`n Enter" -NoNewline
Write-Host ' SHOW OPTIONS' -NoNewline -ForegroundColor Yellow
Write-Host ' for more details.'
}
}
elseif (($acceptableInput -contains $userInput) -or ($overrideAcceptableInput))
{
# User input matches $acceptableInput extracted from the current $Menu, so decide if:
# 1) an obfuscation function needs to be called and remain in current interactive prompt, or
# 2) return value to enter into a new interactive prompt.