-
Notifications
You must be signed in to change notification settings - Fork 770
/
Out-ObfuscatedTokenCommand.ps1
2101 lines (1614 loc) · 208 KB
/
Out-ObfuscatedTokenCommand.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-ObfuscatedTokenCommand
{
<#
.SYNOPSIS
Master function that orchestrates the tokenization and application of all token-based obfuscation functions to provided PowerShell script.
Invoke-Obfuscation Function: Out-ObfuscatedTokenCommand
Author: Daniel Bohannon (@danielhbohannon)
License: Apache License, Version 2.0
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Out-ObfuscatedTokenCommand orchestrates the tokenization and application of all token-based obfuscation functions to provided PowerShell script and places obfuscated tokens back into the provided PowerShell script to evade detection by simple IOCs and process execution monitoring relying solely on command-line arguments. If no $TokenTypeToObfuscate is defined then Out-ObfuscatedTokenCommand will automatically perform ALL token obfuscation functions in random order at the highest obfuscation level.
.PARAMETER ScriptBlock
Specifies a scriptblock containing your payload.
.PARAMETER Path
Specifies the path to your payload.
.PARAMETER TokenTypeToObfuscate
(Optional) Specifies the token type to obfuscate ('Command', 'CommandArgument', 'Comment', 'Member', 'String', 'Type', 'Variable', 'RandomWhitespace'). If not defined then Out-ObfuscatedTokenCommand will automatically perform ALL token obfuscation functions in random order at the highest obfuscation level.
.PARAMETER ObfuscationLevel
(Optional) Specifies the obfuscation level for the given TokenTypeToObfuscate. If not defined then Out-ObfuscatedTokenCommand will automatically perform obfuscation function at the highest available obfuscation level.
Each token has different available obfuscation levels:
'Argument' 1-4
'Command' 1-3
'Comment' 1
'Member' 1-4
'String' 1-2
'Type' 1-2
'Variable' 1
'Whitespace' 1
'All' 1
.EXAMPLE
C:\PS> Out-ObfuscatedTokenCommand {Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green}
.( "{0}{2}{1}" -f'Write','t','-Hos' ) ( 'Hell' + 'o ' +'Wor'+ 'ld!' ) -ForegroundColor ( "{1}{0}" -f 'een','Gr') ; .( "{1}{2}{0}"-f'ost','Writ','e-H' ) ( 'O' + 'bfusca'+ 't' + 'ion Rocks' + '!') -ForegroundColor ( "{1}{0}"-f'een','Gr' )
.NOTES
Out-ObfuscatedTokenCommand orchestrates the tokenization and application of all token-based obfuscation functions to provided PowerShell script and places obfuscated tokens back into the provided PowerShell script to evade detection by simple IOCs and process execution monitoring relying solely on command-line arguments. If no $TokenTypeToObfuscate is defined then Out-ObfuscatedTokenCommand will automatically perform ALL token obfuscation functions in random order at the highest obfuscation level.
This is a personal project developed by Daniel Bohannon while an employee at MANDIANT, A FireEye Company.
.LINK
http://www.danielbohannon.com
#>
[CmdletBinding( DefaultParameterSetName = 'FilePath')] Param (
[Parameter(Position = 0, ValueFromPipeline = $True, ParameterSetName = 'ScriptBlock')]
[ValidateNotNullOrEmpty()]
[ScriptBlock]
$ScriptBlock,
[Parameter(Position = 0, ParameterSetName = 'FilePath')]
[ValidateNotNullOrEmpty()]
[String]
$Path,
[ValidateSet('Member', 'Command', 'CommandArgument', 'String', 'Variable', 'Type', 'RandomWhitespace', 'Comment')]
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty()]
[String]
$TokenTypeToObfuscate,
[Parameter(Position = 2)]
[ValidateNotNullOrEmpty()]
[Int]
$ObfuscationLevel = 10 # Default to highest obfuscation level if $ObfuscationLevel isn't defined
)
# Either convert ScriptBlock to a String or convert script at $Path to a String.
If($PSBoundParameters['Path'])
{
Get-ChildItem $Path -ErrorAction Stop | Out-Null
$ScriptString = [IO.File]::ReadAllText((Resolve-Path $Path))
}
Else
{
$ScriptString = [String]$ScriptBlock
}
# If $TokenTypeToObfuscate was not defined then we will automate randomly calling all available obfuscation functions in Out-ObfuscatedTokenCommand.
If($TokenTypeToObfuscate.Length -eq 0)
{
# All available obfuscation token types (minus 'String') currently supported in Out-ObfuscatedTokenCommand.
# 'Comment' and 'String' will be manually added first and second respectively for reasons defined below.
# 'RandomWhitespace' will be manually added last for reasons defined below.
$ObfuscationChoices = @()
$ObfuscationChoices += 'Member'
$ObfuscationChoices += 'Command'
$ObfuscationChoices += 'CommandArgument'
$ObfuscationChoices += 'Variable'
$ObfuscationChoices += 'Type'
# Create new array with 'String' plus all obfuscation types above in random order.
$ObfuscationTypeOrder = @()
# Run 'Comment' first since it will be the least number of tokens to iterate through, and comments may be introduced as obfuscation technique in future revisions.
$ObfuscationTypeOrder += 'Comment'
# Run 'String' second since otherwise we will have unnecessary command bloat since other obfuscation functions create additional strings.
$ObfuscationTypeOrder += 'String'
$ObfuscationTypeOrder += (Get-Random -Input $ObfuscationChoices -Count $ObfuscationChoices.Count)
# Apply each randomly-ordered $ObfuscationType from above step.
ForEach($ObfuscationType in $ObfuscationTypeOrder)
{
$ScriptString = Out-ObfuscatedTokenCommand ([ScriptBlock]::Create($ScriptString)) $ObfuscationType $ObfuscationLevel
}
Return $ScriptString
}
# Parse out and obfuscate tokens (in reverse to make indexes simpler for adding in obfuscated tokens).
$Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null)
# Handle fringe case of retrieving count of all tokens used when applying random whitespace.
$TokenCount = ([System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null) | Where-Object {$_.Type -eq $TokenTypeToObfuscate}).Count
$TokensForInsertingWhitespace = @('Operator','GroupStart','GroupEnd','StatementSeparator')
# Script-wide variable ($Script:TypeTokenScriptStringGrowth) to speed up Type token obfuscation by avoiding having to re-tokenize ScriptString for every token.
# This is because we are appending variable instantiation at the beginning of each iteration of ScriptString.
# Additional script-wide variable ($Script:TypeTokenVariableArray) allows each unique Type token to only be set once per command/script for efficiency and to create less items to create indicators off of.
$Script:TypeTokenScriptStringGrowth = 0
$Script:TypeTokenVariableArray = @()
If($TokenTypeToObfuscate -eq 'RandomWhitespace')
{
# If $TokenTypeToObfuscate='RandomWhitespace' then calculate $TokenCount for output by adding token count for all tokens in $TokensForInsertingWhitespace.
$TokenCount = 0
ForEach($TokenForInsertingWhitespace in $TokensForInsertingWhitespace)
{
$TokenCount += ([System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null) | Where-Object {$_.Type -eq $TokenForInsertingWhitespace}).Count
}
}
# Handle fringe case of outputting verbiage consistent with options presented in Invoke-Obfuscation.
If($TokenCount -gt 0)
{
# To be consistent with verbiage in Invoke-Obfuscation we will print Argument/Whitespace instead of CommandArgument/RandomWhitespace.
$TokenTypeToObfuscateToPrint = $TokenTypeToObfuscate
If($TokenTypeToObfuscateToPrint -eq 'CommandArgument') {$TokenTypeToObfuscateToPrint = 'Argument'}
If($TokenTypeToObfuscateToPrint -eq 'RandomWhitespace') {$TokenTypeToObfuscateToPrint = 'Whitespace'}
If($TokenCount -gt 1) {$Plural = 's'}
Else {$Plural = ''}
# Output verbiage concerning which $TokenType is currently being obfuscated and how many tokens of each type are left to obfuscate.
# This becomes more important when obfuscated large scripts where obfuscation can take several minutes due to all of the randomization steps.
Write-Host "`n[*] Obfuscating $($TokenCount)" -NoNewLine
Write-Host " $TokenTypeToObfuscateToPrint" -NoNewLine -ForegroundColor Yellow
Write-Host " token$Plural."
}
# Variables for outputting status of token processing for large token counts when obfuscating large scripts.
$Counter = $TokenCount
$OutputCount = 0
$IterationsToOutputOn = 100
$DifferenceForEvenOutput = $TokenCount % $IterationsToOutputOn
For($i=$Tokens.Count-1; $i -ge 0; $i--)
{
$Token = $Tokens[$i]
# Extra output for large scripts with several thousands tokens (like Invoke-Mimikatz).
If(($TokenCount -gt $IterationsToOutputOn*2) -AND ((($TokenCount-$Counter)-($OutputCount*$IterationsToOutputOn)) -eq ($IterationsToOutputOn+$DifferenceForEvenOutput)))
{
$OutputCount++
$ExtraWhitespace = ' '*(([String]($TokenCount)).Length-([String]$Counter).Length)
If($Counter -gt 0)
{
Write-Host "[*] $ExtraWhitespace$Counter" -NoNewLine
Write-Host " $TokenTypeToObfuscateToPrint" -NoNewLine -ForegroundColor Yellow
Write-Host " tokens remaining to obfuscate."
}
}
$ObfuscatedToken = ""
If(($Token.Type -eq 'String') -AND ($TokenTypeToObfuscate.ToLower() -eq 'string'))
{
$Counter--
# If String $Token immediately follows a period (and does not begin $ScriptString) then do not obfuscate as a String.
# In this scenario $Token is originally a Member token that has quotes added to it.
# E.g. both InvokeCommand and InvokeScript in $ExecutionContext.InvokeCommand.InvokeScript
If(($Token.Start -gt 0) -AND ($ScriptString.SubString($Token.Start-1,1) -eq '.'))
{
Continue
}
# Set valid obfuscation levels for current token type.
$ValidObfuscationLevels = @(0,1,2)
# If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
# The below Parameter Binding Validation Attributes cannot have their string values formatted with the -f format operator unless treated as a scriptblock.
# When we find strings following these Parameter Binding Validation Attributes then if we are using a -f format operator we will treat the result as a scriptblock.
# Source: https://technet.microsoft.com/en-us/library/hh847743.aspx
$ParameterValidationAttributesToTreatStringAsScriptblock = @()
$ParameterValidationAttributesToTreatStringAsScriptblock += 'alias'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'allownull'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'allowemptystring'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'allowemptycollection'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'validatecount'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'validatelength'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'validatepattern'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'validaterange'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'validatescript'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'validateset'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'validatenotnull'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'validatenotnullorempty'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'helpmessage'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'outputtype'
$ParameterValidationAttributesToTreatStringAsScriptblock += 'diagnostics.codeanalysis.suppressmessageattribute'
Switch($ObfuscationLevel)
{
0 {Continue}
1 {$ScriptString = Out-ObfuscatedStringTokenLevel1 $ScriptString $Token 1}
2 {$ScriptString = Out-ObfuscatedStringTokenLevel1 $ScriptString $Token 2}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for token type $($Token.Type)."; Exit;}
}
}
ElseIf(($Token.Type -eq 'Member') -AND ($TokenTypeToObfuscate.ToLower() -eq 'member'))
{
$Counter--
# Set valid obfuscation levels for current token type.
$ValidObfuscationLevels = @(0,1,2,3,4)
# If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
# The below Parameter Attributes cannot be obfuscated like other Member Tokens, so we will only randomize the case of these tokens.
# Source 1: https://technet.microsoft.com/en-us/library/hh847743.aspx
$MemberTokensToOnlyRandomCase = @()
$MemberTokensToOnlyRandomCase += 'mandatory'
$MemberTokensToOnlyRandomCase += 'position'
$MemberTokensToOnlyRandomCase += 'parametersetname'
$MemberTokensToOnlyRandomCase += 'valuefrompipeline'
$MemberTokensToOnlyRandomCase += 'valuefrompipelinebypropertyname'
$MemberTokensToOnlyRandomCase += 'valuefromremainingarguments'
$MemberTokensToOnlyRandomCase += 'helpmessage'
$MemberTokensToOnlyRandomCase += 'alias'
# Source 2: https://technet.microsoft.com/en-us/library/hh847872.aspx
$MemberTokensToOnlyRandomCase += 'confirmimpact'
$MemberTokensToOnlyRandomCase += 'defaultparametersetname'
$MemberTokensToOnlyRandomCase += 'helpuri'
$MemberTokensToOnlyRandomCase += 'supportspaging'
$MemberTokensToOnlyRandomCase += 'supportsshouldprocess'
$MemberTokensToOnlyRandomCase += 'positionalbinding'
$MemberTokensToOnlyRandomCase += 'ignorecase'
Switch($ObfuscationLevel)
{
0 {Continue}
1 {$ScriptString = Out-RandomCaseToken $ScriptString $Token}
2 {$ScriptString = Out-ObfuscatedWithTicks $ScriptString $Token}
3 {$ScriptString = Out-ObfuscatedMemberTokenLevel3 $ScriptString $Tokens $i 1}
4 {$ScriptString = Out-ObfuscatedMemberTokenLevel3 $ScriptString $Tokens $i 2}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for token type $($Token.Type)."; Exit;}
}
}
ElseIf(($Token.Type -eq 'CommandArgument') -AND ($TokenTypeToObfuscate.ToLower() -eq 'commandargument'))
{
$Counter--
# Set valid obfuscation levels for current token type.
$ValidObfuscationLevels = @(0,1,2,3,4)
# If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
Switch($ObfuscationLevel)
{
0 {Continue}
1 {$ScriptString = Out-RandomCaseToken $ScriptString $Token}
2 {$ScriptString = Out-ObfuscatedWithTicks $ScriptString $Token}
3 {$ScriptString = Out-ObfuscatedCommandArgumentTokenLevel3 $ScriptString $Token 1}
4 {$ScriptString = Out-ObfuscatedCommandArgumentTokenLevel3 $ScriptString $Token 2}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for token type $($Token.Type)."; Exit;}
}
}
ElseIf(($Token.Type -eq 'Command') -AND ($TokenTypeToObfuscate.ToLower() -eq 'command'))
{
$Counter--
# Set valid obfuscation levels for current token type.
$ValidObfuscationLevels = @(0,1,2,3)
# If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
# If a variable is encapsulated in curly braces (e.g. ${ExecutionContext}) then the string inside is treated as a Command token.
# So we will force tick obfuscation (option 1) instead of splatting (option 2) as that would cause errors.
If(($Token.Start -gt 1) -AND ($ScriptString.SubString($Token.Start-1,1) -eq '{') -AND ($ScriptString.SubString($Token.Start+$Token.Length,1) -eq '}'))
{
$ObfuscationLevel = 1
}
Switch($ObfuscationLevel)
{
0 {Continue}
1 {$ScriptString = Out-ObfuscatedWithTicks $ScriptString $Token}
2 {$ScriptString = Out-ObfuscatedCommandTokenLevel2 $ScriptString $Token 1}
3 {$ScriptString = Out-ObfuscatedCommandTokenLevel2 $ScriptString $Token 2}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for token type $($Token.Type)."; Exit;}
}
}
ElseIf(($Token.Type -eq 'Variable') -AND ($TokenTypeToObfuscate.ToLower() -eq 'variable'))
{
$Counter--
# Set valid obfuscation levels for current token type.
$ValidObfuscationLevels = @(0,1)
# If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
Switch($ObfuscationLevel)
{
0 {Continue}
1 {$ScriptString = Out-ObfuscatedVariableTokenLevel1 $ScriptString $Token}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for token type $($Token.Type)."; Exit;}
}
}
ElseIf(($Token.Type -eq 'Type') -AND ($TokenTypeToObfuscate.ToLower() -eq 'type'))
{
$Counter--
# Set valid obfuscation levels for current token type.
$ValidObfuscationLevels = @(0,1,2)
# If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
# The below Type value substrings are part of Types that cannot be direct Type casted, so we will not perform direct Type casting on Types containing these values.
$TypesThatCannotByDirectTypeCasted = @()
$TypesThatCannotByDirectTypeCasted += 'directoryservices.accountmanagement.'
$TypesThatCannotByDirectTypeCasted += 'windows.clipboard'
Switch($ObfuscationLevel)
{
0 {Continue}
1 {$ScriptString = Out-ObfuscatedTypeToken $ScriptString $Token 1}
2 {$ScriptString = Out-ObfuscatedTypeToken $ScriptString $Token 2}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for token type $($Token.Type)."; Exit;}
}
}
ElseIf(($TokensForInsertingWhitespace -Contains $Token.Type) -AND ($TokenTypeToObfuscate.ToLower() -eq 'randomwhitespace'))
{
$Counter--
# Set valid obfuscation levels for current token type.
$ValidObfuscationLevels = @(0,1)
# If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
Switch($ObfuscationLevel)
{
0 {Continue}
1 {$ScriptString = Out-RandomWhitespace $ScriptString $Tokens $i}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for token type $($Token.Type)."; Exit;}
}
}
ElseIf(($Token.Type -eq 'Comment') -AND ($TokenTypeToObfuscate.ToLower() -eq 'comment'))
{
$Counter--
# Set valid obfuscation levels for current token type.
$ValidObfuscationLevels = @(0,1)
# If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
Switch($ObfuscationLevel)
{
0 {Continue}
1 {$ScriptString = Out-RemoveComments $ScriptString $Token}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for token type $($Token.Type)."; Exit;}
}
}
}
Return $ScriptString
}
Function Out-ObfuscatedStringTokenLevel1
{
<#
.SYNOPSIS
Obfuscates string token by randomly concatenating the string in-line.
Invoke-Obfuscation Function: Out-ObfuscatedStringTokenLevel1
Author: Daniel Bohannon (@danielhbohannon)
License: Apache License, Version 2.0
Required Dependencies: Out-StringDelimitedAndConcatenated, Out-StringDelimitedConcatenatedAndReordered (both located in Out-ObfuscatedStringCommand.ps1)
Optional Dependencies: None
.DESCRIPTION
Out-ObfuscatedStringTokenLevel1 obfuscates a given string token and places it back into the provided PowerShell script to evade detection by simple IOCs and process execution monitoring relying solely on command-line arguments. For the most complete obfuscation all tokens in a given PowerShell script or script block (cast as a string object) should be obfuscated via the corresponding obfuscation functions and desired obfuscation levels in Out-ObfuscatedTokenCommand.ps1.
.PARAMETER ScriptString
Specifies the string containing your payload.
.PARAMETER Token
Specifies the token to obfuscate.
.PARAMETER ObfuscationLevel
Specifies whether to 1) Concatenate or 2) Reorder the String token value.
.EXAMPLE
C:\PS> $ScriptString = "Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green"
C:\PS> $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null) | Where-Object {$_.Type -eq 'String'}
C:\PS> For($i=$Tokens.Count-1; $i -ge 0; $i--) {$Token = $Tokens[$i]; $ScriptString = Out-ObfuscatedStringTokenLevel1 $ScriptString $Token 1}
C:\PS> $ScriptString
Write-Host ('Hello'+' W'+'orl'+'d!') -ForegroundColor Green; Write-Host ('Obfuscation R'+'oc'+'k'+'s'+'!') -ForegroundColor Green
C:\PS> $ScriptString = "Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green"
C:\PS> $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null) | Where-Object {$_.Type -eq 'String'}
C:\PS> For($i=$Tokens.Count-1; $i -ge 0; $i--) {$Token = $Tokens[$i]; $ScriptString = Out-ObfuscatedStringTokenLevel1 $ScriptString $Token 2}
C:\PS> $ScriptString
Write-Host ("{2}{3}{0}{1}" -f 'Wo','rld!','Hel','lo ') -ForegroundColor Green; Write-Host ("{4}{0}{3}{2}{1}"-f 'bfusca','cks!','Ro','tion ','O') -ForegroundColor Green
.NOTES
This cmdlet is most easily used by passing a script block or file path to a PowerShell script into the Out-ObfuscatedTokenCommand function with the corresponding token type and obfuscation level since Out-ObfuscatedTokenCommand will handle token parsing, reverse iterating and passing tokens into this current function.
C:\PS> Out-ObfuscatedTokenCommand {Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green} 'String' 1
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)]
[ValidateNotNullOrEmpty()]
[String]
$ScriptString,
[Parameter(Position = 1, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSToken]
$Token,
[Parameter(Position = 2, Mandatory = $True)]
[ValidateSet(1, 2)]
[Int]
$ObfuscationLevel
)
$EncapsulateAsScriptBlockInsteadOfParentheses = $FALSE
# Extract substring to look for parameter binding values to check against $ParameterValidationAttributesToTreatStringAsScriptblock set in the beginning of this script.
$SubStringLength = 25
If($Token.Start -lt $SubStringLength)
{
$SubStringLength = $Token.Start
}
$SubString = $ScriptString.SubString($Token.Start-$SubStringLength,$SubStringLength).Replace(' ','').Replace("`t",'').Replace("`n",'')
$SubStringLength = 5
If($SubString.Length -lt $SubStringLength)
{
$SubStringLength = $SubString.Length
}
$SubString = $SubString.SubString($SubString.Length-$SubStringLength,$SubStringLength)
# If dealing with ObfuscationLevel -gt 1 (e.g. -f format operator), perform check to see if we're dealing with a string that is part of a Parameter Binding.
If(($ObfuscationLevel -gt 1) -AND ($Token.Start -gt 5) -AND ($SubString.Contains('(') -OR $SubString.Contains(',')) -AND $ScriptString.SubString(0,$Token.Start).Contains('[') -AND $ScriptString.SubString(0,$Token.Start).Contains('('))
{
# Gather substring preceding the current String token to see if we need to treat the obfuscated string as a scriptblock.
$ParameterBindingName = $ScriptString.SubString(0,$Token.Start)
$ParameterBindingName = $ParameterBindingName.SubString(0,$ParameterBindingName.LastIndexOf('('))
$ParameterBindingName = $ParameterBindingName.SubString($ParameterBindingName.LastIndexOf('[')+1).Trim()
# Filter out values that are not Parameter Binding due to contain whitespace, some special characters, etc.
If(!$ParameterBindingName.Contains(' ') -AND !$ParameterBindingName.Contains(']') -AND !($ParameterBindingName.Length -eq 0))
{
# If we have a match then set boolean to True so result will be encapsulated with curly braces at the end of this function.
If($ParameterValidationAttributesToTreatStringAsScriptblock -Contains $ParameterBindingName.ToLower())
{
$EncapsulateAsScriptBlockInsteadOfParentheses = $TRUE
}
}
}
ElseIf(($ObfuscationLevel -gt 1) -AND ($Token.Start -gt 5) -AND $ScriptString.SubString($Token.Start-5,5).Contains('='))
{
# If dealing with ObfuscationLevel -gt 1 (e.g. -f format operator), perform check to see if we're dealing with a string that is part of a Parameter Binding.
ForEach($Parameter in $ParameterValidationAttributesToTreatStringAsScriptblock)
{
$SubStringLength = $Parameter.Length
# Add 10 more to $SubStringLength in case there is excess whitespace between the = sign.
$SubStringLength += 10
# Shorten substring length in case there is not enough room depending on the location of the token in the $ScriptString.
If($Token.Start -lt $SubStringLength)
{
$SubStringLength = $Token.Start
}
# Extract substring to compare against $EncapsulateAsScriptBlockInsteadOfParentheses.
$SubString = $ScriptString.SubString($Token.Start-$SubStringLength,$SubStringLength+1).Trim()
# If we have a match then set boolean to True so result will be encapsulated with curly braces at the end of this function.
If($SubString -Match "$Parameter.*=")
{
$EncapsulateAsScriptBlockInsteadOfParentheses = $TRUE
}
}
}
# Do nothing if the token has length <= 1 (e.g. Write-Host "", single-character tokens, etc.).
If($Token.Content.Length -le 1) {Return $ScriptString}
# Do nothing if the token has length <= 3 and $ObfuscationLevel is 2 (reordering).
If(($Token.Content.Length -le 3) -AND $ObfuscationLevel -eq 2) {Return $ScriptString}
# Do nothing if $Token.Content already contains a { or } to avoid parsing errors when { and } are introduced into substrings.
If($Token.Content.Contains('{') -OR $Token.Content.Contains('}')) {Return $ScriptString}
# If the Token is 'invoke' then do nothing. This is because .invoke() is treated as a member but ."invoke"() is treated as a string.
If($Token.Content.ToLower() -eq 'invoke') {Return $ScriptString}
# Set $Token.Content in a separate variable so it can be modified since Content is a ReadOnly property of $Token.
$TokenContent = $Token.Content
# Tokenizer removes ticks from strings, but we want to keep them. So we will replace the contents of $Token.Content with the manually extracted token data from the original $ScriptString.
$TokenContent = $ScriptString.SubString($Token.Start+1,$Token.Length-2)
# If a variable is present in a string, more work needs to be done to extract from string. Warning maybe should be thrown either way.
# Must come back and address this after vacation.
# Variable can be displaying or setting: "setting var like $($var='secret') and now displaying $var"
# For now just split on whitespace instead of passing to Out-Concatenated
If($TokenContent.Contains('$') -OR $TokenContent.Contains('`'))
{
$ObfuscatedToken = ''
$Counter = 0
# If special use case is met then don't substring the current Token to avoid errors.
# The special cases involve a double-quoted string containing a variable or a string-embedded-command that contains whitespace in it.
# E.g. "string ${var name with whitespace} string" or "string $(gci *whitespace_in_command*) string"
$TokenContentSplit = $TokenContent.Split(' ')
$ContainsVariableSpecialCases = (($TokenContent.Contains('$(') -OR $TokenContent.Contains('${')) -AND ($ScriptString[$Token.Start] -eq '"'))
If($ContainsVariableSpecialCases)
{
$TokenContentSplit = $TokenContent
}
ForEach($SubToken in $TokenContentSplit)
{
$Counter++
$ObfuscatedSubToken = $SubToken
# Determine if use case of variable inside of double quotes is present as this will be handled differently below.
$SpecialCaseContainsVariableInDoubleQuotes = (($ObfuscatedSubToken.Contains('$') -OR $ObfuscatedSubToken.Contains('`')) -AND ($ScriptString[$Token.Start] -eq '"'))
# Since splitting on whitespace removes legitimate whitespace we need to add back whitespace for all but the final subtoken.
If($Counter -lt $TokenContent.Split(' ').Count)
{
$ObfuscatedSubToken = $ObfuscatedSubToken + ' '
}
# Concatenate $SubToken if it's long enough to be concatenated.
If(($ObfuscatedSubToken.Length -gt 1) -AND !($SpecialCaseContainsVariableInDoubleQuotes))
{
# Concatenate each $SubToken via Out-StringDelimitedAndConcatenated so it will handle any replacements for special characters.
# Define -PassThru flag so an invocation is not added to $ObfuscatedSubToken.
$ObfuscatedSubToken = Out-StringDelimitedAndConcatenated $ObfuscatedSubToken -PassThru
# Evenly trim leading/trailing parentheses.
While($ObfuscatedSubToken.StartsWith('(') -AND $ObfuscatedSubToken.EndsWith(')'))
{
$ObfuscatedSubToken = ($ObfuscatedSubToken.SubString(1,$ObfuscatedSubToken.Length-2)).Trim()
}
}
Else
{
If($SpecialCaseContainsVariableInDoubleQuotes)
{
$ObfuscatedSubToken = '"' + $ObfuscatedSubToken + '"'
}
ElseIf($ObfuscatedSubToken.Contains("'") -OR $ObfuscatedSubToken.Contains('$'))
{
$ObfuscatedSubToken = '"' + $ObfuscatedSubToken + '"'
}
Else
{
$ObfuscatedSubToken = "'" + $ObfuscatedSubToken + "'"
}
}
# Add obfuscated/trimmed $SubToken back to $ObfuscatedToken if a Replace operation was used.
If($ObfuscatedSubToken -eq $PreObfuscatedSubToken)
{
# Same, so don't encapsulate. And maybe take off trailing whitespace?
}
ElseIf($ObfuscatedSubToken.ToLower().Contains("replace"))
{
$ObfuscatedToken += ( '(' + $ObfuscatedSubToken + ')' + '+' )
}
Else
{
$ObfuscatedToken += ($ObfuscatedSubToken + '+' )
}
}
# Trim extra whitespace and trailing + from $ObfuscatedToken.
$ObfuscatedToken = $ObfuscatedToken.Trim(' + ')
}
Else
{
# For Parameter Binding the value has to either be plain concatenation or must be a scriptblock in which case we will encapsulate with {} instead of ().
# The encapsulation will occur later in the function. At this point we're just setting the boolean variable $EncapsulateAsScriptBlockInsteadOfParentheses.
# Actual error that led to this is: "Attribute argument must be a constant or a script block."
# ALLOWED :: [CmdletBinding(DefaultParameterSetName={"{1}{0}{2}"-f'd','DumpCre','s'})]
# NOT ALLOWED :: [CmdletBinding(DefaultParameterSetName=("{1}{0}{2}"-f'd','DumpCre','s'))]
$SubStringStart = 30
If($Token.Start -lt $SubStringStart)
{
$SubStringStart = $Token.Start
}
$SubString = $ScriptString.SubString($Token.Start-$SubStringStart,$SubStringStart).ToLower()
If($SubString.Contains('defaultparametersetname') -AND $SubString.Contains('='))
{
$EncapsulateAsScriptBlockInsteadOfParentheses = $TRUE
}
If($SubString.Contains('parametersetname') -OR $SubString.Contains('confirmimpact') -AND !$SubString.Contains('defaultparametersetname') -AND $SubString.Contains('='))
{
# For strings in ParameterSetName parameter binding (but not DefaultParameterSetName) then we will only obfuscate with tick marks.
# Otherwise we may get errors depending on the version of PowerShell being run.
$ObfuscatedToken = $Token.Content
$TokenForTicks = [System.Management.Automation.PSParser]::Tokenize($ObfuscatedToken,[ref]$null)
$ObfuscatedToken = '"' + (Out-ObfuscatedWithTicks $ObfuscatedToken $TokenForTicks[0]) + '"'
}
Else
{
# User input $ObfuscationLevel (1-2) will choose between concatenating String token value string or reordering it with the -f format operator.
# I am leaving out Out-ObfuscatedStringCommand's option 3 since that may introduce a Type token unnecessarily ([Regex]).
Switch($ObfuscationLevel)
{
1 {$ObfuscatedToken = Out-StringDelimitedAndConcatenated $TokenContent -PassThru}
2 {$ObfuscatedToken = Out-StringDelimitedConcatenatedAndReordered $TokenContent -PassThru}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for String Token Obfuscation."; Exit}
}
}
# Evenly trim leading/trailing parentheses.
While($ObfuscatedToken.StartsWith('(') -AND $ObfuscatedToken.EndsWith(')'))
{
$TrimmedObfuscatedToken = ($ObfuscatedToken.SubString(1,$ObfuscatedToken.Length-2)).Trim()
# Check if the parentheses are balanced before permenantly trimming
$Balanced = $True
$Counter = 0
ForEach($char in $TrimmedObfuscatedToken.ToCharArray()) {
If($char -eq '(') {
$Counter = $Counter + 1
}
ElseIf($char -eq ')') {
If($Counter -eq 0) {
$Balanced = $False
break
}
Else {
$Counter = $Counter - 1
}
}
}
# If parantheses are balanced, we can safely trim the parentheses
If($Balanced -and $Counter -eq 0) {
$ObfuscatedToken = $TrimmedObfuscatedToken
}
# If parentheses cannot be trimmed, break out of loop
Else {
break
}
}
}
# Encapsulate concatenated string with parentheses to avoid garbled string in scenarios like Write-* methods.
If($ObfuscatedToken.Length -ne ($TokenContent.Length + 2))
{
# For Parameter Binding the value has to either be plain concatenation or must be a scriptblock in which case we will encapsulate with {} instead of ().
# Actual error that led to this is: "Attribute argument must be a constant or a script block."
# ALLOWED :: [CmdletBinding(DefaultParameterSetName={"{1}{0}{2}"-f'd','DumpCre','s'})]
# NOT ALLOWED :: [CmdletBinding(DefaultParameterSetName=("{1}{0}{2}"-f'd','DumpCre','s'))]
If($EncapsulateAsScriptBlockInsteadOfParentheses)
{
$ObfuscatedToken = '{' + $ObfuscatedToken + '}'
}
ElseIf(($ObfuscatedToken.Length -eq $TokenContent.Length + 5) -AND $ObfuscatedToken.SubString(2,$ObfuscatedToken.Length-4) -eq ($TokenContent + ' '))
{
If($ContainsVariableSpecialCases) {
$ObfuscatedToken = '"' + $TokenContent + '"'
}
Else {
$ObfuscatedToken = $TokenContent
}
}
ElseIf($ObfuscatedToken.StartsWith('"') -AND $ObfuscatedToken.EndsWith('"') -AND !$ObfuscatedToken.Contains('+') -AND !$ObfuscatedToken.Contains('-f'))
{
# No encapsulation is needed for string obfuscation that is only double quotes and tick marks for ParameterSetName (and not DefaultParameterSetName).
$ObfuscatedToken = $ObfuscatedToken
}
ElseIf($ObfuscatedToken.Length -ne $TokenContent.Length + 2)
{
$ObfuscatedToken = '(' + $ObfuscatedToken + ')'
}
}
# Remove redundant blank string concatenations introduced by special use case of $ inside double quotes.
If($ObfuscatedToken.EndsWith("+''") -OR $ObfuscatedToken.EndsWith('+""'))
{
$ObfuscatedToken = $ObfuscatedToken.SubString(0,$ObfuscatedToken.Length-3)
}
# Handle dangling ticks from string concatenation where a substring ends in a tick. Move this tick to the beginning of the following substring.
If($ObfuscatedToken.Contains('`'))
{
If($ObfuscatedToken.Contains('`"+"'))
{
$ObfuscatedToken = $ObfuscatedToken.Replace('`"+"','"+"`')
}
If($ObfuscatedToken.Contains("``'+'"))
{
$ObfuscatedToken = $ObfuscatedToken.Replace("``'+'","'+'``")
}
}
# Add the obfuscated token back to $ScriptString.
# If string is preceded by a . or :: and followed by ( then it is a Member token encapsulated by quotes and now treated as a string.
# We must add a .Invoke to the concatenated Member string to avoid syntax errors.
If((($Token.Start -gt 0) -AND ($ScriptString.SubString($Token.Start-1,1) -eq '.')) -OR (($Token.Start -gt 1) -AND ($ScriptString.SubString($Token.Start-2,2) -eq '::')) -AND ($ScriptString.SubString($Token.Start+$Token.Length,1) -eq '('))
{
$ScriptString = $ScriptString.SubString(0,$Token.Start) + $ObfuscatedToken + '.Invoke' + $ScriptString.SubString($Token.Start+$Token.Length)
}
Else
{
$ScriptString = $ScriptString.SubString(0,$Token.Start) + $ObfuscatedToken + $ScriptString.SubString($Token.Start+$Token.Length)
}
Return $ScriptString
}
Function Out-ObfuscatedCommandTokenLevel2
{
<#
.SYNOPSIS
Obfuscates command token by converting it to a concatenated string and using splatting to invoke the command.
Invoke-Obfuscation Function: Out-ObfuscatedCommandTokenLevel2
Author: Daniel Bohannon (@danielhbohannon)
License: Apache License, Version 2.0
Required Dependencies: Out-StringDelimitedAndConcatenated, Out-StringDelimitedConcatenatedAndReordered (both located in Out-ObfuscatedStringCommand.ps1)
Optional Dependencies: None
.DESCRIPTION
Out-ObfuscatedCommandTokenLevel2 obfuscates a given command token and places it back into the provided PowerShell script to evade detection by simple IOCs and process execution monitoring relying solely on command-line arguments. For the most complete obfuscation all tokens in a given PowerShell script or script block (cast as a string object) should be obfuscated via the corresponding obfuscation functions and desired obfuscation levels in Out-ObfuscatedTokenCommand.ps1.
.PARAMETER ScriptString
Specifies the string containing your payload.
.PARAMETER Token
Specifies the token to obfuscate.
.PARAMETER ObfuscationLevel
Specifies whether to 1) Concatenate or 2) Reorder the splatted Command token value.
.EXAMPLE
C:\PS> $ScriptString = "Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green"
C:\PS> $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null) | Where-Object {$_.Type -eq 'Command'}
C:\PS> For($i=$Tokens.Count-1; $i -ge 0; $i--) {$Token = $Tokens[$i]; $ScriptString = Out-ObfuscatedCommandTokenLevel2 $ScriptString $Token 1}
C:\PS> $ScriptString
&('Wr'+'itE-'+'HOSt') 'Hello World!' -ForegroundColor Green; .('WrITe-Ho'+'s'+'t') 'Obfuscation Rocks!' -ForegroundColor Green
C:\PS> $ScriptString = "Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green"
C:\PS> $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null) | Where-Object {$_.Type -eq 'Command'}
C:\PS> For($i=$Tokens.Count-1; $i -ge 0; $i--) {$Token = $Tokens[$i]; $ScriptString = Out-ObfuscatedCommandTokenLevel2 $ScriptString $Token 1}
C:\PS> $ScriptString
&("{1}{0}{2}"-f'h','wRiTE-','ost') 'Hello World!' -ForegroundColor Green; .("{2}{1}{0}" -f'ost','-h','wrIte') 'Obfuscation Rocks!' -ForegroundColor Green
.NOTES
This cmdlet is most easily used by passing a script block or file path to a PowerShell script into the Out-ObfuscatedTokenCommand function with the corresponding token type and obfuscation level since Out-ObfuscatedTokenCommand will handle token parsing, reverse iterating and passing tokens into this current function.
C:\PS> Out-ObfuscatedTokenCommand {Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green} 'Command' 2
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)]
[ValidateNotNullOrEmpty()]
[String]
$ScriptString,
[Parameter(Position = 1, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSToken]
$Token,
[Parameter(Position = 2, Mandatory = $True)]
[ValidateSet(1, 2)]
[Int]
$ObfuscationLevel
)
# Set $Token.Content in a separate variable so it can be modified since Content is a ReadOnly property of $Token.
$TokenContent = $Token.Content
# If ticks are already present in current Token then remove so they will not interfere with string concatenation.
If($TokenContent.Contains('`')) {$TokenContent = $TokenContent.Replace('`','')}
# Convert $Token to character array for easier manipulation.
$TokenArray = [Char[]]$TokenContent
# Randomly upper- and lower-case characters in current token.
$ObfuscatedToken = Out-RandomCase $TokenArray
# User input $ObfuscationLevel (1-2) will choose between concatenating Command token value string (after trimming square brackets) or reordering it with the -F format operator.
# I am leaving out Out-ObfuscatedStringCommand's option 3 since that may introduce a Type token unnecessarily ([Regex]).
Switch($ObfuscationLevel)
{
1 {$ObfuscatedToken = Out-StringDelimitedAndConcatenated $TokenContent -PassThru}
2 {$ObfuscatedToken = Out-StringDelimitedConcatenatedAndReordered $TokenContent -PassThru}
default {Write-Error "An invalid `$ObfuscationLevel value ($ObfuscationLevel) was passed to switch block for Command Token Obfuscation."; Exit}
}
# Evenly trim leading/trailing parentheses.
While($ObfuscatedToken.StartsWith('(') -AND $ObfuscatedToken.EndsWith(')'))
{
$ObfuscatedToken = ($ObfuscatedToken.SubString(1,$ObfuscatedToken.Length-2)).Trim()
}
# Encapsulate $ObfuscatedToken with parentheses.
$ObfuscatedToken = '(' + $ObfuscatedToken + ')'
# Check if the command is already prepended with an invocation operator. If it is then do not add an invocation operator.
# E.g. & powershell -Sta -Command $cmd
# E.g. https://github.com/adaptivethreat/Empire/blob/master/data/module_source/situational_awareness/host/Invoke-WinEnum.ps1#L139
$SubStringLength = 15
If($Token.Start -lt $SubStringLength)
{
$SubStringLength = $Token.Start
}
# Extract substring leading up to the current token.
$SubString = $ScriptString.SubString($Token.Start-$SubStringLength,$SubStringLength).Trim()
# Set $InvokeOperatorAlreadyPresent boolean variable to TRUE if the substring ends with invocation operators . or &
$InvokeOperatorAlreadyPresent = $FALSE
If($SubString.EndsWith('.') -OR $SubString.EndsWith('&'))
{
$InvokeOperatorAlreadyPresent = $TRUE
}
If(!$InvokeOperatorAlreadyPresent)
{
# Randomly choose between the & and . Invoke Operators.
# In certain large scripts where more than one parameter are being passed into a custom function
# (like Add-SignedIntAsUnsigned in Invoke-Mimikatz.ps1) then using . will cause errors but & will not.
# For now we will default to only & if $ScriptString.Length -gt 10000
If($ScriptString.Length -gt 10000) {$RandomInvokeOperator = '&'}
Else {$RandomInvokeOperator = Get-Random -InputObject @('&','.')}
# Add invoke operator (and potentially whitespace) to complete splatting command.
$ObfuscatedToken = $RandomInvokeOperator + $ObfuscatedToken
}
# Add the obfuscated token back to $ScriptString.
$ScriptString = $ScriptString.SubString(0,$Token.Start) + $ObfuscatedToken + $ScriptString.SubString($Token.Start+$Token.Length)
Return $ScriptString
}
Function Out-ObfuscatedWithTicks
{
<#
.SYNOPSIS
HELPER FUNCTION :: Obfuscates any token by randomizing its case and randomly adding ticks. It takes PowerShell special characters into account so you will get `N instead of `n, `T instead of `t, etc.
Invoke-Obfuscation Function: Out-ObfuscatedWithTicks
Author: Daniel Bohannon (@danielhbohannon)
License: Apache License, Version 2.0
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Out-ObfuscatedWithTicks obfuscates given input as a helper function to evade detection by simple IOCs and process execution monitoring relying solely on command-line arguments. For the most complete obfuscation all tokens in a given PowerShell script or script block (cast as a string object) should be obfuscated via the corresponding obfuscation functions and desired obfuscation levels in Out-ObfuscatedTokenCommand.ps1.
.PARAMETER ScriptString
Specifies the string containing your payload.
.PARAMETER Token
Specifies the token to obfuscate.
.EXAMPLE
C:\PS> $ScriptString = "Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green"
C:\PS> $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptString,[ref]$null) | Where-Object {$_.Type -eq 'Command'}
C:\PS> For($i=$Tokens.Count-1; $i -ge 0; $i--) {$Token = $Tokens[$i]; $ScriptString = Out-ObfuscatedWithTicks $ScriptString $Token}
C:\PS> $ScriptString
WrI`Te-Ho`sT 'Hello World!' -ForegroundColor Green; WrIte-`hO`S`T 'Obfuscation Rocks!' -ForegroundColor Green
.NOTES
This cmdlet is most easily used by passing a script block or file path to a PowerShell script into the Out-ObfuscatedTokenCommand function with the corresponding token type and obfuscation level since Out-ObfuscatedTokenCommand will handle token parsing, reverse iterating and passing tokens into this current function.
C:\PS> Out-ObfuscatedTokenCommand {Write-Host 'Hello World!' -ForegroundColor Green; Write-Host 'Obfuscation Rocks!' -ForegroundColor Green} 'Command' 2
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)]
[ValidateNotNullOrEmpty()]
[String]
$ScriptString,
[Parameter(Position = 1, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSToken]
$Token
)
# If ticks are already present in current Token then Return $ScriptString as is.
If($Token.Content.Contains('`'))
{
Return $ScriptString
}
# The Parameter Attributes in $MemberTokensToOnlyRandomCase (defined at beginning of script) cannot be obfuscated like other Member Tokens
# For these tokens we will only randomize the case and then return as is.
# Source: https://social.technet.microsoft.com/wiki/contents/articles/15994.powershell-advanced-function-parameter-attributes.aspx