├── KQL-Effective-Use
├── 01-kql-Search-with-Let.md
├── 02-kql-MDE-TamperProtection.md
├── 03-kql-MDE-WebProtection.md
├── 04-kql-MDE-ControlledFolderAccess.md
├── 05-kql-AzureADIdentityProtection.md
├── 06-kql-MDO-RemediationActions.md
├── 07-kql-XDR-NRT-CustomDetectionRule.md
├── 08-kql-MDE-WebProtection-CheatSheet-v3.pdf
├── 09-kql-MDE-ASRrule-UseCases-v2.pdf
├── 10-kql-ThreatHunting-IoCs-tips-v1.pdf.pdf
├── 11-kql-MTDI-MangoSandstorm-IoCs.csv
├── 11-kql-externaldata-IoCs-threathunting.md
├── 12-kql-externaldata-IoCs-threathunting-tips-v1.pdf
├── 13-kql-AiTM-HuntingInsight-Part1.pdf
├── 13-kql-AiTM-HuntingInsight-Part2.pdf
├── 13-kql-AiTM-HuntingInsight-Part3.pdf
├── 13-kql-AiTM-HuntingInsight-Part4.pdf
├── 14-kql-MFAfatigue-HuntingInsight.pdf
├── 15-kql-Phishing-db-hunting.md
├── 16-kql-MDE-WebProtection-NetworkData.md
├── 17-kql-MITRE-ATTCK-Detection.md
└── old
│ ├── 08-kql-MDE-WebProtection-CheatSheet-v2.pdf
│ ├── 13-kql-AiTM-HuntingInsight-Part2_v1.pdf
│ └── WIP-kql-MDE-NetworkProtection.md
├── KQL-XDR-Hunting
├── Email-Microsoft-Defender-for-Office365
│ ├── MDO-EOP-Query-Repository
│ │ ├── 01-Email-Audit-SafeAttachments-GlobalSetting.md
│ │ ├── 02-EOP-Detection-Daily-Percentage.md
│ │ ├── 03-MDO-Detection-Daily-Percentage.md
│ │ ├── 04-EOP-MalwareDetection-Filtering.md
│ │ ├── 05-EOP-PhishingDetection-Filtering.md
│ │ ├── 06-MDO-MalwareDetection-Filtering.md
│ │ ├── 07-MDO-PhishingDetection-Filtering.md
│ │ ├── 08-MDO-UserList-for-RemediationAction.md
│ │ ├── 09-Email-MalwareDetection-byAccount.md
│ │ ├── 10-UserInsights-ClickedSuspiciousURLs-PhishMalware-Emails.md
│ │ ├── 11-Email-Weekly-DetectionTrend.md
│ │ ├── 12-Email-MalwarePhishing-Detection-Trends.md
│ │ ├── 13-Email-Spam-Detection-Trend.md
│ │ ├── 14-MDO-QRcode-VolumeInboundEmails.md
│ │ ├── 15-MDO-QRcode-DeliveredEmail.md
│ │ ├── 16-Emails-QRcode-SuspiciousKeywordsSubject.md
│ │ └── 17-MDO-DetectedURL-Insights.md
│ └── README.md
├── Endpoint-Microsoft-Defender-for-Endpoint
│ ├── MDE-Query-Repository
│ │ ├── 01-AV-Detection-ThreatInsightWithFilenameByDeviceList.md
│ │ ├── 01-ExposureManagement-DeviceExposureLevels .md
│ │ ├── 01-MDE-ASR-Rules-Detections-Block-Audit.md
│ │ ├── 01-MDE-CFA-Detections-Block-Audit.md
│ │ ├── 01-MDE-LNKFile-activity.md
│ │ ├── 01-MDE-TVM-InstalledSoftware-List-Windows.md
│ │ ├── 01-MDE-TVM-Linux-AntivirusConfig.md
│ │ ├── 01-MDE-TamperProtection-TSmode-AVver-DeviceList.md
│ │ ├── 01-MDE-URL-Indicators-Block.md
│ │ ├── 02-AV-LastCompletedAVScanTime-For-EachDevice.md
│ │ ├── 02-MDE-ASR-Rules-VisualizingDetectionWithPieChart.md
│ │ ├── 02-MDE-TVM-MacOS-AntivirusConfig.md
│ │ ├── 02-MDE-TVM-RiskyBrowserExtensions-List-Windows.md
│ │ ├── 02-MDE-URL-Indicators-Bypass.md
│ │ ├── 03-MDE-ASR-Rules-DetectionAcrossAllDevices.md
│ │ ├── 03-MDE-NetworkProtection-Detection.md
│ │ ├── 03-MDE-TVM-InstalledSoftware-List-Linux.md
│ │ ├── 04-MDE-ASR-Rules-CategorizedDetection-Graph.md
│ │ ├── 04-MDE-TVM-InstalledSoftware-List-MacOS.md
│ │ ├── 04-SS-DefenderSmartScreen-Detection.md
│ │ └── 05-MDE-WebContentFiltering-Detection.md
│ └── README.md
├── Identity-Microsoft-Defender-for-Identity
│ ├── MDI-Query-Repository
│ │ ├── 01-LDAP-Query-Activities-Endpoint.md
│ │ ├── 02-LDAP-Query-Activities-Identity.md
│ │ ├── 03-Last-PasswordReset-AccountDisabled-TimeList.md
│ │ ├── 04-LMP-Activities.md
│ │ ├── 05-GroupMembershipChanges-Activities.md
│ │ ├── 06-AccountLogin-Review.md
│ │ └── 07-ServiceCreation-Review.md
│ └── README.md
├── MicrosoftSecurity-ThreatInsight
│ ├── 2023-MicrosoftSecurity-ThreatInsight
│ │ ├── 20230407-MangoSandstorm.md
│ │ ├── 20230418-MintSandstorm.md
│ │ ├── 20230525-VoltTyphoon.md
│ │ ├── 20230614-CadetBlizzard.md
│ │ ├── 20230824-FlaxTyphoon.md
│ │ ├── 20230912-Storm-0324.md
│ │ ├── 20231018-DiamondSleet-OnyxSleet.md
│ │ ├── 20231122-DiamondSleet.md
│ │ └── MSSecurityThreatInsight2023.md
│ └── 2024-MicrosoftSecurity-ThreatInsight
│ │ └── MSSecurityThreatInsight2024.md
└── XDR-SIEM-Detection
│ ├── README.md
│ ├── XDR-SIEM-AttackTechniques-Query-Repository
│ ├── 01-AccountDiscovery-NetCommandUsage.md
│ ├── 20220712-MSSecurityBlog-AiTM-HuntingQueries.md
│ ├── 20221018-MSSecurityBlog-PostRansomware-AntivirusTampering.md
│ ├── 20221018-MSSecurityBlog-PostRansomware-Impacket.md
│ ├── 20221018-MSSecurityBlog-PostRansomware-PsExec.md
│ ├── 20221018-MSSecurityBlog-PostRansomware-SSHconnection.md
│ ├── 20221018-MSSecurityBlog-PostRansomware-Taskschedules.md
│ ├── 20221018-MSSecurityBlog-PostRansomware-WDigest.md
│ ├── 20230313-MSSecurityBlog-AiTM-MicrosoftSentinel-AnalyticsTemplate.md
│ ├── 20231129-MSSentinelBlog-AiTM-HuntingQueries.md
│ ├── 20231212-MSSecurityBlog-OAuthApplications-BECreconnaissanceOAuthApp.md
│ ├── 20231212-MSSecurityBlog-OAuthApplications-OAuthApptoAzureWorkloads.md
│ ├── 20231212-MSSecurityBlog-OAuthApplications-PasswordSprayAttempts.md
│ ├── 20231212-MSSecurityBlog-OAuthApplications-SuspiciousAppCreation.md
│ ├── 20231212-MSSecurityBlog-OAuthApplications-SuspiciousEmailEvents.md
│ ├── 20240212-MSSecExpertBlog-QRCodeAiTMPhishing.md
│ └── 20240401-MSSecurityBlog-QRcodeHunting.md
│ └── XDR-SIEM-Detection-Query-Repository
│ ├── 01-XDR-DetectionPercentage-SecurityProducts.md
│ ├── 02-XDR-EDR-Endpoint-AnalyzingDailyDetections.md
│ └── 03-XDR-AnalyzingAllDetections-With-MITRE-ATTCK.md
└── README.md
/KQL-Effective-Use/01-kql-Search-with-Let.md:
--------------------------------------------------------------------------------
1 | ## KQL : search operator with let statement
2 | Firstly, "search" is a very useful and effective operator in KQL when you are searching for a specific keyword or data.
3 | > Searches a text pattern in multiple tables and columns.
4 | [search operator - Azure Data Explorer | Microsoft Learn!](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/searchoperator?pivots=azuredataexplorer)
5 |
6 | If you have ever used Advanced Hunting in Microsoft 365 Defender and selected the "Go hunt" option on a device page, you may have come across KQL queries that use the "let" statement and the "search" operator to seek out specific devices. However, while I have seen examples of the [Let statement](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/letstatement#create-a-view-or-virtual-table) being used with the [Search operator](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/searchoperator?pivots=azuredataexplorer) in Microsoft documentation, they were not fully explained, especially in the context of Microsoft 365 Defender. Therefore, in this article, I will focus on the use case of the "search" operator with the "let" statement.
7 |
8 | #### Question: When do we use this query?
9 | If you would like to search something with "specific tables" and "timeline", then the query - let & search would be a great way to use!!
10 |
11 | #### Ex) "Go hunt" from a device page in Microsoft 365 Defender
12 | This query hunts "DeviceA" with a time range by filtering some tables such as DeviceEvent, DeviceInfo and so on.
13 |
14 | ```kql
15 | let deviceName = "DeviceA";
16 | let deviceId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
17 | let selectedTimestamp = datetime(2022-11-22T10:22:11.2370000Z);
18 | search in (IdentityLogonEvents,IdentityQueryEvents,IdentityDirectoryEvents,DeviceProcessEvents,DeviceNetworkEvents,DeviceFileEvents,DeviceRegistryEvents,DeviceLogonEvents,DeviceImageLoadEvents,DeviceEvents)
19 | Timestamp between ((selectedTimestamp - 1h) .. (selectedTimestamp + 1h))
20 | and
21 | (DeviceName == deviceName
22 | //or DeviceId == deviceId
23 | // Events affecting this target device
24 | //or RemoteDeviceName == deviceName
25 | //or TargetDeviceName == deviceName
26 | //or DestinationDeviceName == deviceName
27 | )
28 | | take 100
29 | ```
30 |
31 |
32 | #### Point 1 - after you write let statement, please be careful to not forget ";" in the end.
33 | ```kql
34 | let deviceName = "DeviceA";
35 | let deviceId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
36 | let selectedTimestamp = datetime(2022-11-22T10:22:11.2370000Z);
37 | ```
38 | #### Point 2 - you can flexibly choose the timestamp - without let or with let.
39 | ```kql
40 | // Timestamp with let statement
41 | let selectedTimestamp = datetime(2022-11-22T10:22:11.2370000Z);
42 | Timestamp between ((selectedTimestamp - 1h) .. (selectedTimestamp + 1h))
43 |
44 | // Timestamp without let statement
45 | Timestamp between (datetime(2022-11-22) .. datetime(2022-11-23))
46 | ```
47 | #### Point 3 - when you want to filter with multiple conditions, you can use "and"
48 | ```kql
49 | Timestamp between ((selectedTimestamp - 1h) .. (selectedTimestamp + 1h))
50 | and
51 | (DeviceName == deviceName)
52 | ```
53 |
54 | ## Example
55 | ```kql
56 | // search mimikatz activities
57 |
58 | let IoC_FileName = "mimikatz";
59 | let IoC_SHA256 = "92804faaab2175dc501d73e814663058c78c0a042675a8937266357bcfb96c50";
60 | let IoC_SHA1 = "d1f7832035c3e8a73cc78afd28cfd7f4cece6d20";
61 | let IoC_MD5 = "e930b05efe23891d19bc354a4209be3e";
62 | let StartTimestamp = datetime(2022-12-01);
63 | let EndTimestamp = datetime(2022-12-17);
64 | search in (DeviceProcessEvents,DeviceFileEvents,DeviceRegistryEvents,DeviceImageLoadEvents,DeviceEvents)
65 | Timestamp between ((StartTimestamp) .. (EndTimestamp))
66 | and
67 | (FileName has IoC_FileName
68 | or InitiatingProcessFileName has IoC_FileName
69 | or ProcessCommandLine has IoC_FileName
70 | or InitiatingProcessCommandLine has IoC_FileName
71 | or MD5 == IoC_MD5
72 | or SHA1 == IoC_SHA1
73 | or SHA256 == IoC_SHA256
74 | or InitiatingProcessMD5 == IoC_MD5
75 | or InitiatingProcessSHA1 == IoC_SHA1
76 | or InitiatingProcessSHA256 == IoC_SHA256
77 | )
78 | ```
79 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/02-kql-MDE-TamperProtection.md:
--------------------------------------------------------------------------------
1 | # KQL : Tamper Protection
2 | Tamper Protection is a security feature in Microsoft Defender Antivirus that helps prevent unauthorized changes to security settings and software. It works by preventing other programs, including malware, from modifying critical security features, files, and settings in the Windows operating system. Therefore, in this section, I am going to share testing commands and hunting queries
3 |
4 | > **Note** : Tamper Protection mainly works for Microsoft Defender Antivirus. In the case of Microsoft Defender for Endpoint, there is a built-in protection for the EDR sensor that prevents security features from being disabled.
5 |
6 |
7 |
8 | ## Microsoft Security blog
9 |
10 | - [Make sure Tamper Protection is turned on](https://techcommunity.microsoft.com/t5/microsoft-defender-for-endpoint/make-sure-tamper-protection-is-turned-on/ba-p/2695568)
11 | - [When coin miners evolve, Part 1: Exposing LemonDuck and LemonCat, modern mining malware infrastructure](https://www.microsoft.com/en-us/security/blog/2021/07/22/when-coin-miners-evolve-part-1-exposing-lemonduck-and-lemoncat-modern-mining-malware-infrastructure/)
12 | - [When coin miners evolve, Part 2: Hunting down LemonDuck and LemonCat attacks](https://www.microsoft.com/en-us/security/blog/2021/07/29/when-coin-miners-evolve-part-2-hunting-down-lemonduck-and-lemoncat-attacks/)
13 |
14 | 
15 | > Figure 1. LemonDuck attack chain from the Duck and Cat infrastructures
16 |
17 | ## Test command
18 | The testing commands are not only for ***Microsoft Defender Antivirus***, but also for ***Microsoft Defender for Endpoint***.
19 |
20 | **PowerShell Cmdlets**
21 |
22 | ```PowerShell
23 | # Microsoft Defender Antivirus
24 | PS : Set-MpPreference -DisableRealtimeMonitoring $true
25 | PS : Set-MpPreference -DisableBlockAtFirstSeen $true
26 | PS : Set-MpPreference -SubmitSamplesConsent 2
27 | PS : Stop-Service -Name "WinDefend"
28 | PS : Stop-Process -Name "MsMpEng"
29 | PS : New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender" -Name DisableAntiSpyware -Value 1 -PropertyType DWORD -Force
30 |
31 | # Microsoft Defender for Endpoint
32 | PS : Stop-Service -Name "Sense"
33 | PS : Stop-Process -Name "MsSense"
34 | ```
35 | **Windows Commands**
36 | ```cmd
37 | :: Microsoft Defender Antivirus
38 | Cmd : reg.exe add "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender" /v "DisableRealtimeMonitoring" /t REG_DWORD /d 1 /f
39 | Cmd : reg.exe add "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet" /v "SpynetReporting" /t REG_DWORD /d 0 /f
40 | Cmd : reg.exe add "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet" /v "SubmitSamplesConsent" /t REG_DWORD /d 2 /f
41 | Cmd : sc stop WinDefend
42 | Cmd : sc config "WinDefend" start= disabled
43 | Cmd : net stop WinDefend
44 | Cmd : reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender" /v DisableAntiSpyware /t REG_DWORD /d 1 /f
45 |
46 | :: Microsoft Defender for Endpoint
47 | Cmd : sc stop Sense
48 | Cmd : net stop Sense
49 | ```
50 |
51 | ## KQL : Hunting queries
52 | 1. Counts how many times 'TamperingAttempt' happened to each device.
53 | ```kql
54 | DeviceEvents
55 | | where Timestamp > ago(30d)
56 | | where ActionType == "TamperingAttempt"
57 | | summarize TamperingAttempt = count() by DeviceId, DeviceName
58 | ```
59 | 2. Counts how many times 'TamperingAttempt' occurred and indicates which registry value impacted each device.
60 | ```kql
61 |
62 | DeviceEvents
63 | | where Timestamp > ago(30d)
64 | | where ActionType == "TamperingAttempt"
65 | | summarize Registry_Value = make_list(RegistryValueName) by DeviceId, DeviceName
66 | ```
67 |
68 | 3. Hunt for registry key activities for Microsoft Defender Antivirus.
69 | ```kql
70 | DeviceRegistryEvents
71 | | where Timestamp > ago(30d)
72 | | where RegistryKey has @"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender"
73 | | project-reorder Timestamp, DeviceId, DeviceName, ActionType, RegistryKey, RegistryValueType, RegistryValueName, RegistryValueData
74 | | sort by Timestamp desc
75 | ```
76 |
77 | 4. Hunt for disabling activities for Microsoft Defender Antivirus and Microsoft Defender for Endpoint.
78 | ```kql
79 | DeviceEvents
80 | | where Timestamp > ago(30d)
81 | | where ActionType == "OtherAlertRelatedActivity"
82 | | where AdditionalFields has "net stop Sense"
83 | or AdditionalFields has "sc stop Sense"
84 | or AdditionalFields has "net stop WinDefend"
85 | or AdditionalFields has "sc stop WinDefend"
86 | | extend Command = split(AdditionalFields, 'line')[1]
87 | | project-reorder Timestamp, DeviceId, DeviceName, Command
88 | ```
89 |
90 | #### Disclaimer
91 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
92 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/03-kql-MDE-WebProtection.md:
--------------------------------------------------------------------------------
1 | # KQL : Web Protection
2 | Microsoft Defender for Endpoint's web protection comprises of several features, including web threat protection, web content filtering, and custom indicators.
3 | Therefore, in this section, I am going to share hunting queries related to web protection.
4 |
5 | The KQL hunting queries will include the following products :
6 | 1. Microsoft Defender for Endpoint - Url Indicators
7 | 2. Microsoft Defender for Endpoint - Network Protection
8 | 3. Microsoft Defender for Endpoint - Web Content Filtering
9 | 4. Microsoft Defender for Cloud Apps - Unsanctioned app
10 | 5. Microsoft Defender SmartScreen
11 |
12 |
13 | ## Web Protection architecture
14 | 
15 | > [Web protection | Microsoft Learn](https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/web-protection-overview?view=o365-worldwide)
16 |
17 |
18 | ## KQL : Hunting queries
19 | **Edge browser** - Microsoft SmartScreen
20 | ```kql
21 | DeviceEvents
22 | | where Timestamp > ago(7d)
23 | | where ActionType == "SmartScreenUrlWarning"
24 | | project-reorder AdditionalFields, RemoteUrl
25 | | extend ParsedFields=parse_json(AdditionalFields)
26 | | summarize MDE_IoC = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", RemoteUrl), Experience=tostring(ParsedFields.Experience) == "CustomBlockList"),
27 | MDE_WCF = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", RemoteUrl), Experience=tostring(ParsedFields.Experience) == "CustomPolicy"),
28 | MDA_CASB = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", RemoteUrl), Experience=tostring(ParsedFields.Experience) == "CasbPolicy"),
29 | Edge_SS = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ParsedFields.Experience," : ", RemoteUrl), Experience=tostring(ParsedFields.Experience) in ("Malicious", "Phishing", "Exploit", "Untrusted")) by DeviceId, DeviceName
30 | | extend MDE_IoC_case = array_length(MDE_IoC)
31 | | extend MDE_WCF_case = array_length(MDE_WCF)
32 | | extend MDA_CASB_case = array_length(MDA_CASB)
33 | | extend Edge_SS_case = array_length(Edge_SS)
34 | | project DeviceId, DeviceName, MDE_IoC_case, MDA_CASB_case, MDE_WCF_case, Edge_SS_case, MDE_IoC, MDE_WCF, MDA_CASB, Edge_SS
35 | ```
36 |
37 | **3rd party browser** - Windows Defender Exploit Guard, Netwrk Protection
38 | ```kql
39 | DeviceEvents
40 | | where Timestamp > ago(7d)
41 | | where ActionType == "ExploitGuardNetworkProtectionBlocked"
42 | | extend ParsedFields=parse_json(AdditionalFields)
43 | | summarize MDE_IoC = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", RemoteUrl), ResponseCategory=tostring(ParsedFields.ResponseCategory) == "CustomBlockList"),
44 | MDE_WCF = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", RemoteUrl), ResponseCategory=tostring(ParsedFields.ResponseCategory) == "CustomPolicy"),
45 | MDE_NP = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ParsedFields.ResponseCategory, " : ", RemoteUrl), ResponseCategory=tostring(ParsedFields.ResponseCategory) in ("CmdCtrl", "Malicious")),
46 | MDA_CASB = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", RemoteUrl), ResponseCategory=tostring(ParsedFields.ResponseCategory) == "CasbPolicy") by DeviceId, DeviceName
47 | | extend MDE_IoC_case = array_length(MDE_IoC)
48 | | extend MDE_WCF_case = array_length(MDE_WCF)
49 | | extend MDE_NP_case = array_length(MDE_NP)
50 | | extend MDA_CASB_case = array_length(MDA_CASB)
51 | | project DeviceId, DeviceName, MDE_IoC_case, MDE_NP_case, MDE_WCF_case, MDA_CASB_case, MDE_IoC, MDE_NP, MDE_WCF, MDA_CASB
52 | ```
53 |
54 | **Bypass** - MDE Indicators Warn & MDA Monitored app
55 | ```kql
56 | DeviceEvents
57 | | where Timestamp > ago(7d)
58 | | where ActionType in ("SmartScreenUserOverride", "NetworkProtectionUserBypassEvent")
59 | | extend Browser = case(
60 | InitiatingProcessFileName has "msedge", "Edge",
61 | InitiatingProcessFileName has "chrome", "Chrome",
62 | InitiatingProcessFileName has "firefox", "Firefox",
63 | InitiatingProcessFileName has "opera", "Opera",
64 | "3rd party browser")
65 | | project Timestamp, DeviceId, DeviceName, ActionType, Browser, RemoteUrl
66 | ```
67 | ## KQL : Hunting results
68 | e.g. Edge browser - Microsoft Defender SmartScreen : "SmartScreenUrlWarning"
69 |
70 | 
71 |
72 | #### Disclaimer
73 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
74 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/04-kql-MDE-ControlledFolderAccess.md:
--------------------------------------------------------------------------------
1 | # KQL : Controlled Folder Access (CFA)
2 | Controlled Folder Access is a security feature in Microsoft Defender for Endpoint that helps protect important files from ransomware and other malicious software. It blocks unauthorized changes to designated folders and allows only trusted applications to access them, which helps prevent malware from accessing or modifying sensitive files.
3 |
4 | ## PowerShell Cmdlet
5 | **PowerShell**
6 | ```powershell
7 | # Confirm CFA configuration
8 | Get-MpPreference | Select-Object EnableControlledFolderAccess, ControlledFolderAccessAllowedApplications, ControlledFolderAccessProtectedFolders
9 |
10 | # Enable/Disable controlled folder access
11 | Set-MpPreference -EnableControlledFolderAccess AuditMode
12 | Set-MpPreference -EnableControlledFolderAccess Enabled
13 | Set-MpPreference -EnableControlledFolderAccess Disabled
14 |
15 | # Customize controlled folder access
16 | Add-MpPreference -ControlledFolderAccessProtectedFolders "c:\apps\"
17 | Add-MpPreference -ControlledFolderAccessAllowedApplications "c:\apps\test.exe"
18 | Remove-MpPreference -ControlledFolderAccessProtectedFolders "c:\apps\"
19 | Remove-MpPreference -ControlledFolderAccessAllowedApplications "c:\apps\test.exe"
20 | ```
21 |
22 | > **Note** : **Windows system folders are protected by default**
23 | > ```
24 | > c:\Users\\Documents
25 | > c:\Users\Public\Documents
26 | > c:\Users\\Pictures
27 | > c:\Users\Public\Pictures
28 | > c:\Users\Public\Videos
29 | > c:\Users\\Videos
30 | > c:\Users\\Music
31 | > c:\Users\Public\Music
32 | > c:\Users\\Favorites
33 | > ```
34 | > [Protect important folders from ransomware from encrypting your files with controlled folder access | Microsoft Learn](https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/controlled-folders?view=o365-worldwide)
35 |
36 | ## CFA quick test
37 | - Download [the CFA test tool](https://demo.wd.microsoft.com/Content/CFAtool.exe).
38 | - Create an executable file with PowerShell script.
39 | ```powershell
40 | $filePath = "C:\Users\Public\Documents\example.exe"
41 | $textContent = "This is an example file."
42 |
43 | New-Item -Path $filePath -ItemType File -Value $textContent
44 | ```
45 |
46 | ## KQL : Hunting queries
47 | **Controlled Folder Access - Block**
48 | ```kql
49 | DeviceEvents
50 | | where Timestamp > ago(7d)
51 | | where ActionType == "ControlledFolderAccessViolationBlocked"
52 | | summarize TargetFolderPath = make_list(strcat(FolderPath, " | ", InitiatingProcessFileName)) by bin(Timestamp, 1d), DeviceId, DeviceName
53 | | extend Num = array_length(TargetFolderPath)
54 | | project Timestamp, DeviceId, DeviceName, Num, TargetFolderPath
55 | ```
56 | **Controlled Folder Access - Audit**
57 | ```kql
58 | DeviceEvents
59 | | where Timestamp > ago(7d)
60 | | where ActionType == "ControlledFolderAccessViolationAudit"
61 | | summarize TargetFolderPath = make_list(strcat(FolderPath, " | ", InitiatingProcessFileName)) by bin(Timestamp, 1d), DeviceId, DeviceName
62 | | extend Num = array_length(TargetFolderPath)
63 | | project Timestamp, DeviceId, DeviceName, Num, TargetFolderPath
64 | ```
65 |
66 | ## KQL : Hunting results
67 | e.g. Controlled Folder Access - Block
68 |
69 | 
70 |
71 |
72 |
73 | #### Disclaimer
74 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
75 |
76 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/05-kql-AzureADIdentityProtection.md:
--------------------------------------------------------------------------------
1 | # KQL : Azure AD Identity Protection & Detection
2 | Azure AD Identity Protection is a cloud-based security service that helps organizations protect their identity infrastructure. It uses machine learning and threat intelligence to identify and mitigate risks related to identity and access. Some of its key features include risk-based conditional access, identity risk assessment, threat intelligence, and self-service password reset. It helps organizations to prevent identity-related attacks and improve the security of their identity infrastructure.
3 |
4 | ## KQL : Hunting queries
5 | 1. This KQL shows AAD Identity Protection data for a given month with barchart.
6 | ```kql
7 | SigninLogs
8 | | where TimeGenerated > ago(180d)
9 | | extend RemovedBracketAndQuotation = replace_regex(replace_regex(RiskEventTypes, @'[\[\]]', ''), @'"', '')
10 | | where isnotempty(RemovedBracketAndQuotation)
11 | | extend ParsedRisk =parse_json(RemovedBracketAndQuotation)
12 | | extend RiskName = split(ParsedRisk, ",")
13 | | mv-expand RiskName
14 | | extend Detection = iff(RiskName in ("impossibleTravel", "newCountry", "riskyIPAddress", "mcasSuspiciousInboxManipulationRules", "suspiciousInboxForwarding"),
15 | "Microsoft Defender for Cloud Apps", "Azure AD Identity Protection")
16 | | summarize count() by tostring(RiskName), Detection
17 | | render barchart
18 | ```
19 | > **Note** :
20 | > SigninLogs table is available in Log Analytics workspace / Microsoft Sentinel, Not in Microsoft 365 Defender.
21 | > [Stream Azure Active Directory logs to Azure Monitor logs - Microsoft Entra | Microsoft Learn](https://learn.microsoft.com/en-us/azure/active-directory/reports-monitoring/howto-integrate-activity-logs-with-log-analytics)
22 |
23 |
24 | 2. This KQL shows the daily AAD Identity Protection data for a given month.
25 | ```kql
26 | SigninLogs
27 | | where TimeGenerated > ago(180d)
28 | | extend RemovedBracketAndQuotation = replace_regex(replace_regex(RiskEventTypes, @'[\[\]]', ''), @'"', '')
29 | | where isnotempty(RemovedBracketAndQuotation)
30 | | extend ParsedRisk =parse_json(RemovedBracketAndQuotation)
31 | | extend RiskName = split(ParsedRisk, ",")
32 | | mv-expand RiskName
33 | | extend Detection = iff(RiskName in ("impossibleTravel", "newCountry", "riskyIPAddress", "mcasSuspiciousInboxManipulationRules", "suspiciousInboxForwarding"),
34 | "Microsoft Defender for Cloud Apps", "Azure AD Identity Protection")
35 | | summarize count() by tostring(RiskName), Detection,bin(TimeGenerated, 1d)
36 | | render columnchart
37 | ```
38 | > **Note** :
39 | > SigninLogs table is available in Log Analytics workspace / Microsoft Sentinel, Not in Microsoft 365 Defender.
40 | > [Stream Azure Active Directory logs to Azure Monitor logs - Microsoft Entra | Microsoft Learn](https://learn.microsoft.com/en-us/azure/active-directory/reports-monitoring/howto-integrate-activity-logs-with-log-analytics)
41 |
42 | ## KQL : Hunting results
43 | **e.g. - Case 1**
44 |
45 | 
46 |
47 | **e.g. - Case 2**
48 |
49 | 
50 |
51 | #### Disclaimer
52 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
53 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/06-kql-MDO-RemediationActions.md:
--------------------------------------------------------------------------------
1 | # KQL : MDO remediation actions
2 | Microsoft Defender for Office 365(MDO) is a cloud-based email filtering service designed to protect organizations that use the Microsoft Office 365 platform from various email-based threats such as malware, phishing, and spam. At this time, I would like to focus on the remediation actions available in Microsoft Defender for Office 365, Explorer.
3 |
4 | ## KQL : Hunting queries
5 | This KQL shows the summary of Microsoft Defender for Office 365 remediation actions.
6 | - Track each cases with **Network Message ID**
7 | - Sort **the users who got a number of actions**- e.g. Soft Delete, Hard Delete, Move to junk folder, Move to deleted items
8 | ```kql
9 | EmailEvents
10 | | where Timestamp > ago(30d)
11 | | where LatestDeliveryAction in ("Hard delete", "Soft delete", "Moved to junk folder", "Moved to deleted items")
12 | | summarize HardDelete_NetworkID = make_list_if(strcat(NetworkMessageId, @"\", Timestamp,@"\", Subject), LatestDeliveryAction == "Hard delete"),
13 | SoftDelete_NetworkID = make_list_if(strcat(NetworkMessageId, @"\", Timestamp,@"\", Subject), LatestDeliveryAction == "Soft delete"),
14 | MoveToJunk_NetworkID = make_list_if(strcat(NetworkMessageId, @"\", Timestamp,@"\", Subject), LatestDeliveryAction == "Moved to junk folder"),
15 | MoveToDelete_NetworkID = make_list_if(strcat(NetworkMessageId, @"\", Timestamp,@"\", Subject), LatestDeliveryAction == "Moved to deleted items") by RecipientEmailAddress
16 | | extend HardDelete_case = array_length(HardDelete_NetworkID)
17 | | extend SoftDelete_case = array_length(SoftDelete_NetworkID)
18 | | extend MoveToJunk_case = array_length(MoveToJunk_NetworkID)
19 | | extend MoveToDelete_case = array_length(MoveToDelete_NetworkID)
20 | | extend Sum_case = HardDelete_case + SoftDelete_case + MoveToJunk_case + MoveToDelete_case
21 | | project RecipientEmailAddress, Sum_case, HardDelete_case, SoftDelete_case, MoveToJunk_case, MoveToDelete_case, HardDelete_NetworkID, SoftDelete_NetworkID, MoveToJunk_NetworkID, MoveToDelete_NetworkID
22 | | order by Sum_case desc
23 | ```
24 |
25 | ## KQL : Hunting results
26 | **e.g. - Case**
27 |
28 | 
29 |
30 | #### Disclaimer
31 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
32 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/07-kql-XDR-NRT-CustomDetectionRule.md:
--------------------------------------------------------------------------------
1 | # KQL : XDR Custom Detection Rule with NRT
2 | A custom detection rule in Microsoft 365 Defender is a way to create a specific rule that detects certain types of threats or activities that are unique to your organization. You can configure these rules to trigger alerts or other actions when a specific condition is met, which can help improve your organization's security. Essentially, it allows you to tailor the detection capabilities of Microsoft 365 Defender to meet the specific needs of your organization.
3 |
4 | Recently, there was an update about the rule frequency - **Near-Real-Time(NRT)** and I will cover how to use the detection rule with NRT in this article.
5 |
6 | #### NRT Advantage
7 | Help faster detections and response
8 | - Detect in near real-time
9 | - Respond in near real-time
10 |
11 | #### NRT Reference
12 | 1. [Create and manage custom detection rules in Microsoft 365 Defender](https://learn.microsoft.com/en-us/microsoft-365/security/defender/custom-detection-rules?view=o365-worldwide)
13 | 2. [Respond to threats in near real-time with custom XDR detections](https://techcommunity.microsoft.com/t5/microsoft-365-defender-blog/respond-to-threats-in-near-real-time-with-custom-detections/ba-p/3761243)
14 |
15 |
16 |
17 | ## KQL : Hunting queries
18 | ```kql
19 | DeviceEvents
20 | | where Timestamp > ago(5m)
21 | | where ActionType startswith "asr" and ActionType endswith "audited"
22 | | project Timestamp, ReportId, DeviceId, DeviceName, FileName, FolderPath
23 | ```
24 | ```kql
25 | DeviceEvents
26 | | where Timestamp > ago(5m)
27 | | where ActionType startswith "asr" and ActionType endswith "blocked"
28 | | project Timestamp, ReportId, DeviceId, DeviceName, FileName, FolderPath
29 | ```
30 | ## Config : Custom Detection Rule NRT
31 | To configure a custom detection rule in the Microsoft 365 Defender portal, select [Continuous (NRT)](https://learn.microsoft.com/en-us/microsoft-365/security/defender/custom-detection-rules?view=o365-worldwide) to try NRT.
32 |
33 | 
34 | > Custom detection rule with NRT
35 |
36 | 
37 | > Custom detection rule list - ASR audit / block
38 |
39 | ## Alerts : Custom Detection Rule NRT
40 |
41 | 
42 | > Generated alert by custom detection rule
43 |
44 | #### Disclaimer
45 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
46 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/08-kql-MDE-WebProtection-CheatSheet-v3.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/08-kql-MDE-WebProtection-CheatSheet-v3.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/09-kql-MDE-ASRrule-UseCases-v2.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/09-kql-MDE-ASRrule-UseCases-v2.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/10-kql-ThreatHunting-IoCs-tips-v1.pdf.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/10-kql-ThreatHunting-IoCs-tips-v1.pdf.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/11-kql-externaldata-IoCs-threathunting.md:
--------------------------------------------------------------------------------
1 | ## KQL : externaldata IoCs threat hunting
2 | Using KQL's 'externaldata' operator is highly effective for hunting suspicious activities with IoCs.
3 | Therefore, today I would like to showcase how we can leverage externaldata with Microsoft Defender Threat Intelligence (MDTI).
4 |
5 | Additionally, I have summarized the process into three steps for leveraging external data to track Mango Sandstorm activities
6 |
7 | 
8 |
9 | ### Step 1
10 | At first, collect Mango Sandstorm IoCs in MDTI and import them as a CSV file.
11 |
12 | 
13 | > Mango Sandstorm, Microsoft Defender Threat Intelligence
14 |
15 | ### Step 2
16 | Next, upload it to an external storage such as GitHub.
17 | ```
18 | https://raw.githubusercontent.com/LearningKijo/KQL/main/KQL-Effective-Use/11-kql-MTDI-MangoSandstorm-IoCs.csv
19 | ```
20 |
21 | 
22 |
23 | ### Step 3
24 |
25 | Lastly, use the 'externaldata' operator to hunt Mango Sandstorm activities in Microsoft 365 Defender.
26 |
27 | 
28 | > Advanced Hunting page, Microsoft 365 Defender portal
29 |
30 | ## KQL : Hunting queries
31 | ```kql
32 | // MangoSandstorm C2C IoCs by MDTI
33 | let MangoSandstorm = externaldata(Type:string, Artifact:string)
34 | [@'https://raw.githubusercontent.com/LearningKijo/KQL/main/KQL-Effective-Use/11-kql-MTDI-MangoSandstorm-IoCs.csv'] with (format='csv', ignorefirstrecord = true);
35 | let Domains = (MangoSandstorm | where Type == "domain"| project Artifact);
36 | let IPaddress = (MangoSandstorm | where Type == "ip"| project Artifact);
37 | let URL = (MangoSandstorm | where Type == "url"| project Artifact);
38 | DeviceNetworkEvents
39 | | where Timestamp > ago(14d)
40 | | where RemoteUrl has_any (Domains) or RemoteUrl in (URL) or RemoteIP in (IPaddress)
41 | | project Timestamp, DeviceId, DeviceName, ActionType, RemoteIP, RemoteUrl, RemotePort, InitiatingProcessFileName
42 | ```
43 | 
44 |
45 |
46 | ## Reference
47 | [What’s New: MDTI Interoperability with Microsoft 365 Defender](https://techcommunity.microsoft.com/t5/microsoft-defender-threat/what-s-new-mdti-interoperability-with-microsoft-365-defender/ba-p/3799846)
48 |
49 | #### Disclaimer
50 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
51 |
52 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/12-kql-externaldata-IoCs-threathunting-tips-v1.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/12-kql-externaldata-IoCs-threathunting-tips-v1.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/13-kql-AiTM-HuntingInsight-Part1.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/13-kql-AiTM-HuntingInsight-Part1.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/13-kql-AiTM-HuntingInsight-Part2.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/13-kql-AiTM-HuntingInsight-Part2.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/13-kql-AiTM-HuntingInsight-Part3.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/13-kql-AiTM-HuntingInsight-Part3.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/13-kql-AiTM-HuntingInsight-Part4.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/13-kql-AiTM-HuntingInsight-Part4.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/14-kql-MFAfatigue-HuntingInsight.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/14-kql-MFAfatigue-HuntingInsight.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/15-kql-Phishing-db-hunting.md:
--------------------------------------------------------------------------------
1 | # Phishing DB hunting
2 | These queries will help find out the inbound emails which include potential phishing links.
3 | 1. [Phishing Domain Database](https://github.com/mitchellkrogza/Phishing.Database/tree/master)
4 | 2. [PhishTank](https://phishtank.org/)
5 |
6 | ### Phishing Domain Database
7 | ```kql
8 | // Phishing Domain Database
9 | // https://github.com/mitchellkrogza/Phishing.Database/tree/master
10 | let PhishingDB = materialize(externaldata(Phish_url:string)[@'https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-links-ACTIVE-TODAY.txt'] with (format='txt'));
11 | let URLs = materialize((PhishingDB | project Phish_url));
12 | EmailUrlInfo
13 | | where TimeGenerated > ago(7d)
14 | | where Url has_any (URLs)
15 | | join kind = inner EmailEvents on NetworkMessageId
16 | | join kind = leftouter UrlClickEvents on NetworkMessageId
17 | | where LatestDeliveryLocation != "Quarantine"
18 | | project TimeGenerated, NetworkMessageId, SenderFromAddress, RecipientEmailAddress, Subject, LatestDeliveryLocation, Url, ActionType, IsClickedThrough
19 | ```
20 |
21 | ### PhishTank
22 | ```kql
23 | // PhishTank
24 | // https://data.phishtank.com/
25 | let PhishingDB = materialize(externaldata(phish_id:string, url:string, phish_detail_url:string, submission_time:datetime, verified:string, verification_time:datetime, online:string, target:string)[@'http://data.phishtank.com/data/online-valid.csv'] with (format='csv', ignorefirstrecord = true));
26 | let URLs = materialize((PhishingDB | where verification_time > ago(8h) | project url));
27 | EmailUrlInfo
28 | | where TimeGenerated > ago(7d)
29 | | where Url has_any (URLs)
30 | | join kind = inner EmailEvents on NetworkMessageId
31 | | join kind = leftouter UrlClickEvents on NetworkMessageId
32 | | where LatestDeliveryLocation != "Quarantine"
33 | | project TimeGenerated, NetworkMessageId, SenderFromAddress, RecipientEmailAddress, Subject, ThreatTypes, LatestDeliveryLocation, Url, ActionType, IsClickedThrough
34 | ```
35 |
36 | ## Appendix
37 | Regarding PhishTank, there is a huge amount of data. Therefore, I filtered the phishing link data every 8 hours. This is a sample query that returns the total number of phishing links detected/reported every 8 hours.
38 | ```kql
39 | // URLs case calculation for every 8 hours
40 | externaldata(phish_id:string, url:string, phish_detail_url:string, submission_time:datetime, verified:string, verification_time:datetime, online:string, target:string)[@'http://data.phishtank.com/data/online-valid.csv'] with (format='csv', ignorefirstrecord = true)
41 | | summarize URLs = count() by bin(verification_time, 8h)
42 | ```
43 | 
44 | > the total number of phishing links detected/reported every 8 hours, Microsoft Sentinel
45 |
46 | #### Disclaimer
47 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
48 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/16-kql-MDE-WebProtection-NetworkData.md:
--------------------------------------------------------------------------------
1 | # Web Protection detection with KQL
2 | Thanks for checking out Web Protection threat hunting series.
3 | In this article, I'll be diving into gathering network insights by merging data from the MDE network table.
4 | If you missed our previous Web Protection threat hunting articles, you can catch up on them here.
5 |
6 | - [x] [03-kql-MDE-WebProtection.md](https://github.com/LearningKijo/KQL/blob/main/KQL-Effective-Use/03-kql-MDE-WebProtection.md)
7 | - [x] [08-kql-MDE-WebProtection-CheatSheet-v3.pdf](https://github.com/LearningKijo/KQL/blob/main/KQL-Effective-Use/08-kql-MDE-WebProtection-CheatSheet-v3.pdf)
8 |
9 | ## KQL : Hunting queries
10 | This query helps you understand URLs accessed by end-users detected by MDE IoC URL and Web Content Filtering.
11 | It also reveals the type of browser launched by the end-user.
12 | Furthermore, by combining network data (DeviceNetworkEvents) with URLs, the query provides insights into IP addresses and ports.
13 |
14 | ```kql
15 | let NetworkLogs = (DeviceNetworkEvents
16 | | where Timestamp > ago(14d)
17 | | where RemotePort in (80, 443)
18 | | extend IPaddress = RemoteIP
19 | | extend Port = RemotePort
20 | | extend URL = RemoteUrl);
21 | DeviceEvents
22 | | where Timestamp > ago(14d)
23 | | where ActionType in ("SmartScreenUrlWarning", "ExploitGuardNetworkProtectionBlocked")
24 | | extend Parsed = parse_json(AdditionalFields)
25 | | extend SmartScreen = Parsed.Experience
26 | | extend NetworkProtection = Parsed.ResponseCategory
27 | | where SmartScreen in ("CustomBlockList", "CustomPolicy") or NetworkProtection in ("CustomBlockList", "CustomPolicy")
28 | | extend DetectionType = case(
29 | ActionType == "SmartScreenUrlWarning" and SmartScreen == "CustomBlockList", "Edge / IoC URL",
30 | ActionType == "SmartScreenUrlWarning" and SmartScreen == "CustomPolicy", "Edge / Web Content Filtering",
31 | ActionType == "ExploitGuardNetworkProtectionBlocked" and NetworkProtection == "CustomBlockList", "3rd party / IoC URL",
32 | ActionType == "ExploitGuardNetworkProtectionBlocked" and NetworkProtection == "CustomPolicy", "3rd party / Web Content Filtering",
33 | "N/A"
34 | )
35 | | join kind=inner NetworkLogs on RemoteUrl
36 | | project Timestamp, DeviceId, DeviceName, DetectionType, InitiatingProcessFileName, URL, IPaddress, Port
37 | ```
38 |
39 | > [!Important]
40 | > In DeviceNetworkEvents, URLs may appear as ***'ConnectionSuccess'***, but this is the expected result due to the three-way handshake that occurs before an IoC, such as blocking a URL.
41 | > Technically, end users were blocked from accessing the URL, even if the record shows ***'ConnectionSuccess'***.
42 | > MS docs : [IP/URL Indicators: Network protection and the TCP three-way handshake](https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/manage-indicators?view=o365-worldwide#ipurl-indicators-network-protection-and-the-tcp-three-way-handshake)
43 |
44 | 
45 | > Query result in Advanced Hunting, Microsoft 365 Defender
46 |
47 | #### Disclaimer
48 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
49 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/17-kql-MITRE-ATTCK-Detection.md:
--------------------------------------------------------------------------------
1 | # Analyzing MITRE ATT&CK Detection with KQL
2 | Welcome to [KQL-Effective-Use](https://github.com/LearningKijo/KQL/tree/main/KQL-Effective-Use).
3 | Today, I'm thrilled to share two insightful Kusto Query Language (KQL) queries for analyzing MITRE ATT&CK techniques and their related categories.
4 |
5 | ## KQL : Hunting queries
6 | 1. This query displays alerts detected in all Defender security products and correlates each of them with MITRE ATT&CK techniques.
7 | Each record (MITRE ATT&CK technique) lists the details of alerts detected in each product as dynamic values, including detection time, ID, title and detection source.
8 |
9 | ```kql
10 | AlertInfo
11 | | where TimeGenerated > ago(14d)
12 | | where isnotempty(AttackTechniques)
13 | | extend Parsed = parse_json(AttackTechniques)
14 | | mv-expand Parsed
15 | | extend MITRE_ATTCK = tostring(Parsed)
16 | | extend PackedData = strcat(format_datetime(TimeGenerated,'yyyy-M-dd H:mm:ss'), " : ", AlertId, " : ", Title, " : ", ServiceSource)
17 | | summarize MDE = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Endpoint"),
18 | MDO = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Office 365"),
19 | MDI = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Identity"),
20 | MDA = make_set_if(PackedData, ServiceSource == "Microsoft Cloud App Security"),
21 | Entra = make_set_if(PackedData, ServiceSource == "AAD Identity Protection"),
22 | M365D = make_set_if(PackedData, ServiceSource == "Microsoft 365 Defender") by MITRE_ATTCK
23 | | extend MDE_case = array_length(MDE)
24 | | extend MDO_case = array_length(MDO)
25 | | extend MDI_case = array_length(MDI)
26 | | extend MDA_case = array_length(MDA)
27 | | extend Entra_case = array_length(Entra)
28 | | extend M365D_case = array_length(M365D)
29 | | extend SUM = MDE_case + MDO_case + MDI_case + MDA_case + Entra_case + M365D_case
30 | | project MITRE_ATTCK, SUM, MDE, MDO, MDI, MDA, Entra, M365D
31 | | order by SUM desc
32 | ```
33 | 
34 |
35 |
36 | 2. This query displays alerts detected in all Defender security products by threat category and by product.
37 | Each record (threat category) lists the details of alerts detected in each product as dynamic values, including detection time, id, title, detection source, and MITRE ATT&CK technique.
38 |
39 | ```kql
40 | AlertInfo
41 | | where TimeGenerated > ago(14d)
42 | | where isnotempty(AttackTechniques)
43 | | extend Parsed = parse_json(AttackTechniques)
44 | | mv-expand Parsed
45 | | extend MITRE_ATTCK = tostring(Parsed)
46 | | extend PackedData = strcat(format_datetime(TimeGenerated,'yyyy-M-dd H:mm:ss'), " : ", AlertId, " : ", Title, " : ", ServiceSource, " : ", MITRE_ATTCK)
47 | | summarize MDE = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Endpoint"),
48 | MDO = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Office 365"),
49 | MDI = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Identity"),
50 | MDA = make_set_if(PackedData, ServiceSource == "Microsoft Cloud App Security"),
51 | Entra = make_set_if(PackedData, ServiceSource == "AAD Identity Protection"),
52 | M365D = make_set_if(PackedData, ServiceSource == "Microsoft 365 Defender") by Category
53 | | extend MDE_case = array_length(MDE)
54 | | extend MDO_case = array_length(MDO)
55 | | extend MDI_case = array_length(MDI)
56 | | extend MDA_case = array_length(MDA)
57 | | extend Entra_case = array_length(Entra)
58 | | extend M365D_case = array_length(M365D)
59 | | extend SUM = MDE_case + MDO_case + MDI_case + MDA_case + Entra_case + M365D_case
60 | | project Category, SUM, MDE, MDO, MDI, MDA, Entra, M365D
61 | | order by SUM desc
62 | ```
63 | 
64 |
65 |
66 | #### Disclaimer
67 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
68 |
--------------------------------------------------------------------------------
/KQL-Effective-Use/old/08-kql-MDE-WebProtection-CheatSheet-v2.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/old/08-kql-MDE-WebProtection-CheatSheet-v2.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/old/13-kql-AiTM-HuntingInsight-Part2_v1.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LearningKijo/KQL/dd920f55bc61bfcddc17a39aa339ad33a727f778/KQL-Effective-Use/old/13-kql-AiTM-HuntingInsight-Part2_v1.pdf
--------------------------------------------------------------------------------
/KQL-Effective-Use/old/WIP-kql-MDE-NetworkProtection.md:
--------------------------------------------------------------------------------
1 | # KQL : Network Protection - WIP
2 |
3 | 
4 |
5 | ```kql
6 | DeviceEvents
7 | | where Timestamp > ago(7d)
8 | | where ActionType == "ExploitGuardNetworkProtectionBlocked"
9 | | extend Parsed = parse_json(AdditionalFields)
10 | | where Parsed.ResponseCategory == "CmdCtrl"
11 | | extend Category = Parsed.ResponseCategory
12 | | project Timestamp, DeviceId, DeviceName, ActionType, Category, RemoteUrl
13 | ```
14 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/01-Email-Audit-SafeAttachments-GlobalSetting.md:
--------------------------------------------------------------------------------
1 | # Email Audit SafeAttachments GlobalSetting
2 | This query displays the configuration auditing for ['Safe Attachments for SharePoint, OneDrive, and Microsoft Teams'](https://learn.microsoft.com/en-us/microsoft-365/security/office-365-security/safe-attachments-for-spo-odfb-teams-configure?view=o365-worldwide) and ['Safe Documents'](https://learn.microsoft.com/en-us/microsoft-365/security/office-365-security/safe-documents-in-e5-plus-security-about?view=o365-worldwide) in Microsoft Defender for Office 365.
3 |
4 | #### Table name & Description
5 | - [CloudAppEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-cloudappevents-table?view=o365-worldwide) : Events involving accounts and objects in Office 365 and other cloud apps and services
6 |
7 | #### Query
8 | ```kusto
9 | CloudAppEvents
10 | | where Application == "Microsoft Exchange Online"
11 | | where ActionType == "Set-AtpPolicyForO365"
12 | | mv-expand ActivityObjects
13 | | extend Name = tostring(ActivityObjects.Name)
14 | | extend Value = tostring(ActivityObjects.Value)
15 | | where Name in ("EnableATPForSPOTeamsODB", "EnableSafeDocs", "AllowSafeDocsOpen")
16 | | extend packed = pack(Name, Value)
17 | | summarize PackedInfo = make_bag(packed), ActionType = any(ActionType) by Timestamp, AccountDisplayName
18 | | evaluate bag_unpack(PackedInfo)
19 | ```
20 |
21 | #### Result
22 | 
23 |
24 |
25 | #### Disclaimer
26 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
27 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/02-EOP-Detection-Daily-Percentage.md:
--------------------------------------------------------------------------------
1 | # EOP Detection Daily Percentage
2 | This query shows the daily percentage of EOP detections.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | EmailEvents
9 | | where Timestamp > ago(7d)
10 | | where isnotempty(DetectionMethods)
11 | | extend EOP_detection = parse_json(DetectionMethods)
12 | | summarize TotalEmailCount = count(),
13 | Phish_detection = countif(isnotempty(EOP_detection.Phish)),
14 | Malware_detection = countif(isnotempty(EOP_detection.Malware)),
15 | URL_malicious_reputation = countif(EOP_detection.Phish == @'["URL malicious reputation"]' or EOP_detection.Malware == @'["URL malicious reputation"]'),
16 | Advanced_filter = countif(EOP_detection.Phish == @'["Advanced filter"]'),
17 | General_filter = countif(EOP_detection.Phish == @'["General filter"]'),
18 | Spoof_intra_org = countif(EOP_detection.Phish == @'["Spoof intra-org"]'),
19 | Spoof_external_domain = countif(EOP_detection.Phish == @'["Spoof external domain"]'),
20 | Spoof_DMARC = countif(EOP_detection.Phish == @'["Spoof DMARC"]'),
21 | Impersonation_brand = countif(EOP_detection.Phish == @'["Impersonation brand"]'),
22 | Mixed_analysis_detection= countif(EOP_detection.Phish == @'["Mixed analysis detection"]'),
23 | File_reputation = countif(EOP_detection.Phish == @'["File reputation"]' or EOP_detection.Malware == @'["File reputation"]'),
24 | Fingerprint_matching = countif(EOP_detection.Phish == @'["Fingerprint matching"]'),
25 | Antimalware_engine = countif(EOP_detection.Malware == @'["Antimalware engine"]') by bin(Timestamp, 1d)
26 | | extend Phish_detection_percentage = todouble(round(Phish_detection / todouble(TotalEmailCount) * 100, 2))
27 | | extend Malware_detection_percentage = todouble(round(Malware_detection / todouble(TotalEmailCount) * 100, 2))
28 | | extend URL_malicious_reputation_percentage = todouble(round(URL_malicious_reputation / todouble(TotalEmailCount) * 100, 2))
29 | | extend Advanced_filter_percentage = todouble(round(Advanced_filter / todouble(TotalEmailCount) * 100, 2))
30 | | extend General_filter_percentage = todouble(round(General_filter / todouble(TotalEmailCount) * 100, 2))
31 | | extend Spoof_intra_org_percentage = todouble(round(Spoof_intra_org / todouble(TotalEmailCount) * 100, 2))
32 | | extend Spoof_external_domain_percentage = todouble(round(Spoof_external_domain / todouble(TotalEmailCount) * 100, 2))
33 | | extend Spoof_DMARC_percentage = todouble(round(Spoof_DMARC / todouble(TotalEmailCount) * 100, 2))
34 | | extend Impersonation_brand_percentage = todouble(round(Impersonation_brand / todouble(TotalEmailCount) * 100, 2))
35 | | extend Mixed_analysis_detection_percentage = todouble(round(Mixed_analysis_detection / todouble(TotalEmailCount) * 100, 2))
36 | | extend File_reputation_percentage = todouble(round(File_reputation / todouble(TotalEmailCount) * 100, 2))
37 | | extend Fingerprint_matching_percentage = todouble(round(Fingerprint_matching / todouble(TotalEmailCount) * 100, 2))
38 | | extend Antimalware_engine_percentage = todouble(round(Antimalware_engine / todouble(TotalEmailCount) * 100, 2))
39 | | project Timestamp, TotalEmailCount, Phish_detection_percentage, Malware_detection_percentage, URL_malicious_reputation_percentage, Advanced_filter_percentage, General_filter_percentage, Spoof_intra_org_percentage, Spoof_external_domain_percentage, Spoof_DMARC_percentage, Impersonation_brand_percentage, Mixed_analysis_detection_percentage, File_reputation_percentage, Antimalware_engine_percentage
40 | ```
41 |
42 | #### Disclaimer
43 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
44 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/03-MDO-Detection-Daily-Percentage.md:
--------------------------------------------------------------------------------
1 | # MDO Detection Daily Percentage
2 | This query shows the daily percentage of MDO detections.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | EmailEvents
9 | | where Timestamp > ago(7d)
10 | | where isnotempty(DetectionMethods)
11 | | extend MDO_detection = parse_json(DetectionMethods)
12 | | summarize TotalEmailCount = count(),
13 | Phish_detection = countif(isnotempty(MDO_detection.Phish)),
14 | Malware_detection = countif(isnotempty(MDO_detection.Malware)),
15 | URL_detonation_reputation = countif(MDO_detection.Phish == @'["URL detonation reputation"]' or MDO_detection.Malware == @'["URL detonation reputation"]'),
16 | URL_detonation = countif(MDO_detection.Phish == @'["URL detonation"]' or MDO_detection.Malware == @'["URL detonation"]'),
17 | Impersonation_user = countif(MDO_detection.Phish == @'["Impersonation user"]'),
18 | Impersonation_domain = countif(MDO_detection.Phish == @'["Impersonation domain"]'),
19 | Mailbox_intelligence_impersonation = countif(MDO_detection.Phish == @'["Mailbox intelligence impersonation"]'),
20 | File_detonation = countif(MDO_detection.Phish == @'["File detonation"]' or MDO_detection.Malware == @'["File detonation"]'),
21 | File_detonation_reputation = countif(MDO_detection.Phish == @'["File detonation reputation"]' or MDO_detection.Malware == @'["File detonation reputation"]'),
22 | Campaign = countif(MDO_detection.Phish == @'["Campaign"]' or MDO_detection.Malware == @'["Campaign"]') by bin(Timestamp, 1d)
23 | | extend Phish_detection_percentage = todouble(round(Phish_detection / todouble(TotalEmailCount) * 100, 2))
24 | | extend Malware_detection_percentage = todouble(round(Malware_detection / todouble(TotalEmailCount) * 100, 2))
25 | | extend URL_detonation_reputation_percentage = todouble(round(URL_detonation_reputation / todouble(TotalEmailCount) * 100, 2))
26 | | extend URL_detonation_percentage = todouble(round(URL_detonation / todouble(TotalEmailCount) * 100, 2))
27 | | extend Impersonation_user_percentage = todouble(round(Impersonation_user / todouble(TotalEmailCount) * 100, 2))
28 | | extend Impersonation_domain_percentage = todouble(round(Impersonation_domain / todouble(TotalEmailCount) * 100, 2))
29 | | extend Mailbox_intelligence_impersonation_percentage = todouble(round(Mailbox_intelligence_impersonation / todouble(TotalEmailCount) * 100, 2))
30 | | extend File_detonation_percentage = todouble(round(File_detonation / todouble(TotalEmailCount) * 100, 2))
31 | | extend File_detonation_reputation_percentage = todouble(round(File_detonation_reputation / todouble(TotalEmailCount) * 100, 2))
32 | | extend Campaign_percentage = todouble(round(Campaign / todouble(TotalEmailCount) * 100, 2))
33 | | project Timestamp, TotalEmailCount, Phish_detection_percentage, Malware_detection_percentage, URL_detonation_reputation_percentage, URL_detonation_percentage, Impersonation_user_percentage, Impersonation_domain_percentage, Mailbox_intelligence_impersonation_percentage, File_detonation_percentage, File_detonation_reputation_percentage, Campaign_percentage
34 | ```
35 |
36 | #### Disclaimer
37 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
38 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/04-EOP-MalwareDetection-Filtering.md:
--------------------------------------------------------------------------------
1 | # EOP Malware Detection filtering
2 | This query displays weekly EOP malware detection.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | EmailEvents
9 | | where Timestamp > ago(30d)
10 | | where isnotempty(DetectionMethods)
11 | | extend EOP_detection = parse_json(DetectionMethods)
12 | | where EOP_detection.Malware in
13 | (
14 | @'["File reputation"]',
15 | @'["Antimalware engine"]',
16 | @'["URL malicious reputation"]'
17 | )
18 | | extend SenderFromAddress_IPv4 = strcat(SenderFromAddress, ", ", SenderIPv4)
19 | | project Timestamp, NetworkMessageId, Subject, SenderFromAddress_IPv4, RecipientEmailAddress, DeliveryLocation, EOP_detection.Malware
20 | ```
21 |
22 | #### Disclaimer
23 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
24 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/05-EOP-PhishingDetection-Filtering.md:
--------------------------------------------------------------------------------
1 | # EOP Phishing Detection filtering
2 | This query displays weekly EOP phishing detection.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | #### Query
8 | ```kusto
9 | EmailEvents
10 | | where Timestamp > ago(7d)
11 | | where isnotempty(DetectionMethods)
12 | | extend EOP_detection = parse_json(DetectionMethods)
13 | | where EOP_detection.Phish in
14 | (
15 | @'["URL malicious reputation"]',
16 | @'["Advanced filter"]',
17 | @'["General filter"]',
18 | @'["Spoof intra-org"]',
19 | @'["Spoof external domain"]',
20 | @'["Spoof DMARC"]',
21 | @'["Impersonation brand"]',
22 | @'["Mixed analysis detection"]',
23 | @'["File reputation"]',
24 | @'["Fingerprint matching"]'
25 | )
26 | | extend SenderFromAddress_IPv4 = strcat(SenderFromAddress, ", ", SenderIPv4)
27 | | project Timestamp, NetworkMessageId, Subject, SenderFromAddress_IPv4, RecipientEmailAddress, DeliveryLocation, EOP_detection.Phish
28 | ```
29 |
30 | ####
31 |
32 | #### Disclaimer
33 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
34 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/06-MDO-MalwareDetection-Filtering.md:
--------------------------------------------------------------------------------
1 | # MDO Malware Detection filtering
2 | This query displays weekly MDO malware detection.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | #### Query
8 | ```kusto
9 | EmailEvents
10 | | where Timestamp > ago(7d)
11 | | where isnotempty(DetectionMethods)
12 | | extend MDO_detection = parse_json(DetectionMethods)
13 | | where MDO_detection.Malware in
14 | (
15 | @'["File detonation"]',
16 | @'["File detonation reputation"]',
17 | @'["URL detonation"]',
18 | @'["URL detonation reputation"]',
19 | @'["Campaign"]'
20 | )
21 | | extend SenderFromAddress_IPv4 = strcat(SenderFromAddress, ", ", SenderIPv4)
22 | | project Timestamp, NetworkMessageId, Subject, SenderFromAddress_IPv4, RecipientEmailAddress, DeliveryLocation, EOP_detection.Phish
23 | ```
24 |
25 | ####
26 |
27 | #### Disclaimer
28 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
29 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/07-MDO-PhishingDetection-Filtering.md:
--------------------------------------------------------------------------------
1 | # MDO Phishing Detection filtering
2 | This query displays weekly MDO phishing detection.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | #### Query
8 | ```kusto
9 | EmailEvents
10 | | where Timestamp > ago(7d)
11 | | where isnotempty(DetectionMethods)
12 | | extend MDO_detection = parse_json(DetectionMethods)
13 | | where MDO_detection.Phish in
14 | (
15 | @'["URL detonation reputation"]',
16 | @'["URL detonation"]',
17 | @'["Impersonation user"]',
18 | @'["Impersonation domain"]',
19 | @'["Mailbox intelligence impersonation"]',
20 | @'["File detonation"]',
21 | @'["File detonation reputation"]',
22 | @'["Campaign"]'
23 | )
24 | | extend SenderFromAddress_IPv4 = strcat(SenderFromAddress, ", ", SenderIPv4)
25 | | project Timestamp, NetworkMessageId, Subject, SenderFromAddress_IPv4, RecipientEmailAddress, DeliveryLocation, MDO_detection.Phish
26 | ```
27 |
28 | ####
29 |
30 | #### Disclaimer
31 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
32 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/08-MDO-UserList-for-RemediationAction.md:
--------------------------------------------------------------------------------
1 | # MDO User List for Remediation Action
2 | This query tracks MDO remediation actions, such as Soft Delete, Hard Delete, Move to Junk Folder, Move to Deleted Items, with Network Message ID.
3 | It also sorts the users based on the number of actions they received.
4 |
5 | #### Table name & Description
6 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
7 |
8 | ```kusto
9 | EmailEvents
10 | | where Timestamp > ago(30d)
11 | | where LatestDeliveryAction in ("Hard delete", "Soft delete", "Moved to junk folder", "Moved to deleted items")
12 | | summarize HardDelete_NetworkID = make_list_if(strcat(NetworkMessageId, @"\", Timestamp,@"\", Subject), LatestDeliveryAction == "Hard delete"),
13 | SoftDelete_NetworkID = make_list_if(strcat(NetworkMessageId, @"\", Timestamp,@"\", Subject), LatestDeliveryAction == "Soft delete"),
14 | MoveToJunk_NetworkID = make_list_if(strcat(NetworkMessageId, @"\", Timestamp,@"\", Subject), LatestDeliveryAction == "Moved to junk folder"),
15 | MoveToDelete_NetworkID = make_list_if(strcat(NetworkMessageId, @"\", Timestamp,@"\", Subject), LatestDeliveryAction == "Moved to deleted items") by RecipientEmailAddress
16 | | extend HardDelete_case = array_length(HardDelete_NetworkID)
17 | | extend SoftDelete_case = array_length(SoftDelete_NetworkID)
18 | | extend MoveToJunk_case = array_length(MoveToJunk_NetworkID)
19 | | extend MoveToDelete_case = array_length(MoveToDelete_NetworkID)
20 | | extend Sum_case = HardDelete_case + SoftDelete_case + MoveToJunk_case + MoveToDelete_case
21 | | project RecipientEmailAddress, Sum_case, HardDelete_case, SoftDelete_case, MoveToJunk_case, MoveToDelete_case, HardDelete_NetworkID, SoftDelete_NetworkID, MoveToJunk_NetworkID, MoveToDelete_NetworkID
22 | | order by Sum_case desc
23 | ```
24 |
25 | #### Disclaimer
26 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
27 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/09-Email-MalwareDetection-byAccount.md:
--------------------------------------------------------------------------------
1 | # Email Malware Detection by Account
2 | This query displays weekly email malware detection cases sorted by account.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 | - [EmailAttachmentInfo](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailattachmentinfo-table?view=o365-worldwide) : Information about files attached to emails
7 |
8 | ```kusto
9 | EmailEvents
10 | | where Timestamp > ago(7d)
11 | | where isnotempty(ThreatNames)
12 | | join kind=inner EmailAttachmentInfo on NetworkMessageId
13 | | extend ThreatFamilyAttachment = strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " /", ThreatNames, " /", FileName, " /", NetworkMessageId)
14 | | summarize ThreatFamily_wih_Attachment= make_list(ThreatFamilyAttachment) by RecipientEmailAddress
15 | | extend Case = array_length(ThreatFamily_wih_Attachment)
16 | | project RecipientEmailAddress, Case, ThreatFamily_wih_Attachment
17 | | sort by Case desc
18 | ```
19 |
20 | #### Disclaimer
21 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
22 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/10-UserInsights-ClickedSuspiciousURLs-PhishMalware-Emails.md:
--------------------------------------------------------------------------------
1 | # User Insights: Clicked Suspicious URLs in Phish/Malware Emails
2 | This query provides insights on users who clicked on a suspicious URL from phishing/malware-categorized inbound emails over the past 7 days.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 | - [UrlClickEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-urlclickevents-table?view=o365-worldwide) : Safe Links clicks from email messages, Teams, and Office 365 apps
7 |
8 | ```kusto
9 | let UrlClicked = (UrlClickEvents
10 | | where Timestamp > ago(30d)
11 | | where ActionType == "ClickAllowed" or IsClickedThrough !="0"
12 | | extend Device_IPv4 = IPAddress
13 | | project ActionType, Device_IPv4, Url, UrlChain, IPAddress, NetworkMessageId);
14 | EmailEvents
15 | | where Timestamp > ago(7d)
16 | | where isnotempty(ThreatTypes) and EmailDirection == "Inbound"
17 | | where ThreatTypes has_any ("Malware", "Phish")
18 | | extend SenderFromAddress_IPv4 = strcat(SenderFromAddress, ", ", SenderIPv4)
19 | | join kind = inner UrlClicked on NetworkMessageId
20 | | project Timestamp,NetworkMessageId, Subject, SenderFromAddress_IPv4,
21 | RecipientEmailAddress, ThreatTypes, ActionType, Url, UrlChain, Device_IPv4,
22 | LatestDeliveryLocation, LatestDeliveryAction, EmailAction, EmailActionPolicy
23 | ```
24 |
25 | #### Result
26 | 
27 |
28 | #### Disclaimer
29 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
30 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/11-Email-Weekly-DetectionTrend.md:
--------------------------------------------------------------------------------
1 | # Email Weekly Detection Trend
2 | This query displays the weekly detection trends captured by MDO and EOP for Phish, Malware, and Spam.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | EmailEvents
9 | | where Timestamp > ago(7d)
10 | | where isnotempty(ThreatTypes)
11 | | extend StringtoDynamic = split(ThreatTypes, ", ")
12 | | mv-expand StringtoDynamic
13 | | extend EmailThreat = tostring(StringtoDynamic)
14 | | summarize Case = count() by EmailThreat, bin(Timestamp, 1d)
15 | | render linechart
16 | ```
17 |
18 | #### Disclaimer
19 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
20 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/12-Email-MalwarePhishing-Detection-Trends.md:
--------------------------------------------------------------------------------
1 | # Targeted Attacks : Malware and Phishing Detection Trends
2 | This query displays the detection trend for malware and phishing-related incidents targeting users over the past 30 days.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | EmailEvents
9 | | where Timestamp > ago(30d)
10 | | where EmailDirection == "Inbound"
11 | | where ThreatTypes in ("Malware", "Phish")
12 | | summarize DetectionCase = count() by bin(Timestamp, 1d), RecipientEmailAddress
13 | | render linechart
14 | ```
15 |
16 | #### Disclaimer
17 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
18 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/13-Email-Spam-Detection-Trend.md:
--------------------------------------------------------------------------------
1 | # Targeted Attacks : Spam Detection Trend
2 | This query displays the detection trend for malware and phishing-related incidents targeting users over the past 30 days.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | EmailEvents
9 | | where Timestamp > ago(30d)
10 | | where EmailDirection == "Inbound"
11 | | where ThreatTypes == "Spam"
12 | | summarize DetectionCase = count() by bin(Timestamp, 1d), RecipientEmailAddress
13 | | render linechart
14 | ```
15 |
16 | #### Disclaimer
17 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
18 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/14-MDO-QRcode-VolumeInboundEmails.md:
--------------------------------------------------------------------------------
1 | # QR code, volume of inbound emails
2 | This query displays volume of inbound emails with QR code in last 30 days
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | EmailEvents
9 | | where Timestamp > ago(30d)
10 | | where EmailDirection == "Inbound"
11 | | join EmailUrlInfo on NetworkMessageId
12 | | where UrlLocation == "QRCode"
13 | | summarize dcount(NetworkMessageId) by bin(Timestamp, 1d)
14 | | render timechart
15 | ```
16 |
17 | #### Reference
18 | [Hunting and responding to QR code-based phishing attacks with Defender for Office 365](https://techcommunity.microsoft.com/t5/microsoft-defender-for-office/hunting-and-responding-to-qr-code-based-phishing-attacks-with/ba-p/4074730)
19 |
20 | #### Disclaimer
21 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
22 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/15-MDO-QRcode-DeliveredEmail.md:
--------------------------------------------------------------------------------
1 | # Emails delivered having URLs(QR codes)
2 | This query displays emails delivered having URLs in the form of QR codes.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | EmailEvents
9 | | where Timestamp > ago(7d)
10 | | where EmailDirection == "Inbound"
11 | | where DeliveryAction == "Delivered"
12 | | join EmailUrlInfo on NetworkMessageId
13 | | where UrlLocation == "QRCode"
14 | | project Timestamp, NetworkMessageId, SenderFromAddress, Subject, Url, UrlDomain, UrlLocation
15 | ```
16 |
17 | #### Reference
18 | [Hunting and responding to QR code-based phishing attacks with Defender for Office 365](https://techcommunity.microsoft.com/t5/microsoft-defender-for-office/hunting-and-responding-to-qr-code-based-phishing-attacks-with/ba-p/4074730)
19 |
20 | #### Disclaimer
21 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
22 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/16-Emails-QRcode-SuspiciousKeywordsSubject.md:
--------------------------------------------------------------------------------
1 | # Emails & QR code with suspicious keywords in subject
2 | This query displays emails with suspicious keywords in subject.
3 |
4 | #### Table name & Description
5 | - [EmailEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-emailevents-table?view=o365-worldwide) : Microsoft 365 email events, including email delivery and blocking events
6 |
7 | ```kusto
8 | let SubjectKeywords = ()
9 | {
10 | pack_array("authorize", "authenticate", "account", "confirmation", "QR", "login", "password", "payment", "urgent", "verify");
11 | };
12 | EmailEvents
13 | | where Timestamp > ago(7d)
14 | | where EmailDirection == "Inbound"
15 | | where DeliveryAction == "Delivered"
16 | | where Subject has_any (SubjectKeywords)
17 | | join EmailUrlInfo on NetworkMessageId
18 | | where UrlLocation == "QRCode"
19 | ```
20 |
21 | #### Reference
22 | [Hunting and responding to QR code-based phishing attacks with Defender for Office 365](https://techcommunity.microsoft.com/t5/microsoft-defender-for-office/hunting-and-responding-to-qr-code-based-phishing-attacks-with/ba-p/4074730)
23 |
24 | #### Disclaimer
25 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
26 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/17-MDO-DetectedURL-Insights.md:
--------------------------------------------------------------------------------
1 | # URL & Domain Insights from MDO Alerts Detection
2 | This query displays URLs (domains) from Microsoft Defender for Office 365 detected alerts. You can also leverage this query as a function.
3 |
4 | Thanks to the Unified Security Operations Platform, there are now no boundaries for threat hunting.
5 | You can use various tables across XDR and Sentinel. In the past, I’ve seen useful queries like ['Phishing Link Clicks in Network Traffic' from a blog](https://techcommunity.microsoft.com/t5/microsoft-sentinel-blog/identifying-adversary-in-the-middle-aitm-phishing-attacks/ba-p/3991358).
6 | However, due to the integration, SecurityAlert table no longer exists in Advanced Hunting. Even though we switched to using the AlertInfo and AlertEvidence tables, they use different columns and data types.
7 | To leverage the great query, I rewrote it to fit this advanced hunting environment.
8 |
9 | #### Table name & Description
10 | - [AlertInfo](https://learn.microsoft.com/en-us/defender-xdr/advanced-hunting-alertinfo-table?view=o365-worldwide) : Alerts from Microsoft Defender for Endpoint, Microsoft Defender for Office 365, Microsoft Defender for Cloud Apps, and Microsoft Defender for Identity, including severity information and threat categorization
11 | - [AlertEvidence](https://learn.microsoft.com/en-us/defender-xdr/advanced-hunting-alertevidence-table) : Files, IP addresses, URLs, users, or devices associated with alerts
12 |
13 | ```kusto
14 | let Alert_List= dynamic([
15 | "Phishing link click observed in Network Traffic",
16 | "Phish delivered due to an IP allow policy",
17 | "A potentially malicious URL click was detected",
18 | "High Risk Sign-in Observed in Network Traffic",
19 | "A user clicked through to a potentially malicious URL",
20 | "Suspicious network connection to AitM phishing site",
21 | "Messages containing malicious entity not removed after delivery",
22 | "Email messages containing malicious URL removed after delivery",
23 | "Email reported by user as malware or phish",
24 | "Phish delivered due to an ETR override",
25 | "Phish not zapped because ZAP is disabled"]);
26 | AlertInfo
27 | | where DetectionSource == "Microsoft Defender for Office 365"
28 | | where Title has_any (Alert_List)
29 | | join kind=inner (
30 | AlertEvidence
31 | | where DetectionSource == "Microsoft Defender for Office 365"
32 | | where EntityType in ("Url", "User")
33 | ) on AlertId
34 | | extend Entities = parse_json(AdditionalFields)
35 | | mv-apply Entity = Entities on (
36 | where Entity.Type in ('account', 'url')
37 | | extend EntityUPN = iff(Entities.Type == 'account', strcat(Entities.Name, "@", Entities.UPNSuffix), Entities.UserPrincipalName), "",
38 | EntityUrl = iff(Entities.Type == 'url', tostring(Entities.Url), "")
39 | )
40 | | extend DomainFromUrl = iff(isnotempty(EntityUrl), tostring(parse_url(EntityUrl).Host), "")
41 | | summarize UPN = make_set(EntityUPN), URL = make_set(EntityUrl) by AlertId, TimeGenerated
42 | | mv-expand URL
43 | | mv-expand UPN
44 | | where isnotempty(URL)
45 | | where isnotempty(UPN)
46 | | extend Url = tostring(URL)
47 | | extend Domain = parse_url(Url).Host
48 | | project TimeGenerated, AlertId, UPN, Url, Domain
49 | ```
50 |
51 | If you create the above query as a function, you can simplify it further and combine it with other tables, such as Sentinel-related network data.
52 |
53 | ```kusto
54 |
55 | | join kind= inner (CommonSecurityLog
56 | | where TimeGenerated > ago(15d)
57 | | where DeviceAction != "Block"
58 | | where DeviceProduct startswith "FortiGate" or DeviceProduct startswith "PAN" or DeviceProduct startswith "VPN" or DeviceProduct startswith "FireWall" or DeviceProduct startswith "NSSWeblog" or DeviceProduct startswith "URL"
59 | | where isnotempty(RequestURL)
60 | | where isnotempty(SourceUserName)
61 | | project 3plogTime=TimeGenerated, DeviceVendor, DeviceProduct,
62 | Activity, DestinationHostName, DestinationIP, RequestURL=tostring(tolower(RequestURL)),
63 | MaliciousIP, Name = tostring(split(SourceUserName,"@")[0]), UPNSuffix =tostring(split(SourceUserName,"@")[1]),
64 | SourceUserName, IndicatorThreatType, ThreatSeverity,AdditionalExtensions, ThreatConfidence
65 | ) on $left.Url == $right.RequestURL
66 | ```
67 |
68 | #### Reference
69 | [Identifying Adversary-in-the-Middle (AiTM) Phishing Attacks through 3rd-Party Network Detection](https://techcommunity.microsoft.com/t5/microsoft-sentinel-blog/identifying-adversary-in-the-middle-aitm-phishing-attacks/ba-p/3991358)
70 |
71 | #### Disclaimer
72 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
73 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/README.md:
--------------------------------------------------------------------------------
1 | # Email-related KQL queries
2 |
3 |
4 |
5 |
6 |
7 | Thank you for visiting @LearningKijo KQL repository.
8 | In this repository, I am excited to share email-based out-of-the-box queries related to ***Microsoft Defender for Office 365 (MDO)*** and ***Exchange Online Protection (EOP)***.
9 |
10 | | Product | KQL query | Comments |
11 | |:--------|:----------|:----------|
12 | | MDO | [01-Email-Audit-SafeAttachments-GlobalSetting.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/01-Email-Audit-SafeAttachments-GlobalSetting.md) |
13 | | EOP | [02-EOP-Detection-Daily-Percentage.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/02-EOP-Detection-Daily-Percentage.md) |
14 | | MDO | [03-MDO-Detection-Daily-Percentage.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/03-MDO-Detection-Daily-Percentage.md) |
15 | | EOP | [04-EOP-MalwareDetection-Filtering.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/04-EOP-MalwareDetection-Filtering.md) |
16 | | EOP | [05-EOP-PhishingDetection-Filtering.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/05-EOP-PhishingDetection-Filtering.md) |
17 | | MDO | [06-MDO-MalwareDetection-Filtering.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/06-MDO-MalwareDetection-Filtering.md) |
18 | | MDO | [07-MDO-PhishingDetection-Filtering.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/07-MDO-PhishingDetection-Filtering.md) |
19 | | MDO | [08-MDO-UserList-for-RemediationAction.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/08-MDO-UserList-for-RemediationAction.md) |
20 | | MDO/EOP | [09-Email-MalwareDetection-byAccount.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/09-Email-MalwareDetection-byAccount.md) |
21 | | MDO | [10-UserInsights-ClickedSuspiciousURLs-PhishMalware-Emails.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/10-UserInsights-ClickedSuspiciousURLs-PhishMalware-Emails.md) |
22 | | MDO/EOP | [11-Email-Weekly-DetectionTrend.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/11-Email-Weekly-DetectionTrend.md) |
23 | | MDO/EOP | [12-Email-MalwarePhishing-Detection-Trends.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/12-Email-MalwarePhishing-Detection-Trends.md) | Visualize Targeted Email Accounts |
24 | | EOP | [13-Email-Spam-Detection-Trend.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/13-Email-Spam-Detection-Trend.md) | Visualize Targeted Email Accounts |
25 | | MDO | [14-MDO-QRcode-VolumeInboundEmails.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/14-MDO-QRcode-VolumeInboundEmails.md) | from [MS blog](https://techcommunity.microsoft.com/t5/microsoft-defender-for-office/hunting-and-responding-to-qr-code-based-phishing-attacks-with/ba-p/4074730) |
26 | | MDO | [15-MDO-QRcode-DeliveredEmail.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/15-MDO-QRcode-DeliveredEmail.md) | from [MS blog](https://techcommunity.microsoft.com/t5/microsoft-defender-for-office/hunting-and-responding-to-qr-code-based-phishing-attacks-with/ba-p/4074730) |
27 | | MDO | [16-Emails-QRcode-SuspiciousKeywordsSubject.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/16-Emails-QRcode-SuspiciousKeywordsSubject.md) | from [MS blog](https://techcommunity.microsoft.com/t5/microsoft-defender-for-office/hunting-and-responding-to-qr-code-based-phishing-attacks-with/ba-p/4074730) |
28 | | MDO | [17-MDO-DetectedURL-Insights.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365/MDO-EOP-Query-Repository/17-MDO-DetectedURL-Insights.md) |
29 | #### Disclaimer
30 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
31 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-AV-Detection-ThreatInsightWithFilenameByDeviceList.md:
--------------------------------------------------------------------------------
1 | # AV detection : Threat Family & Filename by Device
2 | This query displays threat family and filename that were detected by Microsoft Defender Antivirus in the past 7 days for each device.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | ```kusto
8 | DeviceEvents
9 | | where Timestamp > ago(7d)
10 | | where ActionType == "AntivirusDetection"
11 | | extend DetectionType =parse_json(AdditionalFields)
12 | | summarize MalwareFamilyList = make_list(strcat(DetectionType.ThreatName, @"\", FileName)) by DeviceName, DeviceId
13 | | extend ThreatNumber = array_length(MalwareFamilyList)
14 | | project DeviceId, DeviceName, ThreatNumber, MalwareFamilyList
15 | ```
16 |
17 | #### Disclaimer
18 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
19 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-ExposureManagement-DeviceExposureLevels .md:
--------------------------------------------------------------------------------
1 | # Exposure Management : Device Exposure Levels
2 | This query provides a list of devices with 'Medium' or 'High' exposure levels, along with Exposure Management affecting source items.
3 |
4 | > [!Important]
5 | > [Security Exposure Management is currently in public preview.](https://learn.microsoft.com/en-us/security-exposure-management/cross-workload-attack-surfaces)
6 |
7 | #### Table name & Description
8 | - [ExposureGraphEdges](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-exposuregraphedges-table?view=o365-worldwide) : Microsoft Security Exposure Management exposure graph edge information provides visibility into relationships between entities and assets in the graph
9 |
10 | ```kusto
11 | let ExposureItems = (ExposureGraphEdges
12 | | where EdgeLabel == "affecting"
13 | | mv-expand TargetNodeCategories
14 | | where TargetNodeCategories == "device"
15 | | join kind=inner ExposureGraphNodes on $left.TargetNodeId == $right.NodeId
16 | | mv-expand EntityIds
17 | | extend EntityType = tostring(EntityIds.type)
18 | | where EntityType == "DeviceInventoryId"
19 | | extend EntityID = tostring(EntityIds.id)
20 | | summarize Item = make_set(SourceNodeName) by EntityID
21 | | extend Case = array_length(Item));
22 | DeviceInfo
23 | | where ExposureLevel in ("Medium", "High")
24 | | summarize arg_max(Timestamp, *) by DeviceId, DeviceName
25 | | join kind=inner ExposureItems on $left.DeviceId == $right.EntityID
26 | | project Timestamp, DeviceId, DeviceName, OSPlatform, ExposureLevel, Case, Item
27 | | order by Case desc
28 | ```
29 | #### Result
30 | 
31 |
32 | #### Disclaimer
33 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
34 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-MDE-ASR-Rules-Detections-Block-Audit.md:
--------------------------------------------------------------------------------
1 | # ASR Rules Detections : Block & Audit mode
2 | The first query displays ASR rules detection for block mode, and the second query shows ASR rules detection for audit mode.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | ```kusto
8 | DeviceEvents
9 | | where Timestamp > ago(7d)
10 | | where ActionType startswith "asr"
11 | | extend Parsed = parse_json(AdditionalFields)
12 | | where Parsed.IsAudit == "false"
13 | ```
14 |
15 | #### ASR rules : Audit mode
16 | ```kusto
17 | DeviceEvents
18 | | where Timestamp > ago(7d)
19 | | where ActionType startswith "asr"
20 | | extend Parsed = parse_json(AdditionalFields)
21 | | where Parsed.IsAudit == "true"
22 | ```
23 |
24 | ####
25 |
26 | #### Disclaimer
27 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
28 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-MDE-CFA-Detections-Block-Audit.md:
--------------------------------------------------------------------------------
1 | # Controlled Folder Access : Detections List - Block & Audit
2 | This query displays Controlled Folder Access Block and Audit detections for each device over the past 7 days, including detection type (Block/Audit), time, and targeted folder path.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | ```kusto
8 | DeviceEvents
9 | | where Timestamp > ago(7d)
10 | | where ActionType in ("ControlledFolderAccessViolationBlocked", "ControlledFolderAccessViolationAudit")
11 | | extend Detection = iff(ActionType == "ControlledFolderAccessViolationBlocked", "Block", "Audit")
12 | | extend Time = format_datetime(Timestamp,'yyyy-M-dd H:mm:ss')
13 | | extend Type = strcat("<", "CFA", " : ", Detection, ">")
14 | | extend Path = strcat("<", "TargetedFolderPath", " : ", FolderPath, ">")
15 | | extend List = strcat(Time, " : ", Type, " ", Path)
16 | | summarize CFA_List = make_list(List) by DeviceId, DeviceName
17 | | extend Case = array_length(CFA_List)
18 | | project DeviceId, DeviceName, Case, CFA_List
19 | | order by Case desc
20 | ```
21 |
22 | ####
23 |
24 | #### Disclaimer
25 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
26 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-MDE-LNKFile-activity.md:
--------------------------------------------------------------------------------
1 | # MDE : LNK file activity
2 | This query monitors LNK file activity that includes executable content or HTTP/HTTPS file downloading activity.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | ```kusto
8 | DeviceEvents
9 | | where ActionType == "ShellLinkCreateFileEvent"
10 | | extend Parsed = parse_json(AdditionalFields)
11 | | extend CommandLine = Parsed.ShellLinkCommandLine
12 | | where isnotempty(CommandLine)
13 | | where CommandLine has_any ("bat", "exe", "ps1") and CommandLine has_any ("/c", "powershell", ":%username%", "$env") or CommandLine has_any ("http", "https","iwr")
14 | | project TimeGenerated, DeviceId, DeviceName, ActionType, FileName, FolderPath, CommandLine
15 | ```
16 |
17 | #### Disclaimer
18 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
19 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-MDE-TVM-InstalledSoftware-List-Windows.md:
--------------------------------------------------------------------------------
1 | # TVM : Installed Software List for Windows Device
2 | This query displays a list of all installed software on Windows devices.
3 |
4 | #### Table name & Description
5 | - [DeviceTvmSoftwareInventory](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicetvmsoftwareinventory-table?view=o365-worldwide) : Inventory of software installed on devices, including their version information and end-of-support status
6 |
7 | ```kusto
8 | DeviceTvmSoftwareInventory
9 | | where OSPlatform startswith "Windows"
10 | | extend SoftwareName = strcat("<", "Name", " : ", SoftwareName, ">")
11 | | extend SoftwareVersion = strcat("<", "Version", " : ", SoftwareVersion, ">")
12 | | extend SoftwareInfo = strcat(SoftwareName, " ", SoftwareVersion)
13 | | summarize Installed_Software = make_set(SoftwareInfo) by DeviceName, DeviceId, OSPlatform, OSVersion
14 | | extend Installed_Software_Case = array_length(Installed_Software)
15 | | project DeviceId, DeviceName, OSPlatform, OSVersion, Installed_Software_Case, Installed_Software
16 | | order by Installed_Software_Case desc
17 | ```
18 |
19 | #### Result
20 | 
21 |
22 | #### Disclaimer
23 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
24 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-MDE-TVM-Linux-AntivirusConfig.md:
--------------------------------------------------------------------------------
1 | # TVM : Linux AV config report
2 | This query displays Microsoft Defender Antivirus configuration for Linux.
3 |
4 | #### Table name & Description
5 | - [DeviceTvmSecureConfigurationAssessment](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicetvmsecureconfigurationassessment-table?view=o365-worldwide) : Microsoft Defender Vulnerability Management assessment events, indicating the status of various security configurations on devices
6 |
7 | ```kusto
8 | DeviceTvmSecureConfigurationAssessment
9 | | where OSPlatform == "Linux"
10 | | where ConfigurationSubcategory == "Antivirus"
11 | | where IsApplicable == 1
12 | | where ConfigurationId in ('scid-6090', 'scid-6091', 'scid-6094', 'scid-6095')
13 | | extend Test = case(
14 | ConfigurationId == "scid-6090", "Real-time protection",
15 | ConfigurationId == "scid-6091", "PUA protection",
16 | ConfigurationId == "scid-6094", "Cloud-delivered protection",
17 | ConfigurationId == "scid-6095", "Antivirus definitions",
18 | "N/A"),
19 | Result = case(IsApplicable == 0, "N/A", IsCompliant == 1, "GOOD", "BAD")
20 | | extend packed = pack(Test, Result)
21 | | summarize Tests = make_bag(packed), DeviceName = any(DeviceName) by DeviceId
22 | | evaluate bag_unpack(Tests)
23 | ```
24 |
25 | **Note & Source**
26 | ```kusto
27 | DeviceTvmSecureConfigurationAssessmentKB
28 | | where ConfigurationId in ('scid-6090', 'scid-6091', 'scid-6094', 'scid-6095')
29 |
30 | //scid-6090, Turn on Microsoft Defender Antivirus real-time protection for Linux
31 | //scid-6091, Turn on Microsoft Defender Antivirus PUA protection in block mode for Linux
32 | //scid-6094, Enable Microsoft Defender Antivirus cloud-delivered protection for Linux
33 | //scid-6095, Update Microsoft Defender Antivirus definitions for Linux
34 | ```
35 |
36 | #### Reference
37 | 1. [Endpoint Agent Health Status Report](https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/General%20queries/Endpoint%20Agent%20Health%20Status%20Report.md)
38 | 2. [Endpoint AV version report](https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/General%20queries/MD%20AV%20Signature%20and%20Platform%20Version.md)
39 |
40 | ####
41 |
42 | #### Disclaimer
43 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
44 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-MDE-TamperProtection-TSmode-AVver-DeviceList.md:
--------------------------------------------------------------------------------
1 | # TamperProtection & Troubleshooting mode - Device List
2 | This query displays 1) ***Tamper Protection status***, 2) ***Troubleshooting Mode*** status and 3) ***Defender Antivirus versions*** for each device over the past 7 days.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 | - [DeviceTvmSecureConfigurationAssessment](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicetvmsecureconfigurationassessment-table?view=o365-worldwide) : Microsoft Defender Vulnerability Management assessment events, indicating the status of various security configurations on devices
7 |
8 | ```kusto
9 | // TroubleshootMode Status
10 | let TroubleshootMode = (DeviceEvents
11 | | where Timestamp > ago(7d)
12 | | where ActionType == "AntivirusTroubleshootModeEvent"
13 | | extend Parsed = parse_json(AdditionalFields)
14 | | where Parsed.TroubleshootingStateChangeReason == "Troubleshooting mode started"
15 | | extend StartTime = todatetime(Parsed.TroubleshootingStartTime)
16 | | extend EndTime = todatetime(Parsed.TroubleshootingStateExpiry)
17 | | extend CurrentTime = now()
18 | | extend TroubleshootMode_Status = iff(CurrentTime > todatetime(EndTime), "Inactive", "Active")
19 | | summarize arg_max(Timestamp, *) by DeviceId
20 | | project Timestamp, DeviceId, DeviceName, TroubleshootMode_Status, StartTime, EndTime);
21 | // Microsoft Defender Antivirus versions
22 | // Some AV versions are prerequisites for using MDE Troubleshooting Mode
23 | let AV_versions = (DeviceTvmSecureConfigurationAssessment
24 | | where ConfigurationId == "scid-2011" and isnotnull(Context)
25 | | extend avdata=parsejson(Context)
26 | | extend AVSigVersion = tostring(avdata[0][0])
27 | | extend AVEngineVersion = tostring(avdata[0][1])
28 | | extend AVSigLastUpdateTime = tostring(avdata[0][2])
29 | | extend AVProductVersion = tostring(avdata[0][3])
30 | | project DeviceId, DeviceName, OSPlatform, AVSigVersion, AVEngineVersion, AVSigLastUpdateTime, AVProductVersion, IsCompliant, IsApplicable);
31 | let AV_config =(DeviceTvmSecureConfigurationAssessment
32 | | where ConfigurationId in ('scid-2010', 'scid-2012')
33 | | extend Test = case(
34 | ConfigurationId == "scid-2010", "AntivirusEnabled",
35 | ConfigurationId == "scid-2012", "RealtimeProtection",
36 | "N/A"),
37 | Result = case(IsApplicable == 0, "N/A", IsCompliant == 1, "Enable", "Disable")
38 | | extend packed = pack(Test, Result)
39 | | summarize Tests = make_bag(packed), DeviceName = any(DeviceName) by DeviceId
40 | | evaluate bag_unpack(Tests));
41 | // MDE TamperProtection Status
42 | DeviceTvmSecureConfigurationAssessment
43 | | where OSPlatform in ("Windows10", "Windows11", "WindowsServer2019", "WindowsServer2022")
44 | | where ConfigurationId == "scid-2003"
45 | | extend TamperProtection_State = iff(IsCompliant == 1, "Active", "Inactive")
46 | | summarize arg_max(Timestamp, *) by DeviceId
47 | | join kind=leftouter TroubleshootMode on DeviceId
48 | | join kind=leftouter AV_versions on DeviceId
49 | | join kind=leftouter AV_config on DeviceId
50 | | extend TamperProtectionTime = Timestamp
51 | | project DeviceId, DeviceName, OSPlatform, TamperProtection_State, TamperProtectionTime, TroubleshootMode_Status, StartTime, EndTime, AntivirusEnabled, RealtimeProtection, AVProductVersion, AVEngineVersion, AVSigVersion, AVSigLastUpdateTime
52 | ```
53 |
54 | #### Result
55 | 
56 |
57 | #### Reference
58 | 1. [Endpoint Agent Health Status Report](https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/General%20queries/Endpoint%20Agent%20Health%20Status%20Report.md)
59 | 2. [Endpoint AV version report](https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/General%20queries/MD%20AV%20Signature%20and%20Platform%20Version.md)
60 |
61 | #### Disclaimer
62 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
63 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/01-MDE-URL-Indicators-Block.md:
--------------------------------------------------------------------------------
1 | # MDE : URL IoCs Block on Edge & 3rd Party Browsers
2 | This query displays MDE URL Indicators detections by both Edge and 3rd party browsers for each device over the past 7 days.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 | - [DeviceNetworkEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicenetworkevents-table?view=o365-worldwide) : Network connection and related events
7 |
8 | ```kusto
9 | let NetworkLogs = (DeviceNetworkEvents
10 | | where Timestamp > ago(7d)
11 | | where RemotePort in (80, 443)
12 | | extend IPaddress = RemoteIP
13 | | extend Port = RemotePort
14 | | extend URL = RemoteUrl
15 | | project Timestamp, DeviceId, DeviceName, IPaddress, Port, URL);
16 | DeviceEvents
17 | | where Timestamp > ago(7d)
18 | | where ActionType in ("SmartScreenUrlWarning", "ExploitGuardNetworkProtectionBlocked")
19 | | extend Parsed = parse_json(AdditionalFields)
20 | | extend SmartScreen = Parsed.Experience
21 | | extend NetworkProtection = Parsed.ResponseCategory
22 | | where SmartScreen == "CustomBlockList" or NetworkProtection == "CustomBlockList"
23 | | extend Browser = iff( ActionType == "SmartScreenUrlWarning" and SmartScreen == "CustomBlockList", "Edge", "3rd Party")
24 | | join kind=inner NetworkLogs on $left.RemoteUrl == $right.URL
25 | | extend DetectionTime = strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'))
26 | | extend BrowserType = strcat("<", Browser, " /", InitiatingProcessFileName, ">")
27 | | extend DetectionURL = strcat("[", RemoteUrl, " : ", IPaddress, " : ", Port, "]")
28 | | extend Details = strcat(DetectionTime, " ", BrowserType, " ", DetectionURL)
29 | | summarize IoCList = make_list(Details) by DeviceId, DeviceName
30 | | extend Case = array_length(IoCList)
31 | | project DeviceId, DeviceName, Case, IoCList
32 | | order by Case desc
33 | ```
34 | > [!Important]
35 | > In DeviceNetworkEvents, URLs may appear as ***'ConnectionSuccess'***, but this is the expected result due to the three-way handshake that occurs before an IoC, such as blocking a URL.
36 | > Technically, end users were blocked from accessing the URL, even if the record shows ***'ConnectionSuccess'***.
37 | > MS docs : [IP/URL Indicators: Network protection and the TCP three-way handshake](https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/manage-indicators?view=o365-worldwide#ipurl-indicators-network-protection-and-the-tcp-three-way-handshake)
38 |
39 | #### Result
40 | 
41 |
42 | #### Disclaimer
43 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
44 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/02-AV-LastCompletedAVScanTime-For-EachDevice.md:
--------------------------------------------------------------------------------
1 | # AV : Last Completed Scan Time for Each Device in the Past 7 Days
2 | This query displays the last completed scan time, along with the scan type (Quick/Full), for Microsoft Defender Antivirus on each device in the past 7 days.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | ```kusto
8 | DeviceEvents
9 | | where Timestamp > ago(7d)
10 | | where ActionType == "AntivirusScanCompleted"
11 | | extend Parsed = parse_json(AdditionalFields)
12 | | extend ScanType = Parsed.ScanTypeIndex
13 | | summarize arg_max(Timestamp, *) by DeviceId, DeviceName
14 | | project DeviceId, DeviceName, ActionType, ScanType, Timestamp, InitiatingProcessVersionInfoProductVersion
15 | ```
16 |
17 | #### Disclaimer
18 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
19 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/02-MDE-ASR-Rules-VisualizingDetectionWithPieChart.md:
--------------------------------------------------------------------------------
1 | # Visualizing ASR Rules With PieChart : Block & Audit mode
2 | The first query generates a pie chart visualizing the distribution of ASR rules block detections, and the second query does the same for audit detections.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | #### ASR rules : Block mode
8 | ```kusto
9 | DeviceEvents
10 | | where Timestamp > ago(7d)
11 | | where ActionType startswith "asr"
12 | | extend Parsed = parse_json(AdditionalFields)
13 | | where Parsed.IsAudit == "false"
14 | | summarize ASR_rule_case = count() by ActionType
15 | | render piechart
16 | ```
17 |
18 | #### ASR rules : Audit mode
19 | ```kusto
20 | DeviceEvents
21 | | where Timestamp > ago(7d)
22 | | where ActionType startswith "asr"
23 | | extend Parsed = parse_json(AdditionalFields)
24 | | where Parsed.IsAudit == "true"
25 | | summarize ASR_rule_case = count() by ActionType
26 | | render piechart
27 | ```
28 |
29 | #### Result
30 | 
31 |
32 |
33 | #### Disclaimer
34 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
35 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/02-MDE-TVM-MacOS-AntivirusConfig.md:
--------------------------------------------------------------------------------
1 | # TVM : MacOS AV config report
2 | This query displays Microsoft Defender Antivirus configuration for MacOS.
3 |
4 | #### Table name & Description
5 | - [DeviceTvmSecureConfigurationAssessment](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicetvmsecureconfigurationassessment-table?view=o365-worldwide) : Microsoft Defender Vulnerability Management assessment events, indicating the status of various security configurations on devices
6 |
7 | ```kusto
8 | DeviceTvmSecureConfigurationAssessment
9 | | where OSPlatform == "macOS"
10 | | where ConfigurationSubcategory == "Antivirus"
11 | | where IsApplicable == 1
12 | | where ConfigurationId in ('scid-5090', 'scid-5091', 'scid-5092', 'scid-5094', 'scid-5095')
13 | | extend Test = case(
14 | ConfigurationId == "scid-5090", "Real-time protection",
15 | ConfigurationId == "scid-5091", "PUA protection",
16 | ConfigurationId == "scid-5092", "Tamper Protection",
17 | ConfigurationId == "scid-5094", "Cloud-delivered protection",
18 | ConfigurationId == "scid-5095", "Antivirus definitions",
19 | "N/A"),
20 | Result = case(IsApplicable == 0, "N/A", IsCompliant == 1, "GOOD", "BAD")
21 | | extend packed = pack(Test, Result)
22 | | summarize Tests = make_bag(packed), DeviceName = any(DeviceName) by DeviceId
23 | | evaluate bag_unpack(Tests)
24 | ```
25 |
26 | **Note & Source**
27 | ```kusto
28 | DeviceTvmSecureConfigurationAssessmentKB
29 | | where ConfigurationId in ('scid-5090', 'scid-5091', 'scid-5092', 'scid-5094', 'scid-5095')
30 |
31 | //scid-5090, Turn on Microsoft Defender Antivirus real-time protection in macOS
32 | //scid-5091, Turn on Microsoft Defender Antivirus PUA protection in block mode in macOS
33 | //scid-5092, Turn on Tamper Protection for MacOS
34 | //scid-5094, Enable Microsoft Defender Antivirus cloud-delivered protection in macOS
35 | //scid-5095, Update Microsoft Defender Antivirus definitions in macOS
36 | ```
37 |
38 | #### Reference
39 | 1. [Endpoint Agent Health Status Report](https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/General%20queries/Endpoint%20Agent%20Health%20Status%20Report.md)
40 | 2. [Endpoint AV version report](https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/General%20queries/MD%20AV%20Signature%20and%20Platform%20Version.md)
41 |
42 | ####
43 |
44 | #### Disclaimer
45 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/02-MDE-TVM-RiskyBrowserExtensions-List-Windows.md:
--------------------------------------------------------------------------------
1 | # TVM : Risky Browser Extensions List for Windows Device
2 | The query displays all installed browser extensions categorized as 'Medium' or 'High' risk on devices.
3 |
4 | > [!Important]
5 | > To use this feature you'll require Microsoft Defender Vulnerability Management Standalone or if you're already a Microsoft Defender for Endpoint Plan 2 customer, the Defender Vulnerability Management add-on
6 | > : [Browser extensions assessment](https://learn.microsoft.com/en-us/microsoft-365/security/defender-vulnerability-management/tvm-browser-extensions?view=o365-worldwide#use-advanced-hunting)
7 |
8 | #### Table name & Description
9 | - [DeviceInfo](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceinfo-table?view=o365-worldwide) : Machine information, including OS information
10 | - [DeviceTvmBrowserExtensions](https://learn.microsoft.com/en-us/microsoft-365/security/defender-vulnerability-management/tvm-browser-extensions?view=o365-worldwide#use-advanced-hunting) : Details about the browser extensions installed per device
11 |
12 | ```kusto
13 | let ChromeExtensions = DeviceTvmBrowserExtensions
14 | | where BrowserName == "chrome"
15 | | where ExtensionRisk in ("Medium", "High")
16 | | extend Risk = strcat("<", "Risk", " : ", ExtensionRisk, ">")
17 | | extend Name = strcat("<", "Name", " : ", ExtensionName, ">")
18 | | extend Version = strcat("<", "Version", " : ", ExtensionVersion, ">")
19 | | extend ExtensionLists = strcat(Risk , " ", Name, " ", Version)
20 | | summarize Chrome= make_set(ExtensionLists) by DeviceId
21 | | extend Chrome_Case = array_length(Chrome)
22 | | project DeviceId, Chrome_Case, Chrome;
23 | let FireFoxExtensions = DeviceTvmBrowserExtensions
24 | | where BrowserName == "firefox"
25 | | where ExtensionRisk in ("Medium", "High")
26 | | extend Risk = strcat("<", "Risk", " : ", ExtensionRisk, ">")
27 | | extend Name = strcat("<", "Name", " : ", ExtensionName, ">")
28 | | extend Version = strcat("<", "Version", " : ", ExtensionVersion, ">")
29 | | extend ExtensionLists = strcat(Risk , " ", Name, " ", Version)
30 | | summarize Firefox= make_set(ExtensionLists) by DeviceId
31 | | extend Firefox_Case = array_length(Firefox)
32 | | project DeviceId, Firefox_Case, Firefox;
33 | let EdgeExtensions = DeviceTvmBrowserExtensions
34 | | where BrowserName == "edge"
35 | | where ExtensionRisk in ("Medium", "High")
36 | | extend Risk = strcat("<", "Risk", " : ", ExtensionRisk, ">")
37 | | extend Name = strcat("<", "Name", " : ", ExtensionName, ">")
38 | | extend Version = strcat("<", "Version", " : ", ExtensionVersion, ">")
39 | | extend ExtensionLists = strcat(Risk , " ", Name, " ", Version)
40 | | summarize Edge= make_set(ExtensionLists) by DeviceId
41 | | extend Edge_Case = array_length(Edge)
42 | | project DeviceId, Edge_Case, Edge;
43 | DeviceInfo
44 | | where OSPlatform contains "windows"
45 | | summarize arg_max(Timestamp, *) by DeviceId, DeviceName
46 | | join kind=leftouter ChromeExtensions on DeviceId
47 | | join kind=leftouter FireFoxExtensions on DeviceId
48 | | join kind=leftouter EdgeExtensions on DeviceId
49 | | extend Case = coalesce(Edge_Case, 0) + coalesce(Chrome_Case, 0) + coalesce(Firefox_Case, 0)
50 | | project DeviceName, DeviceId, OSPlatform, Case, Edge, Chrome, Firefox
51 | | order by Case desc
52 | ```
53 |
54 | ####
55 |
56 | #### Disclaimer
57 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
58 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/02-MDE-URL-Indicators-Bypass.md:
--------------------------------------------------------------------------------
1 | # MDE : URL IoCs Bypass on Edge & 3rd Party Browsers
2 | This query displays MDE Indicator 'Warn' activity, where the IoC prompts a warning that users can bypass, on both Edge and 3rd party browsers over the past 7 days.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | ```kusto
8 | DeviceEvents
9 | | where Timestamp > ago(7d)
10 | | where ActionType in ("SmartScreenUserOverride", "NetworkProtectionUserBypassEvent")
11 | | extend Browser = case(
12 | InitiatingProcessFileName has "msedge", "Edge",
13 | InitiatingProcessFileName has "chrome", "Chrome",
14 | InitiatingProcessFileName has "firefox", "Firefox",
15 | InitiatingProcessFileName has "opera", "Opera",
16 | "Other 3rd party browser")
17 | | project Timestamp, DeviceId, DeviceName, ActionType, Browser, RemoteUrl
18 | ```
19 |
20 | > [!Important]
21 | > In DeviceNetworkEvents, URLs may appear as ***'ConnectionSuccess'***, but this is the expected result due to the three-way handshake that occurs before an IoC, such as blocking a URL.
22 | > Technically, end users were blocked from accessing the URL, even if the record shows ***'ConnectionSuccess'***.
23 | > MS docs : [IP/URL Indicators: Network protection and the TCP three-way handshake](https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/manage-indicators?view=o365-worldwide#ipurl-indicators-network-protection-and-the-tcp-three-way-handshake)
24 |
25 | #### Result
26 | 
27 |
28 |
29 | #### URL IoCs Bypass
30 | e.g. Warn – the IoC prompts a warning that the user can bypass
31 | 
32 |
33 | #### Disclaimer
34 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
35 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/03-MDE-ASR-Rules-DetectionAcrossAllDevices.md:
--------------------------------------------------------------------------------
1 | # ASR Rules Detections Across All Devices
2 | This query provides a summary of all ASR rules detections across all devices, displaying ***1) ASR rules names***, ***2) Filenames***, and ***3) Timelines***.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | ```kusto
8 | DeviceEvents
9 | | where Timestamp > ago(7d)
10 | | where ActionType startswith "asr"
11 | | extend Parsed = parse_json(AdditionalFields)
12 | | where Parsed.IsAudit == "false"
13 | | summarize Email = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ActionType, " : ", FileName), ActionType in ("AsrExecutableEmailContentBlocked", "AsrOfficeCommAppChildProcessBlocked")),
14 | Script = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ActionType, " : ", FileName),ActionType in ("AsrObfuscatedScriptBlocked", "AsrScriptExecutableDownloadBlocked")),
15 | WMI = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ActionType, " : ", FileName), ActionType in ("AsrPersistenceThroughWmiBlocked", "AsrPsexecWmiChildProcessBlocked")),
16 | OfficeApp = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ActionType, " : ", FileName), ActionType in ("AsrOfficeChildProcessBlocked", "AsrOfficeMacroWin32ApiCallsBlocked", "AsrExecutableOfficeContentBlocked", "AsrOfficeProcessInjectionBlocked")),
17 | 3rdPartyApp = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ActionType, " : ", FileName), ActionType == "AsrAdobeReaderChildProcessBlocked"),
18 | WindowsCredentials = make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ActionType, " : ", FileName), ActionType == "AsrLsassCredentialTheftBlocked"),
19 | PolymorphicThreats =make_list_if(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ActionType, " : ", FileName), ActionType in ("AsrUntrustedExecutableBlocked", "AsrUntrustedUsbProcessBlocked", "AsrRansomwareBlocked", "AsrVulnerableSignedDriverBlocked")) by DeviceId, DeviceName
20 | | extend Case = array_length(Email) + array_length(Script) + array_length(WMI) + array_length(OfficeApp) + array_length(3rdPartyApp) + array_length(WindowsCredentials) + array_length(PolymorphicThreats)
21 | | project DeviceId, DeviceName, Case, Email, Script, WMI, OfficeApp, 3rdPartyApp, WindowsCredentials, PolymorphicThreats
22 | | order by Case desc
23 | ```
24 |
25 | #### Result
26 | 
27 |
28 |
29 |
30 | #### Disclaimer
31 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
32 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/03-MDE-NetworkProtection-Detection.md:
--------------------------------------------------------------------------------
1 | # MDE : Network Protection Detection List
2 | This query displays MDE Network Protection detections for each device over the past 7 days.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 | - [DeviceNetworkEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicenetworkevents-table?view=o365-worldwide) : Network connection and related events
7 |
8 | ```Kusto
9 | let NetworkLogs = (DeviceNetworkEvents
10 | | where Timestamp > ago(7d)
11 | | where RemotePort in (80, 443)
12 | | extend IPaddress = RemoteIP
13 | | extend Port = RemotePort
14 | | extend URL = RemoteUrl
15 | | project Timestamp, DeviceId, DeviceName, IPaddress, Port, URL);
16 | DeviceEvents
17 | | where Timestamp > ago(7d)
18 | | where ActionType == "ExploitGuardNetworkProtectionBlocked"
19 | | extend Parsed = parse_json(AdditionalFields)
20 | | extend NetworkProtectionCategory = Parsed.ResponseCategory
21 | | where NetworkProtectionCategory in ("CmdCtrl", "Malicious")
22 | | join kind=inner NetworkLogs on $left.RemoteUrl == $right.URL
23 | | extend DetectionTime = strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'))
24 | | extend DetectionType = strcat("<", NetworkProtectionCategory, " /", InitiatingProcessFileName, ">")
25 | | extend DetectionURL = strcat("[", RemoteUrl, " : ", IPaddress, " : ", Port, "]")
26 | | extend Details = strcat(DetectionTime, " ", DetectionType, " ", DetectionURL)
27 | | summarize NP_DetectionList = make_list(Details) by DeviceId, DeviceName
28 | | extend Case = array_length(NP_DetectionList)
29 | | project DeviceId, DeviceName, Case, NP_DetectionList
30 | | order by Case desc
31 | ```
32 |
33 | #### Result
34 | 
35 |
36 | 
37 |
38 | #### Disclaimer
39 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
40 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/03-MDE-TVM-InstalledSoftware-List-Linux.md:
--------------------------------------------------------------------------------
1 | # TVM : Installed Software List for Linux Device
2 | This query displays a list of all installed software on Linux devices.
3 |
4 | #### Table name & Description
5 | - [DeviceTvmSoftwareInventory](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicetvmsoftwareinventory-table?view=o365-worldwide) : Inventory of software installed on devices, including their version information and end-of-support status
6 |
7 | ```kusto
8 | DeviceTvmSoftwareInventory
9 | | where OSPlatform == "Linux"
10 | | extend SoftwareName = strcat("<", "Name", " : ", SoftwareName, ">")
11 | | extend SoftwareVersion = strcat("<", "Version", " : ", SoftwareVersion, ">")
12 | | extend SoftwareInfo = strcat(SoftwareName, " ", SoftwareVersion)
13 | | summarize Installed_Software = make_set(SoftwareInfo) by DeviceName, DeviceId, OSPlatform, OSVersion
14 | | extend Installed_Software_Case = array_length(Installed_Software)
15 | | project DeviceId, DeviceName, OSPlatform, OSVersion, Installed_Software_Case, Installed_Software
16 | | order by Installed_Software_Case desc
17 | ```
18 |
19 | ####
20 |
21 | #### Disclaimer
22 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/04-MDE-ASR-Rules-CategorizedDetection-Graph.md:
--------------------------------------------------------------------------------
1 | # Categorized ASR Rules Detection Graph
2 | This query displays a daily categorization of ASR rules.
3 | For example, with the current count of 16 rules, SOC analysts may wish to monitor the day-to-day detection rates for specific categories, such as office-related activities or WMI.
4 |
5 | #### Table name & Description
6 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
7 |
8 | ```kusto
9 | DeviceEvents
10 | | where Timestamp > ago(7d)
11 | | where ActionType startswith "asr"
12 | | extend Parsed = parse_json(AdditionalFields)
13 | // | where Parsed.IsAudit == "true"
14 | | where Parsed.IsAudit == "false"
15 | | summarize Email = countif(ActionType in ("AsrExecutableEmailContentBlocked", "AsrOfficeCommAppChildProcessBlocked")),
16 | Script = countif(ActionType in ("AsrObfuscatedScriptBlocked", "AsrScriptExecutableDownloadBlocked")),
17 | WMI = countif(ActionType in ("AsrPersistenceThroughWmiBlocked", "AsrPsexecWmiChildProcessBlocked")),
18 | OfficeApp = countif(ActionType in ("AsrOfficeChildProcessBlocked", "AsrOfficeMacroWin32ApiCallsBlocked", "AsrExecutableOfficeContentBlocked", "AsrOfficeProcessInjectionBlocked")),
19 | 3rdPartyApp = countif(ActionType == "AsrAdobeReaderChildProcessBlocked"),
20 | WindowsCredentials = countif(ActionType == "AsrLsassCredentialTheftBlocked"),
21 | PolymorphicThreats = countif(ActionType in ("AsrUntrustedExecutableBlocked", "AsrUntrustedUsbProcessBlocked", "AsrRansomwareBlocked", "AsrVulnerableSignedDriverBlocked")) by bin(Timestamp, 1d)
22 | | render columnchart
23 | ```
24 |
25 | #### Result
26 | 
27 |
28 | #### Disclaimer
29 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
30 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/04-MDE-TVM-InstalledSoftware-List-MacOS.md:
--------------------------------------------------------------------------------
1 | # TVM : Installed Software List for MacOS Device
2 | This query displays a list of all installed software on MacOS devices.
3 |
4 | #### Table name & Description
5 | - [DeviceTvmSoftwareInventory](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicetvmsoftwareinventory-table?view=o365-worldwide) : Inventory of software installed on devices, including their version information and end-of-support status
6 |
7 | ```kusto
8 | DeviceTvmSoftwareInventory
9 | | where OSPlatform == "macOS"
10 | | extend SoftwareName = strcat("<", "Name", " : ", SoftwareName, ">")
11 | | extend SoftwareVersion = strcat("<", "Version", " : ", SoftwareVersion, ">")
12 | | extend SoftwareInfo = strcat(SoftwareName, " ", SoftwareVersion)
13 | | summarize Installed_Software = make_set(SoftwareInfo) by DeviceName, DeviceId, OSPlatform, OSVersion
14 | | extend Installed_Software_Case = array_length(Installed_Software)
15 | | project DeviceId, DeviceName, OSPlatform, OSVersion, Installed_Software_Case, Installed_Software
16 | | order by Installed_Software_Case desc
17 | ```
18 |
19 | ####
20 |
21 | #### Disclaimer
22 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/04-SS-DefenderSmartScreen-Detection.md:
--------------------------------------------------------------------------------
1 | # Microsoft Defender SmartScreen : Detection List
2 | This query displays Microsoft Defender SmartScreen detections for each device over the past 7 days.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 | - [DeviceNetworkEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicenetworkevents-table?view=o365-worldwide) : Network connection and related events
7 |
8 | ```kusto
9 | let NetworkLogs = (DeviceNetworkEvents
10 | | where Timestamp > ago(7d)
11 | | where RemotePort in (80, 443)
12 | | extend IPaddress = RemoteIP
13 | | extend Port = RemotePort
14 | | extend URL = RemoteUrl
15 | | project Timestamp, DeviceId, DeviceName, IPaddress, Port, URL);
16 | DeviceEvents
17 | | where Timestamp > ago(7d)
18 | | where ActionType == "SmartScreenUrlWarning"
19 | | extend Parsed = parse_json(AdditionalFields)
20 | | extend SmartScreenCategory = Parsed.Experience
21 | | where SmartScreenCategory in ("Exploit", "Malicious", "Phishing", "Untrusted")
22 | | join kind=leftouter NetworkLogs on $left.RemoteUrl == $right.URL
23 | | extend DetectionTime = strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'))
24 | | extend DetectionType = strcat("<", SmartScreenCategory, " /", InitiatingProcessFileName, ">")
25 | | extend DetectionURL = strcat("[", RemoteUrl, " : ", IPaddress, " : ", Port, "]")
26 | | extend Details = strcat(DetectionTime, " ", DetectionType, " ", DetectionURL)
27 | | summarize SS_DetectionList = make_list(Details) by DeviceId, DeviceName
28 | | extend Case = array_length(SS_DetectionList)
29 | | project DeviceId, DeviceName, Case, SS_DetectionList
30 | | order by Case desc
31 | ```
32 |
33 | #### Result
34 | 
35 |
36 | #### Disclaimer
37 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
38 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint/MDE-Query-Repository/05-MDE-WebContentFiltering-Detection.md:
--------------------------------------------------------------------------------
1 | # MDE : WCF detection on Edge & 3rd Party Browsers
2 | This query displays MDE Web Content Filtering detections by both Edge and 3rd party browsers for each device over the past 7 days.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 | - [DeviceNetworkEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-devicenetworkevents-table?view=o365-worldwide) : Network connection and related events
7 |
8 | ```kusto
9 | let NetworkLogs = (DeviceNetworkEvents
10 | | where Timestamp > ago(7d)
11 | | where RemotePort in (80, 443)
12 | | extend IPaddress = RemoteIP
13 | | extend Port = RemotePort
14 | | extend URL = RemoteUrl
15 | | project Timestamp, DeviceId, DeviceName, IPaddress, Port, URL);
16 | DeviceEvents
17 | | where Timestamp > ago(7d)
18 | | where ActionType in ("SmartScreenUrlWarning", "ExploitGuardNetworkProtectionBlocked")
19 | | extend Parsed = parse_json(AdditionalFields)
20 | | extend SmartScreen = Parsed.Experience
21 | | extend NetworkProtection = Parsed.ResponseCategory
22 | | where SmartScreen == "CustomPolicy" or NetworkProtection == "CustomPolicy"
23 | | extend Browser = iff(ActionType == "SmartScreenUrlWarning" and SmartScreen == "CustomPolicy", "Edge", "3rd Party")
24 | | join kind=inner NetworkLogs on $left.RemoteUrl == $right.URL
25 | | extend DetectionTime = strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'))
26 | | extend BrowserType = strcat("<", Browser, " /", InitiatingProcessFileName, ">")
27 | | extend DetectionURL = strcat("[", RemoteUrl, " : ", IPaddress, " : ", Port, "]")
28 | | extend Details = strcat(DetectionTime, " ", BrowserType, " ", DetectionURL)
29 | | summarize IoCList = make_list(Details) by DeviceId, DeviceName
30 | | extend Case = array_length(IoCList)
31 | | project DeviceId, DeviceName, Case, IoCList
32 | | order by Case desc
33 | ```
34 |
35 | #### Result
36 | 
37 |
38 | #### Disclaimer
39 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
40 |
41 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/01-LDAP-Query-Activities-Endpoint.md:
--------------------------------------------------------------------------------
1 | # LDAP query activities captured by MDE table
2 | This query helps filter weekly LDAP query activities captured by Microsoft Defender for Endpoint sensor.
3 |
4 | #### Table name & Description
5 | - [DeviceEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-deviceevents-table?view=o365-worldwide) : Multiple event types, including events triggered by security controls such as Microsoft Defender Antivirus and exploit protection
6 |
7 | ```kusto
8 | DeviceEvents
9 | | where Timestamp > ago(7d)
10 | | where ActionType == "LdapSearch"
11 | | extend Parsed = parse_json(AdditionalFields)
12 | | extend AttributeList = Parsed.AttributeList
13 | | extend DistinguishedName = Parsed.DistinguishedName
14 | | extend ScopeOfSearch = Parsed.ScopeOfSearch
15 | | extend SearchFilter = Parsed.SearchFilter
16 | | project Timestamp, DeviceName, AttributeList, DistinguishedName, ScopeOfSearch, SearchFilter
17 | ```
18 |
19 |
20 | #### Disclaimer
21 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
22 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/02-LDAP-Query-Activities-Identity.md:
--------------------------------------------------------------------------------
1 | # LDAP query activities captured by MDI table
2 | This query helps filter daily LDAP query activities captured by Microsoft Defender for Identity sensor based on [bin()](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/binfunction) operator.
3 |
4 | #### Table name & Description
5 | - [IdentityQueryEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-identityqueryevents-table?view=o365-worldwide) : Queries for Active Directory objects, such as users, groups, devices, and domains
6 |
7 | ```kusto
8 | IdentityQueryEvents
9 | | where Timestamp > ago(7d)
10 | | where ActionType == "LDAP query"
11 | | extend DeviceQuery = strcat(DeviceName, " : ", QueryType, " : ", Query)
12 | | summarize QueryList = make_list(DeviceQuery) by bin(Timestamp, 1d)
13 | | extend Case = array_length(QueryList)
14 | | project Timestamp, Case, QueryList
15 | ```
16 | #### Result
17 | 
18 |
19 | #### Disclaimer
20 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
21 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/03-Last-PasswordReset-AccountDisabled-TimeList.md:
--------------------------------------------------------------------------------
1 | # Last Password Reset & Account Disabled Time List
2 | This query helps list the last password reset and account disabled time in your environment.
3 |
4 | #### Table name & Description
5 | - [IdentityDirectoryEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-identitydirectoryevents-table?view=o365-worldwide) : Events involving an on-premises domain controller running Active Directory (AD). This table covers a range of identity-related events and system events on the domain controller
6 | - [IdentityInfo](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-identityinfo-table?view=o365-worldwide) : Account information from various sources, including Microsoft Entra ID
7 |
8 | ```kusto
9 | let PasswordChanged = IdentityDirectoryEvents
10 | | where ActionType == "Account Password changed"
11 | | extend PasswordChangedTime = Timestamp
12 | | summarize arg_max(PasswordChangedTime, *) by TargetAccountUpn
13 | | project PasswordChangedTime, TargetAccountUpn, ActionType, Application;
14 | let AccountDisabled = IdentityDirectoryEvents
15 | | where ActionType == "Account Disabled changed"
16 | | extend AccountDisabledTime = Timestamp
17 | | summarize arg_max(AccountDisabledTime, *) by TargetAccountUpn
18 | | project AccountDisabledTime, TargetAccountUpn, ActionType, Application;
19 | IdentityInfo
20 | | where SourceProvider in ("Hybrid", "ActiveDirectory")
21 | | summarize arg_max(Timestamp, *) by AccountUpn
22 | | join kind = leftouter PasswordChanged on $left.AccountUpn == $right.TargetAccountUpn
23 | | join kind = leftouter AccountDisabled on $left.AccountUpn == $right.TargetAccountUpn
24 | | project AccountUpn, AccountDisplayName, SourceProvider, AccountDisabledTime, PasswordChangedTime
25 | ```
26 |
27 | #### Result
28 | 
29 |
30 | #### Disclaimer
31 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
32 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/04-LMP-Activities.md:
--------------------------------------------------------------------------------
1 | # Lateral Movement Paths (LMP)
2 | Lateral movement path is defined as the steps an attacker takes to navigate your network and gain additional access to secure data.
3 | Lateral Movement Paths (LMPs) reporting is available for every identity tracked by Microsoft Defender for Identity and serves as a visual guide that can demonstrate routes from non-sensitive to sensitive accounts.
4 |
5 | Microsoft Incident Response leans on these LMPs frequently via both Advanced Hunting and the visual guides to understand the potential scope of access for a compromised identity.
6 |
7 | 
8 |
9 | During an investigation, the following query can identify service accounts granted a high level of privileges, as well as the machines those accounts regularly logged into.
10 | This can help investigators rapidly identify and remediate Lateral Movement risks.
11 |
12 | #### Table name & Description
13 | - [IdentityDirectoryEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-identitydirectoryevents-table?view=o365-worldwide) : Events involving an on-premises domain controller running Active Directory (AD). This table covers a range of identity-related events and system events on the domain controller
14 |
15 | ```kusto
16 | IdentityDirectoryEvents
17 | | where ActionType == "Potential lateral movement path identified"
18 | | project Timestamp, ActionType, Application, AccountName, AccountDomain, AccountSid, AccountDisplayName, DeviceName, AdditionalFields
19 | ```
20 |
21 | Microsoft Defender for Identity continuously monitors your environment and alerts you to sensitive accounts with the riskiest lateral movement paths.
22 | This assists Microsoft Incident Response during engagements by providing insights into the customer’s attack surface.
23 | In scenarios where we engage after an incident, it’s more efficient to retrieve this information via query.
24 |
25 | #### Reference
26 | [Follow the Breadcrumbs with Microsoft Incident Response and MDI: Working Together to Fight Identity](https://techcommunity.microsoft.com/t5/microsoft-security-experts-blog/follow-the-breadcrumbs-with-microsoft-incident-response-and-mdi/ba-p/4089623)
27 |
28 | #### Disclaimer
29 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
30 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/05-GroupMembershipChanges-Activities.md:
--------------------------------------------------------------------------------
1 | # Group Membership Changes
2 | Privileged groups can grant permissions in Active Directory and other applications, and allow access to resources such as SCCM administration, Domain Admins, and more.
3 | As a result, Threat Actors often add themselves to privileged groups to gain access to a resource that is useful to them.
4 |
5 | The query below can be used to review group changes and track which accounts were added to which groups.
6 |
7 | #### Table name & Description
8 | - [IdentityDirectoryEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-identitydirectoryevents-table?view=o365-worldwide) : Events involving an on-premises domain controller running Active Directory (AD). This table covers a range of identity-related events and system events on the domain controller
9 |
10 | ```kusto
11 | IdentityDirectoryEvents
12 | | where Application == "Active Directory"
13 | | where ActionType == "Group Membership changed"
14 | | where DestinationDeviceName != ""
15 | | extend ToGroup = tostring(parse_json(AdditionalFields).["TO.GROUP"])
16 | | extend FromGroup = tostring(parse_json(AdditionalFields).["FROM.GROUP"])
17 | | extend Action = iff(isempty(ToGroup), "Remove", "Add")
18 | | extend GroupModified = iff(isempty(ToGroup), FromGroup, ToGroup)
19 | | extend Target_Group = tostring(parse_json(AdditionalFields)["TARGET_OBJECT.GROUP"])
20 | | project Timestamp, Action, GroupModified, Target_Account = TargetAccountDisplayName, Target_UPN = TargetAccountUpn, Target_Group, DC=DestinationDeviceName, Actor=AccountName, ActorDomain=AccountDomain, AdditionalFields
21 | ```
22 |
23 | #### Reference
24 | [Follow the Breadcrumbs with Microsoft Incident Response and MDI: Working Together to Fight Identity](https://techcommunity.microsoft.com/t5/microsoft-security-experts-blog/follow-the-breadcrumbs-with-microsoft-incident-response-and-mdi/ba-p/4089623)
25 |
26 | #### Disclaimer
27 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
28 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/06-AccountLogin-Review.md:
--------------------------------------------------------------------------------
1 | # Account Login Review
2 | When investigating a potential compromise, it can often be helpful to understand which devices or locations a user typically logged into, and which type of logon was used.
3 | Typically, the most interesting types of logon for an investigation are Interactive, Remote Interactive and Network.
4 | This information is useful in both proactive and reactive contexts since it can give an indication of the pattern of life of a user and helps identify anomalies.
5 |
6 | #### Table name & Description
7 | - [IdentityLogonEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-identitylogonevents-table?view=o365-worldwide) : Authentication events on Active Directory and Microsoft online services
8 | ```kusto
9 | IdentityLogonEvents
10 | | where AccountName contains "adfsadmin"
11 | | where Application == "Active Directory"
12 | | summarize TotalCount=count(),FirstSeen=min(Timestamp),LastSeen=max(Timestamp),SuccessCount=countif(ActionType=="LogonSuccess"),ListOfSuccessfulDevices=make_set_if(DeviceName,ActionType=="LogonSuccess"),FailureCount=countif(ActionType=="LogonFailed"),ListofFailedDevices=make_set_if(DeviceName,ActionType=="LogonFailure") by AccountName,DeviceName,LogonType
13 | ```
14 |
15 | #### Reference
16 | [Follow the Breadcrumbs with Microsoft Incident Response and MDI: Working Together to Fight Identity](https://techcommunity.microsoft.com/t5/microsoft-security-experts-blog/follow-the-breadcrumbs-with-microsoft-incident-response-and-mdi/ba-p/4089623)
17 |
18 | #### Disclaimer
19 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
20 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/07-ServiceCreation-Review.md:
--------------------------------------------------------------------------------
1 | # Service Creation Review
2 | Services are often used by threat actors as persistence mechanisms, allowing them to leave a running executable which will allow a Threat Actor to maintain long-term access to a compromised system.
3 | The query below will display service creation events on machines protected by MDI, allowing for review to ensure that all newly created services are expected.
4 | These systems should only be used for domain management and any atypical service creation should be investigated. It is a simple query, but an effective one in many cases.
5 |
6 | #### Table name & Description
7 | - [IdentityDirectoryEvents](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-identitydirectoryevents-table?view=o365-worldwide) : Events involving an on-premises domain controller running Active Directory (AD). This table covers a range of identity-related events and system events on the domain controller
8 |
9 | ```kusto
10 | IdentityDirectoryEvents
11 | | where ActionType == 'Service creation'
12 | | project Timestamp, Application, AccountName, AdditionalFields.ServiceName
13 | ```
14 |
15 | #### Reference
16 | [Follow the Breadcrumbs with Microsoft Incident Response and MDI: Working Together to Fight Identity](https://techcommunity.microsoft.com/t5/microsoft-security-experts-blog/follow-the-breadcrumbs-with-microsoft-incident-response-and-mdi/ba-p/4089623)
17 |
18 | #### Disclaimer
19 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
20 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/README.md:
--------------------------------------------------------------------------------
1 | # Identity-related KQL queries
2 |
3 |
4 |
5 |
6 |
7 | Thank you for visiting @LearningKijo KQL repository.
8 | In this Identity KQL repository, I am delighted to share out-of-the-box Identity-related KQL queries based on ***Microsoft Entra ID (Entra)*** and ***Microsoft Defender for Identity (MDI)***.
9 |
10 |
11 | | Product | KQL query |
12 | |:--------|:----------|
13 | | MDE | [01-LDAP-Query-Activities-Endpoint.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/01-LDAP-Query-Activities-Endpoint.md) |
14 | | MDI | [02-LDAP-Query-Activities-Identity.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/02-LDAP-Query-Activities-Identity.md) |
15 | | MDI | [03-Last-PasswordReset-AccountDisabled-TimeList.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/03-Last-PasswordReset-AccountDisabled-TimeList.md) |
16 | | MDI | [04-LMP-Activities.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/04-LMP-Activities.md) |
17 | | MDI | [05-GroupMembershipChanges-Activities.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/05-GroupMembershipChanges-Activities.md) |
18 | | MDI | [06-AccountLogin-Review.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/06-AccountLogin-Review.md) |
19 | | MDI | [07-ServiceCreation-Review.md](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity/MDI-Query-Repository/07-ServiceCreation-Review.md) |
20 |
21 | ## Pinned Identity-related KQL queries contributors
22 | I want to be respectful of the excellent work done by others, and while I aim to avoid duplication, there may be slight overlaps.
23 | To ensure comprehensive coverage of Identity-related queries, I will provide GitHub links, which I hope will be highly valuable for identity threat hunting.
24 |
25 | - [DanielpFR/MDI](https://github.com/DanielpFR/MDI)
26 | - [reprise99/Sentinel-Queries/Azure Activity/](https://github.com/reprise99/Sentinel-Queries/tree/main/Azure%20Activity)
27 | - [Bert-JanP/Hunting-Queries-Detection-Rules/Defender For Identity/](https://github.com/Bert-JanP/Hunting-Queries-Detection-Rules/tree/main/Defender%20For%20Identity)
28 |
29 | #### Disclaimer
30 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
31 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230407-MangoSandstorm.md:
--------------------------------------------------------------------------------
1 | # MERCURY and DEV-1084: Destructive attack on hybrid environments
2 | Microsoft has detected destructive operations by MERCURY, an Iranian-linked nation-state actor, targeting both on-premises and cloud environments. Initially disguised as ransomware, the true goal was destruction and disruption. MERCURY likely collaborated with DEV-1084, executing destructive actions after gaining access. The attack involved exploiting vulnerabilities, extensive reconnaissance, and later, large-scale destruction using compromised credentials. The blog post provides details on detecting these attacks through various Microsoft Defender tools, with direct notifications sent to affected customers for securing their environments.
3 |
4 | > [!Important]
5 | > April 2023 update – Microsoft Threat Intelligence has shifted to a new threat actor naming taxonomy aligned around the theme of weather. MERCURY is now tracked as Mango Sandstorm and DEV-1084 is now tracked as Storm-1084.
6 |
7 | > 👉 April 7, 2023, [MERCURY and DEV-1084: Destructive attack on hybrid environment](https://www.microsoft.com/en-us/security/blog/2023/04/07/mercury-and-dev-1084-destructive-attack-on-hybrid-environment/)
8 |
9 | ## Advanced hunting queries
10 | ***Microsoft 365 Defender : To locate related activity, Microsoft 365 Defender customers can run the following advanced hunting queries:***
11 |
12 | Advanced Hunting Query to surface potential Mercury PowerShell script backdoor installation
13 | ```kusto
14 | DeviceFileEvents
15 | | where InitiatingProcessFileName =~ "powershell.exe"
16 | | where FolderPath in~ (@"c:\programdata\db.ps1", @"c:\programdata\db.sqlite")
17 | | summarize min(Timestamp), max(Timestamp) by DeviceId, SHA256, InitiatingProcessParentFileName
18 | ```
19 | ```kusto
20 | DeviceProcessEvents
21 | | where InitiatingProcessFileName =~ "powershell.exe"
22 | | where InitiatingProcessCommandLine has_cs "-EP BYPASS -NoP -W h"
23 | | summarize makeset(ProcessCommandLine), min(Timestamp), max(Timestamp) by DeviceId
24 | ```
25 |
26 | Advanced Hunting Query to surface potential Mercury PowerShell script backdoor initiating commands
27 | ```kusto
28 | DeviceProcessEvents
29 | | where InitiatingProcessFileName =~ "powershell.exe"
30 | | where InitiatingProcessCommandLine contains_cs @"c:\programdata\db.ps1"
31 | | summarize makeset(ProcessCommandLine), min(Timestamp), max(Timestamp) by DeviceId
32 | ```
33 |
34 | Advanced Hunting Query for Azure resource deletion activity
35 | ```kusto
36 | let PrivEscalation = CloudAppEvents
37 | | where Application == "Microsoft Azure"
38 | | where ActionType == "ElevateAccess Microsoft.Authorization"
39 | | where ActivityObjects has "Azure Subscription" and ActivityObjects has "Azure Resource Group"
40 | | extend PrivEscalationTime = Timestamp
41 | | project AccountObjectId, PrivEscalationTime ,ActionType;
42 | CloudAppEvents
43 | | join kind = inner PrivEscalation on AccountObjectId
44 | | extend DeletionTime = Timestamp
45 | | where (DeletionTime - PrivEscalationTime) <= 1h
46 | | where Application == "Microsoft Azure"
47 | | where ActionType has "Delete"
48 | |summarize min(DeletionTime), TotalResourcersDeleted =count(), CountOfDistinctResources= dcount(ActionType), DistinctResources=make_set(ActionType) by AccountObjectId
49 | ```
50 |
51 | AHQ used to detect attacker abusing OAuth application during the attack
52 | ```kusto
53 | CloudAppEvents
54 | | where Application == "Office 365"
55 | | where ActionType == "Consent to application."
56 | | where RawEventData.ResultStatus =~ "success"
57 | | extend UserId = tostring(RawEventData.UserId)
58 | | mv-expand AdminConsent = RawEventData.ModifiedProperties
59 | | where AdminConsent.Name == "ConsentContext.IsAdminConsent" and AdminConsent.NewValue == "True"
60 | | project ConsentTimestamp =Timestamp, UserId, AccountObjectId, ReportId, ActionType
61 | | join kind = leftouter (CloudAppEvents
62 | | where Application == "Office 365"
63 | | where ActionType == "Add app role assignment to service principal."
64 | | extend PermissionAddedTo = tostring(RawEventData.Target[3].ID)
65 | | extend FullAccessPermission = RawEventData.ModifiedProperties
66 | | extend OuthAppName = tostring(FullAccessPermission[6].NewValue) // Find app name
67 | | extend OAuthApplicationId = tostring(FullAccessPermission[7].NewValue) // Find appId
68 | | extend AppRoleValue = tostring(FullAccessPermission[1].NewValue) // Permission Level
69 | | where AppRoleValue == "full_access_as_app"
70 | | project PermissionTime=Timestamp, InitiatingUser=AccountDisplayName, OuthAppName, OAuthApplicationId, AppRoleValue, AccountObjectId, FullAccessPermission
71 | ) on AccountObjectId
72 | ```
73 |
74 | ## Microsoft Security Blog
75 | April 7, 2023, [MERCURY and DEV-1084: Destructive attack on hybrid environment](https://www.microsoft.com/en-us/security/blog/2023/04/07/mercury-and-dev-1084-destructive-attack-on-hybrid-environment/)
76 |
77 | #### Disclaimer
78 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
79 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230525-VoltTyphoon.md:
--------------------------------------------------------------------------------
1 | # Volt Typhoon targets US critical infrastructure with living-off-the-land techniques
2 | Microsoft has uncovered a targeted cyber-espionage campaign by a Chinese state-sponsored actor, Volt Typhoon, focusing on post-compromise credential access in critical U.S. infrastructure. Active since mid-2021, Volt Typhoon aims to disrupt U.S.-Asia communications infrastructure during crises. The campaign, spanning various sectors, emphasizes stealth through living-off-the-land techniques and custom tools. Microsoft, concerned about potential impact, urges community awareness and enhanced protection. Detecting and mitigating this attack is challenging, involving valid accounts and living-off-the-land tactics. Microsoft recommends closing or changing compromised accounts and shares mitigation steps. The NSA has also published a Cybersecurity Advisory for further guidance.
3 | > 👉 May 24, 2023, [Volt Typhoon targets US critical infrastructure with living-off-the-land techniques](https://www.microsoft.com/en-us/security/blog/2023/05/24/volt-typhoon-targets-us-critical-infrastructure-with-living-off-the-land-techniques/)
4 |
5 | ## Advanced hunting queries
6 | ***Microsoft 365 Defender : Volt Typhoon’s post-compromise activity usually includes distinctive commands. Searching for these can help to determine the scope and impact of an incident.***
7 |
8 | **Find commands creating domain controller installation media** -
9 | This query can identify domain controller installation media creation commands similar to those used by Volt Typhoon.
10 | ```kusto
11 | DeviceProcessEvents
12 | | where ProcessCommandLine has_all ("ntdsutil", "create full", "pro")
13 | ```
14 |
15 | **Find commands establishing internal proxies** -
16 | This query can identify commands that establish internal proxies similar to those used by Volt Typhoon.
17 | ```kusto
18 | DeviceProcessEvents
19 | | where ProcessCommandLine has_all ("portproxy", "netsh", "wmic", "process call create", "v4tov4")
20 | ```
21 |
22 | **Find detections of custom FRP executables** - This query can identify alerts on files that match the SHA-256 hashes of known Volt Typhoon custom FRP binaries.
23 | ```kusto
24 | AlertEvidence
25 | | where SHA256 in
26 | ('baeffeb5fdef2f42a752c65c2d2a52e84fb57efc906d981f89dd518c314e231c',
27 | 'b4f7c5e3f14fb57be8b5f020377b993618b6e3532a4e1eb1eae9976d4130cc74',
28 | '4b0c4170601d6e922cf23b1caf096bba2fade3dfcf92f0ab895a5f0b9a310349',
29 | 'c0fc29a52ec3202f71f6378d9f7f9a8a3a10eb19acb8765152d758aded98c76d',
30 | 'd6ab36cb58c6c8c3527e788fc9239d8dcc97468b6999cf9ccd8a815c8b4a80af',
31 | '9dd101caee49c692e5df193b236f8d52a07a2030eed9bd858ed3aaccb406401a',
32 | '450437d49a7e5530c6fb04df2e56c3ab1553ada3712fab02bd1eeb1f1adbc267',
33 | '93ce3b6d2a18829c0212542751b309dacbdc8c1d950611efe2319aa715f3a066',
34 | '7939f67375e6b14dfa45ec70356e91823d12f28bbd84278992b99e0d2c12ace5',
35 | '389a497f27e1dd7484325e8e02bbdf656d53d5cf2601514e9b8d8974befddf61',
36 | 'c4b185dbca490a7f93bc96eefb9a597684fdf532d5a04aa4d9b4d4b1552c283b',
37 | 'e453e6efc5a002709057d8648dbe9998a49b9a12291dee390bb61c98a58b6e95',
38 | '6036390a2c81301a23c9452288e39cb34e577483d121711b6ba6230b29a3c9ff',
39 | 'cd69e8a25a07318b153e01bba74a1ae60f8fc28eb3d56078f448461400baa984',
40 | '17506c2246551d401c43726bdaec800f8d41595d01311cf38a19140ad32da2f4',
41 | '8fa3e8fdbaa6ab5a9c44720de4514f19182adc0c9c6001c19cf159b79c0ae9c2',
42 | 'd17317e1d5716b09cee904b8463a203dc6900d78ee2053276cc948e4f41c8295',
43 | '472ccfb865c81704562ea95870f60c08ef00bcd2ca1d7f09352398c05be5d05d',
44 | '3e9fc13fab3f8d8120bd01604ee50ff65a40121955a4150a6d2c007d34807642')
45 | ```
46 |
47 |
48 | ## Microsoft Security Blog
49 | May 24, 2023, [Volt Typhoon targets US critical infrastructure with living-off-the-land techniques](https://www.microsoft.com/en-us/security/blog/2023/05/24/volt-typhoon-targets-us-critical-infrastructure-with-living-off-the-land-techniques/)
50 |
51 | #### Disclaimer
52 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
53 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230614-CadetBlizzard.md:
--------------------------------------------------------------------------------
1 | # Cadet Blizzard emerges as a novel and distinct Russian threat actor
2 |
3 | Microsoft has identified a new Russian cyber threat group called Cadet Blizzard, associated with the GRU. Operating separately from other GRU-affiliated groups, Cadet Blizzard has conducted destructive cyber operations supporting military objectives in Ukraine. Microsoft has been tracking them since January 2022, noting their activities since at least 2020. Cadet Blizzard engages in focused attacks, including hack-and-leak operations, primarily targeting Ukrainian government and IT sectors. Microsoft collaborates with CERT-UA and global partners to address the threat, urging organizations to take preventive measures. The blog provides insights on detection and prevention against Cadet Blizzard.
4 | > 👉 June 14, 2023, [Cadet Blizzard emerges as a novel and distinct Russian threat actor](https://www.microsoft.com/en-us/security/blog/2023/06/14/cadet-blizzard-emerges-as-a-novel-and-distinct-russian-threat-actor/)
5 |
6 | ## Advanced hunting queries
7 | ***Microsoft 365 Defender : Microsoft 365 Defender customers can run the following query to find related activity in their networks:***
8 |
9 | Check for WMIExec Impacket activity with common Cadet Blizzard commands
10 | ```kusto
11 | DeviceProcessEvents
12 | | where InitiatingProcessFileName =~ "WmiPrvSE.exe" and FileName =~ "cmd.exe"
13 | | where ProcessCommandLine matches regex "2>&1"
14 | | where ProcessCommandLine has_any ("get-volume","systeminfo","reg.exe","downloadfile","nslookup","query session","route print")
15 | ```
16 |
17 | Find PowerShell file downloads
18 | ```kusto
19 | DeviceProcessEvents
20 | | where FileName == "powershell.exe" and ProcessCommandLine has "DownloadFile"
21 | ```
22 |
23 | Scheduled task creation, command execution and C2 communication
24 | ```kusto
25 | DeviceProcessEvents
26 | | where Timestamp > ago(14d)
27 | | where FileName =~ "schtasks.exe"
28 | | where (ProcessCommandLine contains "splservice" or ProcessCommandLine contains "spl32") and
29 | (ProcessCommandLine contains "127.0.0.1" or ProcessCommandLine contains "2>&1")
30 | ```
31 |
32 | ## Microsoft Security Blog
33 | June 14, 2023, [Cadet Blizzard emerges as a novel and distinct Russian threat actor](https://www.microsoft.com/en-us/security/blog/2023/06/14/cadet-blizzard-emerges-as-a-novel-and-distinct-russian-threat-actor/)
34 |
35 | #### Disclaimer
36 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
37 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230824-FlaxTyphoon.md:
--------------------------------------------------------------------------------
1 | # Flax Typhoon using legitimate software to quietly access Taiwanese organizations
2 | Microsoft has identified a distinct pattern of malicious activity primarily affecting organizations in Taiwan, attributed to Flax Typhoon, a Chinese nation-state actor (overlapping with ETHEREAL PANDA). The campaign involves espionage and maintaining access across various industries. Although no final objectives have been observed, Microsoft highlights the concern for potential impact on customers. The blog aims to raise community awareness and enhance protection measures. The threat relies on valid accounts and living-off-the-land binaries, making detection and mitigation challenging. Recommendations include closing or changing compromised accounts, isolating and investigating compromised systems. Microsoft 365 Defender is equipped to detect such stealthy attacks, and the blog provides additional mitigation steps and best practices.
3 | > 👉 August 24, 2023, [Flax Typhoon using legitimate software to quietly access Taiwanese organizations](https://www.microsoft.com/en-us/security/blog/2023/08/24/flax-typhoon-using-legitimate-software-to-quietly-access-taiwanese-organizations/)
4 |
5 | ## Advanced hunting queries
6 | ***Microsoft 365 Defender : Microsoft 365 Defender customers can run the following queries to find related activity in their networks:***
7 |
8 | Network activity with Flax Typhoon network infrastructure
9 | ```kusto
10 | let ipAddressTimes = datatable(ip: string, startDate: datetime, endDate: datetime)
11 | [
12 | "101.33.205.106", datetime("2022-11-07"), datetime("2022-11-08"),
13 | "39.98.208.61", datetime("2023-07-28"), datetime("2023-08-12"),
14 | "45.195.149.224", datetime("2023-01-04"), datetime("2023-03-29"),
15 | "122.10.89.230", datetime("2023-01-12"), datetime("2023-01-13"),
16 | "45.204.1.248", datetime("2023-02-23"), datetime("2023-05-09"),
17 | "45.204.1.247", datetime("2023-07-24"), datetime("2023-08-10"),
18 | "45.88.192.118", datetime("2022-11-07"), datetime("2022-11-08"),
19 | "154.19.187.92", datetime("2022-12-01"), datetime("2022-12-02"),
20 | "134.122.188.20", datetime("2023-06-13"), datetime("2023-06-20"),
21 | "104.238.149.146", datetime("2023-07-13"), datetime("2023-07-14"),
22 | "139.180.158.51", datetime("2022-08-30"), datetime("2023-07-27"),
23 | "137.220.36.87", datetime("2023-02-23"), datetime("2023-08-04"),
24 | "192.253.235.107", datetime("2023-06-06"), datetime("2023-06-07")
25 | ];
26 | let RemoteIPFiltered = DeviceNetworkEvents
27 | | join kind=inner (ipAddressTimes) on $left.RemoteIP == $right.ip
28 | | where Timestamp between (startDate .. endDate);
29 | let LocalIPFiltered = DeviceNetworkEvents
30 | | join kind=inner (ipAddressTimes) on $left.LocalIP == $right.ip
31 | | where Timestamp between (startDate .. endDate);
32 | union RemoteIPFiltered, LocalIPFiltered
33 | ```
34 |
35 | SoftEther VPN bridge launched by SQL Server process
36 | ```kusto
37 | DeviceProcessEvents
38 | | where ProcessVersionInfoOriginalFileName == "vpnbridge.exe" or ProcessVersionInfoFileDescription == "SoftEther VPN"
39 | | where InitiatingProcessParentFileName == "sqlservr.exe"
40 | ```
41 |
42 | SoftEther VPN bridge renamed to “conhost.exe” or “dllhost.exe”
43 | ```kusto
44 | DeviceProcessEvents
45 | | where ProcessVersionInfoOriginalFileName == "vpnbridge.exe" or ProcessVersionInfoFileDescription == "SoftEther VPN"
46 | | where ProcessCommandLine has_any ("conhost.exe", "dllhost.exe") or FolderPath has_any ("mssql", "conhost.exe", "dllhost.exe")
47 | ```
48 |
49 | Certutil launched by SQL Server process
50 | ```kusto
51 | DeviceProcessEvents
52 | | where ProcessCommandLine has_all ("certutil", "-urlcache")
53 | | where InitiatingProcessFileName has_any ("sqlservr.exe", "sqlagent.exe", "sqlps.exe", "launchpad.exe", "sqldumper.exe")
54 |
55 | ```
56 |
57 | File downloaded by MSSQLSERVER account using certutil
58 | ```kusto
59 | DeviceFileEvents
60 | | where InitiatingProcessAccountName == "MSSQLSERVER"
61 | | where InitiatingProcessFileName == "certutil.exe"
62 | ```
63 |
64 | File renamed to “conhost.exe” or “dllhost.exe”, downloaded using certutil
65 | ```kusto
66 | DeviceFileEvents
67 | | where InitiatingProcessFileName == "certutil.exe"
68 | | where FileName in ("conhost.exe", "dllhost.exe")
69 | ```
70 |
71 | Network connection made by SoftEther VPN bridge renamed to “conhost.exe” or “dllhost.exe”
72 | ```kusto
73 | DeviceNetworkEvents
74 | | where InitiatingProcessVersionInfoOriginalFileName == "vpnbridge.exe" or InitiatingProcessVersionInfoProductName == "SoftEther VPN"
75 | | where InitiatingProcessFileName == "conhost.exe"
76 | ```
77 |
78 | Network connection made by MSSQLSERVER account, using SoftEther VPN bridge
79 | ```kusto
80 | DeviceNetworkEvents
81 | | where InitiatingProcessVersionInfoOriginalFileName == "vpnbridge.exe" or InitiatingProcessVersionInfoProductName == "SoftEther VPN"
82 | | where InitiatingProcessAccountName == "MSSQLSERVER"
83 | ```
84 |
85 | ## Microsoft Security Blog
86 | August 24, 2023, [Flax Typhoon using legitimate software to quietly access Taiwanese organizations](https://www.microsoft.com/en-us/security/blog/2023/08/24/flax-typhoon-using-legitimate-software-to-quietly-access-taiwanese-organizations/)
87 |
88 | #### Disclaimer
89 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
90 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230912-Storm-0324.md:
--------------------------------------------------------------------------------
1 | # Malware distributor Storm-0324 facilitates ransomware access
2 |
3 | Microsoft is tracking a financially motivated threat actor known as Storm-0324, also identified as DEV-0324, TA543, and Sagrid. This group specializes in distributing payloads for other attackers through phishing and exploit kit vectors. Notably, in July 2023, Storm-0324 was observed using an open-source tool to distribute payloads via phishing lures in Microsoft Teams chats, distinct from the Midnight Blizzard campaigns observed earlier in May 2023. Storm-0324 employs highly evasive infection chains, focusing on payment and invoice lures, and is associated with distributing the JSSLoader malware used by the ransomware-as-a-service actor Sangria Tempest (ELBRUS, Carbon Spider, FIN7). Microsoft advises using Microsoft 365 Defender to detect Storm-0324 activity and implementing measures such as the principle of least privilege and credential hygiene to limit the impact of these attacks. The blog provides a detailed analysis of Storm-0324's tools, tactics, and procedures observed in past and recent campaigns.
4 | > 👉 September 12, 2023, [Malware distributor Storm-0324 facilitates ransomware access](https://www.microsoft.com/en-us/security/blog/2023/09/12/malware-distributor-storm-0324-facilitates-ransomware-access/)
5 |
6 | ## Advanced hunting queries
7 | **Possible TeamsPhisher downloads**
8 |
9 | The following query looks for downloaded files that were potentially facilitated by use of the TeamsPhisher tool.
10 | Defenders should customize the SharePoint domain name (‘mysharepointname’) in the query.
11 |
12 | ```kusto
13 | let allowedSharepointDomain = pack_array(
14 | 'mysharepointname' //customize Sharepoint domain name and add more domains as needed for your query
15 | );
16 | //
17 | let executable = pack_array(
18 | 'exe',
19 | 'dll',
20 | 'xll',
21 | 'msi',
22 | 'application'
23 | );
24 | let script = pack_array(
25 | 'ps1',
26 | 'py',
27 | 'vbs',
28 | 'bat'
29 | );
30 | let compressed = pack_array(
31 | 'rar',
32 | '7z',
33 | 'zip',
34 | 'tar',
35 | 'gz'
36 | );
37 | //
38 | let startTime = ago(1d);
39 | let endTime = now();
40 | DeviceFileEvents
41 | | where Timestamp between (startTime..endTime)
42 | | where ActionType =~ 'FileCreated'
43 | | where InitiatingProcessFileName has 'teams.exe'
44 | or InitiatingProcessParentFileName has 'teams.exe'
45 | | where InitiatingProcessFileName !has 'update.exe'
46 | and InitiatingProcessParentFileName !has 'update.exe'
47 | | where FileOriginUrl has 'sharepoint'
48 | and FileOriginReferrerUrl has_any ('sharepoint', 'teams.microsoft')
49 | | extend fileExt = tolower(tostring(split(FileName,'.')[-1]))
50 | | where fileExt in (executable)
51 | or fileExt in (script)
52 | or fileExt in (compressed)
53 | | extend fileGroup = iff( fileExt in (executable),'executable','')
54 | | extend fileGroup = iff( fileExt in (script),'script',fileGroup)
55 | | extend fileGroup = iff( fileExt in (compressed),'compressed',fileGroup)
56 | //
57 | | extend sharePoint_domain = tostring(split(FileOriginUrl,'/')[2])
58 | | where not (sharePoint_domain has_any (allowedSharepointDomain))
59 | | project-reorder Timestamp, DeviceId, DeviceName, sharePoint_domain, FileName, FolderPath, SHA256, FileOriginUrl, FileOriginReferrerUrl
60 | ```
61 |
62 | ## Microsoft Security Blog
63 | September 12, 2023, [Malware distributor Storm-0324 facilitates ransomware access](https://www.microsoft.com/en-us/security/blog/2023/09/12/malware-distributor-storm-0324-facilitates-ransomware-access/)
64 |
65 | #### Disclaimer
66 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
67 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20231018-DiamondSleet-OnyxSleet.md:
--------------------------------------------------------------------------------
1 | # Multiple North Korean threat actors exploiting the TeamCity CVE-2023-42793 vulnerability
2 | Since October 2023, Microsoft has identified two North Korean threat actors, Diamond Sleet and Onyx Sleet, exploiting a remote-code execution vulnerability in JetBrains TeamCity server used for DevOps. These actors pose a high risk due to past successful software supply chain attacks. JetBrains released an update, and Microsoft advises affected organizations to apply it. Despite exploiting the same vulnerability, the threat actors use unique tools and techniques. Microsoft suspects opportunistic compromises of vulnerable servers, with both actors deploying malware and employing methods for persistent access. The company actively notifies and supports affected customers to secure their environments.
3 | > 👉 October 18, 2023, [Multiple North Korean threat actors exploiting the TeamCity CVE-2023-42793 vulnerability](https://www.microsoft.com/en-us/security/blog/2023/10/18/multiple-north-korean-threat-actors-exploiting-the-teamcity-cve-2023-42793-vulnerability/)
4 |
5 | ## Advanced hunting queries
6 | Command and control using iexpress.exe or wksprt.exe
7 | ```kusto
8 | DeviceNetworkEvents
9 | | where (InitiatingProcessFileName =~ "wksprt.exe" and InitiatingProcessCommandLine == "wksprt.exe")
10 | or (InitiatingProcessFileName =~ "iexpress.exe" and InitiatingProcessCommandLine == "iexpress.exe")
11 | ```
12 |
13 | Search order hijack using Wsmprovhost.exe and DSROLE.dll
14 | ```kusto
15 | DeviceImageLoadEvents
16 | | where InitiatingProcessFileName =~ "wsmprovhost.exe"
17 | | where FileName =~ "DSROLE.dll"
18 | | where not(FolderPath has_any("system32", "syswow64"))
19 | ```
20 |
21 | Search order hijack using clip.exe and Version.dll
22 | ```kusto
23 | DeviceImageLoadEvents
24 | | where InitiatingProcessFileName =~ "clip.exe"
25 | | where FileName in~("version.dll")
26 | | where not(FolderPath has_any("system32", "syswow64", "program files", "windows defender\\platform", "winsxs", "platform",
27 | "trend micro"))
28 | ```
29 |
30 | ## Microsoft Security Blog
31 | October 18, 2023, [Multiple North Korean threat actors exploiting the TeamCity CVE-2023-42793 vulnerability](https://www.microsoft.com/en-us/security/blog/2023/10/18/multiple-north-korean-threat-actors-exploiting-the-teamcity-cve-2023-42793-vulnerability/)
32 |
33 | #### Disclaimer
34 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
35 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20231122-DiamondSleet.md:
--------------------------------------------------------------------------------
1 | # Diamond Sleet supply chain compromise distributes a modified CyberLink installer
2 |
3 | Microsoft Threat Intelligence has exposed a supply chain attack by North Korean threat actor Diamond Sleet (ZINC). The attack involved a modified installer of a legitimate application by CyberLink Corp., a multimedia software company. The installer, signed with a valid CyberLink Corp. certificate, downloads a second-stage payload, impacting over 100 devices across multiple countries. Diamond Sleet is attributed to this with high confidence, and the second-stage payload communicates with previously compromised infrastructure. Microsoft has taken steps to mitigate further risks, including informing CyberLink, notifying affected Microsoft Defender for Endpoint customers, reporting the attack to GitHub, and adding the malicious certificate to its disallowed list. Microsoft Defender for Endpoint detects this as Diamond Sleet activity, and Defender Antivirus labels the malware as Trojan:Win32/LambLoad. The blog may be updated with additional insights as the campaign progresses.
4 | > 👉 November 22, 2023, [Diamond Sleet supply chain compromise distributes a modified CyberLink installer](https://www.microsoft.com/en-us/security/blog/2023/11/22/diamond-sleet-supply-chain-compromise-distributes-a-modified-cyberlink-installer/)
5 |
6 | ## Advanced hunting queries
7 | **Microsoft Defender XDR**
8 |
9 | Microsoft Defender XDR (formerly Microsoft 365 Defender) customers can run the following query to find related activity in their networks:
10 | ```kusto
11 | let iocs = dynamic(["166d1a6ddcde4e859a89c2c825cd3c8c953a86bfa92b343de7e5bfbfb5afb8be",
12 | "089573b3a1167f387dcdad5e014a5132e998b2c89bff29bcf8b06dd497d4e63d",
13 | "915c2495e03ff7408f11a2a197f23344004c533ff87db4b807cc937f80c217a1"]);
14 | DeviceFileEvents
15 | | where ActionType == "FileCreated"
16 | | where SHA256 in (iocs)
17 | | project Timestamp, DeviceName, FileName, FolderPath, SHA256
18 | ```
19 |
20 | **Microsoft Defender XDR and Microsoft Sentinel**
21 |
22 | This query can be used in both Microsoft Defender XDR advanced hunting and Microsoft Sentinel Log Analytics. It surfaces devices where the modified CyberLink installer can be found.
23 | ```kusto
24 | DeviceFileCertificateInfo
25 | | where Signer contains "CyberLink Corp"
26 | | where CertificateSerialNumber == "0a08d3601636378f0a7d64fd09e4a13b"
27 | | where SignerHash == "8aa3877ab68ba56dabc2f2802e813dc36678aef4"
28 | | join DeviceFileEvents on SHA1
29 | | distinct DeviceName, FileName, FolderPath, SHA1, SHA256, IsTrusted, IsRootSignerMicrosoft, SignerHash
30 | ```
31 |
32 | ## Microsoft Security Blog
33 | November 22, 2023, [Diamond Sleet supply chain compromise distributes a modified CyberLink installer](https://www.microsoft.com/en-us/security/blog/2023/11/22/diamond-sleet-supply-chain-compromise-distributes-a-modified-cyberlink-installer/)
34 |
35 | #### Disclaimer
36 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
37 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/MSSecurityThreatInsight2023.md:
--------------------------------------------------------------------------------
1 | # Microsoft Security Threat Insight 2023
2 |
3 |
4 |
5 |
6 |
7 | I have seen a variety of valuable insights on nation-based threat actors from MSTIC, DART, the Product Team, and others. While I may not be able to list them all precisely, I would like to keep them here as KQL query logs.
8 |
9 | > [!Note]
10 | > This repository primarily focuses on ***Threat Actors*** from the year 2023 , and therefore, does not include specific attack techniques.
11 | > For details on each KQL, attack backgrounds, etc., please refer to the accompanying blog.
12 |
13 | ## Blizzard
14 | | Date | Name | Microsoft Security Blog / KQL |
15 | |:----------------|:----------------|:------------------------------|
16 | | June 14 | Cadet Blizzard | [Cadet Blizzard emerges as a novel and distinct Russian threat actor](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230614-CadetBlizzard.md) |
17 |
18 | ## Typhoon
19 | | Date | Name | Microsoft Security Blog / KQL |
20 | |:----------------|:----------------|:------------------------------|
21 | | May 24 | Volt Typhoon | [Volt Typhoon targets US critical infrastructure with living-off-the-land techniques](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230525-VoltTyphoon.md) |
22 | | August 24 | Flax Typhoon | [Flax Typhoon using legitimate software to quietly access Taiwanese organizations](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230824-FlaxTyphoon.md) |
23 |
24 | ## Sandstorm
25 | | Date | Name | Microsoft Security Blog / KQL |
26 | |:----------------|:----------------|:------------------------------|
27 | | April 7 | Mango Sandstorm | [MERCURY and DEV-1084: Destructive attack on hybrid environments](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230407-MangoSandstorm.md) |
28 | | April 18 | Mint Sandstorm | [Nation-state threat actor Mint Sandstorm refines tradecraft to attack high-value targets](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230418-MintSandstorm.md) |
29 |
30 | ## Sleet
31 | | Date | Name | Microsoft Security Blog / KQL |
32 | |:----------------|:----------------|:------------------------------|
33 | | October 18 | Diamond Sleet
Onyx Sleet | [Multiple North Korean threat actors exploiting the TeamCity CVE-2023-42793 vulnerability](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20231018-DiamondSleet-OnyxSleet.md)
34 | | November 22 | Diamond Sleet | [Diamond Sleet supply chain compromise distributes a modified CyberLink installer](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight//20231122-DiamondSleet.md) |
35 |
36 | ## Storm
37 | | Date | Name | Microsoft Security Blog / KQL |
38 | |:----------------|:----------------|:------------------------------|
39 | | September 12 | Storm-0324 | [Malware distributor Storm-0324 facilitates ransomware access](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/20230912-Storm-0324.md) |
40 |
41 | ```
42 | Actor category
43 | - Typhoon : China
44 | - Sandstorm : Iran
45 | - Rain : Lebanon
46 | - Sleet : North Korea
47 | - Blizzard : Russia
48 | - Hail : South Korea
49 | - Dust : Turkey
50 | - Cyclone : Vietnam
51 |
52 | Financially motivated
53 | - Tempest : Financially motivated
54 |
55 | Private sector offensive actors
56 | - Tsunami : PSOAs
57 |
58 | Influence operations
59 | - Flood : Influence operations
60 |
61 | Groups in development
62 | - Storm : Groups in development
63 | ```
64 | > [!Important]
65 | > Microsoft has shifted to a new naming taxonomy for threat actors aligned with the theme of weather. With the new taxonomy, we intend to bring better clarity to customers and other security researchers already confronted with an overwhelming amount of threat intelligence data and offer a more organized, articulate, and easy way to reference threat actors so that organizations can better prioritize and protect themselves.
66 | > [How Microsoft names threat actors](https://learn.microsoft.com/en-us/microsoft-365/security/intelligence/microsoft-threat-actor-naming?view=o365-worldwide)
67 |
68 | #### Disclaimer
69 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
70 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2024-MicrosoftSecurity-ThreatInsight/MSSecurityThreatInsight2024.md:
--------------------------------------------------------------------------------
1 | # Microsoft Security Threat Insight 2024
2 |
3 |
4 |
5 |
6 |
7 | I have seen a variety of valuable insights on nation-based threat actors from MSTIC, DART, the Product Team, and others. While I may not be able to list them all precisely, I would like to keep them here as KQL query logs.
8 |
9 | > [!Note]
10 | > This repository primarily focuses on ***Threat Actors*** from the year 2024 , and therefore, does not include specific attack techniques.
11 | > For details on each KQL, attack backgrounds, etc., please refer to the accompanying blog.
12 |
13 | TBD
14 |
15 | ```
16 | Actor category
17 | - Typhoon : China
18 | - Sandstorm : Iran
19 | - Rain : Lebanon
20 | - Sleet : North Korea
21 | - Blizzard : Russia
22 | - Hail : South Korea
23 | - Dust : Turkey
24 | - Cyclone : Vietnam
25 |
26 | Financially motivated
27 | - Tempest : Financially motivated
28 |
29 | Private sector offensive actors
30 | - Tsunami : PSOAs
31 |
32 | Influence operations
33 | - Flood : Influence operations
34 |
35 | Groups in development
36 | - Storm : Groups in development
37 | ```
38 | > [!Important]
39 | > Microsoft has shifted to a new naming taxonomy for threat actors aligned with the theme of weather. With the new taxonomy, we intend to bring better clarity to customers and other security researchers already confronted with an overwhelming amount of threat intelligence data and offer a more organized, articulate, and easy way to reference threat actors so that organizations can better prioritize and protect themselves.
40 | > [How Microsoft names threat actors](https://learn.microsoft.com/en-us/microsoft-365/security/intelligence/microsoft-threat-actor-naming?view=o365-worldwide)
41 |
42 | #### Disclaimer
43 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
44 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/01-AccountDiscovery-NetCommandUsage.md:
--------------------------------------------------------------------------------
1 | # Account Discovery - Net Command Usage
2 |
3 | This query tracks net command activities, specifically focusing on gathering domain account and local account information.
4 | ```kusto
5 | DeviceProcessEvents
6 | | where FileName == "net.exe"
7 | | where ProcessCommandLine has_any ("/domain", "user", "group")
8 | ```
9 |
10 | This query tracks net command activities, specifically focusing on gathering domain account and local account information.
11 | It lists all activities for each device in the past 7 days.
12 | ```kusto
13 | DeviceProcessEvents
14 | | where Timestamp > ago(7d)
15 | | where FileName == "net.exe"
16 | | where ProcessCommandLine has_any ("/domain", "user", "group")
17 | | summarize CmdList = make_set(strcat(format_datetime(Timestamp,'yyyy-M-dd H:mm:ss'), " : ", ProcessCommandLine)) by DeviceId, DeviceName
18 | | extend Case = array_length(CmdList)
19 | | project DeviceId, DeviceName, Case, CmdList
20 | | order by Case desc
21 | ```
22 |
23 | 
24 |
25 | #### Reference
26 | - [Account Discovery: Local Account](https://attack.mitre.org/techniques/T1087/001/)
27 | - [Account Discovery: Domain Account](https://attack.mitre.org/techniques/T1087/002/)
28 |
29 | #### Disclaimer
30 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
31 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20220712-MSSecurityBlog-AiTM-HuntingQueries.md:
--------------------------------------------------------------------------------
1 | # From cookie theft to BEC: Attackers use AiTM phishing sites as entry point to further financial fraud
2 | > [!Note]
3 | > ***AiTM - "adversary-in-the-middle"*** - In AiTM phishing, attackers deploy a proxy server between a target user and the website the user wishes to visit (that is, the site the attacker wishes to impersonate).
4 | > Such a setup allows the attacker to steal and intercept the target’s password and the session cookie that proves their ongoing and authenticated session with the website.
5 | > Note that this is not a vulnerability in MFA; since AiTM phishing steals the session cookie, the attacker gets authenticated to a session on the user’s behalf, regardless of the sign-in method the latter uses.
6 |
7 | When an attacker uses a stolen session cookie, the “SessionId” attribute in the AADSignInEventBeta table will be identical to the SessionId value used in the authentication process against the phishing site.
8 | Use this query to search for cookies that were first seen after OfficeHome application authentication (as seen when the user authenticated to the AiTM phishing site) and then seen being used in other applications in other countries :
9 | ```kusto
10 | let OfficeHomeSessionIds =
11 | AADSignInEventsBeta
12 | | where Timestamp > ago(1d)
13 | | where ErrorCode == 0
14 | | where ApplicationId == "4765445b-32c6-49b0-83e6-1d93765276ca" //OfficeHome application
15 | | where ClientAppUsed == "Browser"
16 | | where LogonType has "interactiveUser"
17 | | summarize arg_min(Timestamp, Country) by SessionId;
18 | AADSignInEventsBeta
19 | | where Timestamp > ago(1d)
20 | | where ApplicationId != "4765445b-32c6-49b0-83e6-1d93765276ca"
21 | | where ClientAppUsed == "Browser"
22 | | project OtherTimestamp = Timestamp, Application, ApplicationId, AccountObjectId, AccountDisplayName, OtherCountry = Country, SessionId
23 | | join OfficeHomeSessionIds on SessionId
24 | | where OtherTimestamp > Timestamp and OtherCountry != Country
25 | ```
26 |
27 | Use this query to summarize for each user the countries that authenticated to the OfficeHome application and find uncommon or untrusted ones :
28 | ```kusto
29 | AADSignInEventsBeta
30 | | where Timestamp > ago(7d)
31 | | where ApplicationId == "4765445b-32c6-49b0-83e6-1d93765276ca" //OfficeHome application
32 | | where ClientAppUsed == "Browser"
33 | | where LogonType has "interactiveUser"
34 | | summarize Countries = make_set(Country) by AccountObjectId, AccountDisplayName
35 | ```
36 |
37 | Use this query to find new email Inbox rules created during a suspicious sign-in session :
38 | ```kusto
39 | //Find suspicious tokens tagged by AAD "Anomalous Token" alert
40 | let suspiciousSessionIds = materialize(
41 | AlertInfo
42 | | where Timestamp > ago(7d)
43 | | where Title == "Anomalous Token"
44 | | join (AlertEvidence | where Timestamp > ago(7d) | where EntityType == "CloudLogonSession") on AlertId
45 | | project sessionId = todynamic(AdditionalFields).SessionId);
46 | //Find Inbox rules created during a session that used the anomalous token
47 | let hasSuspiciousSessionIds = isnotempty(toscalar(suspiciousSessionIds));
48 | CloudAppEvents
49 | | where hasSuspiciousSessionIds
50 | | where Timestamp > ago(21d)
51 | | where ActionType == "New-InboxRule"
52 | | where RawEventData.SessionId in (suspiciousSessionIds)
53 | ```
54 |
55 | #### Reference
56 | - July 12, 2022, [From cookie theft to BEC: Attackers use AiTM phishing sites as entry point to further financial fraud](https://www.microsoft.com/en-us/security/blog/2022/07/12/from-cookie-theft-to-bec-attackers-use-aitm-phishing-sites-as-entry-point-to-further-financial-fraud/)
57 |
58 | #### Disclaimer
59 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
60 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20221018-MSSecurityBlog-PostRansomware-AntivirusTampering.md:
--------------------------------------------------------------------------------
1 | # Antivirus tampering
2 | Microsoft Security Blog title - Defenders beware: A case for post-ransomware investigations
3 |
4 | Organizations should monitor and respond to antivirus and endpoint detection and response (EDR) alerts where antivirus has been disabled or tampered with.
5 | Wherever possible, anti-tampering settings should be enabled to prevent actors from being able to interact with and disable antivirus software.
6 | For more information about Defender for Endpoint tamper protection, visit our docs page: [Protect security settings with tamper protection](https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/prevent-changes-to-security-settings-with-tamper-protection?view=o365-worldwide).
7 |
8 | Microsoft Defender Antivirus provides [event logging](https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/troubleshoot-microsoft-defender-antivirus?view=o365-worldwide) on attempted tampering of the product.
9 | This can include the disabling of services, such as Real Time Protection (Event ID: 5001).
10 | An alert will also be created within the Defender for Endpoint portal where customers have the ability to further triage the alert through the [advanced hunting interface](https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/faqs-on-tamper-protection?view=o365-worldwide#if-the-status-of-tamper-protection-changes-are-alerts-shown-in-the-microsoft-365-defender-portal).
11 | Monitoring for the usage of the Windows PowerShell cmdlet can also help discover instances of anti-virus tampering.
12 |
13 | #### AntivirusTampering
14 |
15 | ```kusto
16 | DeviceProcessEvents
17 | | where FileName =~ "PowerShell.exe"
18 | | where ProcessCommandLine has_any ("Get-MpPreference", "Add-MpPreference", "Set-MpPreference")
19 | | project Timestamp, ProcessCommandLine
20 | ```
21 |
22 | #### Reference
23 | - October 18, 2022, [Defenders beware: A case for post-ransomware investigations](https://www.microsoft.com/en-us/security/blog/2022/10/18/defenders-beware-a-case-for-post-ransomware-investigations/)
24 |
25 | #### Disclaimer
26 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
27 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20221018-MSSecurityBlog-PostRansomware-Impacket.md:
--------------------------------------------------------------------------------
1 | # Possible Impacket (WMI) module usage
2 | Microsoft Security Blog title - Defenders beware: A case for post-ransomware investigations
3 |
4 | Impacket's WMI modules were used throughout the early stages of the compromise for remote execution and discovery.
5 | Impacket is an open-source collection of scripts for working with network protocols.
6 | This toolkit has recently been used by a large variety of crimeware groups for lateral movement and network discovery.
7 |
8 | The actor used Impacket to execute PowerShell scripts out of "C:\Perflogs\", which created .txt files within the same directory.
9 | All commands executed through Impacket output the results of the command to "\\127.0.0.1\ADMIN$\__1648051380.61".
10 | The actor then deleted the PowerShell scripts and text files after execution.
11 |
12 | The actor also used Impacket to test if the destination server was able to ping the actor's C2 before deploying Cobalt Strike to the device.
13 | #### Possible Impacket (WMI) module usage
14 |
15 | ```kusto
16 | DeviceEvents
17 | | where Timestamp > ago(7d)
18 | | where ActionType == "ProcessCreatedUsingWmiQuery"
19 | | where FileName == "cmd.exe"
20 | | where ProcessCommandLine contains "/Q /c"
21 | | project Timestamp, DeviceId, DeviceName, ActionType, FolderPath, FileName, ProcessCommandLine, InitiatingProcessCommandLine
22 | ```
23 |
24 | ```kusto
25 | DeviceProcessEvents
26 | | where Timestamp > ago(7d)
27 | | where InitiatingProcessParentFileName == "WmiPrvSE.exe"
28 | | where InitiatingProcessFolderPath has "cmd.exe"
29 | | where InitiatingProcessCommandLine contains "/Q /c"
30 | | project Timestamp, DeviceId, DeviceName, ActionType, FolderPath, FileName, InitiatingProcessCommandLine, ProcessCommandLine
31 | ```
32 |
33 | #### Reference
34 | - October 18, 2022, [Defenders beware: A case for post-ransomware investigations](https://www.microsoft.com/en-us/security/blog/2022/10/18/defenders-beware-a-case-for-post-ransomware-investigations/)
35 | - August 31, 2022, [Defense Against the Lateral Arts: Detecting and Preventing Impacket’s Wmiexec](https://www.crowdstrike.com/blog/how-to-detect-and-prevent-impackets-wmiexec/)
36 |
37 | #### Disclaimer
38 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
39 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20221018-MSSecurityBlog-PostRansomware-PsExec.md:
--------------------------------------------------------------------------------
1 | # PsExec.exe usage
2 | Microsoft Security Blog title - Defenders beware: A case for post-ransomware investigations
3 |
4 | The actor used PsExec.exe to spread the ransomware on the victims' network.
5 | The actor first executed "open.bat", which executed "net share [C-Z]=[C-Z]:\ /grant:everyone,FULL".
6 | This shared every drive on the host, granting access to everyone. "A.exe", "Anet.exe", and "Aus.exe" are all variants of the Cuba ransomware.
7 |
8 | #### PsExec.exe usage
9 |
10 | ```kusto
11 | DeviceProcessEvents
12 | | where InitiatingProcessCommandLine contains "psexe"
13 | | distinct ProcessCommandLine
14 | ```
15 |
16 | #### Reference
17 | - October 18, 2022, [Defenders beware: A case for post-ransomware investigations](https://www.microsoft.com/en-us/security/blog/2022/10/18/defenders-beware-a-case-for-post-ransomware-investigations/)
18 |
19 | #### Disclaimer
20 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20221018-MSSecurityBlog-PostRansomware-SSHconnection.md:
--------------------------------------------------------------------------------
1 | # Monitoring SSH connection
2 | Microsoft Security Blog title - Defenders beware: A case for post-ransomware investigations
3 |
4 | **Scheduled task: OpenSSH**
5 |
6 | The actor installed OpenSSH on the client's network to maintain persistence on critical servers, including domain controllers and domain administrator workstations. The actor installed OpenSSH within C:\Windows\OpenSSH, rather than the standard OpenSSH path in System32.
7 |
8 | The actor created a scheduled task for a persistent SSH connection to their C2 as "NT AUTHORITY\System". The actor used TCP 443 for their SSH traffic rather than the standard TCP 22. In many organizations, TCP 22 outbound may be blocked, but as TCP 443 is needed for web traffic the port is often open. The actor also enabled port forwarding on TCP 7878 to allow the tunneling of malicious tools through the SSH connection.
9 |
10 | The actor was also observed renaming ssh.exe to "C:\Windows\OpenSSH\svchost.exe" in a likely attempt to evade detection.
11 |
12 | Four days after the actor deployed the ransomware, the actor returned to the compromised network through their existing OpenSSH persistence to install further persistence SSH services on additional domain controllers and domain administrator workstations.
13 |
14 | The actor used OpenSSH's sftp-server to transfer files between their C2 and the compromised host. The actor generated SSH keys on compromised hosts using ssh-keygen.exe, a tool apart of the OpenSSH tool suite. This allowed the actor to SSH using the keys rather than credentials, after credentials had been reset.
15 |
16 | #### Monitoring SSH connection
17 |
18 | ```kusto
19 | DeviceProcessEvents
20 | | where Timestamp > ago(7d)
21 | | where FolderPath has "OpenSSH"
22 | or FileName == "ssh.exe"
23 | or FileName == "scp.exe"
24 | or FileName == "sftp.exe"
25 | or FileName == "sshd.exe"
26 | or FileName == "ssh-add.exe"
27 | or FileName == "ssh-agent.exe"
28 | or FileName == "ssh-keygen.exe"
29 | or FileName == "ssh-keyscan.exe"
30 | | where ProcessCommandLine has_all ("ssh", "-p")
31 | | project-reorder ProcessCommandLine
32 | ```
33 |
34 | #### Reference
35 | - October 18, 2022, [Defenders beware: A case for post-ransomware investigations](https://www.microsoft.com/en-us/security/blog/2022/10/18/defenders-beware-a-case-for-post-ransomware-investigations/)
36 |
37 | #### Disclaimer
38 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
39 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20221018-MSSecurityBlog-PostRansomware-Taskschedules.md:
--------------------------------------------------------------------------------
1 | # Monitoring Task schedules
2 | Microsoft Security Blog title - Defenders beware: A case for post-ransomware investigations
3 |
4 | **Scheduled task: OpenSSH**
5 |
6 | The actor installed OpenSSH on the client's network to maintain persistence on critical servers, including domain controllers and domain administrator workstations. The actor installed OpenSSH within C:\Windows\OpenSSH, rather than the standard OpenSSH path in System32.
7 |
8 | ***The actor created a scheduled task for a persistent SSH connection to their C2 as "NT AUTHORITY\System".*** The actor used TCP 443 for their SSH traffic rather than the standard TCP 22. In many organizations, TCP 22 outbound may be blocked, but as TCP 443 is needed for web traffic the port is often open. The actor also enabled port forwarding on TCP 7878 to allow the tunneling of malicious tools through the SSH connection.
9 |
10 | The actor was also observed renaming ssh.exe to "C:\Windows\OpenSSH\svchost.exe" in a likely attempt to evade detection.
11 |
12 | Four days after the actor deployed the ransomware, the actor returned to the compromised network through their existing OpenSSH persistence to install further persistence SSH services on additional domain controllers and domain administrator workstations.
13 |
14 | The actor used OpenSSH's sftp-server to transfer files between their C2 and the compromised host. The actor generated SSH keys on compromised hosts using ssh-keygen.exe, a tool apart of the OpenSSH tool suite. This allowed the actor to SSH using the keys rather than credentials, after credentials had been reset.
15 |
16 | #### Monitoring Task schedules
17 |
18 | ```kusto
19 | DeviceProcessEvents
20 | | where Timestamp > ago(7d)
21 | | where FileName == "schtasks.exe"
22 | | where ProcessCommandLine has_any ("/run", "/create")
23 | | where FolderPath has_any
24 | (@"C:\ProgramData\",
25 | @"C:\Windows\Temp\",
26 | @"C:\Windows\",
27 | @"C:\Temp\")
28 | | project Timestamp, DeviceId, DeviceName, FileName, FolderPath, ProcessCommandLine
29 | ```
30 |
31 | #### Monitoring Task schedules with NT AUTHORITY/SYSTEM (local SYSTEM) privileges
32 | ```kusto
33 | DeviceProcessEvents
34 | | where Timestamp > ago(7d)
35 | | where FileName == "schtasks.exe"
36 | | where AccountName == "system" and AccountDomain == "nt authority"
37 | | where ProcessCommandLine has_any ("/run", "/create")
38 | | where FolderPath has_any
39 | (@"C:\ProgramData\",
40 | @"C:\Windows\Temp\",
41 | @"C:\Windows\",
42 | @"C:\Temp\")
43 | | project Timestamp, DeviceId, DeviceName, FileName, FolderPath, ProcessCommandLine
44 | ```
45 |
46 | #### Reference
47 | - October 18, 2022, [Defenders beware: A case for post-ransomware investigations](https://www.microsoft.com/en-us/security/blog/2022/10/18/defenders-beware-a-case-for-post-ransomware-investigations/)
48 |
49 | #### Disclaimer
50 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
51 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20221018-MSSecurityBlog-PostRansomware-WDigest.md:
--------------------------------------------------------------------------------
1 | # WDigest credential harvesting
2 | Microsoft Security Blog title - Defenders beware: A case for post-ransomware investigations
3 |
4 | **WDigest**
5 |
6 | The actor abused WDigest to cache credentials early in the compromise. This enabled the actor to gain access to domain administrator credentials.
7 |
8 | WDigest is a Windows feature that when enabled, caches credentials in clear text. This is often abused by credential access tools, such as Mimikatz.
9 | To detect if WDigest has been enabled within your network, the registry key HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential will be set to 1. This can be disabled by setting the value to 0.
10 |
11 | #### WDigest credential harvesting
12 | Find attempts to turn on WDigest credential caching
13 | ```kusto
14 | DeviceRegistryEvents
15 | | where Timestamp > ago(7d)
16 | | where RegistryKey contains "wdigest" and RegistryValueName == "UseLogonCredential" and RegistryValueData == "1"
17 | | project Timestamp, DeviceId, DeviceName, PreviousRegistryValueData, RegistryKey, RegistryValueName, RegistryValueData, InitiatingProcessAccountName, InitiatingProcessFileName, InitiatingProcessCommandLine, InitiatingProcessParentFileName
18 | ```
19 | Find processes created with commandlines that attempt to turn on WDigest caching
20 | ```kusto
21 | DeviceProcessEvents
22 | | where Timestamp > ago(7d)
23 | | where ProcessCommandLine has "WDigest" and ProcessCommandLine has "UseLogonCredential" and ProcessCommandLine has "dword" and ProcessCommandLine has "1"
24 | | project Timestamp, DeviceId, DeviceName, InitiatingProcessAccountName, InitiatingProcessFileName, InitiatingProcessCommandLine, InitiatingProcessParentFileName, FileName, ProcessCommandLine
25 | ```
26 |
27 | #### Reference
28 | - October 18, 2022, [Defenders beware: A case for post-ransomware investigations](https://www.microsoft.com/en-us/security/blog/2022/10/18/defenders-beware-a-case-for-post-ransomware-investigations/)
29 |
30 | #### Disclaimer
31 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
32 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20230313-MSSecurityBlog-AiTM-MicrosoftSentinel-AnalyticsTemplate.md:
--------------------------------------------------------------------------------
1 | # DEV-1101 enables high-volume AiTM campaigns with open-source phishing kit
2 | > [!Important]
3 | > April 2023 update – Microsoft Threat Intelligence has shifted to a new threat actor naming taxonomy aligned around the theme of weather. DEV-1101 is now tracked as Storm-1101.
4 |
5 | > [!Note]
6 | > ***AiTM - "adversary-in-the-middle"*** - In AiTM phishing, attackers deploy a proxy server between a target user and the website the user wishes to visit (that is, the site the attacker wishes to impersonate).
7 | > Such a setup allows the attacker to steal and intercept the target’s password and the session cookie that proves their ongoing and authenticated session with the website.
8 | > Note that this is not a vulnerability in MFA; since AiTM phishing steals the session cookie, the attacker gets authenticated to a session on the user’s behalf, regardless of the sign-in method the latter uses.
9 |
10 | #### Microsoft Sentinel Analytics template - [Possible AiTM Phishing Attempt Against Azure AD](https://github.com/Azure/Azure-Sentinel/blob/master/Solutions/SecurityThreatEssentialSolution/Analytic%20Rules/PossibleAiTMPhishingAttemptAgainstAAD.yaml)
11 | This detection uses signals from Azure AD Identity Protection, specifically it looks for successful sign ins that have been flagged as high risk, and then combines this with data from Web Proxy services such as ZScaler to identify where users might have connected to the source of those sign ins immediately prior.
12 | This can indicate a user interacting with a AiTM phishing site and having their session hijacked. This detection uses the Advanced Security Information Model (ASIM) Web Session schema.
13 | More details on the schema and its requirements can be found in the documentation: https://learn.microsoft.com/azure/sentinel/normalization-schema-web
14 | ```kusto
15 | let time_threshold = 10m;
16 | let RiskySignins = materialize (SigninLogs
17 | | where TimeGenerated > ago(1d)
18 | | where ResultType == 0
19 | | where RiskLevelDuringSignIn =~ "high" or RiskLevelAggregated =~ "high"
20 | | extend SignInTime = TimeGenerated, Name=split(UserPrincipalName, "@")[0], UPNSuffix=split(UserPrincipalName, "@")[1]);
21 | let ips = todynamic(toscalar(RiskySignins | summarize make_list(IPAddress)));
22 | RiskySignins
23 | | join kind=inner (_Im_WebSession(starttime=ago(1d), ipaddr_has_any_prefix=ips, eventresult="Success", pack=True)) on $left.IPAddress == $right.DstIpAddr
24 | | where EventStartTime < TimeGenerated
25 | | extend TimeDelta = TimeGenerated - EventStartTime
26 | | where TimeDelta <= time_threshold
27 | | extend NetworkEventStartTime = EventStartTime, NetworkEventEndTime = EventEndTime
28 | | extend SrcUsername = column_ifexists("SrcUsername", "Unknown")
29 | | project-reorder SignInTime, UserPrincipalName, IPAddress, AppDisplayName, ClientAppUsed, DeviceDetail, LocationDetails, NetworkLocationDetails, RiskEventTypes, UserAgent, NetworkEventStartTime, NetworkEventEndTime, SrcIpAddr, DstIpAddr, DstPortNumber, Dvc, DvcHostname, SrcBytes, NetworkProtocol, SrcUsername
30 | ```
31 |
32 | #### Reference
33 | - March 13, 2023, [DEV-1101 enables high-volume AiTM campaigns with open-source phishing kit](https://www.microsoft.com/en-us/security/blog/2023/03/13/dev-1101-enables-high-volume-aitm-campaigns-with-open-source-phishing-kit/)
34 |
35 | #### Disclaimer
36 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
37 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20231212-MSSecurityBlog-OAuthApplications-OAuthApptoAzureWorkloads.md:
--------------------------------------------------------------------------------
1 | # OAuth application interacting with Azure workloads
2 | Microsoft Security Blog title - Threat actors misuse OAuth applications to automate financially driven attacks
3 |
4 | #### OAuth application interacting with Azure workloads
5 | ```kusto
6 | let OAuthAppId = ;
7 | CloudAppEvents
8 | | where Timestamp >ago (7d)
9 | | where AccountId == OAuthAppId
10 | | where AccountType== "Application"
11 | | extend Azure_Workloads = RawEventData["operationName"]
12 | | distinct Azure_Workloads by AccountId
13 | ```
14 |
15 | #### Reference
16 | - December 12, 2023, [Threat actors misuse OAuth applications to automate financially driven attacks](https://www.microsoft.com/en-us/security/blog/2023/12/12/threat-actors-misuse-oauth-applications-to-automate-financially-driven-attacks/)
17 |
18 | #### Disclaimer
19 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
20 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20231212-MSSecurityBlog-OAuthApplications-PasswordSprayAttempts.md:
--------------------------------------------------------------------------------
1 | # Password spray attempts
2 | Microsoft Security Blog title - Threat actors misuse OAuth applications to automate financially driven attacks
3 |
4 | #### Password spray attempts
5 | This query identifies failed sign-in attempts to Microsoft Exchange Online from multiple IP addresses and locations.
6 | ```kusto
7 | IdentityLogonEvents
8 | | where ActionType == "LogonFailed" and LogonType == "OAuth2:Token" and Application == "Microsoft Exchange Online"
9 | | summarize count(), dcount(IPAddress), dcount(Location) by AccountObjectId, AccountDisplayName, bin(Timestamp, 1h)
10 | ```
11 | > [!note]
12 | > As 'dcount(CountryCode)' is not available in IdentityLogonEvents, it has been shifted to 'Location'.
13 |
14 | #### Reference
15 | - December 12, 2023, [Threat actors misuse OAuth applications to automate financially driven attacks](https://www.microsoft.com/en-us/security/blog/2023/12/12/threat-actors-misuse-oauth-applications-to-automate-financially-driven-attacks/)
16 |
17 | #### Disclaimer
18 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
19 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20231212-MSSecurityBlog-OAuthApplications-SuspiciousAppCreation.md:
--------------------------------------------------------------------------------
1 | # Suspicious application creation
2 | Microsoft Security Blog title - Threat actors misuse OAuth applications to automate financially driven attacks
3 |
4 | #### Suspicious application creation
5 | This query finds new applications added in your tenant.
6 | ```kusto
7 | CloudAppEvents
8 | | where ActionType in ("Add application.", "Add service principal.")
9 | | mvexpand modifiedProperties = RawEventData.ModifiedProperties
10 | | where modifiedProperties.Name == "AppAddress"
11 | | extend AppAddress = tolower(extract('\"Address\": \"(.*)\",',1,tostring(modifiedProperties.NewValue)))
12 | | mvexpand ExtendedProperties = RawEventData.ExtendedProperties
13 | | where ExtendedProperties.Name == "additionalDetails"
14 | | extend OAuthApplicationId = tolower(extract('\"AppId\":\"(.*)\"',1,tostring(ExtendedProperties.Value)))
15 | | project Timestamp, ReportId, AccountObjectId, Application, ApplicationId, OAuthApplicationId, AppAddress
16 | ```
17 |
18 | #### Reference
19 | - December 12, 2023, [Threat actors misuse OAuth applications to automate financially driven attacks](https://www.microsoft.com/en-us/security/blog/2023/12/12/threat-actors-misuse-oauth-applications-to-automate-financially-driven-attacks/)
20 |
21 | #### Disclaimer
22 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
23 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20231212-MSSecurityBlog-OAuthApplications-SuspiciousEmailEvents.md:
--------------------------------------------------------------------------------
1 | # Suspicious email events
2 |
3 | Microsoft Security Blog title - Threat actors misuse OAuth applications to automate financially driven attacks
4 |
5 | > [!Note]
6 | > These queries need to be updated with timestamps related to application creation time before running.
7 |
8 | #### Suspicious email events
9 | Identify High Outbound Email Sender
10 | ```kusto
11 | EmailEvents
12 | | where Timestamp between ( .. ) //Timestamp from the app creation time to few hours upto 24 hours or more
13 | | where EmailDirection in ("Outbound")
14 | | project RecipientEmailAddress, SenderFromAddress, SenderMailFromAddress, SenderObjectId, NetworkMessageId
15 | | summarize RecipientCount = dcount(RecipientEmailAddress), UniqueEmailSentCount = dcount(NetworkMessageId) by SenderFromAddress, SenderMailFromAddress, SenderObjectId
16 | | sort by UniqueEmailSentCount desc
17 | //| where UniqueEmailSentCount > //Optional, return only if the sender sent more than the threshold
18 | //| take 100 //Optional, return only top 100
19 | ```
20 |
21 | Identify Suspicious Outbound Email Sender
22 | ```kusto
23 | EmailEvents
24 | //| where Timestamp between ( .. ) //Timestamp from the app creation time to few hours upto 24 hours or more
25 | | where EmailDirection in ("Outbound")
26 | | project RecipientEmailAddress, SenderFromAddress, SenderMailFromAddress, SenderObjectId, DetectionMethods, NetworkMessageId
27 | | summarize RecipientCount = dcount(RecipientEmailAddress), UniqueEmailSentCount = dcount(NetworkMessageId), SuspiciousEmailCount = dcountif(NetworkMessageId,isnotempty(DetectionMethods)) by SenderFromAddress, SenderMailFromAddress, SenderObjectId
28 | | extend SuspiciousEmailPercentage = SuspiciousEmailCount/UniqueEmailSentCount * 100 //Calculate the percentage of suspicious email compared to all email sent
29 | | sort by SuspiciousEmailPercentage desc
30 | //| where UniqueEmailSentCount > //Optional, return only if the sender suspicious email percentage is more than the threshold
31 | //| take 100 //Optional, return only top 100
32 | ```
33 |
34 | Identify Recent Emails Sent by Restricted Email Sender
35 | ```kusto
36 | AlertEvidence
37 | | where Title has "User restricted from sending email"
38 | | project AccountObjectId //Identify the user who are restricted to send email
39 | | join EmailEvents on $left.AccountObjectId == $right.SenderObjectId //Join information from Alert Evidence and Email Events
40 | | project Timestamp, RecipientEmailAddress, SenderFromAddress, SenderMailFromAddress, SenderObjectId, SenderIPv4, Subject, UrlCount, AttachmentCount, DetectionMethods, AuthenticationDetails, NetworkMessageId
41 | | sort by Timestamp desc
42 | //| take 100 //Optional, return only first 100
43 | ```
44 |
45 | #### Reference
46 | - December 12, 2023, [Threat actors misuse OAuth applications to automate financially driven attacks](https://www.microsoft.com/en-us/security/blog/2023/12/12/threat-actors-misuse-oauth-applications-to-automate-financially-driven-attacks/)
47 |
48 | #### Disclaimer
49 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
50 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-AttackTechniques-Query-Repository/20240401-MSSecurityBlog-QRcodeHunting.md:
--------------------------------------------------------------------------------
1 | # Hunting and responding to QR code-based phishing attacks with Defender for Office 365
2 |
3 | **Hunting for adversary-in-the-middle (AiTM) phishing and user compromise:**
4 |
5 | The downside of users not being able to decode what is hidden behind a QR code has been a major factor behind the attacks involving malicious QR codes.
6 | One such example is adversary-in-the-middle (AiTM) attacks.
7 | Adversaries have the capability to design QR codes that reroute users to counterfeit versions of trusted websites, including banks, social media platforms, or online services.
8 | Once the unsuspecting user scans the QR code, they are promptly directed to a fraudulent phishing page.
9 | Upon authentication by the user, attackers seize the user's session token, providing them with the means to execute various malicious activities, such as Business Email Compromise attacks and attempts to illicitly extract data.
10 | Conversely, attackers may also engineer QR codes that prompt users to unknowingly download malware onto their devices.
11 | These forms of attacks carry grave consequences, potentially leading to identity theft, financial detriment, data breaches, or compromise of the user's device integrity.
12 |
13 |
14 | ```kusto
15 | let senderprevalence =
16 | EmailEvents
17 | | where Timestamp between (ago(7d)..(now()-24h))
18 | | where isnotempty(SenderFromAddress)
19 | | summarize TotalEmailCount = dcount(NetworkMessageId) by SenderFromAddress
20 | | where TotalEmailCount > 1;
21 | let prevalent_Sender = senderprevalence
22 | | where isnotempty (SenderFromAddress)
23 | | distinct SenderFromAddress;
24 | let QR_from_non_prevalent =
25 | EmailEvents
26 | | where EmailDirection == "Inbound"
27 | | where Timestamp > ago(1d)
28 | | where SenderFromAddress !in (prevalent_Sender)
29 | | join EmailUrlInfo on NetworkMessageId
30 | | where UrlLocation == "QRCode"
31 | | distinct SenderFromAddress,Url,NetworkMessageId;
32 | QR_from_non_prevalent
33 | ```
34 |
35 | **Next Steps:**
36 |
37 | In addition to conducting threat hunting activities and implementing remediation measures, there are several proactive steps that organizations can take to enhance their protection against potential attacks covering continuous monitoring along with providing essential training against such attacks to the end users.
38 | Here are a few steps security teams can take to ensure secure posture:
39 |
40 | **1) Write a custom detection rule:**
41 |
42 | Custom detection rules are customizable rules that defined using advanced hunting queries.
43 | These rules facilitate proactive surveillance of suspicious events and activities, which allows security teams to have proactive monitors on the threat landscape in their organization.
44 | They can be scheduled for periodic execution, facilitating the generation of incidents/alerts and triggering automatic email remediation actions as per the rule configuration.
45 | To learn more about how to create and manage custom detection rules, check out - [Create and manage custom detection rules in Microsoft Defender XDR | Microsoft Learn](https://learn.microsoft.com/en-us/microsoft-365/security/defender/custom-detection-rules?view=o365-worldwide)
46 | With the new QR code-based emerging attack patterns, security teams can write a custom detection rule to check the sender prevalence over the last 14 days and use the same to detect malicious activity via email containing QR code.
47 | Here’s a sample custom detection rule using sender prevalence over emails containing QR codes:
48 |
49 | ```kusto
50 | let QRCode_emails = EmailUrlInfo
51 | | where Timestamp > ago (2d)
52 | | where UrlLocation == "QRCode"
53 | | distinct Url,NetworkMessageId;
54 | let nMIDs = QRCode_emails | distinct NetworkMessageId;
55 | // Extracting sender of the email with QRCode:
56 | let senders_NMIDs = EmailEvents
57 | | where Timestamp > ago (2d)
58 | | where DeliveryLocation != "Blocked" // Only delivered or Junked emails are interesting
59 | | where isnotempty(NetworkMessageId)
60 | | where NetworkMessageId in (nMIDs)
61 | | distinct Timestamp, NetworkMessageId, RecipientEmailAddress, SenderFromAddress, InternetMessageId, RecipientObjectId, ReportId;
62 | let senders = senders_NMIDs
63 | | distinct SenderFromAddress;
64 | // Checking sender prevalence in the organization
65 | let senderprevalence = EmailEvents
66 | | where Timestamp between (ago(14d)..(now()-24h))
67 | | where isnotempty(SenderFromAddress)
68 | | where SenderFromAddress in (senders)
69 | | summarize TotalEmailCount = count() by SenderFromAddress
70 | | where TotalEmailCount > 1;
71 | let prevalent_Sender = senderprevalence
72 | | where isnotempty (SenderFromAddress)
73 | | distinct SenderFromAddress;
74 | // Checking if in clicked emails sender was not prevalent.
75 | let nMIDs_from_non_prevalent_Senders = senders_NMIDs
76 | | where SenderFromAddress !in (prevalent_Sender)
77 | | distinct NetworkMessageId;
78 | let QRCode_emails_from_non_prevalent_senders = QRCode_emails
79 | | where NetworkMessageId in (nMIDs_from_non_prevalent_Senders)
80 | | join kind=inner senders_NMIDs on NetworkMessageId
81 | | project Timestamp,Url, NetworkMessageId, InternetMessageId, RecipientObjectId, ReportId;
82 | QRCode_emails_from_non_prevalent_senders
83 | ```
84 |
85 |
86 |
87 | #### Reference
88 | - Apr 01 2024, [Hunting and responding to QR code-based phishing attacks with Defender for Office 365](https://techcommunity.microsoft.com/t5/microsoft-defender-for-office/hunting-and-responding-to-qr-code-based-phishing-attacks-with/ba-p/4074730)
89 | - Feb 12 2024, [Hunting for QR Code AiTM Phishing and User Compromise](https://techcommunity.microsoft.com/t5/microsoft-security-experts-blog/hunting-for-qr-code-aitm-phishing-and-user-compromise/bc-p/4054850)
90 |
91 | #### Disclaimer
92 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
93 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-Detection-Query-Repository/01-XDR-DetectionPercentage-SecurityProducts.md:
--------------------------------------------------------------------------------
1 | # XDR : Daily Security Product Detections Breakdown
2 | This query provides a daily breakdown, indicating the percentage of detections attributed to various security products, including:
3 | - [x] Microsoft Defender XDR (Microsoft 365 Defender)
4 | - [x] Microsoft Defender for Identity
5 | - [x] Microsoft Defender for Cloud Apps
6 | - [x] Microsoft Defender for Office 365
7 | - [x] Microsoft Defender for Endpoint
8 | - [x] Microsoft Entra ID Protection (AAD Identity Protection)
9 | - [x] App Governance
10 | - [x] Microsoft Data Loss Prevention"
11 |
12 | #### Table name & Description
13 | - [AlertInfo](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-alertinfo-table?view=o365-worldwide) : Alerts from Microsoft Defender for Endpoint, Microsoft Defender for Office 365, Microsoft Defender for Cloud Apps, and Microsoft Defender for Identity, including severity information and threat categorization
14 |
15 | ```kusto
16 | AlertInfo
17 | | where TimeGenerated > ago(7d)
18 | | summarize TotalAlertCount = count(),
19 | App_Governance = countif(ServiceSource == "App Governance"),
20 | AAD_Identity_Protection = countif(ServiceSource == "AAD Identity Protection"),
21 | Microsoft_365_Defender = countif(ServiceSource == "Microsoft 365 Defender"),
22 | Microsoft_Defender_for_Identity = countif(ServiceSource == "Microsoft Defender for Identity"),
23 | Microsoft_Defender_for_Cloud_Apps = countif(ServiceSource == "Microsoft Cloud App Security"),
24 | Microsoft_Defender_for_Office365 = countif(ServiceSource == "Microsoft Defender for Office 365"),
25 | Microsoft_Defender_for_Endpoint = countif(ServiceSource == "Microsoft Defender for Endpoint"),
26 | Microsoft_Data_Loss_Prevention = countif(ServiceSource == "Microsoft Data Loss Prevention") by bin(TimeGenerated, 1d)
27 | | extend App_Governance_percentage = todouble(round(App_Governance / todouble(TotalAlertCount) * 100, 2))
28 | | extend AAD_Identity_Protection_percentage = todouble(round(AAD_Identity_Protection / todouble(TotalAlertCount) * 100, 2))
29 | | extend Microsoft_365_Defender_percentage = todouble(round(Microsoft_365_Defender / todouble(TotalAlertCount) * 100, 2))
30 | | extend Microsoft_Defender_for_Identity_percentage = todouble(round(Microsoft_Defender_for_Identity / todouble(TotalAlertCount) * 100, 2))
31 | | extend Microsoft_Defender_for_Cloud_Apps_percentage = todouble(round(Microsoft_Defender_for_Cloud_Apps / todouble(TotalAlertCount) * 100, 2))
32 | | extend Microsoft_Defender_for_Office365_percentage = todouble(round(Microsoft_Defender_for_Office365 / todouble(TotalAlertCount) * 100, 2))
33 | | extend Microsoft_Defender_for_Endpoint_percentage = todouble(round(Microsoft_Defender_for_Endpoint / todouble(TotalAlertCount) * 100, 2))
34 | | extend Microsoft_Data_Loss_Prevention_percentage = todouble(round(Microsoft_Data_Loss_Prevention / todouble(TotalAlertCount) * 100, 2))
35 | | project TimeGenerated,
36 | App_Governance_percentage,
37 | AAD_Identity_Protection_percentage,
38 | Microsoft_365_Defender_percentage,
39 | Microsoft_Defender_for_Identity_percentage,
40 | Microsoft_Defender_for_Cloud_Apps_percentage,
41 | Microsoft_Defender_for_Office365_percentage,
42 | Microsoft_Defender_for_Endpoint_percentage,
43 | Microsoft_Data_Loss_Prevention_percentage
44 | | render columnchart
45 | ```
46 | > [!Important]
47 | > You can use this query in Advanced Hunting, Microsoft Defender XDR, by shifting 'TimeGenerated' to 'Timestamp' (Line 2). However, in terms of columnchart and data visualization, I recommend utilizing this query in Microsoft Sentinel.
48 |
49 | #### Result
50 | 
51 |
52 | #### Disclaimer
53 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
54 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-Detection-Query-Repository/02-XDR-EDR-Endpoint-AnalyzingDailyDetections.md:
--------------------------------------------------------------------------------
1 | # EDR : Endpoint Analyzing Daily Detections
2 | This query presents endpoint-based daily detections over the past 30 days.
3 | It proves valuable for analyzing devices—understanding those targeted by attackers, identifying vulnerable devices, determining the most frequently alerted devices, and more.
4 |
5 | #### Table name & Description
6 | - [AlertEvidence](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-alertevidence-table?view=o365-worldwide) : Files, IP addresses, URLs, users, or devices associated with alerts
7 |
8 | ```kusto
9 | AlertEvidence
10 | | where TimeGenerated > ago(30d)
11 | | where EntityType == "Machine"
12 | | summarize Case= count() by DeviceName, bin(TimeGenerated, 1d)
13 | | render timechart
14 | ```
15 | > [!Important]
16 | > You can use this query in Advanced Hunting, Microsoft Defender XDR, by shifting 'TimeGenerated' to 'Timestamp' (Line 2). However, in terms of columnchart and data visualization, I recommend utilizing this query in Microsoft Sentinel.
17 |
18 | #### Result
19 | 
20 |
21 |
22 | #### Disclaimer
23 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
24 |
--------------------------------------------------------------------------------
/KQL-XDR-Hunting/XDR-SIEM-Detection/XDR-SIEM-Detection-Query-Repository/03-XDR-AnalyzingAllDetections-With-MITRE-ATTCK.md:
--------------------------------------------------------------------------------
1 | # XDR : Analyzing All Detections With MITRE ATT&CK
2 | This query displays alerts detected in all Defender security products and correlates each of them with MITRE ATT&CK techniques. Each record (MITRE ATT&CK technique) lists the details of alerts detected in each product as dynamic values, including detection time, ID, title and detection source.
3 |
4 | #### Table name & Description
5 | - [AlertInfo](https://learn.microsoft.com/en-us/microsoft-365/security/defender/advanced-hunting-alertinfo-table?view=o365-worldwide) : Alerts from Microsoft Defender for Endpoint, Microsoft Defender for Office 365, Microsoft Defender for Cloud Apps, and Microsoft Defender for Identity, including severity information and threat categorization
6 |
7 | ```kusto
8 | AlertInfo
9 | | where TimeGenerated > ago(14d)
10 | | where isnotempty(AttackTechniques)
11 | | extend Parsed = parse_json(AttackTechniques)
12 | | mv-expand Parsed
13 | | extend MITRE_ATTCK = tostring(Parsed)
14 | | extend PackedData = strcat(format_datetime(TimeGenerated,'yyyy-M-dd H:mm:ss'), " : ", AlertId, " : ", Title, " : ", ServiceSource)
15 | | summarize MDE = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Endpoint"),
16 | MDO = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Office 365"),
17 | MDI = make_set_if(PackedData, ServiceSource == "Microsoft Defender for Identity"),
18 | MDA = make_set_if(PackedData, ServiceSource in ("Microsoft Cloud App Security", "App Governance")),
19 | Entra = make_set_if(PackedData, ServiceSource == "AAD Identity Protection"),
20 | M365D = make_set_if(PackedData, ServiceSource == "Microsoft 365 Defender") by MITRE_ATTCK
21 | | extend MDE_case = array_length(MDE)
22 | | extend MDO_case = array_length(MDO)
23 | | extend MDI_case = array_length(MDI)
24 | | extend MDA_case = array_length(MDA)
25 | | extend Entra_case = array_length(Entra)
26 | | extend M365D_case = array_length(M365D)
27 | | extend SUM = MDE_case + MDO_case + MDI_case + MDA_case + Entra_case + M365D_case
28 | | project MITRE_ATTCK, SUM, MDE, MDO, MDI, MDA, Entra, M365D
29 | | order by SUM desc
30 | ```
31 | > [!Important]
32 | > You can use this query in Advanced Hunting, Microsoft Defender XDR, by shifting 'TimeGenerated' to 'Timestamp' (Line 2, 7). However, in terms of columnchart and data visualization, I recommend utilizing this query in Microsoft Sentinel.
33 |
34 | #### Result
35 | 
36 |
37 | #### Disclaimer
38 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
39 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # KQL - Detection & Threat Hunting
2 |
3 |
4 |
5 |
6 |
7 | Being able to fully leverage the data you have means you can control all activities that occurred across all Defender's workloads.
8 | However, starting from scratch can be challenging for some, and sample queries may not always suffice.
9 | Therefore, in this repository on KQL-XDR-Hunting, I will be sharing ***'out-of-the-box' KQL queries*** based on feedback, security blogs, and new cyber attacks to assist you in your threat hunting.
10 |
11 | ## LearningKijo/KQL repo architecture
12 |
13 | | Category | Products |
14 | | :------------- | :------------- |
15 | | Endpoint | [- Microsoft Defender for Endpoint
- Microsoft Defender Antivirus](https://github.com/LearningKijo/KQL/tree/main/KQL-XDR-Hunting/Endpoint-Microsoft-Defender-for-Endpoint) |
16 | | Email | [- Exchange Online Protection
- Microsoft Defender for Office 365](https://github.com/LearningKijo/KQL/tree/main/KQL-XDR-Hunting/Email-Microsoft-Defender-for-Office365) |
17 | | Identity | [- Microsoft Entra ID (Azure AD)
- Microsoft Defender for Identity](https://github.com/LearningKijo/KQL/tree/main/KQL-XDR-Hunting/Identity-Microsoft-Defender-for-Identity) |
18 |
19 | **LOGs**
20 | | Category | Links |
21 | | :------------- | :------------- |
22 | | Detection | [XDR-SIEM-Detection](https://github.com/LearningKijo/KQL/tree/main/KQL-XDR-Hunting/XDR-SIEM-Detection) |
23 | | Detection | [Microsoft Security Threat Insight 2023](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2023-MicrosoftSecurity-ThreatInsight/MSSecurityThreatInsight2023.md) |
24 | | Detection | [Microsoft Security Threat Insight 2024](https://github.com/LearningKijo/KQL/blob/main/KQL-XDR-Hunting/MicrosoftSecurity-ThreatInsight/2024-MicrosoftSecurity-ThreatInsight/MSSecurityThreatInsight2024.md) |
25 |
26 | ## Usage
27 | 
28 | > [!Note]
29 | > If you would like to change some lines, you can even change them by yourself and adjust them depending on what data you want to take out.
30 |
31 | #### Disclaimer
32 | The views and opinions expressed herein are those of the author and do not necessarily reflect the views of company.
33 |
--------------------------------------------------------------------------------