Example implementation of an AWS IoT Device Defender metrics collection agent, and other Device Defender Python samples.
On starting up for the first time - the DD agent publishes the metric values read from the network stats to DD, without computing any metric values delta. It does this because when it starts up it does not have any information of the previously collected metric values. The side-effect of this is the device's metrics will indicate a large spike each time the device restarts or the agent is restarted which can cause false-positives. Now, we have updated the agent to not send any metrics if it cannot compute the delta.
The provided sample agent can be used as a basis to implement a custom metrics collection agent.
The Following requirements are shared with the AWS IoT Device SDK for Python
- Python 3.5+ for X.509 certificate-based mutual authentication via port 8883 and MQTT over WebSocket protocol with AWS Signature Version 4 authentication
- Python 3.5+ for X.509 certificate-based mutual authentication via port 443
- OpenSSL version 1.0.1+ (TLS version 1.2) compiled with the Python executable for X.509 certificate-based mutual authentication
If you have never connected your device to AWS IoT before, please follow the Getting Started with AWS IoT Guide. Make sure you note the location of your certificates, you will need to provide the location of these to the Device Defender Sample Agent.
client id: The sample agent requires a client id that will also be used as the "Thing Name". This only for the sake of making the sample easy to get started with. To customize this behavior, you can modify the way the agent generates the MQTT topic for publishing metrics reports, to use a value other than client id as the thing name portion of the topic.
metric selection: The sample agent attempts to gather all supported Device Defender metrics. Depending on your platform requirements and use case, you may wish to customize your agent to a subset of the metrics.
- Clone the repository
git clone https://github.com/aws-samples/aws-iot-device-defender-agent-sdk-python.git
- Install Using pip
Pip is the easiest way to install the sample agent, it will take care of installing dependencies
pip install /path/to/sample/package
python agent.py --endpoint <your.custom.endpoint.amazonaws.com> --rootCA </path/to/rootca> --cert </path/to/cert> --key <path/to/key> --format json -i 300 -id <ThingName>
To see a summary of all commandline options:
python agent.py --help
python collector.py -n 1 -s 1
The sample agent has a flag allowing it to publish custom metrics
python agent.py --include-custom-metrics --endpoint <your.custom.endpoint.amazonaws.com> --rootCA </path/to/rootca> --cert </path/to/cert> --key <path/to/key> --format json -i 300 -id <ThingName>
This flag will tell the agent to publish the custom metric cpu_usage, a number float representing the current cpu usage as a percent. How this looks in the generated report can be seen in the sample report below.
We can run the command seen below to create the custom_metric for cpu_usage.
aws iot create-custom-metric --metric-name "cpu_usage" --metric-type "number" --client-request-token "access-test" --region us-east-1
After creating this custom_metric you will be able to create security profiles that use it.
aws iot create-security-profile \
--security-profile-name CpuUsageIssue \
--security-profile-description "High-Cpu-Usage" \
--behaviors "[{\"name\":\"great-than-75\",\"metric\":\"cpu_usage\",\"criteria\":{\"comparisonOperator\":\"greater-than\",\"value\":{\"count\":75},\"consecutiveDatapointsToAlarm\":5,\"consecutiveDatapointsToClear\":1}}]" \
--region us-east-1
AWS IoT Device Defender can be used in conjunction with AWS Greengrass. Integration follows the standard Greengrass lambda deployment model, making it easy to add AWS IoT Device Defender security to your Greengrass Core devices.
- Greengrass environment setup
- Greengrass core configured and running
- Ensure you can successfully deploy and run a lambda on your core
You can deploy a Device Defender to your Greengrass core in two ways:
- Using the pre-built Greengrass Device Defender Connector (recommended)
- Create a lambda package manually
The Device Defender Greengrass Connector provides the most streamlined and automated means of deploy the Device Defender agent to your Greengrass core, and is the recommended method of using Device Defender with Greengrass.
For detailed information about using Greengrass Connectors see Getting Started with Greengrass Connectors For information about configuring the Device Defender Connector see Device Defender Connector Details
- Create a local resource to allow your lambda to collect metrics from the Greengrass Core host
- Follow the instructions here
- Use the following parameters:
- Resource Name:
Core_Proc
- Type:
Volume
- Source Path:
/proc
- Destination Path:
/host_proc
(make sure the same value is configured for the PROCFS_PATH environment variable above) - Group owner file access permission: "Automatically add OS group permissions of the Linux group that owns the resource"
- Associate the resource with your metrics lambda
- Resource Name:
- From the detail page of your Greengrass Group, click "Connectors" in the left-hand menu
- Click the "Add a Connector" button
- In the "Select a connector" screen, select the "Device Defender" connector from the list, click "Next"
- On the "Configure parameters" screen, select the resource you created in Step 1, in the "Resource for /proc" box
- In the "Metrics reporting interval" box, enter 300, or larger if you wish to use a longer reporting interval
- Click the "add" button
- Deploy your connector to your Greengrass Group
For this portion will be following the general process outlined here
Note: Due to platform-specific binary extensions in the psutil package, this process should be performed on the platform where you plan to deploy your lambda.
Clone the AWS IoT Device Defender Python Samples Repository
git clone https://github.com/aws-samples/aws-iot-device-defender-agent-sdk-python.git
Create, and activate a virtual environment (optional, recommended)
pip install virtualenv virtualenv metrics_lambda_environment source metrics_lambda_environment/bin/activate
Install the AWS IoT Device Defender sample agent in the virtual environment Install from PyPi
pip install AWSIoTDeviceDefenderAgentSDK
Install from downloaded source
cd aws-iot-device-defender-agent-sdk-python #This must be run from the same directory as setup.py pip install .
Create an empty directory to assemble your lambda, we will refer to this as your "lambda directory"
mkdir metrics_lambda cd metrics_lambda
Complete steps 1-4 from this guide
Unzip the Greengrass python sdk into your lambda directory
unzip ../aws_greengrass_core_sdk/sdk/python_sdk_1_1_0.zip cp -R ../aws_greengrass_core_sdk/examples/HelloWorld/greengrass_common . cp -R ../aws_greengrass_core_sdk/examples/HelloWorld/greengrasssdk . cp -R ../aws_greengrass_core_sdk/examples/HelloWorld/greengrass_ipc_python_sdk .
Copy the AWSIoTDeviceDefenderAgentSDK module to the root level of your lambda
cp -R ../aws-iot-device-defender-agent-sdk-python/AWSIoTDeviceDefenderAgentSDK .
Copy the Greengrass agent to the root level of your lambda directory
cp ../aws-iot-device-defender-agent-sdk-python/samples/greengrass/greengrass_core_metrics_agent/greengrass_defender_agent.py .
Copy the dependencies from your virtual environment or your system, into the the root level of your lambda
cp -R ../metrics_lambda_environment/lib/python2.7/site-packages/psutil . cp -R ../metrics_lambda_environment/lib/python2.7/site-packages/cbor .
Create your lambda zipfile Note: you should perform this command in the root level of your lambda directory
rm *.zip zip -r greengrass_defender_metrics_lambda.zip *
- Upload your lambda zip file
- Select the Python 2.7 runtime, and enter
greengrass_defender_agent.function_handler
in the Handler field - Configure your lambda as a long-lived lambda
- Configure the following environment variables:
- SAMPLE_INTERVAL_SECONDS: The metrics generation interval. The default is 300 seconds. Note: 5 minutes (300 seconds) is the shortest reporting interval supported by AWS IoT Device Defender
- PROCFS_PATH: The destination path that you will configure for your /proc resource as shown below.
- Configure a subscription from your lambda to the AWS IoT Cloud Note: For AWS IoT Device Defender, a subscription from AWS IoT Cloud to your lambda is not required
- Create a local resource to allow your lambda to collect metrics from the Greengrass Core host
- Follow the instructions here
- Use the following parameters:
- Resource Name:
Core_Proc
- Type:
Volume
- Source Path:
/proc
- Destination Path:
/host_proc
(make sure the same value is configured for the PROCFS_PATH environment variable above) - Group owner file access permission: "Automatically add OS group permissions of the Linux group that owns the resource"
- Associate the resource with your metrics lambda
- Resource Name:
- Deploy your connector to your Greengrass Group
- Temporarily modify your publish topic in your Greengrass lambda to something such as metrics/test
- Deploy the lambda
- Add a subscription to the temporary topic in the "Test" section of the iot console, shortly you should the metrics your Greengrass Core is emitting
Long Name | Short Name | Required | Type | Constraints | Notes |
---|---|---|---|---|---|
header | hed | Y | Object | Complete block required for well-formed report | |
metrics | met | Y | Object | Complete block required for well-formed report | |
custom_metrics | cmet | N | Object | Complete block required for well-formed report |
Long Name | Short Name | Requi red | Type | Constr aints | Notes |
---|---|---|---|---|---|
report _id | rid | Y | Inte ger | Monotonically increasing value, epoch timestamp recommended | |
versio n | v | Y | Stri ng | Major. Minor | Minor increments with addition of field, major increments if metrics removed |
Long Name | Short Name | Parent Element | Required | Type | Constraints | Notes |
---|---|---|---|---|---|---|
tcp_connections | tc | metrics | N | Object | ||
established_connections | ec | tcp_connections | N | List | ESTABLISHED TCP State | |
connections | cs | established_connections | N | List | ||
remote_addr | rad | connections | Y | Number | ip:port | ip can be ipv6 or ipv4 |
local_port | lp | connections | N | Number | >0 | |
local_interface | li | connections | N | String | interface name | |
total | t | established_connections | N | Number | >= 0 | Number established connections |
Long Name | Short Name | Parent Element | Required | Type | Constraints | Notes |
---|---|---|---|---|---|---|
listening_tcp_ports | tp | metrics | N | Object | ||
ports | pts | listening_tcp_ports | N | List | > 0 | |
port | pt | ports | N | Number | >= 0 | ports should be numbers > 0 |
interface | if | ports | N | String | Interface Name | |
total | t | listening_tcp_ports | N | Number | >= 0 |
Long Name | Short Name | Parent Element | Required | Type | Constraints | Notes |
---|---|---|---|---|---|---|
listening_udp_ports | up | metrics | N | Object | ||
ports | pts | listening_udp_ports | N | List | > 0 | |
port | pt | ports | N | Number | > 0 | ports should be numbers > 0 |
interface | if | ports | N | String | Interface Name | |
total | t | listening_udp_ports | N | Number | >= 0 |
Long Name | Short Name | Parent Element | Required | Type | Constraints | Notes |
---|---|---|---|---|---|---|
network_stats | ns | metrics | N | Object | ||
bytes_in | bi | network_stats | N | Number | Delta Metric, >= 0 | |
bytes_out | bo | network_stats | N | Number | Delta Metric, >= 0 | |
packets_in | pi | network_stats | N | Number | Delta Metric, >= 0 | |
packets_out | po | network_stats | N | Number | Delta Metric, >= 0 |
Long Name | Short Name | Parent Element | Required | Type | Constraints | Notes |
---|---|---|---|---|---|---|
cpu_usage | cpu | custom_metrics | N | Number |
{
"header": {
"report_id": 1529963534,
"version": "1.0"
},
"metrics": {
"listening_tcp_ports": {
"ports": [
{
"interface": "eth0",
"port": 24800
},
{
"interface": "eth0",
"port": 22
},
{
"interface": "eth0",
"port": 53
}
],
"total": 3
},
"listening_udp_ports": {
"ports": [
{
"interface": "eth0",
"port": 5353
},
{
"interface": "eth0",
"port": 67
}
],
"total": 2
},
"network_stats": {
"bytes_in": 1157864729406,
"bytes_out": 1170821865,
"packets_in": 693092175031,
"packets_out": 738917180
},
"tcp_connections": {
"established_connections":{
"connections": [
{
"local_interface": "eth0",
"local_port": 80,
"remote_addr": "192.168.0.1:8000"
},
{
"local_interface": "eth0",
"local_port": 80,
"remote_addr": "192.168.0.1:8000"
}
],
"total": 2
}
}
},
"custom_metrics": {
"cpu_usage": [
{
"number": 26.1
}
]
}
}
{
"hed": {
"rid": 1529963534,
"v": "1.0"
},
"met": {
"tp": {
"pts": [
{
"if": "eth0",
"pt": 24800
},
{
"if": "eth0",
"pt": 22
},
{
"if": "eth0",
"pt": 53
}
],
"t": 3
},
"up": {
"pts": [
{
"if": "eth0",
"pt": 5353
},
{
"if": "eth0",
"pt": 67
}
],
"t": 2
},
"ns": {
"bi": 1157864729406,
"bo": 1170821865,
"pi": 693092175031,
"po": 738917180
},
"tc": {
"ec":{
"cs": [
{
"li": "eth0",
"lp": 80,
"rad": "192.168.0.1:8000"
},
{
"li": "eth0",
"lp": 80,
"rad": "192.168.0.1:8000"
}
],
"t": 2
}
}
},
"cmet": {
"cpu": [
{
"number": 26.1
}
]
}
}
You can find the API documentation here
- AWS Lambda: Creating a Deployment Package (Python)
- Monitoring with AWS Greengrass Logs
- Troubleshooting AWS Greengrass Applications
- Access Local Resources with Lambda Functions
This library is licensed under the Apache 2.0 License.
If you have technical questions about the AWS IoT Device SDK, use the AWS IoT Forum. For any other questions about AWS IoT, contact AWS Support.