From bdae10aa525933b4e53525c25acaa6f1efbe82e9 Mon Sep 17 00:00:00 2001
From: Michael Haag <5632822+MHaggis@users.noreply.github.com>
Date: Wed, 30 Oct 2024 12:02:16 -0600
Subject: [PATCH] In tune with Intune
---
Attack_Surface_Reduction.py | 2 +
asr.py | 347 ++++++++++++++++++++++++
pages/6_ASR_Intune_Policy_Generator.py | 351 +++++++++++++++++++++++++
3 files changed, 700 insertions(+)
create mode 100644 pages/6_ASR_Intune_Policy_Generator.py
diff --git a/Attack_Surface_Reduction.py b/Attack_Surface_Reduction.py
index 04afa07..d6d9815 100644
--- a/Attack_Surface_Reduction.py
+++ b/Attack_Surface_Reduction.py
@@ -29,6 +29,8 @@
4ī¸âŖ ASR PwSh Group Policy Generator đ ī¸: A tool for generating Group Policy Objects (GPO) with PowerShell. đ
5ī¸âŖ ASR .pol File Reader đ: A tool for reading and displaying the contents of GPO .pol files. đ
+
+ 6ī¸âŖ ASR Intune Policy Generator đ: A tool for generating Intune policies for ASR rules. đ
The ASR Generator is an ongoing project, and we are constantly working to improve its features and capabilities. We welcome feedback and suggestions from our users to help us make this tool even better đ. đĄ
diff --git a/asr.py b/asr.py
index ae38d3c..9d1cbb0 100644
--- a/asr.py
+++ b/asr.py
@@ -20,7 +20,354 @@
"Block use of copied or impersonated system tools (preview)": "C0033C00-D16D-4114-A5A0-DC9B3A7D2CEB"
}
+intune_asr_rules = {
+"Block abuse of exploited vulnerable signed drivers": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockabuseofexploitedvulnerablesigneddrivers",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockabuseofexploitedvulnerablesigneddrivers"
+},
+"Block Adobe Reader from creating child processes": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockadobereaderfromcreatingchildprocesses",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockadobereaderfromcreatingchildprocesses"
+},
+"Block all Office applications from creating child processes": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockallofficeapplicationsfromcreatingchildprocesses",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockallofficeapplicationsfromcreatingchildprocesses"
+},
+"Block credential stealing from the Windows local security authority subsystem": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockcredentialstealingfromwindowslocalsecurityauthoritysubsystem",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockcredentialstealingfromwindowslocalsecurityauthoritysubsystem"
+},
+"Block executable content from email client and webmail": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockexecutablecontentfromemailclientandwebmail",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockexecutablecontentfromemailclientandwebmail"
+},
+"Block executable files from running unless they meet a prevalence, age, or trusted list criterion": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockexecutablefilesrunningunlesstheymeetprevalenceagetrustedlistcriterion",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockexecutablefilesrunningunlesstheymeetprevalenceagetrustedlistcriterion"
+},
+"Block execution of potentially obfuscated scripts": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockexecutionofpotentiallyobfuscatedscripts",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockexecutionofpotentiallyobfuscatedscripts"
+},
+"Block JavaScript or VBScript from launching downloaded executable content": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockjavascriptorvbscriptfromlaunchingdownloadedexecutablecontent",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockjavascriptorvbscriptfromlaunchingdownloadedexecutablecontent"
+},
+"Block Office applications from creating executable content": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockofficeapplicationsfromcreatingexecutablecontent",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockofficeapplicationsfromcreatingexecutablecontent"
+},
+"Block Office applications from injecting code into other processes": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockofficeapplicationsfrominjectingcodeintootherprocesses",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockofficeapplicationsfrominjectingcodeintootherprocesses"
+},
+"Block Office communication application from creating child processes": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockofficecommunicationappfromcreatingchildprocesses",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockofficecommunicationappfromcreatingchildprocesses"
+},
+"Block persistence through WMI event subscription": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockpersistencethroughwmieventsubscription",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockpersistencethroughwmieventsubscription"
+},
+"Block process creations originating from PSExec and WMI commands": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockprocesscreationsfrompsexecandwmicommands",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockprocesscreationsfrompsexecandwmicommands"
+},
+"Block untrusted and unsigned processes that run from USB": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockuntrustedunsignedprocessesthatrunfromusb",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockuntrustedunsignedprocessesthatrunfromusb"
+},
+"Block Win32 API calls from Office macros": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockwin32apicallsfromofficemacros",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockwin32apicallsfromofficemacros"
+},
+"Use advanced protection against ransomware": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_useadvancedprotectionagainstransomware",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_useadvancedprotectionagainstransomware"
+},
+"Block Webshell creation for Servers": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockwebshellcreationforservers",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockwebshellcreationforservers"
+},
+"Block rebooting machine in Safe Mode": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockrebootingmachineinsafemode",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockrebootingmachineinsafemode"
+},
+"Block use of copied or impersonated system tools": {
+"settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockuseofcopiedorimpersonatedsystemtools",
+"value_prefix": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules_blockuseofcopiedorimpersonatedsystemtools"
+}
+}
+
html_code = """
Sponsor MHaggis
"""
+
+asr_rule_descriptions = {
+ "Block abuse of exploited vulnerable signed drivers": """
+ Prevents an application from writing a vulnerable signed driver to disk. Vulnerable signed drivers can be exploited to disable security solutions and gain kernel access. This rule doesn't block existing drivers from loading.
+
+ Note: This rule doesn't block a driver already existing on the system from being loaded.
+
+ Advanced hunting action type:
+ - AsrVulnerableSignedDriverAudited
+ - AsrVulnerableSignedDriverBlocked
+
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block Adobe Reader from creating child processes": """
+ Prevents attacks by blocking Adobe Reader from creating processes. This stops malware from using Adobe Reader to download and launch additional payloads through social engineering or exploits.
+
+ Advanced hunting action type:
+ - AsrAdobeReaderChildProcessAudited
+ - AsrAdobeReaderChildProcessBlocked
+
+ EDR alerts: Yes
+ Toast notifications: Yes (in block mode)
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block all Office applications from creating child processes": """
+ Blocks Office apps (Word, Excel, PowerPoint, OneNote, Access) from creating child processes. This prevents malware from using Office macros and exploits to download payloads and spread malicious code.
+
+ Note: Some legitimate line-of-business applications might generate child processes for benign purposes.
+
+ Advanced hunting action type:
+ - AsrOfficeChildProcessAudited
+ - AsrOfficeChildProcessBlocked
+
+ EDR alerts: Yes
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block credential stealing from the Windows local security authority subsystem": """
+ Helps prevent credential stealing by locking down LSASS (Local Security Authority Subsystem Service). Particularly useful when Credential Guard cannot be enabled due to compatibility issues.
+
+ Note:
+ - Not needed if LSA protection and Credential Guard are enabled
+ - Doesn't support WARN mode
+ - Doesn't honor Microsoft Defender for Endpoint Indicators of Compromise (IOC)
+
+ Advanced hunting action type:
+ - AsrLsassCredentialTheftAudited
+ - AsrLsassCredentialTheftBlocked
+
+ EDR alerts: No
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block executable content from email client and webmail": """
+ Blocks executable files and scripts (.exe, .dll, .ps1, .vbs, .js etc.) from being launched from email opened in Microsoft Outlook or other webmail providers.
+
+ Alternative names:
+ - Intune: Execution of executable content (exe, dll, ps, js, vbs, etc.) dropped from email (webmail/mail client) (no exceptions)
+ - Configuration Manager: Block executable content download from email and webmail clients
+ - Group Policy: Block executable content from email client and webmail
+
+ Advanced hunting action type:
+ - AsrExecutableEmailContentAudited
+ - AsrExecutableEmailContentBlocked
+
+ EDR alerts: Yes
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block executable files from running unless they meet a prevalence, age, or trusted list criterion": """
+ Blocks execution of executable files (.exe, .dll, .scr) that don't meet prevalence, age, or trusted list criteria. Requires cloud-delivered protection.
+
+ Note:
+ - Cloud-delivered protection must be enabled
+ - This rule is owned by Microsoft and uses cloud-delivered protection to update its trusted list regularly
+
+ Advanced hunting action type:
+ - AsrUntrustedExecutableAudited
+ - AsrUntrustedExecutableBlocked
+
+ EDR alerts: Yes
+ Dependencies: Microsoft Defender Antivirus, Cloud Protection
+ """,
+
+ "Block execution of potentially obfuscated scripts": """
+ Detects suspicious properties within obfuscated scripts. Targets both malicious code hiding and legitimate intellectual property protection. Supports PowerShell, JavaScript, and VBScript.
+
+ Note: PowerShell scripts are now supported for this rule.
+
+ Advanced hunting action type:
+ - AsrObfuscatedScriptAudited
+ - AsrObfuscatedScriptBlocked
+
+ EDR alerts: Yes (in block mode), No (in audit mode)
+ Toast notifications: Yes (in block mode)
+ Dependencies: Microsoft Defender Antivirus, AMSI
+ """,
+
+ "Block JavaScript or VBScript from launching downloaded executable content": """
+ Prevents scripts from launching potentially malicious downloaded content. Malware written in JavaScript or VBScript often acts as a downloader to fetch and launch other malware from the Internet.
+
+ Note: Some line-of-business applications might use scripts to download and launch installers.
+
+ Advanced hunting action type:
+ - AsrScriptExecutableDownloadAudited
+ - AsrScriptExecutableDownloadBlocked
+
+ EDR alerts: Yes
+ Toast notifications: Yes (in block mode)
+ Dependencies: Microsoft Defender Antivirus, AMSI
+ """,
+
+ "Block Office applications from creating executable content": """
+ Prevents Office apps from creating potentially malicious executable content by blocking malicious code from being written to disk. These malicious components would survive a computer reboot and persist on the system.
+
+ Note: This rule also blocks execution of untrusted files that may have been saved by Office macros.
+
+ Advanced hunting action type:
+ - AsrExecutableOfficeContentAudited
+ - AsrExecutableOfficeContentBlocked
+
+ EDR alerts: Yes
+ Dependencies: Microsoft Defender Antivirus, RPC
+ """,
+
+ "Block Office applications from injecting code into other processes": """
+ Blocks code injection attempts from Office apps into other processes. Prevents attackers from using Office apps to inject malicious code that can masquerade as a clean process.
+
+ Note:
+ - Doesn't support WARN mode
+ - Requires Microsoft 365 Apps restart for changes to take effect
+ - Doesn't honor Microsoft Defender for Endpoint Indicators of Compromise (IOC)
+ - No known legitimate business purposes for using code injection
+
+ Advanced hunting action type:
+ - AsrOfficeProcessInjectionAudited
+ - AsrOfficeProcessInjectionBlocked
+
+ EDR alerts: Yes
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block Office communication application from creating child processes": """
+ Prevents Outlook from creating child processes while allowing legitimate Outlook functions. Protects against social engineering attacks and prevents exploiting code from abusing vulnerabilities in Outlook.
+
+ Note:
+ - Blocks DLP policy tips and ToolTips in Outlook
+ - Applies to Outlook and Outlook.com only
+
+ Advanced hunting action type:
+ - AsrOfficeCommAppChildProcessAudited
+ - AsrOfficeCommAppChildProcessBlocked
+
+ EDR alerts: Yes
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block persistence through WMI event subscription": """
+ Prevents malware from abusing WMI to attain persistence on a device. Protects against fileless threats that use WMI repository and event model to stay hidden.
+
+ Note:
+ - File and folder exclusions don't apply to this rule
+ - If CcmExec.exe (SCCM Agent) is detected, rule is classified as "not applicable"
+
+ Advanced hunting action type:
+ - AsrPersistenceThroughWmiAudited
+ - AsrPersistenceThroughWmiBlocked
+
+ EDR alerts: Yes (in block mode), No (in audit mode)
+ Toast notifications: Yes (in block mode)
+ Dependencies: Microsoft Defender Antivirus, RPC
+ """,
+
+ "Block process creations originating from PSExec and WMI commands": """
+ Blocks processes created through PsExec and WMI commands. Prevents malware from using these tools for remote code execution and lateral movement.
+
+ Warning: Incompatible with Configuration Manager management as it blocks WMI commands the Configuration Manager client uses.
+
+ Advanced hunting action type:
+ - AsrPsexecWmiChildProcessAudited
+ - AsrPsexecWmiChildProcessBlocked
+
+ EDR alerts: Yes
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block untrusted and unsigned processes that run from USB": """
+ Prevents unsigned or untrusted executable files from running from USB removable drives, including SD cards. Applies to executable files like .exe, .dll, or .scr.
+
+ Note: Files copied from USB to disk drive will be blocked by this rule when executed from disk.
+
+ Advanced hunting action type:
+ - AsrUntrustedUsbProcessAudited
+ - AsrUntrustedUsbProcessBlocked
+
+ EDR alerts: Yes (in block mode), No (in audit mode)
+ Toast notifications: Yes (in block mode)
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block Win32 API calls from Office macros": """
+ Prevents VBA macros from calling Win32 APIs, which malware can abuse to launch malicious shellcode without writing to disk. Most organizations don't need Win32 API calls in macros.
+
+ Note: Doesn't honor Microsoft Defender for Endpoint Indicators of Compromise (IOC) for certificates.
+
+ Advanced hunting action type:
+ - AsrOfficeMacroWin32ApiCallsAudited
+ - AsrOfficeMacroWin32ApiCallsBlocked
+
+ EDR alerts: Yes
+ Dependencies: Microsoft Defender Antivirus, AMSI
+ """,
+
+ "Use advanced protection against ransomware": """
+ Provides enhanced protection against ransomware using client and cloud heuristics. Excludes files that are known safe, validly signed, or sufficiently prevalent.
+
+ Note: Cloud-delivered protection must be enabled.
+
+ Advanced hunting action type:
+ - AsrRansomwareAudited
+ - AsrRansomwareBlocked
+
+ EDR alerts: Yes (in block mode), No (in audit mode)
+ Toast notifications: Yes (in block mode)
+ Dependencies: Microsoft Defender Antivirus, Cloud Protection
+ """,
+
+ "Block Webshell creation for Servers": """
+ Blocks web shell script creation on Microsoft Server with Exchange Role. Prevents attackers from using web shells to control compromised servers and execute malicious commands.
+
+ Note: Only applies to servers with Exchange Role.
+
+ Advanced hunting action type: Not specified
+
+ EDR alerts: No
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block rebooting machine in Safe Mode": """
+ Prevents execution of commands to restart machines in Safe Mode, where security products may be disabled or limited. Helps prevent attackers from bypassing security controls.
+
+ Note: Currently in preview.
+
+ Advanced hunting action type:
+ - AsrSafeModeRebootedAudited
+ - AsrSafeModeRebootBlocked
+ - AsrSafeModeRebootWarnBypassed
+
+ EDR alerts: No
+ Dependencies: Microsoft Defender Antivirus
+ """,
+
+ "Block use of copied or impersonated system tools": """
+ Blocks executable files identified as copies or impostors of Windows system tools. Prevents malicious programs from using duplicated system tools to avoid detection or gain privileges.
+
+ Note: Currently in preview.
+
+ Advanced hunting action type:
+ - AsrAbusedSystemToolAudited
+ - AsrAbusedSystemToolBlocked
+ - AsrAbusedSystemToolWarnBypassed
+
+ EDR alerts: No
+ Dependencies: Microsoft Defender Antivirus
+ """
+}
\ No newline at end of file
diff --git a/pages/6_ASR_Intune_Policy_Generator.py b/pages/6_ASR_Intune_Policy_Generator.py
new file mode 100644
index 0000000..44d4624
--- /dev/null
+++ b/pages/6_ASR_Intune_Policy_Generator.py
@@ -0,0 +1,351 @@
+import streamlit as st
+import json
+from datetime import datetime
+from asr import intune_asr_rules, asr_rule_descriptions
+import requests
+import logging
+import msal
+import uuid
+import pandas as pd
+
+logging.basicConfig(level=logging.INFO)
+
+st.set_page_config(page_title="ASR Intune Policy Generator", layout="wide")
+
+st.title("đĄī¸ ASR Intune Policy Generator")
+st.markdown("### Generate and Deploy Attack Surface Reduction!")
+
+
+if "messages" not in st.session_state:
+ st.session_state.messages = []
+
+
+def add_message(message, type="info"):
+ st.session_state.messages.append({"message": message, "type": type})
+
+for msg in st.session_state.messages:
+ if msg["type"] == "success":
+ st.success(msg["message"])
+ elif msg["type"] == "error":
+ st.error(msg["message"])
+ else:
+ st.info(msg["message"])
+
+with st.spinner("đ Loading configuration..."):
+
+ pass
+
+with st.expander("Azure AD App Registration Details", expanded=True):
+ client_id = st.text_input("Client ID", value='your-client-id-here')
+ client_secret = st.text_input("Client Secret", value='your-client-secret-here', type="password")
+ tenant_id = st.text_input("Tenant ID", value='your-tenant-id-here')
+ st.info("""
+ **Required Permissions:**
+ - `DeviceManagementConfiguration.ReadWrite.All`
+ - `DeviceManagementManagedDevices.ReadWrite.All`
+ """)
+
+graph_api_endpoint = 'https://graph.microsoft.com/beta'
+
+def get_access_token():
+ authority = f'https://login.microsoftonline.com/{tenant_id}'
+ app = msal.ConfidentialClientApplication(
+ client_id,
+ authority=authority,
+ client_credential=client_secret
+ )
+ result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
+ if "access_token" in result:
+ logging.info("Access token obtained successfully.")
+ return result['access_token']
+ else:
+ error_message = f"Could not acquire token: {json.dumps(result, indent=2)}"
+ st.error(error_message)
+ logging.error(error_message)
+ return None
+
+def deploy_policy(policy_json):
+ token = get_access_token()
+ if not token:
+ st.error("Failed to obtain access token.")
+ logging.error("Failed to obtain access token.")
+ return False, "Failed to obtain access token"
+
+ headers = {
+ 'Authorization': f'Bearer {token}',
+ 'Content-Type': 'application/json'
+ }
+
+ create_url = f"{graph_api_endpoint}/deviceManagement/configurationPolicies"
+ try:
+ logging.info(f"Sending policy creation request to {create_url}")
+ response = requests.post(create_url, headers=headers, json=policy_json)
+ response.raise_for_status()
+ policy_id = response.json().get('id')
+ logging.info(f"Policy created with ID: {policy_id}")
+ return True, policy_id
+ except requests.exceptions.RequestException as e:
+ if e.response is not None:
+ error_message = e.response.json()
+ logging.error(f"Failed to create policy: {error_message}")
+ st.error(f"Failed to create policy: {error_message}")
+ else:
+ logging.error(f"Failed to create policy: {str(e)}")
+ st.error(f"Failed to create policy: {str(e)}")
+ return False, str(e)
+
+def delete_policy(policy_id):
+ """Delete an ASR policy from Intune"""
+ try:
+ token = get_access_token()
+ if not token:
+ st.error("Failed to get access token")
+ return False
+
+ url = f"https://graph.microsoft.com/beta/deviceManagement/configurationPolicies/{policy_id}"
+ headers = {
+ "Authorization": f"Bearer {token}",
+ "Content-Type": "application/json"
+ }
+
+ response = requests.delete(url, headers=headers)
+ if response.status_code == 204:
+ return True
+ else:
+ st.error(f"Failed to delete policy: {response.status_code}")
+ return False
+
+ except Exception as e:
+ st.error(f"Error deleting policy: {str(e)}")
+ return False
+
+def list_policies():
+ """List all ASR policies and their contents from Intune"""
+ try:
+ token = get_access_token()
+ if not token:
+ st.error("Failed to get access token")
+ return
+
+ url = "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies"
+ headers = {
+ "Authorization": f"Bearer {token}",
+ "Content-Type": "application/json"
+ }
+
+ response = requests.get(url, headers=headers)
+ if response.status_code == 200:
+ policies = response.json().get('value', [])
+
+ asr_policies = [p for p in policies if "Attack Surface Reduction" in p.get('name', '')]
+
+ if not asr_policies:
+ st.info("No ASR policies found")
+ return
+
+ for policy in asr_policies:
+ with st.expander(f"đ {policy['name']} ({policy['id']})"):
+ st.write("**Description:**", policy.get('description', 'No description'))
+ st.write("**Current Rules Configuration:**")
+ settings_url = f"{url}/{policy['id']}/settings"
+ settings_response = requests.get(settings_url, headers=headers)
+
+ if settings_response.status_code == 200:
+ settings = settings_response.json().get('value', [])
+
+ for setting in settings:
+ if 'settingInstance' in setting:
+ instance = setting['settingInstance']
+ if 'groupSettingCollectionValue' in instance:
+ for group in instance['groupSettingCollectionValue']:
+ for child in group.get('children', []):
+ rule_id = child.get('settingDefinitionId', '')
+ rule_value = child.get('choiceSettingValue', {}).get('value', '')
+
+ rule_name = next((name for name, info in intune_asr_rules.items()
+ if info['settingDefinitionId'] == rule_id), rule_id)
+ mode = rule_value.split('_')[-1] if '_' in rule_value else rule_value
+
+ st.write(f"- {rule_name}: **{mode}**")
+ else:
+ st.error(f"Failed to fetch policy settings: {settings_response.status_code}")
+
+ else:
+ st.error(f"Failed to list policies: {response.status_code}")
+
+ except Exception as e:
+ st.error(f"Error listing policies: {str(e)}")
+
+user_inputs = {}
+
+st.write("## đĻ Configuration")
+col1, col2 = st.columns([3, 1])
+
+with col1:
+ enable_all = st.selectbox("Enable All As", ["", "Audit", "Block", "Warn", "Off"],
+ key="enable_all")
+
+with col2:
+ st.info("Quick set all rules to the same mode")
+
+for rule_name, rule_info in intune_asr_rules.items():
+ with st.expander(f"đ {rule_name}", expanded=False):
+ st.info(asr_rule_descriptions[rule_name], icon="âšī¸")
+
+ mode = st.selectbox("Select Mode", ["Audit", "Block", "Warn", "Off"],
+ key=f"mode_{rule_info['settingDefinitionId']}",
+ index=["Audit", "Block", "Warn", "Off"].index(enable_all) if enable_all else 0)
+ st.write(f"**Current Mode:** {mode}")
+
+ user_inputs[rule_info['settingDefinitionId']] = {"mode": mode.lower()}
+
+policy_name = st.text_input("Policy Name", value="Attack Surface Reduction Rules",
+ help="Enter a custom name for your policy",
+ key="policy_name_input")
+
+policy_description = st.text_area(
+ "Policy Description",
+ value="ASR Rules Category",
+ help="Enter a description for your policy",
+ key="policy_description_input"
+)
+
+tab1, tab2 = st.tabs(["Deploy via Intune", "Manual Import"])
+
+with tab1:
+ st.markdown("### đ Deploy via Intune")
+ if st.button("Generate Intune Policy", key="generate_policy_api"):
+ with st.spinner("Generating policy..."):
+ policy = {
+ "description": policy_description,
+ "name": policy_name,
+ "platforms": "windows10",
+ "technologies": "mdm",
+ "roleScopeTagIds": ["0"],
+ "settings": [
+ {
+ "id": "0",
+ "settingInstance": {
+ "@odata.type": "#microsoft.graph.deviceManagementConfigurationGroupSettingCollectionInstance",
+ "settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules",
+ "groupSettingCollectionValue": [
+ {
+ "children": [
+ {
+ "@odata.type": "#microsoft.graph.deviceManagementConfigurationChoiceSettingInstance",
+ "settingDefinitionId": rule_info['settingDefinitionId'],
+ "choiceSettingValue": {
+ "value": f"{rule_info['value_prefix']}_{user_inputs[rule_info['settingDefinitionId']]['mode']}"
+ }
+ } for rule_name, rule_info in intune_asr_rules.items()
+ ]
+ }
+ ]
+ }
+ }
+ ]
+ }
+ st.success("â
Policy generated successfully!")
+ st.json(policy)
+ st.session_state.generated_policy = policy
+
+ if st.button("đ Deploy Policy", key="deploy_policy_api"):
+ if not client_id or not client_secret or not tenant_id:
+ st.error("â ī¸ Please fill in all Azure AD credentials before deploying")
+ elif 'generated_policy' not in st.session_state:
+ st.warning("Please generate a policy first.")
+ else:
+ with st.spinner("Deploying policy..."):
+ success, result = deploy_policy(st.session_state.generated_policy)
+ if success:
+ st.success(f"Policy deployed successfully! Policy ID: {result}")
+ st.markdown("[View the configuration in Intune](https://intune.microsoft.com/#view/Microsoft_Intune_DeviceSettings/DevicesMenu/~/configuration)")
+ else:
+ st.error(f"Failed to deploy policy: {result}")
+
+with tab2:
+ st.markdown("### âšī¸ How to Import Manually")
+ st.markdown("""
+ 1. Choose 'Enable All' to set all rules at once
+ 2. Or expand each rule to set individually
+ 3. Click 'Generate Intune Policy' when done
+ 4. Download the JSON file
+ 5. Import the file into your Intune portal
+ """)
+
+ if st.button("Generate Intune Policy", key="generate_policy_manual"):
+ with st.spinner("Generating policy..."):
+ policy = {
+ "description": "ASR Rules Category",
+ "name": "Attack Surface Reduction Rules",
+ "platforms": "windows10",
+ "technologies": "mdm",
+ "roleScopeTagIds": ["0"],
+ "settings": [
+ {
+ "id": "0",
+ "settingInstance": {
+ "@odata.type": "#microsoft.graph.deviceManagementConfigurationGroupSettingCollectionInstance",
+ "settingDefinitionId": "device_vendor_msft_policy_config_defender_attacksurfacereductionrules",
+ "groupSettingCollectionValue": [
+ {
+ "children": [
+ {
+ "@odata.type": "#microsoft.graph.deviceManagementConfigurationChoiceSettingInstance",
+ "settingDefinitionId": rule_info['settingDefinitionId'],
+ "choiceSettingValue": {
+ "value": f"{rule_info['value_prefix']}_{user_inputs[rule_info['settingDefinitionId']]['mode']}"
+ }
+ } for rule_name, rule_info in intune_asr_rules.items()
+ ]
+ }
+ ]
+ }
+ }
+ ]
+ }
+ st.success("â
Policy generated successfully!")
+ st.json(policy)
+ st.session_state.generated_policy = policy
+ st.download_button(
+ label="đĨ Download Policy JSON",
+ data=json.dumps(policy, indent=2),
+ file_name="asr_policy.json",
+ mime="application/json"
+ )
+
+st.sidebar.image("assets/logo.png", width=300)
+st.sidebar.markdown("## About")
+st.sidebar.info("This helps you generate Attack Surface Reduction (ASR) rules for Microsoft Intune. Configure your rules and download the policy JSON file or Deploy the policy to Intune directly.")
+
+col1, col2 = st.columns([2, 1])
+
+with col1:
+ st.write("## đ§ Review Policies Deployed")
+
+if st.button("đ List Intune Policies"):
+ with st.spinner("Retrieving policies..."):
+ list_policies()
+
+st.write("## đ Current Configuration Preview")
+preview_data = {}
+for rule_name, rule_info in intune_asr_rules.items():
+ preview_data[rule_name] = user_inputs[rule_info['settingDefinitionId']]['mode']
+st.dataframe(pd.DataFrame.from_dict(preview_data, orient='index', columns=['Mode']))
+
+def validate_credentials():
+ if not client_id or not client_secret or not tenant_id:
+ st.error("â ī¸ Please fill in all Azure AD credentials before deploying")
+ return False
+ return True
+
+if st.sidebar.button("đ Reset All Settings"):
+ for key in st.session_state.keys():
+ del st.session_state[key]
+ st.rerun()
+
+st.sidebar.markdown("""
+### đ Resources
+- [ASR Rules Documentation](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction)
+- [Intune Configuration Guide](https://docs.microsoft.com/en-us/mem/intune/protect/endpoint-security-asr-profile-settings)
+""")