The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by suphakorn.it, 2023-08-02 02:09:29

azure-defender-for-iot-device-builders

azure-defender-for-iot-device-builders

Keywords: azure-defender

3. Select the device or double select it to open the Device details page. 4. Select the Module identities menu, and confirm existence of the azureiotsecurity module in the list of module identities associated with the device. To learn more about customizing properties of Defender for IoT module twins, see Agent configuration. Next steps


Advance to the next article to learn how to investigate security recommendations... Investigate security recommendations


Select and deploy a security agent on your IoT device Article • 04/24/2022 Defender for IoT provides reference architectures for security agents that monitor and collect data from IoT devices. To learn more, see Security agent reference architecture. Agents are developed as open-source projects, and are available in two flavors: C , and C# . In this article, you learn how to: Compare security agent flavors Discover supported agent platforms Choose the right agent flavor for your solution Every Defender for IoT security agent flavor offers the same set of features, and supports similar configuration options. The C-based security agent has a lower memory footprint, and is the ideal choice for devices with fewer available resources. C-based security agent C#-based security agent Open-source Available under MIT license in GitHub Available under MIT license in GitHub Development language C C# Supported Windows platforms? No Yes Windows prerequisites --- WMI Supported Linux platforms? Yes, x64 and x86 Yes, x64 only Linux prerequisites libunwind8, libcurl3, uuidruntime, auditd, audispdplugins libunwind8, libcurl3, uuid-runtime, auditd, audispd-plugins, sudo, netstat, iptables Disk footprint 10.5 MB 90 MB Understand security agent options


C-based security agent C#-based security agent Memory footprint (on average) 5.5 MB 33 MB Authentication to IoT Hub Yes Yes Security data collection Yes Yes Event aggregation Yes Yes Remote configuration through Defender-IoTmicro-agent twin Yes Yes For Windows: The Install SecurityAgent.ps1 script must be executed from an Administrator PowerShell window. For Linux: The InstallSecurityAgent.sh must be run as superuser. We recommend prefixing the installation command with "sudo". Answer the following questions about your IoT devices to select the correct agent: Are you using Windows Server or Windows IoT Core? Deploy a C#-based security agent for Windows. Are you using a Linux distribution with x86 architecture? Deploy a C-based security agent for Linux. Are you using a Linux distribution with x64 architecture? Both agent flavors can be used. Deploy a C-based security agent for Linux and/or Deploy a C#-based security agent for Linux. Both agent flavors offer the same set of features and support similar configuration options. See Security agent comparison to learn more. Security agent installation guidelines Choose an agent flavor Supported platforms


The following list includes all currently supported platforms. Defender for IoT agent Operating System Architecture C Ubuntu 16.04 x64 C Ubuntu 18.04 x64, ARMv7 C Debian 9 x64, x86 C# Ubuntu 16.04 x64 C# Ubuntu 18.04 x64, ARMv7 C# Debian 9 x64 C# Windows Server 2016 X64 C# Windows 10 IoT Core, build 17763 x64 To learn more about configuration options, continue to the how-to guide for agent configuration. Next steps Agent configuration how to guide


Deploy a Defender for IoT C#-based security agent for Windows Article • 04/24/2022 This guide explains how to install the Defender for IoT C#-based security agent on Windows. In this guide, you learn how to: Install Verify deployment Uninstall the agent Troubleshoot For other platforms and agent flavors, see Choose the right security agent. 1. Local admin rights on the machine you wish to install on. 2. Create a Defender-IoT-micro-agent for the device. To install the security agent, use the following workflow: 1. Install the Defender for IoT Windows C# agent on the device. Download the most recent version to your machine from the Defender for IoT GitHub repository . 2. Extract the contents of the package, and navigate to the /Install folder. 3. Open Windows PowerShell as Administrator. 4. Add running permissions to the InstallSecurityAgent script by running: then run: Prerequisites Installation Unblock-File .\InstallSecurityAgent.ps1


For example: For more information about authentication parameters, see How to configure authentication. This script does the following actions: Installs prerequisites. Adds a service user (with interactive sign-in disabled). Installs the agent as a System Service. Configures the agent with the provided authentication parameters. For extra help, use the Get-Help command in PowerShell. Get-Help example: Get-Help .\InstallSecurityAgent.ps1 Check the agent deployment status by running: sc.exe query "ASC IoT Agent" To uninstall the agent: 1. Run the following PowerShell script with the -mode parameter set to Uninstall. .\InstallSecurityAgent.ps1 -Install -aui <authentication identity> -aum <authentication method> -f <file path> -hn <host name> -di <device id> -cl <certificate location kind> .\InstallSecurityAgent.ps1 -Install -aui Device -aum SymmetricKey -f c:\Temp\Key.txt -hn MyIotHub.azure-devices.net -di Mydevice1 -cl store Verify deployment status Uninstall the agent .\InstallSecurityAgent.ps1 -Uninstall Troubleshooting


If the agent fails to start, turn on logging (logging is off by default) to get more information. To turn on logging: 1. Open the configuration file (General.config) for editing using a standard file editor. 2. Edit the following values: XML 3. Restart the agent by running the following PowerShell or command line: PowerShell or CMD 4. Review the log file for more information about the failure. The log file would be present in the working directory where we run the script. Log file location: .\IoTAgentLog.log <add key="logLevel" value="Debug" /> <add key="fileLogLevel" value="Debug"/> <add key="diagnosticVerbosityLevel" value="Some" /> <add key="logFilePath" value="IoTAgentLog.log" /> 7 Note We recommend turning logging off after troubleshooting is complete. Leaving logging on increases log file size and data usage. Restart-Service "ASC IoT Agent" sc.exe stop "ASC IoT Agent" sc.exe start "ASC IoT Agent" Next steps


Read the Defender for IoT service Overview Learn more about Defender for IoT What is agent-based solution for device builders Enable the service Read the Microsoft Defender for IoT agent frequently asked questions Understand alerts


Deploy Defender for IoT C# based security agent for Linux Article • 06/01/2022 This guide explains how to install and deploy the Defender for IoT C#-based security agent on Linux. In this guide, you learn how to: Install Verify deployment Uninstall the agent Troubleshoot For other platforms and agent flavors, see Choose the right security agent. 1. To deploy the security agent, local admin rights are required on the machine you wish to install on. 2. Create a Defender-IoT-micro-agent for the device. To deploy the security agent, use the following steps: 1. Download the most recent version to your machine from GitHub . 2. Extract the contents of the package and navigate to the /Install folder. 3. Add running permissions to the InstallSecurityAgent script by running chmod +x InstallSecurityAgent.sh 4. Next, run the following command with root privileges: Prerequisites Installation ./InstallSecurityAgent.sh -i -aui <authentication identity> -aum <authentication method> -f <file path> -hn <host name> -di <device id> -cl <certificate location kind>


for more information about authentication parameters, see How to configure authentication. This script performs the following actions: Installs prerequisites. Adds a service user (with interactive sign-in disabled). Installs the agent as a Daemon - assumes the device uses systemd for legacy deployment model. Configures sudoers to allow the agent to do certain tasks as root. Configures the agent with the provided authentication parameters. For additional help, run the script with the –help parameter: ./InstallSecurityAgent.sh --help To uninstall the agent, run the script with the –u parameter: ./InstallSecurityAgent.sh -u . 1. Check the deployment status by running: systemctl status ASCIoTAgent.service 2. Enable logging. If the agent fails to start, turn on logging to get more information. Turn on the logging by: a. Open the configuration file for editing in any Linux editor: vi /var/ASCIoTAgent/General.config b. Edit the following values: Uninstall the agent 7 Note Uninstall does not remove any missing prerequisites that were installed during installation. Troubleshooting


The logFilePath value is configurable. c. Restart the agent by running: systemctl restart ASCIoTAgent.service d. View the log file for more information about the failure. Log file location is: /var/ASCIoTAgent/IotAgentLog.log Change the file location path according to the name you chose for the logFilePath in step 2. Read the Defender for IoT service Overview Learn more about Defender for IoT What is agent-based solution for device builders Enable the service Read the Microsoft Defender for IoT agent frequently asked questions Understand alerts <add key="logLevel" value="Debug"/> <add key="fileLogLevel" value="Debug"/> <add key="diagnosticVerbosityLevel" value="Some" /> <add key="logFilePath" value="IotAgentLog.log"/> 7 Note We recommend turning logging off after troubleshooting is complete. Leaving logging on increases log file size and data usage. Next steps


Deploy Defender for IoT C based security agent for Linux Article • 06/01/2022 This guide explains how to install and deploy the Defender for IoT C-based security agent on Linux. Install Verify deployment Uninstall the agent Troubleshoot For other platforms and agent flavors, see Choose the right security agent. 1. To deploy the security agent, local admin rights are required on the machine you wish to install on (sudo). 2. Create a Defender-IoT-micro-agent for the device. To install and deploy the security agent, use the following workflow: 1. Download the most recent version to your machine from GitHub . 2. Extract the contents of the package and navigate to the /src/installation folder. 3. Add running permissions to the InstallSecurityAgent script by running the following command: 4. Next, run: Prerequisites Installation chmod +x InstallSecurityAgent.sh ./InstallSecurityAgent.sh -aui <authentication identity> -aum <authentication method> -f <file path> -hn <host name> -di <device id>


See How to configure authentication for more information about authentication parameters. This script performs the following function: 1. Installs prerequisites. 2. Adds a service user (with interactive sign-in disabled). 3. Installs the agent as a Daemon - assumes the device uses systemd for service management. 4. Configures the agent with the authentication parameters provided. For additional help, run the script with the –help parameter: ./InstallSecurityAgent.sh --help To uninstall the agent, run the script with the –-uninstall parameter: ./InstallSecurityAgent.sh -–uninstall Check the deployment status by running: systemctl status ASCIoTAgent.service Read the Defender for IoT service Overview Learn more about Defender for IoT What is agent-based solution for device builders Enable the service Read the Microsoft Defender for IoT agent frequently asked questions Understand security alerts -i Uninstall the agent Troubleshooting Next steps


Security agent troubleshoot guide (Linux) Article • 06/01/2022 This article explains how to solve potential problems in the security agent start-up process. Microsoft Defender for IoT agent self-starts immediately after installation. The agent startup process includes reading local configuration, connecting to Azure IoT Hub, and retrieving the remote twin configuration. Failure in any one of these steps may cause the security agent to fail. In this troubleshooting guide you'll learn how to: Validate if the security agent is running Get security agent errors Understand and remediate security agent errors 1. To validate that the security agent is running, wait a few minutes after installing the agent and run the following command. C agent Bash C# agent Bash 2. If the command returns an empty line, the security agent was unable to start successfully. In cases where the security agent is unable to start, stop the agent with the following command, then continue to the error table below: Bash Validate if the security agent is running grep "ASC for IoT Agent initialized" /var/log/syslog grep "Agent is initialized!" /var/log/syslog Force stop the security agent


1. Retrieve security agent error(s) by running the following command: Bash 2. The get security agent error command retrieves all logs created by the Defender for IoT agent. Use the following table to understand the errors and take the correct steps for remediation. 1. After locating and fixing a security agent error, try to restart the agent by running the following command. Bash 2. Repeat the previous process to retrieve stop and retrieve the errors if the agent continues to fail the startup process. Most of the Security agent errors are displayed in the following format: systemctl stop ASCIoTAgent.service Get security agent errors grep ASCIoTAgent /var/log/syslog 7 Note Error logs are shown in chronological order. Make sure to note the timestamp of each error to help your remediation. Restart the agent systemctl restart ASCIoTAgent.service Understand security agent errors Defender for IoT agent encountered an error! Error in: {Error Code}, reason: {Error sub code}, extra details: {error specific details}


Error Code Error sub code Error Code Error sub Error details Remediate C Remediate C# code Error details Remediate C Remediate C# Local Configuration Missing configuration A configuration is missing in the local configuration file. The error message should state which key is missing. Add the missing key to the /var/LocalConfiguration.json file, see the cs-localconfigreference for details. Add the missing key to the General.config file, see the c#- localconfig-reference for details. Local Configuration Cant Parse Configuration A configuration value can't be parsed. The error message should state which key can't be parsed. A configuration value cannot be parsed either because the value isn't in the expected type, or the value is out of range. Fix the value of the key in /var/LocalConfiguration.json file so that it matches the LocalConfiguration schema, see the c#-localconfigreference for details. Fix the value of the key in General.config file so that it matches the schema, see the cs-localconfigreference for details. Local Configuration File Format Failed to parse configuration file. The configuration file is corrupted, download the agent and re-install. - Remote Configuration Timeout The agent could not fetch the azureiotsecurity module twin within the timeout period. Make sure authentication configuration is correct and try again. The agent couldn't fetch the azureiotsecurity module twin within timeout period. Make sure authentication configuration is correct and try again. Authentication File Not Exist The file in the given path doesn't exist. Make sure the file exists in the given path or go to the LocalConfiguration.json file and change the FilePath configuration. Make sure the file exists in the given path or go to the Authentication.config file and change the filePath configuration. Authentication File Permission The agent does not have sufficient permissions to open the file. Give the asciotagent user read permissions on the file in the given path. Make sure the file is accessible.


Error Code Error sub code Error details Remediate C Remediate C# Authentication File Format The given file is not in the correct format. Make sure the file is in the correct format. The supported file types are .pfx and .pem. Make sure the file is a valid certificate file. Authentication Unauthorized The agent was not able to authenticate against IoT Hub with the given credentials. Validate authentication configuration in LocalConfiguration file, go through the authentication configuration and make sure all the details are correct, validate that the secret in the file matches the authenticated identity. Validate authentication configuration in Authentication.config, go through the authentication configuration and make sure all the details are correct, then validate that the secret in the file matches the authenticated identity. Authentication Not Found The device / module was found. Validate authentication configuration - make sure the hostname is correct, the device exists in IoT Hub and has an azureiotsecurity twin module. Validate authentication configuration - make sure the hostname is correct, the device exists in IoT Hub and has an azureiotsecurity twin module. Authentication Missing Configuration A configuration is missing in the Authentication.config file. The error message should state which key is missing. Add the missing key to the LocalConfiguration.json file. Add the missing key to the Authentication.config file, see the c#- localconfig-reference for details.


Error Code Error sub code Error details Remediate C Remediate C# Authentication Cant Parse Configuration A configuration value can't be parsed. The error message should state which key can't be parsed. A configuration value can not be parsed because either the value is not of the expected type, or the value is out of range. Fix the value of the key in the LocalConfiguration.json file. Fix the value of the key in Authentication.config file to match the schema, see the cslocalconfig-reference for details. Read the Defender for IoT service Overview Learn more about Defender for IoT agent-based solution for device builders Enable the Defender for IoT service Read the Defender for IoT service Defender for IoT FAQ Learn how to access raw security data Understand recommendations Understand security alerts Next steps


Understanding the LocalConfiguration.json file - C agent Article • 04/24/2022 The Defender for IoT security agent uses configurations from a local configuration file. The security agent reads the configuration once, at agent start-up. The configuration found in the local configuration file contains authentication configuration and other agent related configurations. The file contains configurations in "Key-Value" pairs in JSON notation and the configurations get populated when the agent is installed. By default, the file is located at: /var/ASCIoTAgent/LocalConfiguration.json Changes to the configuration file take place when the agent is restarted. Configuration Name Possible values Details AgentId GUID The agent Unique identifier TriggerdEventsInterval ISO8601 string Scheduler interval for triggered events collection ConnectionTimeout ISO8601 string Time period before the connection to IoThub gets timed out Authentication JsonObject Authentication configuration. This object contains all the information needed for authentication against IoTHub Identity "DPS", "SecurityModule", "Device" Authentication identity - DPS if authentication is made through DPS, SecurityModule if authentication is made via Defender-IoT-microagentcredentials or device if authentication is made with Device credentials AuthenticationMethod "SasToken", "SelfSignedCertificate" the user secret for authentication - Choose SasToken if the use secret is a Symmetric key, choose self-signed certificate if the secret is a selfsigned certificate Security agent configurations for C


Configuration Name Possible values Details FilePath Path to file (string) Path to the file that contains the authentication secret HostName string The host name of the Azure IoT hub. usually <my-hub>.azure-devices.net DeviceId string The ID of the device (as registered in Azure IoT Hub) DPS JsonObject DPS related configurations IDScope string ID scope of DPS RegistrationId string DPS device registration ID Logging JsonObject Agent logger related configurations SystemLoggerMinimumSeverity 0 <= number <= 4 log messages equal and above this severity will be logged to /var/log/syslog (0 is the lowest severity) DiagnosticEventMinimumSeverity 0 <= number <= 4 log messages equal and above this severity will be sent as diagnostic events (0 is the lowest severity) JSON Security agent configurations code example { "Configuration" : { "AgentId" : "b97faf0a-0f57-471f-9dab-46a8e1764946", "TriggerdEventsInterval" : "PT2M", "ConnectionTimeout" : "PT30S", "Authentication" : { "Identity" : "Device", "AuthenticationMethod" : "SasToken", "FilePath" : "/path/to/my/SymmetricKey", "DeviceId" : "my-device", "HostName" : "my-iothub.azure-devices.net", "DPS" : { "IDScope" : "", "RegistrationId" : "" } }, "Logging": { "SystemLoggerMinimumSeverity": 0, "DiagnoticEventMinimumSeverity": 2


Read the Defender for IoT service Overview Learn more about Defender for IoT Agent-based solution architecture Enable the Defender for IoT service Read the Defender for IoT service FAQ Learn how to access raw security data Understand recommendations Understand security alerts } } } Next steps


Understanding the local configuration file (C# agent) Article • 06/16/2022 The Defender for IoT security agent uses configurations from a local configuration file. The security agent reads the configuration file once, when the agent starts running. Configurations found in the local configuration file contain both authentication configuration and other agent related configurations. The C# security agent uses multiple configuration files: General.config - Agent related configurations. Authentication.config - Authentication related configuration (including authentication details). SecurityIotInterface.config - IoT related configurations. The configuration files contain the default configuration. Authentication configuration is populated during agent installation and changes to the configuration file are made when the agent is restarted. For Linux: Operating system configuration files are located in /var/ASCIoTAgent . For Windows: Operating system configuration files are located within the directory of the security agent. Configuration Name Possible values Details agentId GUID Agent unique identifier Configuration file location General.config configurations


Configuration Name Possible values Details readRemoteConfigurationTimeout TimeSpan Time period for fetching remote configuration from IoT Hub. If the agent can't fetch the configuration within the specified time, the operation will time out. schedulerInterval TimeSpan Internal scheduler interval. producerInterval TimeSpan Event producer worker interval. consumerInterval TimeSpan Event consumer worker interval. highPriorityQueueSizePercentage 0 < number < 1 The portion of total cache dedicated for high priority messages. logLevel "Off", "Fatal", "Error", "Warning", "Information", "Debug" Log messages equal and above this severity are logged to debug console (Syslog in Linux). fileLogLevel "Off", "Fatal", "Error", "Warning", "Information", "Debug" Log messages equal and above this severity are logged to file (Syslog in Linux). diagnosticVerbosityLevel "None", "Some", "All", Verbosity level of diagnostic events. None - diagnostic events are not sent. Some - Only diagnostic events with high importance are sent. All - all logs are also sent as diagnostic events. logFilePath Path to file If fileLogLevel > Off, logs are written to this file. defaultEventPriority "High", "Low", "Off" Default event priority. XML General.config example <?xml version="1.0" encoding="utf-8"?> <General> <add key="agentId" value="da00006c-dae9-4273-9abc-bcb7b7b4a987" /> <add key="readRemoteConfigurationTimeout" value="00:00:30" /> <add key="schedulerInterval" value="00:00:01" />


Configuration name Possible values Details moduleName string Name of the Defender-IoT-micro-agent identity. This name must correspond to the module identity name in the device. deviceId string ID of the device (as registered in Azure IoT Hub). schedulerInterval TimeSpan string Internal scheduler interval. gatewayHostname string Host name of the Azure Iot Hub. Usually <myhub>.azure-devices.net filePath string - path to file Path to the file that contains the authentication secret. type "SymmetricKey", "SelfSignedCertificate" The user secret for authentication. Choose SymmetricKey if the user secret is a Symmetric key, choose self-signed certificate if the secret is a self-signed certificate. identity "DPS", "Module", "Device" Authentication identity - DPS if authentication is made through DPS, Module if authentication is made using module credentials, or device if authentication is made using device credentials. certificateLocationKind "LocalFile", "Store" LocalFile if the certificate is stored in a file, store if the certificate is located in a certificate store. idScope string ID scope of DPS registrationId string DPS device registration ID. <add key="producerInterval" value="00:02:00" /> <add key="consumerInterval" value="00:02:00" /> <add key="highPriorityQueueSizePercentage" value="0.5" /> <add key="logLevel" value="Information" /> <add key="fileLogLevel" value="Off"/> <add key="diagnosticVerbosityLevel" value="Some" /> <add key="logFilePath" value="IotAgentLog.log" /> <add key="defaultEventPriority" value="Low"/> </General> Authentication.config Authentication.config example


XML Configuration Name Possible values Details transportType "Ampq" "Mqtt" IoT Hub transport type. XML Read the Defender for IoT service Overview Learn more about Defender for IoT Agent-based solution architecture Enable the Defender for IoT service Read the Defender for IoT service FAQ Learn how to access raw security data Understand recommendations Understand security alerts <?xml version="1.0" encoding="utf-8"?> <Authentication> <add key="moduleName" value="azureiotsecurity"/> <add key="deviceId" value="d1"/> <add key="gatewayHostname" value=""/> <add key="filePath" value="c:\p-dps-d1.pfx"/> <add key="type" value="SelfSignedCertificate" /> <!-- SymmetricKey, SelfSignedCertificate--> <add key="identity" value="DPS" /> <!-- Device, Module, DPS --> <add key="certificateLocationKind" value="LocalFile" /> <!-- LocalFile, Store --> <add key="idScope" value="0ne0005335B"/> <add key="registrationId" value="d1"/> </Authentication> SecurityIotInterface.config SecurityIotInterface.config example <ExternalInterface> <add key="facadeType" value="Microsoft.Azure.Security.IoT.Agent.Common.SecurityIoTHubInterface, Security.Common" /> <add key="transportType" value="Amqp"/> </ExternalInterface> Next steps


Deploy a security module on your IoT Edge device Article • 04/24/2022 Defender for IoT module provides a comprehensive security solution for your IoT Edge devices. The security module collects, aggregates, and analyzes raw security data from your Operating System and Container system into actionable security recommendations and alerts. To learn more, see Security module for IoT Edge. In this article, you'll learn how to deploy a security module on your IoT Edge device. Use the following steps to deploy a Defender for IoT security module for IoT Edge. 1. In your IoT Hub, make sure your device is Register a new device. 2. Defender for IoT Edge module requires the AuditD framework is installed on the IoT Edge device. Install the framework by running the following command on your IoT Edge device: sudo apt-get install auditd audispd-plugins Verify AuditD is active by running the following command: sudo systemctl status auditd Expected response is: active (running) 1. From the Azure portal, open Marketplace. 2. Select Internet of Things, then search for Azure Security Center for IoT and select it. Deploy security module Prerequisites Deployment using Azure portal


3. Select Create to configure the deployment. 4. Choose the Azure Subscription of your IoT Hub, then select your IoT Hub. Select Deploy to a device to target a single device or select Deploy at Scale to target multiple devices, and select Create. For more information about deploying at scale, see How to deploy. Complete each step to complete your IoT Edge deployment for Defender for IoT. 1. Select the AzureSecurityCenterforIoT module. 2. On the Module Settings tab, change the name to azureiotsecurity. 3. On the Environment Variables tab, add a variable if needed (for example, you can add debug level and set it to one of the following values: "Fatal", "Error", "Warning", or "Information"). 4. On the Container Create Options tab, add the following configuration: JSON 7 Note If you selected Deploy at Scale, add the device name and details before continuing to the Add Modules tab in the following instructions. Step 1: Modules { "NetworkingConfig": { "EndpointsConfig": { "host": {} } }, "HostConfig": { "Privileged": true,


5. On the Module Twin Settings tab, add the following configuration: Module Twin Property: JSON Module Twin Property Content: JSON For more information about configuring the agent, see Configure security agents. 6. Select Update. 1. Select Runtime Settings. 2. Under Edge Hub, change the Image to mcr.microsoft.com/azureiotedgehub:1.0.8.3. 3. Verify Create Options is set to the following configuration: JSON "NetworkMode": "host", "PidMode": "host", "Binds": [ "/:/host" ] } } "ms_iotn:urn_azureiot_Security_SecurityAgentConfiguration" { } Step 2: Runtime settings 7 Note Currently, version 1.0.8.3 or older is supported. { "HostConfig":{


4. Select Save. 5. Select Next. 1. On the Specify Routes tab, make sure you have a route (explicit or implicit) that will forward messages from the azureiotsecurity module to $upstream according to the following examples. Only when the route is in place, select Next. Example routes: Default Explicit 2. Select Next. "PortBindings":{ "8883/tcp":[ { "HostPort":"8883" } ], "443/tcp":[ { "HostPort":"443" } ], "5671/tcp":[ { "HostPort":"5671" } ] } } } Step 3: Specify routes "route": "FROM /messages/* INTO $upstream" "ASCForIoTRoute": "FROM /messages/modules/azureiotsecurity/* INTO $upstream" Step 4: Review deployment


On the Review Deployment tab, review your deployment information, then select Create to complete the deployment. If you encounter an issue, container logs are the best way to learn about the state of an IoT Edge security module device. Use the commands and tools in this section to gather information. 1. Run the following command on your IoT Edge device: sudo docker ps 2. Verify that the following containers are running: Name IMAGE azureiotsecurity mcr.microsoft.com/ascforiot/azureiotsecurity:1.0.2 edgeHub mcr.microsoft.com/azureiotedge-hub:1.0.8.3 edgeAgent mcr.microsoft.com/azureiotedge-agent:1.0.1 If the minimum required containers are not present, check if your IoT Edge deployment manifest is aligned with the recommended settings. For more information, see Deploy IoT Edge module. 1. Run the following command on your IoT Edge device: sudo docker logs azureiotsecurity 2. For more verbose logs, add the following environment variable to the azureiotsecurity module deployment: logLevel=Debug . Diagnostic steps Verify the required containers are installed and functioning as expected Inspect the module logs for errors Next steps


To learn more about configuration options, continue to the how-to guide for module configuration. Module configuration how-to guide


Tutorial: Configure security agents Article • 06/23/2022 This article explains Defender for IoT security agents, and details how to change and configure them. Defender for IoT security agents collect data from IoT devices and perform security actions to mitigate the detected vulnerabilities. Security agent configuration is controllable using a set of module twin properties you can customize. In general, secondary updates to these properties are infrequent. Defender for IoT's security agent twin configuration object is a JSON format object. The configuration object is a set of controllable properties that you can define to control the behavior of the agent. These configurations help you customize the agent for each scenario required. For example, automatically excluding some events, or keeping power consumption to a minimal level are possible by configuring these properties. Use the Defender for IoT security agent configuration schema to make changes. Properties related to every Defender for IoT security agent are located in the agent configuration object, within the desired properties section, of the azureiotsecurity module. To modify the configuration, create and modify this object inside the azureiotsecurity module twin identity. If the agent configuration object does not exist in the azureiotsecurity module twin, all security agent property values are set to default. JSON " Configure security agents " Change agent behavior by editing twin properties " Discover default configuration Agents Configuration objects


Make sure to validate your agent configuration against this schema . An agent will not launch if the configuration object doesn't match the schema. If, while the agent is running, the configuration object is changed to a non-valid configuration (the configuration doesn't match the schema), the agent will ignore the invalid configuration and will continue using the current configuration. Defender for IoT security agent reports its current configuration inside the reported properties section of the azureiotsecurity module twin identity. The agent reports all the available properties, if a property was not set by the user, the agent reports the default configuration. In order to validate your configuration, compare the values set on the desired section with the values reported in the reported section. If there is a mismatch between the desired and the reported properties, then the agent was not able to parse the configuration. Validate your desired properties against the schema , fix the errors and set your desired properties again! All custom properties must be set inside the agent configuration object within the azureiotsecurity module twin. To use a default property value, remove the property "desired": { "ms_iotn:urn_azureiot_Security_SecurityAgentConfiguration": { } } Configuration schema and validation Configuration validation 7 Note A configuration error alert will be fired from the agent in case that the agent was not able to parse the desired configuration. Compare the reported and desired section to understand if the alert still applies Editing a property


from the configuration object. 1. In your IoT Hub, locate and select the device you wish to change. 2. Click on your device, and then on azureiotsecurity module. 3. Click on Module Identity Twin. 4. Edit the properties you wish to change in the Defender-IoT-micro-agent. For example, to configure connection events as high priority and collect high priority events every 7 minutes, use the following configuration. JSON 5. Click Save. To use a default property value, remove the property from the configuration object. The following table contains the controllable properties of Defender for IoT security agents. Default values are available in the proper schema in GitHub . Name Status Valid values Default values Description Setting a property "desired": { "ms_iotn:urn_azureiot_Security_SecurityAgentConfiguration": { "highPriorityMessageFrequency": { "value": "PT7M" }, "eventPriorityConnectionCreate": { "value": "High" } } } Using a default value Default properties


Name Status Valid values Default values Description highPriorityMessageFrequency Required: false Valid values: Duration in ISO 8601 Format Default value: PT7M Max time interval before high priority messages are sent. lowPriorityMessageFrequency Required: false Valid values: Duration in ISO 8601 Format Default value: PT5H Max time before lowpriority messages are sent. snapshotFrequency Require: false Valid values: Duration in ISO 8601 Format Default value PT13H Time interval for the creation of device status snapshots. maxLocalCacheSizeInBytes Required: false Valid values: Default value: 2560000, larger than 8192 Maximum storage (in bytes) allowed for the message cache of an agent. Maximum amount of space allowed to store messages on the device, before messages are sent. maxMessageSizeInBytes Required: false Valid values: A positive number, larger than 8192, less than 262144 Default value: 204800 Maximum allowed size of an agent to cloud message. This setting controls the amount of maximum data sent in each message. eventPriority${EventName} Required: false Valid values: High, Low, Off Default values: Priority of every agentgenerated event Supported security events


Event name PropertyName Default Value Snapshot Event Event name PropertyName Default Details Status Value Snapshot Event Details Status Diagnostic event eventPriorityDiagnostic Off False Agent related diagnostic events. Use this event for verbose logging. Configuration error eventPriorityConfigurationError Low False Agent failed to parse the configuration. Verify the configuration against the schema. Dropped events statistics eventPriorityDroppedEventsStatistics Low True Agent related event statistics. Connected hardware eventPriorityConnectedHardware Low True Snapshot of all hardware connected to the device. Listening ports eventPriorityListeningPorts High True Snapshot of all open listening ports on the device. Process create eventPriorityProcessCreate Low False Audits process creation on the device. Process terminate eventPriorityProcessTerminate Low False Audits process termination on the device. System information eventPrioritySystemInformation Low True A snapshot of system information (for example: OS or CPU). Local users eventPriorityLocalUsers High True A snapshot of the registered local users within the system.


Event name PropertyName Default Value Snapshot Event Details Status Login eventPriorityLogin High False Audit the login events to the device (local and remote logins). Connection create eventPriorityConnectionCreate Low False Audits TCP connections created to and from the device. Firewall configuration eventPriorityFirewallConfiguration Low True Snapshot of device firewall configuration (firewall rules). OS baseline eventPriorityOSBaseline Low True Snapshot of device OS baseline check. Understand Defender for IoT recommendations Explore Defender for IoT alerts Access raw security data Next steps


Send security messages SDK Article • 04/24/2022 This how-to guide explains the Defender for IoT service capabilities when you choose to collect and send your device security messages without using a Defender for IoT agent, and explains how to do so. In this guide, you learn how to: Defender for IoT can process and analyze any kind of security message data as long as the data sent conforms to the Defender for IoT schema and the message is set as a security message. Defender for IoT defines a security message using the following criteria: If the message was sent with Azure IoT SDK If the message conforms to the security message schema If the message was set as a security message prior to sending Each security message includes the metadata of the sender such as AgentId , AgentVersion , MessageSchemaVersion and a list of security events. The schema defines the valid and required properties of the security message including the types of events. " Send security messages using the Azure IoT C SDK " Send security messages using the Azure IoT C# SDK " Send security messages using the Azure IoT Python SDK " Send security messages using the Azure IoT Node.js SDK " Send security messages using the Azure IoT Java SDK Defender for IoT capabilities Security message 7 Note Messages sent that do not comply with the schema are ignored. Make sure to verify the schema before initiating sending data as ignored messages are not currently stored.


The example below shows a valid security message object. The example contains the message metadata and one ProcessCreate security event. Once set as a security message and sent, this message will be processed by Defender for IoT. JSON Send security messages without using Defender for IoT agent, by using the Azure IoT C device SDK , Azure IoT C# device SDK , , Azure IoT Node.js SDK , Azure IoT Python 7 Note Messages sent that were not set as a security message using the Azure IoT SDK will not be routed to the Defender for IoT pipeline. Valid message example "AgentVersion": "0.0.1", "AgentId": "e89dc5f5-feac-4c3e-87e2-93c16f010c25", "MessageSchemaVersion": "1.0", "Events": [ { "EventType": "Security", "Category": "Triggered", "Name": "ProcessCreate", "IsEmpty": false, "PayloadSchemaVersion": "1.0", "Id": "21a2db0b-44fe-42e9-9cff-bbb2d8fdf874", "TimestampLocal": "2019-01-27 15:48:52Z", "TimestampUTC": "2019-01-27 13:48:52Z", "Payload": [ { "Executable": "/usr/bin/myApp", "ProcessId": 11750, "ParentProcessId": 1593, "UserName": "aUser", "CommandLine": "myApp -a -b" } ] } ] Send security messages


SDK , or Azure IoT Java SDK . To send the device data from your devices for processing by Defender for IoT, use one of the following APIs to mark messages for correct routing to Defender for IoT processing pipeline. All data that is sent, even if marked with the correct header, must also comply with the Defender for IoT message schema. The Send security messages API is currently available in C and C#, Python, Node.js, and Java. C Send security message API C API bool SendMessageAsync(IoTHubAdapter* iotHubAdapter, const void* data, size_t dataSize) { bool success = true; IOTHUB_MESSAGE_HANDLE messageHandle = NULL; messageHandle = IoTHubMessage_CreateFromByteArray(data, dataSize); if (messageHandle == NULL) { success = false; goto cleanup; } if (IoTHubMessage_SetAsSecurityMessage(messageHandle) != IOTHUB_MESSAGE_OK) { success = false; goto cleanup; } if (IoTHubModuleClient_SendEventAsync(iotHubAdapter->moduleHandle, messageHandle, SendConfirmCallback, iotHubAdapter) != IOTHUB_CLIENT_OK) { success = false; goto cleanup; } cleanup: if (messageHandle != NULL) { IoTHubMessage_Destroy(messageHandle); } return success;


C# TypeScript } static void SendConfirmCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback) { if (userContextCallback == NULL) { //error handling return; } if (result != IOTHUB_CLIENT_CONFIRMATION_OK){ //error handling } } C# API private static async Task SendSecurityMessageAsync(string messageContent) { ModuleClient client = ModuleClient.CreateFromConnectionString(" <connection_string>"); Message securityMessage = new Message(Encoding.UTF8.GetBytes(messageContent)); securityMessage.SetAsSecurityMessage(); await client.SendEventAsync(securityMessage); } Node.js API var Protocol = require('azure-iot-device-mqtt').Mqtt function SendSecurityMessage(messageContent) { var client = Client.fromConnectionString(connectionString, Protocol); var connectCallback = function (err) { if (err) { console.error('Could not connect: ' + err.message); } else { var message = new Message(messageContent); message.setAsSecurityMessage(); client.sendEvent(message); client.on('error', function (err) { console.error(err.message);


To use the Python API you need to install the package azure-iot-device . When using the Python API, you can either send the security message through the module or through the device using the unique device or module connection string. When using the following Python script example, with a device, use IoTHubDeviceClient, and with a module, use IoTHubModuleClient. Python Java }); client.on('disconnect', function () { clearInterval(sendInterval); client.removeAllListeners(); client.open(connectCallback); }); } }; client.open(connectCallback); } Python API from azure.iot.device.aio import IoTHubDeviceClient, IoTHubModuleClient from azure.iot.device import Message async def send_security_message_async(message_content): conn_str = os.getenv("<connection_string>") device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) await device_client.connect() security_message = Message(message_content) security_message.set_as_security_message() await device_client.send_message(security_message) await device_client.disconnect() Java API public void SendSecurityMessage(string message) { ModuleClient client = new ModuleClient("<connection_string>", IotHubClientProtocol.MQTT); Message msg = new Message(message); msg.setAsSecurityMessage(); EventCallback callback = new EventCallback();


Read the Defender for IoT service Overview Learn more about Defender for IoT What is agent-based solution for device builders Enable the service Read the Microsoft Defender for IoT agent frequently asked questions Learn how to access raw security data Understand recommendations Understand alerts string context = "<user_context>"; client.sendEventAsync(msg, callback, context); } Next steps


Access your security data Article • 06/01/2022 Defender for IoT stores security alerts, recommendations, and raw security data (if you choose to save it) in your Log Analytics workspace. To configure which Log Analytics workspace is used: 1. Open your IoT hub. 2. Select the Settings blade under the Security section. 3. Select Data Collection, and change your Log Analytics workspace configuration. To access your alerts and recommendations in your Log Analytics workspace after configuration: 1. Choose an alert or recommendation in Defender for IoT. 2. Select further investigation, then select To see which devices have this alert click here and view the DeviceId column. For details on querying data from Log Analytics, see Get started with log queries in Azure Monitor. Security alerts are stored in AzureSecurityOfThings.SecurityAlert table in the Log Analytics workspace configured for the Defender for IoT solution. We've provided a number of useful queries to help you get started exploring security alerts. Select a few random records TimeGenerated IoTHubId DeviceId AlertSe 2018-11- 18T18:10:29.000 /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> High 7 Note The Microsoft Defender for IoT legacy experience under IoT Hub has been replaced by our new Defender for IoT standalone experience, in the Defender for IoT area of the Azure portal. The legacy experience under IoT Hub will not be supported after March 31, 2023. For more information, see Tutorial: Configure Microsoft Defender for IoT agent-based solution. Log Analytics Security alerts Sample records // Select a few random records // SecurityAlert | project TimeGenerated, IoTHubId=ResourceId, DeviceId=tostring(parse_json(ExtendedProperties)["DeviceId"]), AlertSeverity, DisplayName, Description, ExtendedProperties | take 3


TimeGenerated IoTHubId DeviceId AlertSe 2018-11- 19T12:40:31.000 /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> High 2018-11- 19T12:40:31.000 /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> High Get the number of distinct security alerts detected in the last week, grouped by IoT Hub, device, alert severity, alert type. IoTHubId DeviceId AlertSeverity DisplayN /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> High Brute forc attack succeeded /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> Medium Failed loca login atte on device /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> High Successfu local login device /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> Medium Crypto Co Miner Select a number of distinct devices that had alerts in the last week, by IoT Hub, alert severity, alert type Device summary // Get the number of distinct security alerts detected in the last week, grouped by // IoT hub, device, alert severity, alert type // SecurityAlert | where TimeGenerated > ago(7d) | summarize Cnt=dcount(SystemAlertId) by IoTHubId=ResourceId, DeviceId=tostring(parse_json(ExtendedProperties)["DeviceId"]), AlertSeverity, DisplayName IoT hub summary // Select number of distinct devices which had alerts in the last week, by // IoT hub, alert severity, alert type // SecurityAlert | where TimeGenerated > ago(7d) | extend DeviceId=tostring(parse_json(ExtendedProperties)["DeviceId"]) | summarize CntDevices=dcount(DeviceId) by IoTHubId=ResourceId,


IoTHubId AlertSeverity DisplayName CntDevices /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> High Brute force attack succeeded 1 /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> Medium Failed local login attempt on device 1 /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> High Successful local login on device 1 /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> Medium Crypto Coin Miner 1 Security recommendations are stored in AzureSecurityOfThings.SecurityRecommendation table in the Log Analytics workspace configured for the Defender for IoT solution. We've provided a number of useful queries to help you get start exploring security recommendations. Select a few random records TimeGenerated IoTHubId DeviceId Recom 2019-03- 22T10:21:06.060 /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> Medium 2019-03- 22T10:50:27.237 /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> Medium AlertSeverity, DisplayName Security recommendations Sample records // Select a few random records // SecurityRecommendation | project TimeGenerated, IoTHubId=AssessedResourceId, DeviceId, RecommendationSeverity, RecommendationState, RecommendationDisplayName, Description, RecommendationAdditionalData | take 2


Get the number of distinct active security recommendations, grouped by IoT Hub, device, recommendation severity, and type. IoTHubId DeviceId RecommendationSeverit /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> High /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> Medium /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> High /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Devices/IotHubs/<iot_hub> <device_name> Medium Read the Defender for IoT Overview Learn about Defender for IoT What is agent-based solution for device builders Understand and explore Defender for IoT alerts Understand and explore Defender for IoT recommendations Device summary // Get the number of distinct active security recommendations, grouped by by // IoT hub, device, recommendation severity and type // SecurityRecommendation | extend IoTHubId=AssessedResourceId | summarize CurrentState=arg_max(RecommendationState, DiscoveredTimeUTC) by IoTHubId, DeviceId, RecommendationSeverity, RecommendationDisplayName | where CurrentState == "Active" | summarize Cnt=count() by IoTHubId, DeviceId, RecommendationSeverity Next steps


Investigate a suspicious IoT device Article • 06/16/2022 Defender for IoT service alerts provides clear indications when IoT devices are suspected of involvement in suspicious activities or when indications exist that a device is compromised. In this guide, use the investigation suggestions provided to help determine the potential risks to your organization, decide how to remediate, and discover the best ways to prevent similar attacks in the future. By default, Defender for IoT stores your security alerts and recommendations in your Log Analytics workspace. You can also choose to store your raw security data. To locate your Log Analytics workspace for data storage: 1. Open your IoT hub, 2. Under Security, select Settings, and then select Data Collection. 3. Change your Log Analytics workspace configuration details. 4. Select Save. Following configuration, do the following to access data stored in your Log Analytics workspace: 1. Select and select on a Defender for IoT alert in your IoT Hub. 2. Select Further investigation. " Find your device data " Investigate using KQL queries 7 Note The Microsoft Defender for IoT legacy experience under IoT Hub has been replaced by our new Defender for IoT standalone experience, in the Defender for IoT area of the Azure portal. The legacy experience under IoT Hub will not be supported after March 31, 2023. For more information, see Tutorial: Investigate security recommendations and Tutorial: Investigate security alerts. How can I access my data?


3. Select To see which devices have this alert click here and view the DeviceId column. To view insights and raw data about your IoT devices, go to your Log Analytics workspace to access your data. See the sample KQL queries below to get started with investigating alerts and activities on your device. You can find out if other alerts were triggered around the same time through the following KQL query: To find out which users have access to this device use the following KQL query: Investigation steps for suspicious IoT devices Related alerts let device = "YOUR_DEVICE_ID"; let hub = "YOUR_HUB_NAME"; SecurityAlert | where ExtendedProperties contains device and ResourceId contains tolower(hub) | project TimeGenerated, AlertName, AlertSeverity, Description, ExtendedProperties Users with access let device = "YOUR_DEVICE_ID"; let hub = "YOUR_HUB_NAME"; SecurityIoTRawEvent | where DeviceId == device and AssociatedResourceId contains tolower(hub) and RawEventName == "LocalUsers" | project TimestampLocal=extractjson("$.TimestampLocal", EventDetails, typeof(datetime)), GroupNames=extractjson("$.GroupNames", EventDetails, typeof(string)), UserName=extractjson("$.UserName", EventDetails, typeof(string)) | summarize FirstObserved=min(TimestampLocal) by GroupNames, UserName


Click to View FlipBook Version