forked from danielbohannon/Invoke-Obfuscation
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Out-PowerShellLauncher.ps1
1627 lines (1323 loc) · 191 KB
/
Out-PowerShellLauncher.ps1
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-Obfuscation.
#
# Copyright 2017 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.
Function Out-PowerShellLauncher
{
<#
.SYNOPSIS
Applies launch syntax to PowerShell command so it can be run from cmd.exe and have its command line arguments further obfuscated via launch obfuscation techniques.
Invoke-Obfuscation Function: Out-PowerShellLauncher
Author: Daniel Bohannon (@danielhbohannon)
License: Apache License, Version 2.0
Required Dependencies: Out-ObfuscatedTokenCommand, Out-EncapsulatedInvokeExpression (used for WMIC launcher -- located in Out-ObfuscatedStringCommand.ps1), Out-ConcatenatedString (used for WMIC and MSHTA launchers -- located in Out-ObfuscatedTokenCommand.ps1)
Optional Dependencies: None
.DESCRIPTION
Out-PowerShellLauncher obfuscates a given PowerShell command (via stdin, process-level environment variables, clipboard, etc.) while wrapping it in syntax to be launched directly from cmd.exe. Some techniques also push command line arguments to powershell.exe's parent (denoted with +) or even grandparent (denoted with ++) process command line arguments.
1 --> PS
2 --> CMD
3 --> WMIC
4 --> RUNDLL
5 --> VAR+
6 --> STDIN+
7 --> CLIP+
8 --> VAR++
9 --> STDIN++
10 --> CLIP++
11 --> RUNDLL++
12 --> MSHTA++
.PARAMETER ScriptBlock
Specifies a scriptblock containing your payload.
.PARAMETER LaunchType
Specifies the launch syntax to apply to ScriptBlock.
.PARAMETER NoExit
Outputs the option to not exit after running startup commands.
.PARAMETER NoProfile
Outputs the option to not load the Windows PowerShell profile.
.PARAMETER NonInteractive
Outputs the option to not present an interactive prompt to the user.
.PARAMETER NoLogo
Outputs the option to not present the logo to the user.
.PARAMETER Wow64
Calls the x86 (Wow64) version of PowerShell on x86_64 Windows installations.
.PARAMETER Command
Outputs the option to execute the specified commands (and any parameters) as though they were typed at the Windows PowerShell command prompt.
.PARAMETER WindowStyle
Outputs the option to set the window style to Normal, Minimized, Maximized or Hidden.
.PARAMETER ExecutionPolicy
Outputs the option to set the default execution policy for the current session.
.PARAMETER SwitchesAsString
(Optional) Specifies above PowerShell execution flags per a single string.
.EXAMPLE
C:\PS> Out-PowerShellLauncher -ScriptBlock {Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green} -NoProfile -NonInteractive 3
C:\windows\SYstEM32\cmd.EXe /C "sET oPUWV=Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green&& POWErshELl -NOnINt -noPrOfil ${eX`eCUti`on`cO`NTeXT}.\"INVO`k`e`coMMANd\".\"INvo`KeS`C`RIPt\"( ( GET-CHI`Ldit`EM EnV:OPuwV ).\"v`AlUE\" )"
.NOTES
This cmdlet is an ideal last step after applying other obfuscation cmdlets to your script block or file path contents. Its more advanced obfuscation options are included to show the Blue Team that powershell.exe's command line arguments may not contain any contents of the command itself, but these could be stored in the parent or grandparent process' command line arguments. There are additional techniques to split the command contents cross multiple commands and have the final PowerShell command re-assemble in memory and execute that are not currently included in this version.
This is a personal project developed by Daniel Bohannon while an employee at MANDIANT, A FireEye Company.
.LINK
http://www.danielbohannon.com
#>
[CmdletBinding(DefaultParameterSetName = 'ScriptBlock')] Param (
[Parameter(Position = 0, ValueFromPipeline = $True, ParameterSetName = 'ScriptBlock')]
[ValidateNotNullOrEmpty()]
[ScriptBlock]
$ScriptBlock,
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty()]
[ValidateSet(1,2,3,4,5,6,7,8,9,10,11,12)]
[Int]
$LaunchType,
[Switch]
$NoExit,
[Switch]
$NoProfile,
[Switch]
$NonInteractive,
[Switch]
$NoLogo,
[Switch]
$Wow64,
[Switch]
$Command,
[ValidateSet('Normal', 'Minimized', 'Maximized', 'Hidden')]
[String]
$WindowStyle,
[ValidateSet('Bypass', 'Unrestricted', 'RemoteSigned', 'AllSigned', 'Restricted')]
[String]
$ExecutionPolicy,
[Parameter(Position = 2)]
[String]
$SwitchesAsString
)
# To capture and output args in a process tree format for the applied launcher syntax.
$ArgsDefenderWillSee = @()
# Convert ScriptBlock to a String.
$ScriptString = [String]$ScriptBlock
# Check and throw warning message if input $ScriptString contains new line characters.
If($ScriptString.Contains([Char]13+[Char]10))
{
Write-Host ""
Write-Warning "Current script content contains newline characters.`n Applying a launcher will not work on the command line.`n Apply ENCODING obfuscation before applying LAUNCHER."
Start-Sleep 1
Return $ScriptString
}
# $SwitchesAsString argument for passing in flags from user input in Invoke-Obfuscation.
If($SwitchesAsString.Length -gt 0)
{
If(!($SwitchesAsString.Contains('0')))
{
$SwitchesAsString = ([Char[]]$SwitchesAsString | Sort-Object -Unique -Descending) -Join ' '
ForEach($SwitchAsString in $SwitchesAsString.Split(' '))
{
Switch($SwitchAsString)
{
'1' {$NoExit = $TRUE}
'2' {$NonInteractive = $TRUE}
'3' {$NoLogo = $TRUE}
'4' {$NoProfile = $TRUE}
'5' {$Command = $TRUE}
'6' {$WindowsStyle = 'Hidden'}
'7' {$ExecutionPolicy = 'Bypass'}
'8' {$Wow64 = $TRUE}
default {Write-Error "An invalid `$SwitchAsString value ($SwitchAsString) was passed to switch block for Out-PowerShellLauncher"; Exit;}
}
}
}
}
# Parse out and escape key characters in particular token types for powershell.exe (in reverse to make indexes simpler for escaping tokens).
$Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null)
$CharsToEscape = @('&','|','<','>')
For($i=$Tokens.Count-1; $i -ge 0; $i--)
{
$Token = $Tokens[$i]
# Manually extract token since tokenization will remove certain characters and whitespace which we want to retain.
$PreTokenStr = $ScriptString.SubString(0,$Token.Start)
$ExtractedToken = $ScriptString.SubString($Token.Start,$Token.Length)
$PostTokenStr = $ScriptString.SubString($Token.Start+$Token.Length)
# Escape certain characters that will be problematic on the command line for powershell.exe (\) and cmd.exe (^).
# Single cmd escaping (^) for strings encapsulated by double quotes. For all other tokens apply double layer escaping (^^^).
If($Token.Type -eq 'String' -AND !($ExtractedToken.StartsWith("'") -AND $ExtractedToken.EndsWith("'")))
{
ForEach($Char in $CharsToEscape)
{
If($ExtractedToken.Contains($Char)) {$ExtractedToken = $ExtractedToken.Replace($Char,"^$Char")}
}
If($ExtractedToken.Contains('\')) {$ExtractedToken = $ExtractedToken.Replace('\','\\')}
If($ExtractedToken.Contains('"')) {$ExtractedToken = '\"' + $ExtractedToken.SubString(1,$ExtractedToken.Length-1-1) + '\"'}
}
Else
{
# Before adding layered escaping for special characters for cmd.exe, preserve escaping of ^ used NOT as an escape character (like as part of an Empire key).
If($ExtractedToken.Contains('^'))
{
$ExtractedTokenSplit = $ExtractedToken.Split('^')
$ExtractedToken = ''
For($j=0; $j -lt $ExtractedTokenSplit.Count; $j++)
{
$ExtractedToken += $ExtractedTokenSplit[$j]
$FirstCharFollowingCaret = $ExtractedTokenSplit[$j+1]
If(!$FirstCharFollowingCaret -OR ($CharsToEscape -NotContains $FirstCharFollowingCaret.SubString(0,1)) -AND ($j -ne $ExtractedTokenSplit.Count-1))
{
$ExtractedToken += '^^^^'
}
}
}
ForEach($Char in $CharsToEscape)
{
If($ExtractedToken.Contains($Char)) {$ExtractedToken = $ExtractedToken.Replace($Char,"^^^$Char")}
}
}
# Add $ExtractedToken back into context in $ScriptString
$ScriptString = $PreTokenStr + $ExtractedToken + $PostTokenStr
}
# Randomly select PowerShell execution flag argument substrings and randomize the order for all flags passed to this function.
# This is to prevent the Blue Team from placing false hope in simple signatures for the shortest form of these arguments or consistent ordering.
$PowerShellFlags = New-Object String[](0)
If($PSBoundParameters['NoExit'] -OR $NoExit)
{
$FullArgument = "-NoExit"
$PowerShellFlags += $FullArgument.SubString(0,(Get-Random -Minimum 4 -Maximum ($FullArgument.Length+1)))
}
If($PSBoundParameters['NoProfile'] -OR $NoProfile)
{
$FullArgument = "-NoProfile"
$PowerShellFlags += $FullArgument.SubString(0,(Get-Random -Minimum 4 -Maximum ($FullArgument.Length+1)))
}
If($PSBoundParameters['NonInteractive'] -OR $NonInteractive)
{
$FullArgument = "-NonInteractive"
$PowerShellFlags += $FullArgument.SubString(0,(Get-Random -Minimum 5 -Maximum ($FullArgument.Length+1)))
}
If($PSBoundParameters['NoLogo'] -OR $NoLogo)
{
$FullArgument = "-NoLogo"
$PowerShellFlags += $FullArgument.SubString(0,(Get-Random -Minimum 4 -Maximum ($FullArgument.Length+1)))
}
If($PSBoundParameters['WindowStyle'] -OR $WindowsStyle)
{
$FullArgument = "-WindowStyle"
If($WindowsStyle) {$ArgumentValue = $WindowsStyle}
Else {$ArgumentValue = $PSBoundParameters['WindowStyle']}
# Randomly decide to overwrite the WindowStyle value with the corresponding integer representation of the predefined parameter value.
Switch($ArgumentValue.ToLower())
{
'normal' {If(Get-Random -Input @(0..1)) {$ArgumentValue = (Get-Random -Input @('0','n','no','nor','norm','norma'))}}
'hidden' {If(Get-Random -Input @(0..1)) {$ArgumentValue = (Get-Random -Input @('1','h','hi','hid','hidd','hidde'))}}
'minimized' {If(Get-Random -Input @(0..1)) {$ArgumentValue = (Get-Random -Input @('2','mi','min','mini','minim','minimi','minimiz','minimize'))}}
'maximized' {If(Get-Random -Input @(0..1)) {$ArgumentValue = (Get-Random -Input @('3','ma','max','maxi','maxim','maximi','maximiz','maximize'))}}
default {Write-Error "An invalid `$ArgumentValue value ($ArgumentValue) was passed to switch block for Out-PowerShellLauncher."; Exit;}
}
$PowerShellFlags += $FullArgument.SubString(0,(Get-Random -Minimum 2 -Maximum ($FullArgument.Length+1))) + ' '*(Get-Random -Minimum 1 -Maximum 3) + $ArgumentValue
}
If($PSBoundParameters['ExecutionPolicy'] -OR $ExecutionPolicy)
{
$FullArgument = "-ExecutionPolicy"
If($ExecutionPolicy) {$ArgumentValue = $ExecutionPolicy}
Else {$ArgumentValue = $PSBoundParameters['ExecutionPolicy']}
# Take into account the shorted flag of -EP as well.
$ExecutionPolicyFlags = @()
$ExecutionPolicyFlags += '-EP'
For($Index=3; $Index -le $FullArgument.Length; $Index++)
{
$ExecutionPolicyFlags += $FullArgument.SubString(0,$Index)
}
$ExecutionPolicyFlag = Get-Random -Input $ExecutionPolicyFlags
$PowerShellFlags += $ExecutionPolicyFlag + ' '*(Get-Random -Minimum 1 -Maximum 3) + $ArgumentValue
}
# Randomize the order of the command-line arguments.
# This is to prevent the Blue Team from placing false hope in simple signatures for consistent ordering of these arguments.
If($PowerShellFlags.Count -gt 1)
{
$PowerShellFlags = Get-Random -InputObject $PowerShellFlags -Count $PowerShellFlags.Count
}
# If selected then the -Command flag needs to be added last.
If($PSBoundParameters['Command'] -OR $Command)
{
$FullArgument = "-Command"
$PowerShellFlags += $FullArgument.SubString(0,(Get-Random -Minimum 2 -Maximum ($FullArgument.Length+1)))
}
# Randomize the case of all command-line arguments.
For($i=0; $i -lt $PowerShellFlags.Count; $i++)
{
$PowerShellFlags[$i] = ([Char[]]$PowerShellFlags[$i] | ForEach-Object {$Char = $_.ToString().ToLower(); If(Get-Random -Input @(0..1)) {$Char = $Char.ToUpper()} $Char}) -Join ''
}
# Insert random-length whitespace between all command-line arguments.
# Maintain array of PS flags for some launch types (namely CLIP+, CLIP++ and RunDll32).
$PowerShellFlagsArray = $PowerShellFlags
$PowerShellFlags = ($PowerShellFlags | ForEach-Object {$_ + ' '*(Get-Random -Minimum 1 -Maximum 3)}) -Join ''
$PowerShellFlags = ' '*(Get-Random -Minimum 1 -Maximum 3) + $PowerShellFlags + ' '*(Get-Random -Minimum 1 -Maximum 3)
# Build out paths to binaries depending if 32-bit or 64-bit options were selected.
$WinPath = "C:\WINDOWS"
$System32Path = "C:\WINDOWS\system32"
$PathToRunDll = Get-Random -Input @("$System32Path\rundll32" , "$System32Path\rundll32.exe" , "rundll32" , "rundll32.exe")
$PathToMshta = Get-Random -Input @("$System32Path\mshta" , "$System32Path\mshta.exe" , "mshta" , "mshta.exe")
$PathToCmd = Get-Random -Input @("$System32Path\cmd" , "$System32Path\cmd.exe" , "cmd.exe" , "cmd")
$PathToClip = Get-Random -Input @("$System32Path\clip" , "$System32Path\clip.exe" , "clip" , "clip.exe")
$PathToWmic = Get-Random -Input @("$System32Path\WBEM\wmic" , "$System32Path\WBEM\wmic.exe" , "wmic" , "wmic.exe")
# If you use cmd or cmd.exe instead of the pathed version, then you don't need to put a whitespace between cmd and and cmd flags. E.g. cmd/c or cmd.exe/c.
If($PathToCmd.Contains('\'))
{
$PathToCmd = $PathToCmd + ' '*(Get-Random -Minimum 2 -Maximum 4)
}
Else
{
$PathToCmd = $PathToCmd + ' '*(Get-Random -Minimum 0 -Maximum 4)
}
If($PSBoundParameters['Wow64'] -OR $Wow64)
{
$PathToPowerShell = "$WinPath\SysWOW64\WindowsPowerShell\v1.0\powershell.exe"
}
Else
{
# Obfuscation isn't about saving space, and there are reasons you'd potentially want to fully path powershell.exe (more info on this soon).
#$PathToPowerShell = "$($Env:windir)\System32\WindowsPowerShell\v1.0\powershell.exe"
$PathToPowerShell = "powershell"
}
# Randomize the case of the following variables.
$PowerShellFlags = ([Char[]]$PowerShellFlags.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$PathToPowerShell = ([Char[]]$PathToPowerShell.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$PathToRunDll = ([Char[]]$PathToRunDll.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$PathToMshta = ([Char[]]$PathToMshta.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$PathToCmd = ([Char[]]$PathToCmd.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$PathToClip = ([Char[]]$PathToClip.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$PathToWmic = ([Char[]]$PathToWmic.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$SlashC = ([Char[]]'/c'.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$Echo = ([Char[]]'echo'.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Show warning if an uneven number of double-quotes exists for any $LaunchType.
$NumberOfDoubleQuotes = $ScriptString.Length-$ScriptString.Replace('"','').Length
If($NumberOfDoubleQuotes%2 -eq 1)
{
Write-Host ""
Write-Warning "This command contains an unbalanced number of double quotes ($NumberOfDoubleQuotes).`n Try applying STRING or ENCODING obfuscation options first to encode the double quotes.`n"
Start-Sleep 1
Return $ScriptString
}
# If no $LaunchType is specified then randomly choose from options 3-20.
If($LaunchType -eq 0)
{
$LaunchType = Get-Random -Input @(3..12)
}
# Select launcher syntax.
Switch($LaunchType)
{
1 {
########
## PS ##
########
# Undo some escaping from beginning of function.
ForEach($Char in $CharsToEscape)
{
If($ScriptString.Contains("^^^$Char")) {$ScriptString = $ScriptString.Replace("^^^$Char",$Char)}
}
If($ScriptString.Contains('^^^^'))
{
$ScriptString = $ScriptString.Replace('^^^^','^')
}
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = $PowerShellFlags + '"' + $ScriptString + '"'
# Set argument info for process tree output after this Switch block.
$ArgsDefenderWillSee += , @($PathToPowerShell, $PSCmdSyntax)
$CmdLineOutput = $PathToPowerShell + $PSCmdSyntax
}
2 {
#########
## CMD ##
#########
# Undo some escaping from beginning of function.
ForEach($Char in $CharsToEscape)
{
If($ScriptString.Contains("^^^$Char")) {$ScriptString = $ScriptString.Replace("^^^$Char",$Char)}
If($ScriptString.Contains("^$Char")) {$ScriptString = $ScriptString.Replace("^$Char","^^^$Char")}
}
If($ScriptString.Contains('^^^^'))
{
$ScriptString = $ScriptString.Replace('^^^^','^')
}
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = $PowerShellFlags + '"' + $ScriptString + '"'
$CmdSyntax = $SlashC + ' '*(Get-Random -Minimum 0 -Maximum 4) + $PathToPowerShell + $PSCmdSyntax
# Set argument info for process tree output after this Switch block.
$ArgsDefenderWillSee += , @($PathToCmd , $CmdSyntax)
$ArgsDefenderWillSee += , @($PathToPowerShell, $PSCmdSyntax)
$CmdLineOutput = $PathToCmd + $CmdSyntax
}
3 {
##########
## WMIC ##
##########
# WMIC errors when variables contain more than 2 adjacent whitespaces in variable names. Thus we are escaping them here.
For($i=1; $i -le 12; $i++)
{
$StringToReplace = '${' + ' '*$i + '}'
If($ScriptString.Contains($StringToReplace))
{
$ScriptString = $ScriptString.Replace($StringToReplace,$StringToReplace.Replace(' ','\ '))
}
}
# Undo escaping from beginning of function. $CharsToEscape is defined at beginning of this function.
ForEach($Char in $CharsToEscape)
{
While($ScriptString.Contains('^' + $Char))
{
$ScriptString = $ScriptString.Replace(('^' + $Char),$Char)
}
}
If($ScriptString.Contains('^^^^'))
{
$ScriptString = $ScriptString.Replace('^^^^','^')
}
# Perform inline substitutions to remove commas from command line for wmic.exe.
If($ScriptString.Contains(','))
{
# SetVariables will only be used if more than 5 double quotes or more than 5 commas need to be escaped.
$SetVariables = ''
# Since we are converting the PowerShell command into strings for concatenation we need to escape and double-escape $ for proper variable interpretation by PowerShell.
If($ScriptString.Contains('$'))
{
$ScriptString = $ScriptString.Replace('$','`$')
# Double escape any $ characters that were already escaped prior to above escaping step.
If($ScriptString.Contains('``$'))
{
$ScriptString = $ScriptString.Replace('``$','```$')
}
}
# Double escape any escaped " characters.
If($ScriptString.Contains('`"'))
{
$ScriptString = $ScriptString.Replace('`"','``"')
}
# Substitute double quotes as well if we're substituting commas as this requires treating the entire command as a string by encapsulating it with double quotes.
If($ScriptString.Contains('"'))
{
# Remove all layers of escaping for double quotes as they are no longer necessary since we're casting these double quotes to ASCII values.
While($ScriptString.Contains('\"'))
{
$ScriptString = $ScriptString.Replace('\"','"')
}
# Randomly select a syntax for the Char conversion of a double quote ASCII value and then ramdomize the case.
$CharCastDoubleQuote = ([Char[]](Get-Random -Input @('[String][Char]34','([Char]34).ToString()')) | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
If($ScriptString.Length-$ScriptString.Replace('"','').Length -le 5)
{
# Replace double quote(s) with randomly selected ASCII value conversion representation -- inline concatenation.
$SubstitutionSyntax = ('\"' + ' '*(Get-Random -Minimum 0 -Maximum 3) + '+' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $CharCastDoubleQuote + ' '*(Get-Random -Minimum 0 -Maximum 3) + '+' + ' '*(Get-Random -Minimum 0 -Maximum 3) + '\"')
$ScriptString = $ScriptString.Replace('"',$SubstitutionSyntax).Replace('\"\"+','').Replace('\"\" +','').Replace('\"\" +','').Replace('\"\" +','')
}
Else
{
# Characters we will use to generate random variable names.
# For simplicity do NOT include single- or double-quotes in this array.
$CharsToRandomVarName = @(0..9)
$CharsToRandomVarName += @('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
# Randomly choose variable name starting length.
$RandomVarLength = (Get-Random -Input @(1..2))
# Create random variable with characters from $CharsToRandomVarName.
If($CharsToRandomVarName.Count -lt $RandomVarLength) {$RandomVarLength = $CharsToRandomVarName.Count}
$RandomVarName = ((Get-Random -Input $CharsToRandomVarName -Count $RandomVarLength) -Join '').Replace(' ','')
# Keep generating random variables until we find one that is not a substring of $ScriptString.
While($ScriptString.ToLower().Contains($RandomVarName.ToLower()))
{
$RandomVarName = ((Get-Random -Input $CharsToRandomVarName -Count $RandomVarLength) -Join '').Replace(' ','')
$RandomVarLength++
}
# Randomly decide if the variable name will be concatenated inline or not.
$RandomVarNameMaybeConcatenated = $RandomVarName
If((Get-Random -Input @(0..1)) -eq 0)
{
$RandomVarNameMaybeConcatenated = '(' + (Out-ConcatenatedString $RandomVarName "'") + ')'
}
# Generate random variable SET syntax.
$RandomVarSetSyntax = @()
$RandomVarSetSyntax += '$' + $RandomVarName + ' '*(Get-Random @(0..2)) + '=' + ' '*(Get-Random @(0..2)) + $CharCastDoubleQuote
$RandomVarSetSyntax += (Get-Random -Input @('Set-Variable','SV','Set')) + ' '*(Get-Random @(1..2)) + $RandomVarNameMaybeConcatenated + ' '*(Get-Random @(1..2)) + '(' + ' '*(Get-Random @(0..2)) + $CharCastDoubleQuote + ' '*(Get-Random @(0..2)) + ')'
# Randomly choose from above variable syntaxes.
$RandomVarSet = (Get-Random -Input $RandomVarSetSyntax)
# Replace double quotes with randomly selected ASCII value conversion representation -- variable replacement to save space for high counts of double quotes to substitute.
$SetVariables += $RandomVarSet + ' '*(Get-Random @(1..2)) + ';'
$ScriptString = $ScriptString.Replace('"',"`${$RandomVarName}")
}
}
# Randomly select a syntax for the Char conversion of a comma ASCII value and then ramdomize the case.
$CharCastComma= ([Char[]](Get-Random -Input @('[String][Char]44','([Char]44).ToString()')) | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
If($ScriptString.Length-$ScriptString.Replace(',','').Length -le 5)
{
# Replace commas with randomly selected ASCII value conversion representation -- inline concatenation.
$SubstitutionSyntax = ('\"' + ' '*(Get-Random -Minimum 0 -Maximum 3) + '+' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $CharCastComma + ' '*(Get-Random -Minimum 0 -Maximum 3) + '+' + ' '*(Get-Random -Minimum 0 -Maximum 3) + '\"')
$ScriptString = $ScriptString.Replace(',',$SubstitutionSyntax).Replace('\"\"+','').Replace('\"\" +','').Replace('\"\" +','').Replace('\"\" +','')
}
Else
{
# Characters we will use to generate random variable names.
# For simplicity do NOT include single- or double-quotes in this array.
$CharsToRandomVarName = @(0..9)
$CharsToRandomVarName += @('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
# Randomly choose variable name starting length.
$RandomVarLength = (Get-Random -Input @(1..2))
# Create random variable with characters from $CharsToRandomVarName.
If($CharsToRandomVarName.Count -lt $RandomVarLength) {$RandomVarLength = $CharsToRandomVarName.Count}
$RandomVarName = ((Get-Random -Input $CharsToRandomVarName -Count $RandomVarLength) -Join '').Replace(' ','')
# Keep generating random variables until we find one that is not a substring of $ScriptString.
While($ScriptString.ToLower().Contains($RandomVarName.ToLower()))
{
$RandomVarName = ((Get-Random -Input $CharsToRandomVarName -Count $RandomVarLength) -Join '').Replace(' ','')
$RandomVarLength++
}
# Randomly decide if the variable name will be concatenated inline or not.
$RandomVarNameMaybeConcatenated = $RandomVarName
If((Get-Random -Input @(0..1)) -eq 0)
{
$RandomVarNameMaybeConcatenated = '(' + (Out-ConcatenatedString $RandomVarName "'") + ')'
}
# Generate random variable SET syntax.
$RandomVarSetSyntax = @()
$RandomVarSetSyntax += '$' + $RandomVarName + ' '*(Get-Random @(0..2)) + '=' + ' '*(Get-Random @(0..2)) + $CharCastComma
$RandomVarSetSyntax += (Get-Random -Input @('Set-Variable','SV','Set')) + ' '*(Get-Random @(1..2)) + $RandomVarNameMaybeConcatenated + ' '*(Get-Random @(1..2)) + '(' + ' '*(Get-Random @(0..2)) + $CharCastComma + ' '*(Get-Random @(0..2)) + ')'
# Randomly choose from above variable syntaxes.
$RandomVarSet = (Get-Random -Input $RandomVarSetSyntax)
# Replace commas with randomly selected ASCII value conversion representation -- variable replacement to save space for high counts of commas to substitute.
$SetVariables += $RandomVarSet + ' '*(Get-Random @(1..2)) + ';'
$ScriptString = $ScriptString.Replace(',',"`${$RandomVarName}")
}
# Encapsulate entire command with escaped double quotes since entire command is now an inline concatenated string to support the above character substitution(s).
$ScriptString = '\"' + $ScriptString + '\"'
# Randomly decide on invoke operation since we've applied an additional layer of string manipulation in above steps.
# Keep running Out-EncapsulatedInvokeExpression until we get a syntax that does NOT contain commas.
# Examples like .((gv '*mdR*').Name[3,11,2]-Join'') can have their commas escaped like in above step. However, wmic.exe errors with opening [ without a closing ] in the string literal.
$ScriptStringTemp = ','
While($ScriptStringTemp.Contains(','))
{
$ScriptStringTemp = Out-EncapsulatedInvokeExpression $ScriptString
}
# Now that we have an invocation syntax that does not contain commas we will set $ScriptStringTemp's results back into $ScriptString.
$ScriptString = $ScriptStringTemp
# Prepend with $SetVariables (which will be blank if no variables were set in above sustitution logic depending on the number of double quotes and commas that need to be replaced.
$ScriptString = $SetVariables + $ScriptString
}
# Generate random case syntax for PROCESS CALL CREATE arguments for WMIC.exe.
$WmicArguments = ([Char[]]'process call create' | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Randomize the whitespace between each element of $WmicArguments which randomly deciding between encapsulating each argument with single quotes, double quotes or no quote.
$WmicArguments = (($WmicArguments.Split(' ') | ForEach-Object {$RandomQuotes = (Get-Random -Input @('"',"'",' ')); $RandomQuotes + $_ + $RandomQuotes + ' '*(Get-Random -Minimum 1 -Maximum 4)}) -Join '').Trim()
# Pair escaped double quotes with a prepended additional double quote so that wmic.exe does not treat the string as a separate argument for wmic.exe but the double quote still exists for powershell.exe's functionality.
If($ScriptString.Contains('\"'))
{
$ScriptString = $ScriptString.Replace('\"','"\"')
}
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = $PowerShellFlags + $ScriptString
$WmicCmdSyntax = ' '*(Get-Random -Minimum 1 -Maximum 4) + $WmicArguments + ' '*(Get-Random -Minimum 1 -Maximum 4) + '"' + $PathToPowerShell + $PSCmdSyntax + '"'
# Set argument info for process tree output after this Switch block.
# Even though wmic.exe will show in command line arguments, it will not be the parent process of powershell.exe. Instead, the already-existing instance of WmiPrvSE.exe will spawn powershell.exe.
$ArgsDefenderWillSee += , @("[Unrelated to WMIC.EXE execution] C:\WINDOWS\system32\wbem\wmiprvse.exe", " -secured -Embedding")
$ArgsDefenderWillSee += , @($PathToPowerShell, $PSCmdSyntax)
$CmdLineOutput = $PathToWmic + $WmicCmdSyntax
}
4 {
############
## RUNDLL ##
############
# Shout out and big thanks to Matt Graeber (@mattifestation) for pointing out this method of executing any binary directly from rundll32.exe.
# Undo escaping from beginning of function.
ForEach($Char in $CharsToEscape)
{
If($ScriptString.Contains("^^^$Char")) {$ScriptString = $ScriptString.Replace("^^^$Char","$Char")}
}
If($ScriptString.Contains('^^^^'))
{
$ScriptString = $ScriptString.Replace('^^^^','^')
}
# Generate random case syntax for SHELL32.DLL argument for RunDll32.exe.
$Shell32Dll = ([Char[]]'SHELL32.DLL' | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Put the execution flags in the format required by rundll32.exe: each argument separately encapusulated in double quotes.
$ExecutionFlagsRunDllSyntax = ($PowerShellFlagsArray | Where-Object {$_.Trim().Length -gt 0} | ForEach-Object {'"' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $_ + ' '*(Get-Random -Minimum 0 -Maximum 3) + '"' + ' '*(Get-Random -Minimum 1 -Maximum 4)}) -Join ''
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = ' '*(Get-Random -Minimum 1 -Maximum 4) + $ExecutionFlagsRunDllSyntax + ' '*(Get-Random -Minimum 1 -Maximum 4) + "`"$ScriptString`""
$RunDllCmdSyntax = ' '*(Get-Random -Minimum 1 -Maximum 4) + $Shell32Dll + (Get-Random -Input @(',',' ', ((Get-Random -Input @(',',',',',',' ',' ',' ') -Count (Get-Random -Input @(4..6)))-Join''))) + 'ShellExec_RunDLL' + ' '*(Get-Random -Minimum 1 -Maximum 4) + "`"$PathToPowerShell`"" + $PSCmdSyntax
# Set argument info for process tree output after this Switch block.
$ArgsDefenderWillSee += , @($PathToRunDll , $RunDllCmdSyntax)
$ArgsDefenderWillSee += , @("`"$PathToPowerShell`"", $PSCmdSyntax.Replace('^',''))
$CmdLineOutput = $PathToRunDll + $RunDllCmdSyntax
}
5 {
##########
## VAR+ ##
##########
# Undo some escaping from beginning of function.
ForEach($Char in $CharsToEscape)
{
If($ScriptString.Contains("^^^$Char")) {$ScriptString = $ScriptString.Replace("^^^$Char","^$Char")}
}
If($ScriptString.Contains('^^^^'))
{
$ScriptString = $ScriptString.Replace('^^^^','^^')
}
# Switch cmd.exe escape with powershell.exe escape of double-quote.
If($ScriptString.Contains('\"')) {$ScriptString = $ScriptString.Replace('\"','"')}
# Choose random syntax for invoking command stored in process-level environment variable.
# Generate random variable name to store the $ScriptString command.
$CharsForVarName = @('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
$VariableName = (Get-Random -Input $CharsForVarName -Count ($CharsForVarName.Count/(Get-Random -Input @(5..10)))) -Join ''
$VariableName = ([Char[]]$VariableName.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Generate random syntax for invoking process-level environment variable syntax.
$InvokeVariableSyntax = Out-RandomInvokeRandomEnvironmentVariableSyntax $VariableName
# Generate random case syntax for setting the above random variable name.
$SetSyntax = ([Char[]]'set' | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$SetSyntax = $SetSyntax + ' '*(Get-Random -Minimum 2 -Maximum 4) + $VariableName + '='
# Randomize the case of the following variables.
$SetSyntax = ([Char[]]$SetSyntax.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = $PowerShellFlags + $InvokeVariableSyntax
$CmdSyntax = $SlashC + ' '*(Get-Random -Minimum 0 -Maximum 4) + '"' + $SetSyntax + $ScriptString + '&&' + ' '*(Get-Random -Minimum 0 -Maximum 4) + $PathToPowerShell + $PSCmdSyntax + '"'
# Set argument info for process tree output after this Switch block.
$ArgsDefenderWillSee += , @($PathToCmd , $CmdSyntax)
$ArgsDefenderWillSee += , @($PathToPowerShell, $PSCmdSyntax.Replace('^',''))
$CmdLineOutput = $PathToCmd + $CmdSyntax
}
6 {
############
## STDIN+ ##
############
# Switch cmd.exe escape with powershell.exe escape of double-quote.
If($ScriptString.Contains('\"')) {$ScriptString = $ScriptString.Replace('\"','"')}
# Choose random syntax for invoking powershell.exe's StdIn.
$PowerShellStdin = Out-RandomPowerShellStdInInvokeSyntax
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = $PowerShellFlags + $PowerShellStdin
$CmdSyntax = $SlashC + ' '*(Get-Random -Minimum 0 -Maximum 4) + '"' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $Echo + (Get-Random -Input ('/','\',' '*(Get-Random -Minimum 1 -Maximum 3))) + $ScriptString + ' '*(Get-Random -Minimum 1 -Maximum 3) + '|' + ' '*(Get-Random -Minimum 1 -Maximum 3) + $PathToPowerShell + $PSCmdSyntax + '"'
# Set argument info for process tree output after this Switch block.
$ArgsDefenderWillSee += , @($PathToCmd , $CmdSyntax)
$ArgsDefenderWillSee += , @($PathToPowerShell, $PSCmdSyntax.Replace('^',''))
$CmdLineOutput = $PathToCmd + $CmdSyntax
}
7 {
###########
## CLIP+ ##
###########
# Switch cmd.exe escape with powershell.exe escape of double-quote.
If($ScriptString.Contains('\"')) {$ScriptString = $ScriptString.Replace('\"','"')}
# Choose random syntax for invoking powershell.exe's StdIn.
$PowerShellClip = Out-RandomClipboardInvokeSyntax
# If this launcher is run in PowerShell 2.0 then Single-Threaded Apartment must be specified with -st or -sta.
# Otherwise you will get the following error: "Current thread must be set to single thread apartment (STA) mode before OLE calls can be made."
# Since Invoke-Obfuscation output is designed to run on any PowerShell version then for this launcher we will add the -st/-sta flag to $PowerShellFlags.
# If selected then the -Command flag needs to remain last (where it currently is).
$CommandFlagValue = $NULL
If($PSBoundParameters['Command'] -OR $Command)
{
$UpperLimit = $PowerShellFlagsArray.Count-1
$CommandFlagValue = $PowerShellFlagsArray[$PowerShellFlagsArray.Count-1]
}
Else
{
$UpperLimit = $PowerShellFlagsArray.Count
}
# Re-extract PowerShellFlags so we can add in -st/-sta and then reorder (maintaining command flag at the end if present).
$PowerShellFlags = @()
For($i=0; $i -lt $UpperLimit; $i++)
{
$PowerShellFlags += $PowerShellFlagsArray[$i]
}
# Add in -st/-sta to PowerShellFlags.
$PowerShellFlags += (Get-Random -Input @('-st','-sta'))
# Randomize the order of the command-line arguments.
# This is to prevent the Blue Team from placing false hope in simple signatures for consistent ordering of these arguments.
If($PowerShellFlags.Count -gt 1)
{
$PowerShellFlags = Get-Random -InputObject $PowerShellFlags -Count $PowerShellFlags.Count
}
# If selected then the -Command flag needs to be added last.
If($CommandFlagValue)
{
$PowerShellFlags += $CommandFlagValue
}
# Randomize the case of all command-line arguments.
For($i=0; $i -lt $PowerShellFlags.Count; $i++)
{
$PowerShellFlags[$i] = ([Char[]]$PowerShellFlags[$i] | ForEach-Object {$Char = $_.ToString().ToLower(); If(Get-Random -Input @(0..1)) {$Char = $Char.ToUpper()} $Char}) -Join ''
}
# Insert random-length whitespace between all command-line arguments.
$PowerShellFlags = ($PowerShellFlags | ForEach-Object {$_ + ' '*(Get-Random -Minimum 1 -Maximum 3)}) -Join ''
$PowerShellFlags = ' '*(Get-Random -Minimum 1 -Maximum 3) + $PowerShellFlags + ' '*(Get-Random -Minimum 1 -Maximum 3)
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = $PowerShellFlags + $PowerShellClip
$CmdSyntax = $SlashC + ' '*(Get-Random -Minimum 0 -Maximum 4) + '"' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $Echo + (Get-Random -Input ('/','\',' '*(Get-Random -Minimum 1 -Maximum 3))) + $ScriptString + ' '*(Get-Random -Minimum 0 -Maximum 2) + '|' + ' '*(Get-Random -Minimum 0 -Maximum 2) + $PathToClip + ' '*(Get-Random -Minimum 0 -Maximum 2) + '&&' + ' '*(Get-Random -Minimum 1 -Maximum 3) + $PathToPowerShell + $PSCmdSyntax + '"'
# Set argument info for process tree output after this Switch block.
$ArgsDefenderWillSee += , @($PathToCmd , $CmdSyntax)
$ArgsDefenderWillSee += , @($PathToPowerShell, $PSCmdSyntax.Replace('^',''))
$CmdLineOutput = $PathToCmd + $CmdSyntax
}
8 {
###########
## VAR++ ##
###########
# Undo some escaping from beginning of function.
ForEach($Char in $CharsToEscape)
{
If($ScriptString.Contains("^^^$Char")) {$ScriptString = $ScriptString.Replace("^^^$Char","^$Char")}
}
If($ScriptString.Contains('^^^^'))
{
$ScriptString = $ScriptString.Replace('^^^^','^^')
}
# Switch cmd.exe escape with powershell.exe escape of double-quote.
If($ScriptString.Contains('\"')) {$ScriptString = $ScriptString.Replace('\"','"')}
# Choose random syntax for invoking command stored in process-level environment variable.
# Generate random variable names to store the $ScriptString command and PowerShell syntax.
$CharsForVarName = @('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
$VariableName = (Get-Random -Input $CharsForVarName -Count ($CharsForVarName.Count/(Get-Random -Input @(5..10)))) -Join ''
$VariableName = ([Char[]]$VariableName.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$VariableName2 = (Get-Random -Input $CharsForVarName -Count ($CharsForVarName.Count/(Get-Random -Input @(5..10)))) -Join ''
$VariableName2 = ([Char[]]$VariableName2.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Generate random case syntax for setting the above random variable names.
$SetSyntax = ([Char[]]'set' | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$SetSyntax = $SetSyntax + ' '*(Get-Random -Minimum 2 -Maximum 4) + $VariableName + '='
$SetSyntax2 = ([Char[]]'set' | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$SetSyntax2 = $SetSyntax2 + ' '*(Get-Random -Minimum 2 -Maximum 4) + $VariableName2 + '='
# Randomize the case of the following variables.
$SetSyntax = ([Char[]]$SetSyntax.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$SetSyntax2 = ([Char[]]$SetSyntax2.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$VariableName = ([Char[]]$VariableName.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$VariableName2 = ([Char[]]$VariableName2.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Generate random syntax for invoking process-level environment variable syntax.
$InvokeOption = Out-RandomInvokeRandomEnvironmentVariableSyntax $VariableName
# Add additional escaping for vertical pipe (and other characters defined below) if necessary since this is going inside an environment variable for the final $CmdLineOutput set below.
ForEach($Char in @('<','>','|','&'))
{
If($InvokeOption.Contains("^$Char"))
{
$InvokeOption = $InvokeOption.Replace("^$Char","^^^$Char")
}
}
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = $PowerShellFlags + ' '*(Get-Random -Minimum 1 -Maximum 3) + $InvokeOption
$CmdSyntax2 = $SlashC + ' '*(Get-Random -Minimum 0 -Maximum 2) + "%$VariableName2%"
$CmdSyntax = $SlashC + ' '*(Get-Random -Minimum 0 -Maximum 4) + '"' + $SetSyntax + $ScriptString + '&&' + $SetSyntax2 + $PathToPowerShell + $PSCmdSyntax + '&&' + ' '*(Get-Random -Minimum 0 -Maximum 4) + $PathToCmd + $CmdSyntax2 + '"'
# Set argument info for process tree output after this Switch block.
$ArgsDefenderWillSee += , @($PathToCmd , $CmdSyntax)
$ArgsDefenderWillSee += , @($PathToCmd , $CmdSyntax2)
$ArgsDefenderWillSee += , @($PathToPowerShell, $PSCmdSyntax.Replace('^',''))
$CmdLineOutput = $PathToCmd + $CmdSyntax
}
9 {
#############
## STDIN++ ##
#############
# Switch cmd.exe escape with powershell.exe escape of double-quote.
If($ScriptString.Contains('\"')) {$ScriptString = $ScriptString.Replace('\"','"')}
# Choose random syntax for invoking command stored in process-level environment variable.
# Generate random variable names to store the $ScriptString command and PowerShell syntax.
$CharsForVarName = @('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
$VariableName = (Get-Random -Input $CharsForVarName -Count ($CharsForVarName.Count/(Get-Random -Input @(5..10)))) -Join ''
$VariableName = ([Char[]]$VariableName.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$VariableName2 = (Get-Random -Input $CharsForVarName -Count ($CharsForVarName.Count/(Get-Random -Input @(5..10)))) -Join ''
$VariableName2 = ([Char[]]$VariableName2.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Generate random case syntax for setting the above random variable names.
$SetSyntax = ([Char[]]'set' | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$SetSyntax = $SetSyntax + ' '*(Get-Random -Minimum 2 -Maximum 4) + $VariableName + '='
$SetSyntax2 = ([Char[]]'set' | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$SetSyntax2 = $SetSyntax2 + ' '*(Get-Random -Minimum 2 -Maximum 4) + $VariableName2 + '='
# Generate numerous ways to invoke with $ExecutionContext as a variable, including Get-Variable varname, Get-ChildItem Variable:varname, Get-Item Variable:varname, etc.
$ExecContextVariable = @()
$ExecContextVariable += '(' + (Get-Random -Input @('DIR','Get-ChildItem','GCI','ChildItem','LS','Get-Item','GI','Item')) + ' ' + 'variable:' + (Get-Random -Input @('Ex*xt','E*t','*xec*t','*ecu*t','*cut*t','*cuti*t','*uti*t','E*ext','E*xt','E*Cont*','E*onte*','E*tex*','ExecutionContext')) + ').Value'
# Select random option from above.
$ExecContextVariable = Get-Random -Input $ExecContextVariable
# Generate numerous ways to invoke command stored in environment variable.
$GetRandomVariableSyntax = @()
$GetRandomVariableSyntax += '(' + (Get-Random -Input @('DIR','Get-ChildItem','GCI','ChildItem','LS','Get-Item','GI','Item')) + ' ' + 'env:' + $VariableName + ').Value'
$GetRandomVariableSyntax += ('(' + '[Environment]::GetEnvironmentVariable(' + "'$VariableName'" + ',' + "'Process'" + ')' + ')')
# Select random option from above.
$GetRandomVariableSyntax = Get-Random -Input $GetRandomVariableSyntax
# Generate random Invoke-Expression/IEX/$ExecutionContext syntax.
$InvokeOptions = @()
$InvokeOptions += (Get-Random -Input ('IEX','Invoke-Expression')) + ' '*(Get-Random -Minimum 1 -Maximum 3) + $GetRandomVariableSyntax
$InvokeOptions += (Get-Random -Input @('$ExecutionContext','${ExecutionContext}',$ExecContextVariable)) + '.InvokeCommand.InvokeScript(' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $GetRandomVariableSyntax + ' '*(Get-Random -Minimum 0 -Maximum 3) + ')'
# Select random option from above.
$InvokeOption = Get-Random -Input $InvokeOptions
# Randomize the case of the following variables.
$SetSyntax = ([Char[]]$SetSyntax.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$SetSyntax2 = ([Char[]]$SetSyntax2.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$VariableName = ([Char[]]$VariableName.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$VariableName2 = ([Char[]]$VariableName2.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$InvokeOption = ([Char[]]$InvokeOption.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$ExecContextVariable = ([Char[]]$ExecContextVariable.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
$GetRandomVariableSyntax = ([Char[]]$GetRandomVariableSyntax.ToLower() | ForEach-Object {$Char = $_; If(Get-Random -Input (0..1)){$Char = $Char.ToString().ToUpper()} $Char}) -Join ''
# Generate random syntax for invoking process-level environment variable syntax.
$InvokeVariableSyntax = Out-RandomInvokeRandomEnvironmentVariableSyntax $VariableName
# Choose random syntax for invoking powershell.exe's StdIn.
$PowerShellStdin = Out-RandomPowerShellStdInInvokeSyntax
# Undo some escaping from beginning of function.
ForEach($Char in $CharsToEscape)
{
If($ScriptString.Contains("^^^$Char")) {$ScriptString = $ScriptString.Replace("^^^$Char","^$Char")}
If($PowerShellStdin.Contains("^$Char")) {$PowerShellStdin = $PowerShellStdin.Replace("^$Char","^^^$Char")}
}
If($ScriptString.Contains('^^^^'))
{
$ScriptString = $ScriptString.Replace('^^^^','^^')
}
# Build out command line syntax in reverse so we can display the process argument tree at the end of this Switch block.
$PSCmdSyntax = $PowerShellFlags + ' '*(Get-Random -Minimum 1 -Maximum 3) + $PowerShellStdin + ' '*(Get-Random -Minimum 0 -Maximum 3)
$CmdSyntax2 = $SlashC + ' '*(Get-Random -Minimum 0 -Maximum 2) + "%$VariableName2%"
$CmdSyntax = $SlashC + ' '*(Get-Random -Minimum 0 -Maximum 4) + '"' + $SetSyntax + ' '*(Get-Random -Minimum 0 -Maximum 3)+ $ScriptString + ' '*(Get-Random -Minimum 0 -Maximum 3) + '&&' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $SetSyntax2 + $Echo + ' '*(Get-Random -Minimum 1 -Maximum 3) + $InvokeOption + ' '*(Get-Random -Minimum 0 -Maximum 3) + '^|' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $PathToPowerShell + $PSCmdSyntax + '&&' + ' '*(Get-Random -Minimum 0 -Maximum 3) + $PathToCmd + $CmdSyntax2 + '"'
# Set argument info for process tree output after this Switch block.
$ArgsDefenderWillSee += , @($PathToCmd , $CmdSyntax)
$ArgsDefenderWillSee += , @($PathToCmd , $CmdSyntax2)
$ArgsDefenderWillSee += , @($PathToPowerShell, $PSCmdSyntax.Replace('^',''))
$CmdLineOutput = $PathToCmd + $CmdSyntax
}
10 {
############
## CLIP++ ##
############
# Switch cmd.exe escape with powershell.exe escape of double-quote.
If($ScriptString.Contains('\"')) {$ScriptString = $ScriptString.Replace('\"','"')}
# Choose random syntax for invoking powershell.exe's StdIn.
$PowerShellClip = Out-RandomClipboardInvokeSyntax
# Since we're embedding $PowerShellClip syntax one more process deep we need to double-escape & < > and | characters for cmd.exe.
ForEach($Char in @('<','>','|','&'))
{
# Remove single escaping and then escape all characters. This will handle single-escaped and not-escaped characters.
If($PowerShellClip.Contains("^$Char"))
{
$PowerShellClip = $PowerShellClip.Replace("^$Char","^^^$Char")
}
}
# If this launcher is run in PowerShell 2.0 then Single-Threaded Apartment must be specified with -st or -sta.
# Otherwise you will get the following error: "Current thread must be set to single thread apartment (STA) mode before OLE calls can be made."
# Since Invoke-Obfuscation output is designed to run on any PowerShell version then for this launcher we will add the -st/-sta flag to $PowerShellFlags.
# If selected then the -Command flag needs to remain last (where it currently is).
$CommandFlagValue = $NULL
If($PSBoundParameters['Command'] -OR $Command)
{
$UpperLimit = $PowerShellFlagsArray.Count-1
$CommandFlagValue = $PowerShellFlagsArray[$PowerShellFlagsArray.Count-1]
}
Else
{
$UpperLimit = $PowerShellFlagsArray.Count
}
# Re-extract PowerShellFlags so we can add in -st/-sta and then reorder (maintaining command flag at the end if present).
$PowerShellFlags = @()
For($i=0; $i -lt $UpperLimit; $i++)
{
$PowerShellFlags += $PowerShellFlagsArray[$i]
}
# Add in -st/-sta to PowerShellFlags.
$PowerShellFlags += (Get-Random -Input @('-st','-sta'))
# Randomize the order of the command-line arguments.
# This is to prevent the Blue Team from placing false hope in simple signatures for consistent ordering of these arguments.
If($PowerShellFlags.Count -gt 1)
{
$PowerShellFlags = Get-Random -InputObject $PowerShellFlags -Count $PowerShellFlags.Count