-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCustomDetectionRuleModule.psm1
More file actions
815 lines (740 loc) · 33.3 KB
/
CustomDetectionRuleModule.psm1
File metadata and controls
815 lines (740 loc) · 33.3 KB
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
$script:GraphBaseUrl = "https://graph.microsoft.com/beta/security/rules/detectionRules"
# All valid impacted asset types and their valid identifier values
# https://learn.microsoft.com/en-us/graph/api/resources/security-impactedasset?view=graph-rest-beta
$script:ImpactedAssetTypes = @{
'#microsoft.graph.security.impactedDeviceAsset' = @{
ValidIdentifiers = @('deviceId', 'deviceName', 'remoteDeviceName', 'targetDeviceName', 'destinationDeviceName')
}
'#microsoft.graph.security.impactedUserAsset' = @{
ValidIdentifiers = @(
'accountObjectId', 'accountSid', 'accountUpn', 'accountName', 'accountDomain', 'accountId',
'requestAccountSid', 'requestAccountName', 'requestAccountDomain', 'recipientObjectId',
'processAccountObjectId', 'initiatingAccountSid', 'initiatingProcessAccountUpn',
'initiatingAccountName', 'initiatingAccountDomain', 'servicePrincipalId',
'servicePrincipalName', 'targetAccountUpn'
)
}
'#microsoft.graph.security.impactedMailboxAsset' = @{
ValidIdentifiers = @(
'accountUpn', 'fileOwnerUpn', 'initiatingProcessAccountUpn', 'lastModifyingAccountUpn',
'targetAccountUpn', 'senderFromAddress', 'senderDisplayName', 'recipientEmailAddress',
'senderMailFromAddress'
)
}
}
# All valid response action types, their identifiers, required/optional properties, and target entity
# Ref https://learn.microsoft.com/en-us/graph/api/resources/security-responseaction?view=graph-rest-beta
$script:ResponseActionTypes = @{
#Device actions
'#microsoft.graph.security.isolateDeviceResponseAction' = @{
ValidIdentifiers = @('deviceId')
RequiredProperties = @('isolationType')
ValidPropertyValues = @{ isolationType = @('full', 'selective') }
TargetEntity = 'Device'
}
'#microsoft.graph.security.collectInvestigationPackageResponseAction' = @{
ValidIdentifiers = @('deviceId')
RequiredProperties = @()
TargetEntity = 'Device'
}
'#microsoft.graph.security.runAntivirusScanResponseAction' = @{
ValidIdentifiers = @('deviceId')
RequiredProperties = @()
TargetEntity = 'Device'
}
'#microsoft.graph.security.initiateInvestigationResponseAction' = @{
ValidIdentifiers = @('deviceId')
RequiredProperties = @()
TargetEntity = 'Device'
}
'#microsoft.graph.security.restrictAppExecutionResponseAction' = @{
ValidIdentifiers = @('deviceId')
RequiredProperties = @()
TargetEntity = 'Device'
}
#File actions
'#microsoft.graph.security.stopAndQuarantineFileResponseAction' = @{
ValidIdentifiers = @('deviceId,sha1', 'deviceId,initiatingProcessSHA1')
RequiredProperties = @()
TargetEntity = 'File'
}
'#microsoft.graph.security.allowFileResponseAction' = @{
ValidIdentifiers = @('sha1', 'initiatingProcessSHA1', 'sha256', 'initiatingProcessSHA256')
RequiredProperties = @('deviceGroupNames')
TargetEntity = 'File'
}
'#microsoft.graph.security.blockFileResponseAction' = @{
ValidIdentifiers = @('sha1', 'initiatingProcessSHA1', 'sha256', 'initiatingProcessSHA256')
RequiredProperties = @('deviceGroupNames')
TargetEntity = 'File'
}
# User actions
'#microsoft.graph.security.markUserAsCompromisedResponseAction' = @{
ValidIdentifiers = @('accountObjectId', 'initiatingProcessAccountObjectId', 'servicePrincipalId', 'recipientObjectId')
RequiredProperties = @()
TargetEntity = 'User'
}
'#microsoft.graph.security.disableUserResponseAction' = @{
ValidIdentifiers = @('accountSid', 'initiatingProcessAccountSid', 'requestAccountSid', 'onPremSid')
RequiredProperties = @()
TargetEntity = 'User'
}
'#microsoft.graph.security.forceUserPasswordResetResponseAction' = @{
ValidIdentifiers = @('accountSid', 'initiatingProcessAccountSid', 'requestAccountSid', 'onPremSid')
RequiredProperties = @()
TargetEntity = 'User'
}
# Email actions
#NOTE: The API requires the combined identifier 'networkMessageId,recipientEmailAddress' for email actions.
'#microsoft.graph.security.hardDeleteResponseAction' = @{
ValidIdentifiers = @('networkMessageId,recipientEmailAddress')
RequiredProperties = @()
TargetEntity = 'Email'
}
'#microsoft.graph.security.softDeleteResponseAction' = @{
ValidIdentifiers = @('networkMessageId,recipientEmailAddress')
RequiredProperties = @()
TargetEntity = 'Email'
}
'#microsoft.graph.security.moveToInboxResponseAction' = @{
ValidIdentifiers = @('networkMessageId,recipientEmailAddress')
RequiredProperties = @()
TargetEntity = 'Email'
}
'#microsoft.graph.security.moveToDeletedItemsResponseAction' = @{
ValidIdentifiers = @('networkMessageId,recipientEmailAddress')
RequiredProperties = @()
TargetEntity = 'Email'
}
'#microsoft.graph.security.moveToJunkResponseAction' = @{
ValidIdentifiers = @('networkMessageId,recipientEmailAddress')
RequiredProperties = @()
TargetEntity = 'Email'
}
}
function Get-GraphAccessToken {
[CmdletBinding(DefaultParameterSetName = 'AzContext')]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'SPN')]
[ValidateNotNullOrEmpty()]
[string]$ClientId,
[Parameter(Mandatory = $true, ParameterSetName = 'SPN')]
[ValidateNotNullOrEmpty()]
[string]$ClientSecret,
[Parameter(Mandatory = $true, ParameterSetName = 'SPN')]
[ValidateNotNullOrEmpty()]
[string]$TenantId
)
if ($PSCmdlet.ParameterSetName -eq 'SPN') {
Write-Host "[A] Getting Microsoft Graph API token for SPN in tenant: $TenantId"
try {
$body = @{
grant_type = "client_credentials"
client_id = $ClientId
client_secret = $ClientSecret
scope = "https://graph.microsoft.com/.default"
}
$tokenResponse = Invoke-RestMethod -Method POST `
-Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" `
-ContentType "application/x-www-form-urlencoded" `
-Body $body
$token = $tokenResponse.access_token
Write-Host "[*] Access token obtained successfully (SPN)"
return $token
}
catch {
Write-Host "[!] Failed to get SPN access token: $_" -ForegroundColor Red
throw $_
}
}
# Default: AzContext (managed identity / interactive)
if (-not (Get-AzContext)) {
Write-Host "[A] Connecting to Azure..."
$null = Connect-AzAccount -Identity
}
$tenantId = (Get-AzContext).Tenant.Id
Write-Host "[A] Getting Microsoft Graph API token for tenant: $tenantId"
try {
$tokenResponse = Get-AzAccessToken -ResourceUrl "https://graph.microsoft.com/"
$token = ConvertFrom-SecureString -SecureString $tokenResponse.Token -AsPlainText
Write-Host "[*] Access token obtained successfully"
return $token
}
catch {
Write-Host "[!] Failed to get access token: $_" -ForegroundColor Red
throw $_
}
}
function Get-GraphHeader {
param (
[Parameter(Mandatory = $false)]
[string]$token
)
if (-not $token) { $token = Get-GraphAccessToken }
return @{
"Authorization" = "Bearer $token"
"Content-Type" = "application/json"
}
}
function Get-DetectionRules {
param (
[Parameter(Mandatory = $false)]
[string]$token,
[Parameter(Mandatory = $false)]
[string]$OutputPath
)
try {
if ($token) {
$headers = Get-GraphHeader -token $token
$result = Invoke-RestMethod -Method Get -Uri $script:GraphBaseUrl -Headers $headers
}
else {
$result = Invoke-MgGraphRequest -Method GET -Uri $script:GraphBaseUrl
}
}
catch {
Write-Host "ERROR: Failed to get custom detection rules: $_" -ForegroundColor Red
throw $_
}
$rules = if ($result.value) { $result.value } else { $result }
if ($OutputPath) {
if (-not (Test-Path $OutputPath)) { $null = New-Item -ItemType Directory -Path $OutputPath -Force }
foreach ($rule in $rules) {
$safeName = ($rule.displayName -replace '[^\w\-\.]', '_')
$filePath = Join-Path $OutputPath "$safeName.json"
$rule | ConvertTo-Json -Depth 10 | Out-File -FilePath $filePath -Encoding UTF8
Write-Host "Saved: $filePath"
}
}
return $rules
}
function Get-DetectionRule {
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ruleId,
[Parameter(Mandatory = $false)]
[string]$token,
[Parameter(Mandatory = $false)]
[string]$OutputPath
)
$url = "$script:GraphBaseUrl/$ruleId"
try {
if ($token) {
$headers = Get-GraphHeader -token $token
$result = Invoke-RestMethod -Method Get -Uri $url -Headers $headers
}
else {
$result = Invoke-MgGraphRequest -Method GET -Uri $url
}
}
catch {
Write-Host "ERROR: Failed to get custom detection rule $ruleId`: $_" -ForegroundColor Red
throw $_
}
if ($OutputPath) {
if (-not (Test-Path $OutputPath)) { $null = New-Item -ItemType Directory -Path $OutputPath -Force }
$safeName = if ($result.displayName) { $result.displayName -replace '[^\w\-\.]', '_' } else { $ruleId }
$filePath = Join-Path $OutputPath "$safeName.json"
$result | ConvertTo-Json -Depth 10 | Out-File -FilePath $filePath -Encoding UTF8
Write-Host "Saved: $filePath"
}
return $result
}
function Test-ImpactedAsset {
<#
.SYNOPSIS
Validates an impacted asset hashtable against the Graph API schema.
#>
param (
[Parameter(Mandatory = $true)]
[hashtable]$Asset
)
if (-not $Asset['@odata.type']) {
throw "Impacted asset is missing required '@odata.type' property."
}
if (-not $Asset['identifier']) {
throw "Impacted asset is missing required 'identifier' property."
}
$typeDef = $script:ImpactedAssetTypes[$Asset['@odata.type']]
if (-not $typeDef) {
$validTypes = ($script:ImpactedAssetTypes.Keys | Sort-Object) -join ", "
throw "Invalid impacted asset type '$($Asset['@odata.type'])'. Valid types: $validTypes"
}
if ($Asset['identifier'] -notin $typeDef.ValidIdentifiers) {
$validIds = ($typeDef.ValidIdentifiers | Sort-Object) -join ", "
throw "Invalid identifier '$($Asset['identifier'])' for type '$($Asset['@odata.type'])'. Valid identifiers: $validIds"
}
}
function Test-ResponseAction {
<#
.SYNOPSIS
Validates a response action hashtable against the Graph API schema.
#>
param (
[Parameter(Mandatory = $true)]
[hashtable]$Action
)
if (-not $Action['@odata.type']) {
throw "Response action is missing required '@odata.type' property."
}
if (-not $Action['identifier']) {
throw "Response action is missing required 'identifier' property."
}
$typeDef = $script:ResponseActionTypes[$Action['@odata.type']]
if (-not $typeDef) {
$validTypes = ($script:ResponseActionTypes.Keys | Sort-Object) -join "`n "
throw "Invalid response action type '$($Action['@odata.type'])'. Valid types:`n $validTypes"
}
if ($Action['identifier'] -notin $typeDef.ValidIdentifiers) {
$validIds = ($typeDef.ValidIdentifiers | Sort-Object) -join ", "
throw "Invalid identifier '$($Action['identifier'])' for action '$($Action['@odata.type'])'. Valid identifiers: $validIds"
}
foreach ($reqProp in $typeDef.RequiredProperties) {
if (-not $Action[$reqProp]) {
throw "Response action '$($Action['@odata.type'])' is missing required property '$reqProp'."
}
}
if ($typeDef.ValidPropertyValues) {
foreach ($propName in $typeDef.ValidPropertyValues.Keys) {
if ($Action[$propName] -and $Action[$propName] -notin $typeDef.ValidPropertyValues[$propName]) {
$validVals = ($typeDef.ValidPropertyValues[$propName] | Sort-Object) -join ", "
throw "Invalid value '$($Action[$propName])' for property '$propName' on '$($Action['@odata.type'])'. Valid values: $validVals"
}
}
}
}
function New-DetectionRule {
<#
.SYNOPSIS
Creates a new custom detection rule via Microsoft Graph API.
.DESCRIPTION
Creates a custom detection rule using the Microsoft Graph Security API (beta).
Supports all impacted asset types (Device, User, Mailbox) and all 16 response action types.
IMPACTED ASSET TYPES & IDENTIFIERS:
Device (#microsoft.graph.security.impactedDeviceAsset):
deviceId, deviceName, remoteDeviceName, targetDeviceName, destinationDeviceName
User (#microsoft.graph.security.impactedUserAsset):
accountObjectId, accountSid, accountUpn, accountName, accountDomain, accountId,
requestAccountSid, requestAccountName, requestAccountDomain, recipientObjectId,
processAccountObjectId, initiatingAccountSid, initiatingProcessAccountUpn,
initiatingAccountName, initiatingAccountDomain, servicePrincipalId,
servicePrincipalName, targetAccountUpn
Mailbox (#microsoft.graph.security.impactedMailboxAsset):
accountUpn, fileOwnerUpn, initiatingProcessAccountUpn, lastModifyingAccountUpn,
targetAccountUpn, senderFromAddress, senderDisplayName, recipientEmailAddress,
senderMailFromAddress
RESPONSE ACTION TYPES:
Device actions (identifier: deviceId):
#microsoft.graph.security.isolateDeviceResponseAction (+ isolationType: full|selective)
#microsoft.graph.security.collectInvestigationPackageResponseAction
#microsoft.graph.security.runAntivirusScanResponseAction
#microsoft.graph.security.initiateInvestigationResponseAction
#microsoft.graph.security.restrictAppExecutionResponseAction
File actions:
#microsoft.graph.security.stopAndQuarantineFileResponseAction (identifier: 'deviceId,sha1' or 'deviceId,initiatingProcessSHA1' - combined, comma-separated)
#microsoft.graph.security.allowFileResponseAction (identifier: sha1|initiatingProcessSHA1|sha256|initiatingProcessSHA256 + REQUIRED deviceGroupNames)
#microsoft.graph.security.blockFileResponseAction (identifier: sha1|initiatingProcessSHA1|sha256|initiatingProcessSHA256 + REQUIRED deviceGroupNames)
User actions:
#microsoft.graph.security.markUserAsCompromisedResponseAction (identifier: accountObjectId|initiatingProcessAccountObjectId|servicePrincipalId|recipientObjectId)
#microsoft.graph.security.disableUserResponseAction (identifier: accountSid|initiatingProcessAccountSid|requestAccountSid|onPremSid)
#microsoft.graph.security.forceUserPasswordResetResponseAction (identifier: accountSid|initiatingProcessAccountSid|requestAccountSid|onPremSid)
Email actions (identifier: 'networkMessageId,recipientEmailAddress' - combined, comma-separated):
#microsoft.graph.security.hardDeleteResponseAction
#microsoft.graph.security.softDeleteResponseAction
#microsoft.graph.security.moveToInboxResponseAction
#microsoft.graph.security.moveToDeletedItemsResponseAction
#microsoft.graph.security.moveToJunkResponseAction
.PARAMETER impactedAssets
Array of hashtables. Each must contain '@odata.type' and 'identifier'. See description for valid values.
.PARAMETER responseActions
Array of hashtables. Each must contain '@odata.type' and 'identifier', plus any action-specific properties. See description for valid values.
.EXAMPLE
# Device detection with isolate + AV scan
$assets = @(
@{ '@odata.type' = '#microsoft.graph.security.impactedDeviceAsset'; identifier = 'deviceId' }
)
$actions = @(
@{ '@odata.type' = '#microsoft.graph.security.isolateDeviceResponseAction'; identifier = 'deviceId'; isolationType = 'full' },
@{ '@odata.type' = '#microsoft.graph.security.runAntivirusScanResponseAction'; identifier = 'deviceId' }
)
New-DetectionRule -displayName "Suspicious Process" -isEnabled $true `
-queryText "DeviceProcessEvents | where FileName == 'mimikatz.exe'" `
-period "1H" -alertTitle "Mimikatz Detected" -alertDescription "Mimikatz was detected" `
-severity "high" -category "CredentialAccess" `
-impactedAssets $assets -responseActions $actions
.EXAMPLE
# User detection with mark as compromised
$assets = @(
@{ '@odata.type' = '#microsoft.graph.security.impactedUserAsset'; identifier = 'accountObjectId' }
)
$actions = @(
@{ '@odata.type' = '#microsoft.graph.security.markUserAsCompromisedResponseAction'; identifier = 'accountObjectId' },
@{ '@odata.type' = '#microsoft.graph.security.disableUserResponseAction'; identifier = 'accountSid' }
)
New-DetectionRule -displayName "Compromised User" -isEnabled $true `
-queryText "IdentityLogonEvents | where ..." -period "1H" `
-alertTitle "User Compromised" -alertDescription "User account compromised" `
-severity "high" -category "CredentialAccess" `
-impactedAssets $assets -responseActions $actions
.EXAMPLE
# Email detection with hard delete
$assets = @(
@{ '@odata.type' = '#microsoft.graph.security.impactedMailboxAsset'; identifier = 'recipientEmailAddress' }
)
$actions = @(
@{ '@odata.type' = '#microsoft.graph.security.hardDeleteResponseAction'; identifier = 'networkMessageId,recipientEmailAddress' }
)
New-DetectionRule -displayName "Phishing Remediation" -isEnabled $true `
-queryText "EmailEvents | where ..." -period "1H" `
-alertTitle "Phishing Email" -alertDescription "Phishing email detected" `
-severity "high" -category "InitialAccess" `
-impactedAssets $assets -responseActions $actions
.EXAMPLE
# File block with device group scoping
$assets = @(
@{ '@odata.type' = '#microsoft.graph.security.impactedDeviceAsset'; identifier = 'deviceId' }
)
$actions = @(
@{ '@odata.type' = '#microsoft.graph.security.blockFileResponseAction'; identifier = 'sha256'; deviceGroupNames = @('Production') }
)
New-DetectionRule -displayName "Block Malware Hash" -isEnabled $true `
-queryText "DeviceFileEvents | where SHA256 == '...'" -period "1H" `
-alertTitle "Malware File" -alertDescription "Known malware file detected" `
-severity "high" -category "Malware" `
-impactedAssets $assets -responseActions $actions
#>
[CmdletBinding(DefaultParameterSetName = 'Parameters')]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'InputFile')]
[ValidateScript({ Test-Path $_ })]
[string]$InputFile,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[string]$displayName,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[bool]$isEnabled,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[string]$queryText,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[ValidateSet("0", "NRT", "1H", "3H", "12H", "24H")]
[string]$period,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[string]$alertTitle,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[string]$alertDescription,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[ValidateSet("informational", "low", "medium", "high")]
[string]$severity,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[ValidateSet(
"Malware", "Execution", "Discovery", "Lateral Movement", "Persistence",
"PrivilegeEscalation", "DefenseEvasion", "CredentialAccess", "Collection",
"Exfiltration", "CommandAndControl", "SuspiciousActivity", "Unwanted Software",
"Ransomware", "Exploit", "Impact", "InitialAccess", "Reconnaissance", "ResourceDevelopment"
)]
[string]$category,
[Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[hashtable[]]$impactedAssets,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[hashtable[]]$responseActions,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[string[]]$mitreTechniques,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
$recommendedActions,
[Parameter(Mandatory = $false)]
[string]$token
)
if ($PSCmdlet.ParameterSetName -eq 'InputFile') {
$jsonContent = Get-Content -Path $InputFile -Raw | ConvertFrom-Json
$body = @{}
foreach ($prop in $jsonContent.PSObject.Properties) {
if ($prop.Name -notin @('id', '@odata.context', 'createdDateTime', 'lastModifiedDateTime', 'wasRecentlyDeactivated', 'lastRunDetails')) {
$body[$prop.Name] = $prop.Value
}
}
$jsonBody = $body | ConvertTo-Json -Depth 10
try {
if ($token) {
$headers = Get-GraphHeader -token $token
$result = Invoke-RestMethod -Method POST -Uri $script:GraphBaseUrl -Body $jsonBody -Headers $headers
}
else {
$result = Invoke-MgGraphRequest -Method POST -Uri $script:GraphBaseUrl -Body $jsonBody -Headers @{ "Content-Type" = "application/json" }
}
}
catch {
Write-Host "ERROR: Failed to create detection rule from file: $_" -ForegroundColor Red
throw $_
}
Write-Host "Successfully created detection rule from file: $InputFile" -ForegroundColor Green
return $result
}
# Validate impacted assets
foreach ($asset in $impactedAssets) {
Test-ImpactedAsset -Asset $asset
}
# Validate response actions
$validatedActions = @()
if ($PSBoundParameters.ContainsKey('responseActions') -and $responseActions) {
foreach ($action in $responseActions) {
Test-ResponseAction -Action $action
}
$validatedActions = $responseActions
}
# Map NRT to API value "0"
$schedulePeriod = if ($period -eq 'NRT') { '0' } else { $period }
$body = @{
displayName = $displayName
isEnabled = $isEnabled
queryCondition = @{
queryText = $queryText
}
schedule = @{
period = $schedulePeriod
}
detectionAction = @{
alertTemplate = @{
title = $alertTitle
description = $alertDescription
severity = $severity.ToLower()
category = $category
impactedAssets = @($impactedAssets)
}
organizationalScope = $null
responseActions = @($validatedActions)
}
}
if ($PSBoundParameters.ContainsKey('mitreTechniques') -and $mitreTechniques.Count -gt 0) {
$body.detectionAction.alertTemplate.mitreTechniques = $mitreTechniques
}
if ($PSBoundParameters.ContainsKey('recommendedActions') -and $recommendedActions) {
$body.detectionAction.alertTemplate.recommendedActions = $recommendedActions
}
$jsonBody = $body | ConvertTo-Json -Depth 10
try {
if ($token) {
$headers = Get-GraphHeader -token $token
$result = Invoke-RestMethod -Method POST -Uri $script:GraphBaseUrl -Body $jsonBody -Headers $headers
}
else {
$result = Invoke-MgGraphRequest -Method POST -Uri $script:GraphBaseUrl -Body $jsonBody -Headers @{ "Content-Type" = "application/json" }
}
}
catch {
Write-Host "ERROR: Failed to create detection rule: $_" -ForegroundColor Red
throw $_
}
Write-Host "Successfully created detection rule: $displayName" -ForegroundColor Green
return $result
}
function Update-DetectionRule {
<#
.SYNOPSIS
Updates an existing custom detection rule via Microsoft Graph API.
.DESCRIPTION
Updates a custom detection rule using PATCH. Only specified parameters are updated.
Supports all impacted asset types and response action types.
See New-DetectionRule for full documentation of asset types and response actions.
.PARAMETER ruleId
The ID of the detection rule to update.
.PARAMETER impactedAssets
Array of hashtables. Each must contain '@odata.type' and 'identifier'.
.PARAMETER responseActions
Array of hashtables. Each must contain '@odata.type' and 'identifier', plus action-specific properties.
.EXAMPLE
# Change response actions to also disable the user
$actions = @(
@{ '@odata.type' = '#microsoft.graph.security.isolateDeviceResponseAction'; identifier = 'deviceId'; isolationType = 'full' },
@{ '@odata.type' = '#microsoft.graph.security.disableUserResponseAction'; identifier = 'accountSid' }
)
Update-DetectionRule -ruleId '12345' -responseActions $actions
#>
[CmdletBinding(DefaultParameterSetName = 'Parameters')]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ruleId,
[Parameter(Mandatory = $true, ParameterSetName = 'InputFile')]
[ValidateScript({ Test-Path $_ })]
[string]$InputFile,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[string]$displayName,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[bool]$isEnabled,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[string]$queryText,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[ValidateSet("0", "NRT", "1H", "3H", "12H", "24H")]
[string]$period,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[string]$alertTitle,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[ValidateNotNullOrEmpty()]
[string]$alertDescription,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[ValidateSet("informational", "low", "medium", "high")]
[string]$severity,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[ValidateSet(
"Malware", "Execution", "Discovery", "Lateral Movement", "Persistence",
"PrivilegeEscalation", "DefenseEvasion", "CredentialAccess", "Collection",
"Exfiltration", "CommandAndControl", "SuspiciousActivity", "Unwanted Software",
"Ransomware", "Exploit", "Impact", "InitialAccess", "Reconnaissance", "ResourceDevelopment"
)]
[string]$category,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[hashtable[]]$impactedAssets,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[hashtable[]]$responseActions,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
[string[]]$mitreTechniques,
[Parameter(Mandatory = $false, ParameterSetName = 'Parameters')]
$recommendedActions,
[Parameter(Mandatory = $false)]
[string]$token
)
if ($PSCmdlet.ParameterSetName -eq 'InputFile') {
$jsonContent = Get-Content -Path $InputFile -Raw | ConvertFrom-Json
$body = @{}
foreach ($prop in $jsonContent.PSObject.Properties) {
if ($prop.Name -notin @('id', '@odata.context', 'createdDateTime', 'lastModifiedDateTime', 'wasRecentlyDeactivated', 'lastRunDetails')) {
$body[$prop.Name] = $prop.Value
}
}
$jsonBody = $body | ConvertTo-Json -Depth 10
$url = "$script:GraphBaseUrl/$ruleId"
try {
if ($token) {
$headers = Get-GraphHeader -token $token
$result = Invoke-RestMethod -Method PATCH -Uri $url -Body $jsonBody -Headers $headers
}
else {
$result = Invoke-MgGraphRequest -Method PATCH -Uri $url -Body $jsonBody -Headers @{ "Content-Type" = "application/json" }
}
}
catch {
Write-Host "ERROR: Failed to update detection rule $ruleId from file: $_" -ForegroundColor Red
throw $_
}
Write-Host "Successfully updated detection rule $ruleId from file: $InputFile" -ForegroundColor Green
return $result
}
# Validate impacted assets if provided
if ($PSBoundParameters.ContainsKey('impactedAssets')) {
foreach ($asset in $impactedAssets) {
Test-ImpactedAsset -Asset $asset
}
}
# Validate response actions if provided
if ($PSBoundParameters.ContainsKey('responseActions') -and $responseActions) {
foreach ($action in $responseActions) {
Test-ResponseAction -Action $action
}
}
$body = @{}
if ($PSBoundParameters.ContainsKey('displayName')) {
$body.displayName = $displayName
}
if ($PSBoundParameters.ContainsKey('isEnabled')) {
$body.isEnabled = $isEnabled
}
if ($PSBoundParameters.ContainsKey('queryText')) {
$body.queryCondition = @{ queryText = $queryText }
}
if ($PSBoundParameters.ContainsKey('period')) {
$schedulePeriod = if ($period -eq 'NRT') { '0' } else { $period }
$body.schedule = @{ period = $schedulePeriod }
}
$alertTemplate = @{}
if ($PSBoundParameters.ContainsKey('alertTitle')) {
$alertTemplate.title = $alertTitle
}
if ($PSBoundParameters.ContainsKey('alertDescription')) {
$alertTemplate.description = $alertDescription
}
if ($PSBoundParameters.ContainsKey('severity')) {
$alertTemplate.severity = $severity.ToLower()
}
if ($PSBoundParameters.ContainsKey('category')) {
$alertTemplate.category = $category
}
if ($PSBoundParameters.ContainsKey('recommendedActions')) {
$alertTemplate.recommendedActions = $recommendedActions
}
if ($PSBoundParameters.ContainsKey('mitreTechniques')) {
$alertTemplate.mitreTechniques = $mitreTechniques
}
if ($PSBoundParameters.ContainsKey('impactedAssets')) {
$alertTemplate.impactedAssets = @($impactedAssets)
}
$detectionAction = @{}
if ($alertTemplate.Count -gt 0) {
$detectionAction.alertTemplate = $alertTemplate
}
if ($PSBoundParameters.ContainsKey('responseActions')) {
$detectionAction.responseActions = @($responseActions)
}
if ($detectionAction.Count -gt 0) {
$body.detectionAction = $detectionAction
}
$jsonBody = $body | ConvertTo-Json -Depth 10
$url = "$script:GraphBaseUrl/$ruleId"
try {
if ($token) {
$headers = Get-GraphHeader -token $token
$result = Invoke-RestMethod -Method PATCH -Uri $url -Body $jsonBody -Headers $headers
}
else {
$result = Invoke-MgGraphRequest -Method PATCH -Uri $url -Body $jsonBody -Headers @{ "Content-Type" = "application/json" }
}
}
catch {
Write-Host "ERROR: Failed to update detection rule $ruleId`: $_" -ForegroundColor Red
throw $_
}
Write-Host "Successfully updated detection rule: $ruleId" -ForegroundColor Green
return $result
}
function Remove-DetectionRule {
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ruleId,
[Parameter(Mandatory = $false)]
[string]$token
)
$url = "$script:GraphBaseUrl/$ruleId"
try {
if ($token) {
$headers = Get-GraphHeader -token $token
$null = Invoke-RestMethod -Method DELETE -Uri $url -Headers $headers
}
else {
$null = Invoke-MgGraphRequest -Method DELETE -Uri $url
}
}
catch {
Write-Host "ERROR: Failed to delete detection rule $ruleId`: $_" -ForegroundColor Red
throw $_
}
Write-Host "Successfully deleted detection rule: $ruleId" -ForegroundColor Green
}
Export-ModuleMember -Function @(
'Get-GraphAccessToken'
'Get-GraphHeader'
'Get-DetectionRules'
'Get-DetectionRule'
'New-DetectionRule'
'Update-DetectionRule'
'Remove-DetectionRule'
'Test-ImpactedAsset'
'Test-ResponseAction'
)